{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Electric sensor: dielectric objects in a box\n",
    "\n",
    "A capacitive sensor finds objects by the charge they draw onto an electrode. The box is 5 m long,\n",
    "3 m wide and $h=1$ m high, with an electrode on its top held at $V_0=1$ V and a grounded\n",
    "electrode on its bottom; the side walls are insulating. Two dielectric objects stand on the\n",
    "bottom electrode: a rectangular bar of $1.0\\times0.6$ m, 0.8 m high, with $\\varepsilon_r=2$, and\n",
    "a disc of radius 0.4 m, 0.5 m high, with $\\varepsilon_r=3$. The potential follows from\n",
    "\n",
    "$$\\nabla\\cdot\\big(\\varepsilon_0\\varepsilon_r\\,\\nabla V\\big)=0,$$\n",
    "\n",
    "with $V$ and the normal displacement $D_n$ continuous on the surfaces of the objects. The sensor\n",
    "signal is the surface charge on the top electrode, $\\sigma=\\mathbf D\\cdot\\mathbf n=-\\varepsilon_0E_z$,\n",
    "and its total, the charge $Q=CV_0$.\n",
    "\n",
    "The air box comes from the CAD file `dielectric_inclusion_sensor.step` with the face groups\n",
    "`top`, `bottom` and `walls`; the objects from `dielectric_inclusion_sensor_bar.step` and\n",
    "`..._disc.step`, and the same objects extended to the full height from `..._bar_column.step` and\n",
    "`..._disc_column.step`. The script `dielectric_inclusion_sensor_geometry.py` builds them with the\n",
    "CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `top` | $V=V_0$ |\n",
    "| `bottom` | $V=0$ |\n",
    "| `walls` | $\\mathbf D\\cdot\\mathbf n=0$ |\n",
    "| surfaces of the objects | continuous $V$ and $D_n$ (interfaces inside the mesh) |\n",
    "\n",
    "**Reference.** The capacitance has no closed form, but the two variational principles of\n",
    "electrostatics bound it from both sides (J. D. Jackson, *Classical Electrodynamics*, 3rd ed.,\n",
    "Sec. 1.12 and the capacitance bounds in the problems of Chapter 1; G. Pólya and G. Szegő,\n",
    "*Isoperimetric Inequalities in Mathematical Physics*, 1951). Dirichlet's principle with the\n",
    "uniform field $V=V_0z/h$ as trial potential gives the upper bound, Thomson's principle with a\n",
    "vertical displacement that is constant in each column gives the lower bound:\n",
    "\n",
    "$$C_\\mathrm{low}=\\varepsilon_0\\!\\int_A\\!\\frac{\\mathrm dA}{h-t+t/\\varepsilon_r}\\;\\le\\;C\\;\\le\\;\n",
    "  C_\\mathrm{up}=\\frac{\\varepsilon_0}{h^2}\\Big(Ah+\\sum_i(\\varepsilon_{r,i}-1)\\,V_i\\Big),$$\n",
    "\n",
    "where $t(x,y)$ is the height of the object in the column at $(x,y)$ and $V_i$ the volume of\n",
    "object $i$. When the objects fill the full height ($t=h$) both bounds meet: the field stays\n",
    "uniform and $C=\\varepsilon_0\\big(A+\\sum_i(\\varepsilon_{r,i}-1)A_i\\big)/h$ exactly."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import VacuumPermittivity\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.electrostatics import (\n",
    "    FixedPotential,\n",
    "    PoissonEquation,\n",
    "    ZeroNormalElectricDisplacement,\n",
    ")\n",
    "from onesim.results.comparisons import convergence\n",
    "from onesim.simulation import Problem, Simulation, regionwise\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the box with its named faces and the objects. The tetrahedral mesher embeds the\n",
    "objects, so their surfaces run along faces of the mesh, and refines inside them. Three meshes\n",
    "with 0.25, 0.18 and 0.13 m in the air (two thirds of that in the objects) make the mesh study; the\n",
    "columns get one mesh of the middle size."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "box = load(\"dielectric_inclusion_sensor.step\")\n",
    "faces = box.boundaries\n",
    "objects = {\n",
    "    name: load(f\"dielectric_inclusion_sensor_{name}.step\")\n",
    "    for name in (\"bar\", \"disc\", \"bar_column\", \"disc_column\")\n",
    "}\n",
    "length, width, height = box.size\n",
    "sizes = (0.25, 0.18, 0.13)\n",
    "generate = lambda bar, disc, size: TetrahedralMesher(\n",
    "    target_size=size,\n",
    "    embedded_regions=(bar, disc),\n",
    "    refinements=(\n",
    "        LocalRefinement(region=bar, target_size=size / 1.5),\n",
    "        LocalRefinement(region=disc, target_size=size / 1.5),\n",
    "    ),\n",
    ").generate(box)\n",
    "meshes = [generate(objects[\"bar\"], objects[\"disc\"], size) for size in sizes]\n",
    "column_mesh = generate(objects[\"bar_column\"], objects[\"disc_column\"], sizes[1])\n",
    "\n",
    "view = plots.Camera(elevation=30, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.geometry(\n",
    "    [objects[\"bar\"].named(\"bar, eps_r = 2\"), objects[\"disc\"].named(\"disc, eps_r = 3\")],\n",
    "    camera=view,\n",
    "    title=\"The two objects on the bottom electrode\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Air box 5 m x 3 m x 1 m, middle mesh: {meshes[1].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`regionwise` gives each object its permittivity; the tests are the boxes of the bar and the disc\n",
    "taken from their CAD bounds. Quadratic elements. The charge on the electrodes is the reaction of\n",
    "the potential on the face."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "voltage, eps0 = 1.0, float(VacuumPermittivity().evaluate())\n",
    "relative = {\"bar\": 2.0, \"disc\": 3.0}\n",
    "(bx0, by0, _), (bx1, by1, _) = objects[\"bar\"].bounding_box\n",
    "(dx0, dy0, _), (dx1, dy1, _) = objects[\"disc\"].bounding_box\n",
    "radius, centre = (dx1 - dx0) / 2, ((dx0 + dx1) / 2, (dy0 + dy1) / 2)\n",
    "tops = {\n",
    "    \"\": (objects[\"bar\"].size[2], objects[\"disc\"].size[2]),\n",
    "    \"_column\": (height, height),\n",
    "}\n",
    "permittivity = lambda suffix: regionwise(\n",
    "    (\n",
    "        (\n",
    "            lambda p: (p[:, 0] >= bx0)\n",
    "            & (p[:, 0] <= bx1)\n",
    "            & (p[:, 1] >= by0)\n",
    "            & (p[:, 1] <= by1)\n",
    "            & (p[:, 2] <= tops[suffix][0]),\n",
    "            relative[\"bar\"] * eps0,\n",
    "        ),\n",
    "        (\n",
    "            lambda p: (np.hypot(p[:, 0] - centre[0], p[:, 1] - centre[1]) <= radius)\n",
    "            & (p[:, 2] <= tops[suffix][1]),\n",
    "            relative[\"disc\"] * eps0,\n",
    "        ),\n",
    "    ),\n",
    "    default=eps0,\n",
    "    unit=\"F/m\",\n",
    ")\n",
    "models = {\n",
    "    suffix: PoissonEquation(\n",
    "        domain=box.volume, permittivity=permittivity(suffix), charge_density=0.0\n",
    "    )\n",
    "    for suffix in tops\n",
    "}\n",
    "problems = {\n",
    "    suffix: Problem(\n",
    "        name=\"Electric sensor\",\n",
    "        geometry=box,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            FixedPotential(boundary=faces.top, physics=model, value=voltage),\n",
    "            FixedPotential(boundary=faces.bottom, physics=model, value=0.0),\n",
    "            ZeroNormalElectricDisplacement(boundary=faces.walls, physics=model),\n",
    "        ),\n",
    "    )\n",
    "    for suffix, model in models.items()\n",
    "}\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "results = [\n",
    "    Simulation(problem=problems[\"\"], mesh=mesh, numerics=numerics).solve_stationary()\n",
    "    for mesh in meshes\n",
    "]\n",
    "column = Simulation(\n",
    "    problem=problems[\"_column\"], mesh=column_mesh, numerics=numerics\n",
    ").solve_stationary()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The capacitance on the three meshes against the two bounds, the charge balance of the two\n",
    "electrodes, the surface charge above the middle of each object against the value of a vertical\n",
    "column of air and dielectric in series, and the columns against the exact capacitance."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "potentials = [result.field(models[\"\"].potential) for result in results]\n",
    "capacitance = [potential.reaction(faces.top) / voltage for potential in potentials]\n",
    "study = convergence(capacitance, sizes)\n",
    "area = length * width\n",
    "footprints = {\"bar\": (bx1 - bx0) * (by1 - by0), \"disc\": np.pi * radius**2}\n",
    "heights = dict(zip(relative, tops[\"\"]))\n",
    "upper = (\n",
    "    eps0\n",
    "    / height**2\n",
    "    * (\n",
    "        area * height\n",
    "        + sum((relative[n] - 1) * footprints[n] * heights[n] for n in relative)\n",
    "    )\n",
    ")\n",
    "lower = eps0 * (\n",
    "    (area - sum(footprints.values())) / height\n",
    "    + sum(\n",
    "        footprints[n] / (height - heights[n] + heights[n] / relative[n])\n",
    "        for n in relative\n",
    "    )\n",
    ")\n",
    "exact_column = (\n",
    "    eps0 * (area + sum((relative[n] - 1) * footprints[n] for n in relative)) / height\n",
    ")\n",
    "print(\n",
    "    f\"empty box {1e12 * eps0 * area / height:.3f} pF; bounds with the objects: lower {1e12 * lower:.3f} pF, upper {1e12 * upper:.3f} pF\"\n",
    ")\n",
    "print(\n",
    "    \"cell size in air [m]   tetrahedra   C [pF]    position between the bounds   (Q_top + Q_bottom) / Q_top\"\n",
    ")\n",
    "for size, mesh, C, potential in zip(sizes, meshes, capacitance, potentials):\n",
    "    print(\n",
    "        f\"{size:20.2f} {mesh.cell_count:12d} {1e12 * C:9.4f} {(C - lower) / (upper - lower):24.3f}\"\n",
    "        f\" {(potential.reaction(faces.top) + potential.reaction(faces.bottom)) / potential.reaction(faces.top):+24.1e}\"\n",
    "    )\n",
    "print(\n",
    "    f\"mesh study: change between the two finest meshes {100 * study.change:.3f} %, extrapolated {1e12 * study.extrapolated:.4f} pF\"\n",
    ")\n",
    "field = results[-1].field(models[\"\"].electric_field)\n",
    "probes = {\"bar\": (1.5, 1.5), \"disc\": centre}\n",
    "for name, (x, y) in probes.items():\n",
    "    sigma = -eps0 * field.evaluate(np.array([[x, y, height - 1e-6]]))[0, 2]\n",
    "    series = eps0 * voltage / (height - heights[name] + heights[name] / relative[name])\n",
    "    print(\n",
    "        f\"surface charge above the {name:4s} {1e12 * sigma:8.3f} pC/m^2   series column {1e12 * series:8.3f} pC/m^2   \"\n",
    "        f\"empty box {1e12 * eps0 * voltage / height:8.3f} pC/m^2\"\n",
    "    )\n",
    "C_column = column.field(models[\"_column\"].potential).reaction(faces.top) / voltage\n",
    "print(\n",
    "    f\"objects over the full height: C = {1e12 * C_column:.4f} pF, exact {1e12 * exact_column:.4f} pF, \"\n",
    "    f\"deviation {100 * (C_column / exact_column - 1):+.3f} %\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The surface charge on the top electrode, the field strength in the vertical section through both\n",
    "objects, the surface charge along the middle line $y=1.5$ m against the series-column estimate,\n",
    "and the mesh study between the two bounds."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(0.01, length - 0.01, 400)\n",
    "line = np.column_stack((x, np.full_like(x, 1.5), np.full_like(x, height - 1e-6)))\n",
    "series_line = (\n",
    "    eps0\n",
    "    * voltage\n",
    "    / np.where(\n",
    "        (x >= bx0) & (x <= bx1),\n",
    "        height - heights[\"bar\"] + heights[\"bar\"] / relative[\"bar\"],\n",
    "        np.where(\n",
    "            np.abs(x - centre[0]) <= radius,\n",
    "            height - heights[\"disc\"] + heights[\"disc\"] / relative[\"disc\"],\n",
    "            height,\n",
    "        ),\n",
    "    )\n",
    ")\n",
    "fig = plots.figure(2, 2, size=(15, 11))\n",
    "plots.surface(\n",
    "    field,\n",
    "    boundary=faces.top,\n",
    "    component=lambda E, position: -1e12 * eps0 * E[:, 2],\n",
    "    limits=(8.0, 15.0),\n",
    "    contours=15,\n",
    "    subdivisions=2,\n",
    "    label=\"σ [pC/m²]\",\n",
    "    title=\"Surface charge on the top electrode\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.section(\n",
    "    field,\n",
    "    plane=Plane(origin=(0.0, 1.5, 0.0), normal=(0.0, 1.0, 0.0)),\n",
    "    component=lambda E, position: np.linalg.norm(E, axis=1),\n",
    "    limits=(0.3, 1.8),\n",
    "    contours=16,\n",
    "    subdivisions=2,\n",
    "    label=\"|E| [V/m]\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Field strength in the section y = 1.5 m\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    x,\n",
    "    {\"simulation\": -1e12 * eps0 * field.evaluate(line)[:, 2]},\n",
    "    reference={\"series columns\": 1e12 * series_line},\n",
    "    hlines={\"empty box\": 1e12 * eps0 * voltage / height},\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"σ on the top electrode [pC/m²]\",\n",
    "    title=\"Surface charge along y = 1.5 m\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    list(sizes),\n",
    "    {\"simulation\": [1e12 * C for C in capacitance]},\n",
    "    hlines={\n",
    "        \"upper bound (Dirichlet)\": 1e12 * upper,\n",
    "        \"lower bound (Thomson)\": 1e12 * lower,\n",
    "    },\n",
    "    markers=True,\n",
    "    xlabel=\"cell size in the air [m]\",\n",
    "    ylabel=\"capacitance [pF]\",\n",
    "    title=\"Mesh study and variational bounds\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move the objects, change their height or permittivity in `dielectric_inclusion_sensor_geometry.py`\n",
    "and in the model, and watch the imprint in the surface charge: a high, narrow object shows a\n",
    "sharper but weaker peak than a low, wide one of the same volume. Split the top electrode into\n",
    "strips and read each with `reaction`, as a sensor array does."
   ]
  }
 ]
}
