{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1.3 Dirichlet boundary conditions\n",
    "\n",
    "This tutorial goes in depth into the mechanisms required to solve the Dirichlet problem \n",
    "$$\n",
    "-\\Delta u  = f \\quad \\text{ in } \\Omega, \n",
    "$$\n",
    "with a **nonzero** Dirichlet boundary condition\n",
    "$$\n",
    "u|_{\\Gamma_D} = g\n",
    "\\quad \\text{ on a boundary part }  \\Gamma_D \\subset \\partial\\Omega.\n",
    "$$ \n",
    "The same mechanisms are used in solving boundary value problems involving operators other than the Laplacian. You will see how to perform these tasks in NGSolve:\n",
    "* extend Dirichlet data from boundary parts, \n",
    "* convert boundary data into a volume source,\n",
    "* reduce inhomogeneous Dirichlet case to the homogeneous case, and \n",
    "* perform all these tasks automatically within a utility.\n",
    "\n",
    "If you are interested only in an *automatic utility* that does all these steps under the hood, then please skip to the last part of the tutorial. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Spaces with Dirichlet conditions on part of the boundary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ngsolve import *\n",
    "from ngsolve.webgui import Draw\n",
    "from netgen.geom2d import unit_square\n",
    "\n",
    "mesh = Mesh(unit_square.GenerateMesh(maxh=0.2))\n",
    "mesh.GetBoundaries()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `unit_square` has its boundaries marked as `left`, `right`, `top` and `bottom`. Suppose we want non-homogeneous Dirichlet boundary conditions on \n",
    "\n",
    "$$\n",
    "\\Gamma_D = \\Gamma_{left} \\cup \\Gamma_{right}.\n",
    "$$\n",
    "\n",
    "Then, we set the space as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fes = H1(mesh, order=2, dirichlet=\"left|right\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Compare this space with the one without the `dirichlet` flag:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fs2 = H1(mesh, order=2)\n",
    "fes.ndof, fs2.ndof    # total number of unknowns"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Thus, the `dirichlet` flag did not change `ndof`. In NGSolve the unknowns are split into two groups: \n",
    " * dirichlet dofs (or constrained dofs), \n",
    " * free dofs.\n",
    " \n",
    "The facility `FreeDofs` gives a `BitArray` such that `FreeDofs[dof]` is True if and only if `dof` is a free degree of freedom."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"free dofs of fs2 without \\\"dirichlet\\\" flag:\\n\",\n",
    "      fs2.FreeDofs())\n",
    "print(\"free dofs of fes:\\n\", fes.FreeDofs())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* The space `fs2` without `dirichlet` flag has only free dofs (no dirichlet dofs).\n",
    "\n",
    "* The other space `fes` has a few dofs that are marked as *not* free. These are the dofs that are located on the boundary regions we marked as `dirichlet`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  Extension of boundary data  \n",
    "\n",
    "We use the standard technique of reducing a problem with essential non-homogeneous boundary conditions to one with homogeneous boundary condition using an  extension. The solution $u$ in $H^1$ satisfies \n",
    "\n",
    "$$\n",
    "u|_{\\Gamma_D} = g$$\n",
    "\n",
    "and \n",
    "\n",
    "$$ \n",
    "\\int_\\Omega \\nabla u \\cdot \\nabla v_0 = \\int_\\Omega f v_0\n",
    "$$\n",
    "\n",
    "for all $v_0$ in $\\in H_{0,D}^1 = \\{ v \\in H^1: v|_{\\Gamma_D} = 0\\}$. Split the solution \n",
    "\n",
    "$$\n",
    "u = u_0 + u_D\n",
    "$$\n",
    "\n",
    "where $u_D$ is an extension of $g$ into $\\Omega$.   Then we only need to find $u_0$ in $H^1_{0,D}$ satisfying the homogeneous Dirichlet problem \n",
    "\n",
    "$$\n",
    "\\int_\\Omega \\nabla u_0 \\cdot \\nabla v_0 = \\int_\\Omega f v_0 - \\int_\\Omega \\nabla u_D \\cdot \\nabla v_0 \n",
    "$$\n",
    "\n",
    "for all $v_0$ in $H_{0,D}^1$. These are the **issues to consider** in this approach:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " * How to define an extension $u_D$ in the finite element space?\n",
    " * How to form and solve the system for $u_0$?\n",
    "\n",
    "Let us address the first in the following example."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Suppose we are given that \n",
    "$$\n",
    "g = \\sin(y) \\qquad \\text{ on } \\; \\Gamma_D.\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sin(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We interpolate $g$ on the boundary of the domain and extend it to zero  on the elements not having an intersection with $\\Gamma_D$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gfu = GridFunction(fes)\n",
    "gfu.Set(g, BND)\n",
    "Draw(gfu);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The keyword `BND` tells `Set` that `g` need only be interpolated on those parts of the boundary that are marked `dirichlet`.\n",
    "\n",
    "Thus, `gfu` now contains the extension $u_D$. Next, we turn to set up the system for $u_0$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Forms and assembly"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In NGSolve, bilinear and linear forms are defined independently of the dirichlet flags. Matrices and vectors are set up with respect to all unknowns (free or constrained) so they may be restricted to any group of unknowns later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "u, v = fes.TnT()\n",
    "a = BilinearForm(grad(u)*grad(v)*dx).Assemble();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If $A=$ `a.mat` is the matrix just assembled, then we want to solve for \n",
    "\n",
    "$$\n",
    "  A (u_0 + u_D) = f \\quad \\Rightarrow \\quad A u_0 = f - A u_D\n",
    "$$\n",
    "\n",
    "or\n",
    "\n",
    "$$\n",
    "  \\left( \\begin{array}{cc} A_{FF} & A_{FD} \\\\ A_{DF} & A_{DD} \\end{array} \\right) \\left( \\begin{array}{c} u_{0,F} \\\\ 0 \\end{array} \\right) = \\left( \\begin{array}{c} {f}_F \\\\ {f}_D \\end{array} \\right) - \\left( \\begin{array}{cc} A_{FF} & A_{FD} \\\\ A_{DF} & A_{DD} \\end{array} \\right) \\left( \\begin{array}{c} u_{D,F} \\\\ u_{D,D} \\end{array} \\right)\n",
    "$$\n",
    "\n",
    "where we have block partitioned using free dofs ($F$) and dirichlet dofs ($D$) as if they were numbered consecutively (which may not be the case in  practice) for ease of presentation.  The first row gives\n",
    "\n",
    "$$\n",
    "A_{FF} u_{0,F} = f_F - [A u_D]_F.\n",
    "$$\n",
    "\n",
    "Since we have already constructed $u_D$, we need to perform \n",
    "these next steps:\n",
    "\n",
    "- Set up the right hand side from $f$ and $u_D$.\n",
    "- Solve a linear system which involves only $A_{FF}$.\n",
    "- Add solution: $u = u_0 + u_D$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Solve for the free dofs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We need to assemble the right hand side of $A_{FF} u_{0,F} = f_F - [A u_D]_F$, namely\n",
    "$$\n",
    "r = f - A u_D.\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = LinearForm(1*v*dx).Assemble()\n",
    "r = f.vec - a.mat * gfu.vec"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The implementation of \n",
    "\n",
    "$$\n",
    "u = \n",
    "u_D + \n",
    "\\left( \\begin{array}{cc} A_{FF}^{-1} & 0 \\\\ 0 & 0 \\end{array} \\right) r\n",
    "$$\n",
    "\n",
    "by sparse solvers is achieved by the following:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gfu.vec.data += a.mat.Inverse(freedofs=fes.FreeDofs()) * r  \n",
    "Draw(gfu);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The automatic utility `BVP`\n",
    "\n",
    "NGSolve also provides a `BVP` facility in the `solvers` submodule, within which the above steps are performed automatically. You provide $A$, $f$, a grid function `gfu` with your boundary condition $g$, and a preconditioner. Then `BVP` solves the problem with non-homogeneous Dirichlet boundary condition and overwrites `gfu` with the solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gfu.Set(g, BND)\n",
    "c = Preconditioner(a,\"local\")   #<- Jacobi preconditioner\n",
    "#c = Preconditioner(a,\"direct\") #<- sparse direct solver\n",
    "c.Update()\n",
    "solvers.BVP(bf=a, lf=f, gf=gfu, pre=c)\n",
    "Draw(gfu)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
