{
 "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": [
    "# Capacitance of a disc capacitor with fringing fields\n",
    "\n",
    "A capacitor in its simplest form: two metal discs of radius $a=10$ cm and thickness $5$ mm,\n",
    "separated by a $d=3$ cm thick disc of quartz glass ($\\varepsilon_r=4.2$) of the same radius. Each\n",
    "disc carries a lead (radius $7.5$ mm) that runs along the axis to the boundary of a cylindrical air\n",
    "region of radius and height $20$ cm. The upper electrode is held at $V_0=1$ V, the lower one is\n",
    "grounded, and the outer boundary of the air carries no charge ($\\mathbf D\\cdot\\mathbf n=0$).\n",
    "\n",
    "The field is not confined to the dielectric: it bulges out at the rim of the discs into the\n",
    "surrounding air (fringing), and the field at the sharp metal edges is singular. Both raise the\n",
    "capacitance above the ideal parallel-plate value $\\varepsilon_0\\varepsilon_r A/d$.\n",
    "\n",
    "One quarter of everything that carries a field, the air together with the glass, comes from the\n",
    "CAD file `disc_capacitor_fringing.step`; the metal is cut out, its surface is a boundary. The\n",
    "glass disc, which the mesh follows and which marks the dielectric, comes from\n",
    "`disc_capacitor_fringing_glass.step`, and `disc_capacitor_fringing_wide.step` holds the same\n",
    "capacitor in an air cylinder of twice the radius. The script\n",
    "`disc_capacitor_fringing_geometry.py` builds all three with the CAD objects of OneSimulation.\n",
    "\n",
    "| faces | condition |\n",
    "|---|---|\n",
    "| `terminal`: upper disc and its lead | $V=V_0$ |\n",
    "| `ground`: lower disc and its lead | $V=0$ |\n",
    "| `symmetry`: the cut planes $x=0$ and $y=0$ | $\\mathbf D\\cdot\\mathbf n=0$ |\n",
    "| `outer`: wall, bottom and top of the air cylinder | $\\mathbf D\\cdot\\mathbf n=0$ |\n",
    "\n",
    "OneSimulation solves $-\\nabla\\cdot(\\varepsilon\\nabla V)=0$ with second-order Lagrange elements.\n",
    "The charge of an electrode is the reaction of the potential on its faces, $C=Q/V_0$.\n",
    "\n",
    "**Reference.** There is no closed form for the complete device. It is checked by a mesh study\n",
    "with a Richardson estimate, by the charges of the two electrodes, which must be equal and\n",
    "opposite, and by a larger air region. The example *Fringing fields and the capacitance of a disc\n",
    "capacitor* compares the same discs without glass and leads with a boundary-integral reference."
   ]
  },
  {
   "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",
    "The mesh follows the surface of the glass (`embedded_regions`), so every tetrahedron lies in one\n",
    "material. Three meshes differ in the cell size in the air, in the glass and along the four rim\n",
    "edges of the discs; the wide air cylinder is meshed with the coarsest sizes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "regions = {\n",
    "    \"air cylinder 20 cm\": load(\"disc_capacitor_fringing.step\"),\n",
    "    \"air cylinder 40 cm\": load(\"disc_capacitor_fringing_wide.step\"),\n",
    "}\n",
    "glass = load(\"disc_capacitor_fringing_glass.step\")\n",
    "device = regions[\"air cylinder 20 cm\"]\n",
    "disc_radius, _, gap = glass.size\n",
    "sizes = ((0.040, 0.0080, 0.0040), (0.0283, 0.00566, 0.00283), (0.020, 0.0040, 0.0020))\n",
    "cases = [(\"air cylinder 20 cm\", level) for level in sizes] + [\n",
    "    (\"air cylinder 40 cm\", sizes[0])\n",
    "]\n",
    "meshes = [\n",
    "    TetrahedralMesher(\n",
    "        target_size=in_air,\n",
    "        embedded_regions=(glass,),\n",
    "        refinements=(\n",
    "            LocalRefinement(region=glass, target_size=in_glass),\n",
    "            LocalRefinement(\n",
    "                region=regions[name].select(\n",
    "                    edges=lambda edge: edge.kind != \"line\"\n",
    "                    and abs(np.hypot(*edge.midpoint[:2]) - disc_radius) < 1e-6\n",
    "                ),\n",
    "                target_size=at_rim,\n",
    "            ),\n",
    "        ),\n",
    "    ).generate(regions[name])\n",
    "    for name, (in_air, in_glass, at_rim) in cases\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=18, azimuth=40)\n",
    "fig = plots.figure(1, 2, size=(14, 7))\n",
    "plots.geometry(\n",
    "    device,\n",
    "    selection={\n",
    "        name: device.boundaries[name] for name in (\"terminal\", \"ground\", \"symmetry\")\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Quarter of the air and the glass with the named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0],\n",
    "    groups=(\"terminal\", \"ground\", \"symmetry\"),\n",
    "    camera=view,\n",
    "    title=f\"Coarsest mesh: {meshes[0].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 the points inside the glass disc its permittivity and the air the vacuum\n",
    "value. Each mesh is solved once; the reactions on `terminal` and `ground` are the charges of a\n",
    "quarter of each electrode."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "voltage, relative_permittivity = 1.0, 4.2\n",
    "vacuum = float(VacuumPermittivity().evaluate())\n",
    "bottom, top = glass.bounding_box[0][2], glass.bounding_box[1][2]\n",
    "in_glass = (\n",
    "    lambda points: (np.hypot(points[:, 0], points[:, 1]) < disc_radius)\n",
    "    & (points[:, 2] > bottom)\n",
    "    & (points[:, 2] < top)\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "potentials, fields, charges = [], [], []\n",
    "for (name, level), mesh in zip(cases, meshes):\n",
    "    faces = regions[name].boundaries\n",
    "    model = PoissonEquation(\n",
    "        domain=regions[name].volume,\n",
    "        permittivity=regionwise(\n",
    "            ((in_glass, relative_permittivity * vacuum),), default=vacuum, unit=\"F/m\"\n",
    "        ),\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Disc capacitor\",\n",
    "        geometry=regions[name],\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            FixedPotential(boundary=faces.terminal, physics=model, value=voltage),\n",
    "            FixedPotential(boundary=faces.ground, physics=model, value=0.0),\n",
    "            ZeroNormalElectricDisplacement(\n",
    "                boundary=faces.symmetry | faces.outer, physics=model\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=problem, mesh=mesh, numerics=numerics\n",
    "    ).solve_stationary()\n",
    "    potentials.append(result.field(model.potential))\n",
    "    fields.append(result.field(model.electric_field))\n",
    "    charges.append(\n",
    "        (\n",
    "            4 * potentials[-1].reaction(faces.terminal),\n",
    "            4 * potentials[-1].reaction(faces.ground),\n",
    "        )\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The capacitance on the three meshes, the charge balance of the two electrodes, the effect of the\n",
    "larger air cylinder and the share of the fringing field."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "capacitance = np.array([terminal / voltage for terminal, ground in charges])\n",
    "ideal = vacuum * relative_permittivity * np.pi * disc_radius**2 / gap\n",
    "study = convergence(capacitance[:3], [level[2] for level in sizes])\n",
    "print(\n",
    "    \"air region           rim size [mm]   tetrahedra   C [pF]     (Q_terminal + Q_ground) / Q_terminal\"\n",
    ")\n",
    "for (name, level), mesh, value, (terminal, ground) in zip(\n",
    "    cases, meshes, capacitance, charges\n",
    "):\n",
    "    print(\n",
    "        f\"{name:20s} {1e3 * level[2]:13.2f} {mesh.cell_count:12d} {1e12 * value:9.4f} {(terminal + ground) / terminal:+12.1e}\"\n",
    "    )\n",
    "print(\n",
    "    f\"change between the two finest meshes {100 * abs(capacitance[2] / capacitance[1] - 1):.4f} %, \"\n",
    "    f\"extrapolated {1e12 * study.extrapolated:.4f} pF (observed order {study.order:.2f})\"\n",
    ")\n",
    "print(\n",
    "    f\"air cylinder of 40 cm instead of 20 cm radius (coarsest sizes): {100 * (capacitance[3] / capacitance[0] - 1):+.3f} %\"\n",
    ")\n",
    "print(\n",
    "    f\"ideal plates eps0 eps_r A/d = {1e12 * ideal:.3f} pF: {100 * (1 - ideal / capacitance[2]):.1f} % below the device; \"\n",
    "    f\"fringing and leads add {1e12 * (capacitance[2] - ideal):.3f} pF\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The potential in the section through the axis (the quarter mirrored), the field strength at the\n",
    "rim of the discs on a logarithmic scale, and the mesh study in the air cylinder of 20 cm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cut = Plane(origin=(0.0, 1e-6, 0.0), normal=(0.0, 1.0, 0.0))\n",
    "decades = lambda E, position: np.log10(np.maximum(np.linalg.norm(E, axis=1), 1e-3))\n",
    "fig = plots.figure(1, 3, size=(18, 6))\n",
    "plots.section(\n",
    "    potentials[2],\n",
    "    plane=cut,\n",
    "    symmetry={\"planes\": [((1, 0, 0), (0, 0, 0))]},\n",
    "    limits=(0, voltage),\n",
    "    contours=19,\n",
    "    subdivisions=3,\n",
    "    label=\"potential [V]\",\n",
    "    title=\"Potential, section through the axis\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.section(\n",
    "    fields[2],\n",
    "    plane=cut,\n",
    "    component=decades,\n",
    "    limits=(0.6, 2.2),\n",
    "    contours=16,\n",
    "    subdivisions=3,\n",
    "    label=\"log10(|E| / (V/m))\",\n",
    "    title=\"Fringing field at the rim of the discs\",\n",
    "    xlimits=(0.07, 0.13),\n",
    "    ylimits=(0.065, 0.135),\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    [mesh.cell_count for mesh in meshes[:3]],\n",
    "    {\"air cylinder 20 cm\": 1e12 * capacitance[:3]},\n",
    "    hlines={\"extrapolated\": 1e12 * study.extrapolated},\n",
    "    markers=True,\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"tetrahedra in the quarter\",\n",
    "    ylabel=\"capacitance [pF]\",\n",
    "    title=\"Mesh study\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the gap or the glass in `disc_capacitor_fringing_geometry.py` and write the STEP files\n",
    "again; remove the leads to see their share of the fringing; or drive each electrode in turn\n",
    "against a grounded outer boundary to obtain the capacitance matrix."
   ]
  }
 ]
}
