{
 "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": [
    "# Trimmer capacitor with a rotating electrode\n",
    "\n",
    "A trimmer capacitor is adjusted by turning one electrode with a screwdriver. Here the stator and\n",
    "the rotor are half-discs of radius $R=5$ mm and thickness 0.1 mm, $d=0.5$ mm apart in air. At the\n",
    "rotor angle $\\theta$ the two half-discs overlap over the angle $\\varphi=\\pi-\\theta$, so the\n",
    "capacitance should fall linearly from full overlap at $\\theta=0$ to nearly nothing at\n",
    "$\\theta=180°$; a linear angular response is what makes a trimmer easy to set.\n",
    "\n",
    "The rotor is held at $V_0=1$ V, the stator is grounded, the air around them is charge-free,\n",
    "$-\\nabla\\cdot(\\varepsilon_0\\nabla V)=0$, and the capacitance is the charge on the rotor,\n",
    "$C=Q/V_0$.\n",
    "\n",
    "The air comes from the CAD files `trimmer_capacitor_rotation.step` (rotor at 0°) and\n",
    "`trimmer_capacitor_rotation_030.step` to `trimmer_capacitor_rotation_180.step`; the electrodes are\n",
    "cut out of it, their surfaces are the face groups `rotor` and `stator`. The script\n",
    "`trimmer_capacitor_rotation_geometry.py` builds all seven files with the CAD objects of\n",
    "OneSimulation.\n",
    "\n",
    "| faces | condition |\n",
    "|---|---|\n",
    "| `rotor` | $V=V_0$ |\n",
    "| `stator` | $V=0$ |\n",
    "| `outer`: the air cylinder, radius 12 mm and height 10 mm | $\\mathbf D\\cdot\\mathbf n=0$ |\n",
    "\n",
    "**Reference.** For the overlap angle $\\varphi$ the parallel-plate capacitance is\n",
    "$\\varepsilon_0R^2\\varphi/(2d)$, so an ideal trimmer has the slope\n",
    "\n",
    "$$\\frac{\\mathrm dC}{\\mathrm d\\varphi}=\\frac{\\varepsilon_0R^2}{2d}$$\n",
    "\n",
    "(plate capacitor, e.g. Jackson, *Classical Electrodynamics*, 3rd ed., Sec. 1.13). The fringing\n",
    "field at the edges and around the rims adds a share that hardly depends on the angle: it shifts\n",
    "the line but should leave its slope close to the parallel-plate value. Linearity is checked by a\n",
    "straight-line fit between 30° and 150°, the mesh by a study at 90°."
   ]
  },
  {
   "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.simulation import Problem, Simulation\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 air for each rotor angle; the radius is read from the rotor faces. The cells\n",
    "are fine on the electrodes and grow towards the outer faces. The rotor at 90° is meshed three\n",
    "times for a mesh study; the sweep uses the middle size."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "angles = np.arange(0, 181, 30)\n",
    "regions = {\n",
    "    angle: load(\n",
    "        \"trimmer_capacitor_rotation.step\"\n",
    "        if angle == 0\n",
    "        else f\"trimmer_capacitor_rotation_{angle:03d}.step\"\n",
    "    )\n",
    "    for angle in angles\n",
    "}\n",
    "radius = max(\n",
    "    face.radius\n",
    "    for face in regions[0].faces\n",
    "    if face.kind == \"cylinder\" and face.id.startswith(\"rotor.\")\n",
    ")\n",
    "gap = 0.0005\n",
    "sizes = (0.0005, 0.00035, 0.00025)\n",
    "mesher = lambda air, size: TetrahedralMesher(\n",
    "    target_size=0.002,\n",
    "    refinements=(\n",
    "        LocalRefinement(\n",
    "            region=air.boundaries.rotor | air.boundaries.stator, target_size=size\n",
    "        ),\n",
    "    ),\n",
    ").generate(air)\n",
    "study_meshes = [mesher(regions[90], size) for size in sizes]\n",
    "meshes = {\n",
    "    angle: study_meshes[1] if angle == 90 else mesher(regions[angle], sizes[1])\n",
    "    for angle in angles\n",
    "}\n",
    "\n",
    "view = plots.Camera(elevation=35, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "air = regions[90]\n",
    "plots.geometry(\n",
    "    air,\n",
    "    selection={\"rotor\": air.boundaries.rotor, \"stator\": air.boundaries.stator},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Electrodes in the air, rotor at 90°\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[90],\n",
    "    groups=(\"rotor\", \"stator\"),\n",
    "    camera=view,\n",
    "    title=f\"{meshes[90].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One solve per rotor angle and mesh; the reactions of the potential on `rotor` and `stator` are the\n",
    "charges of the two electrodes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "voltage = 1.0\n",
    "eps0 = float(VacuumPermittivity().evaluate())\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "\n",
    "\n",
    "def solve(air, mesh):\n",
    "    \"\"\"Potential with the rotor at 1 V and the stator grounded.\"\"\"\n",
    "    model = PoissonEquation(\n",
    "        domain=air.volume, permittivity=VacuumPermittivity(), charge_density=0.0\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Trimmer capacitor\",\n",
    "        geometry=air,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            FixedPotential(boundary=air.boundaries.rotor, physics=model, value=voltage),\n",
    "            FixedPotential(boundary=air.boundaries.stator, physics=model, value=0.0),\n",
    "            ZeroNormalElectricDisplacement(\n",
    "                boundary=air.boundaries.outer, physics=model\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=problem, mesh=mesh, numerics=numerics\n",
    "    ).solve_stationary()\n",
    "    return result.field(model.potential), result.field(model.electric_field)\n",
    "\n",
    "\n",
    "study = [solve(regions[90], mesh)[0] for mesh in study_meshes]\n",
    "sweep = {angle: solve(regions[angle], mesh) for angle, mesh in meshes.items()}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The mesh study at 90°, the capacitance over the rotor angle, its straight-line fit between 30°\n",
    "and 150° and its slope against the parallel-plate value."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "at_90 = [\n",
    "    potential.reaction(regions[90].boundaries.rotor) / voltage for potential in study\n",
    "]\n",
    "print(\"cell size on the electrodes [mm]   tetrahedra   C at 90 deg [pF]\")\n",
    "for size, mesh, value in zip(sizes, study_meshes, at_90):\n",
    "    print(f\"{1e3 * size:32.2f} {mesh.cell_count:12d} {1e12 * value:16.5f}\")\n",
    "print(f\"change on the last refinement {100 * abs(at_90[2] / at_90[1] - 1):.2f} %\")\n",
    "\n",
    "capacitance = np.array(\n",
    "    [\n",
    "        sweep[angle][0].reaction(regions[angle].boundaries.rotor) / voltage\n",
    "        for angle in angles\n",
    "    ]\n",
    ")\n",
    "balance = [\n",
    "    sweep[angle][0].reaction(regions[angle].boundaries.stator)\n",
    "    / (capacitance[k] * voltage)\n",
    "    + 1\n",
    "    for k, angle in enumerate(angles)\n",
    "]\n",
    "overlap = np.radians(180 - angles)\n",
    "inner = (angles >= 30) & (angles <= 150)\n",
    "slope, offset = np.polyfit(overlap[inner], capacitance[inner], 1)\n",
    "ideal_slope = eps0 * radius**2 / (2 * gap)\n",
    "print(\n",
    "    \"angle [deg]   overlap [deg]   C [pF]   parallel plates [pF]   (Q_stator + Q_rotor) / Q_rotor\"\n",
    ")\n",
    "for angle, value, phi, check in zip(angles, capacitance, overlap, balance):\n",
    "    print(\n",
    "        f\"{angle:11d} {180 - angle:15d} {1e12 * value:8.4f} {1e12 * ideal_slope * phi:22.4f} {check:+18.1e}\"\n",
    "    )\n",
    "print(\n",
    "    f\"slope dC/dphi: simulation {1e12 * slope:.4f} pF/rad, parallel plates {1e12 * ideal_slope:.4f} pF/rad \"\n",
    "    f\"({100 * (slope / ideal_slope - 1):+.1f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"largest deviation from the straight line between 30 and 150 deg: \"\n",
    "    f\"{100 * np.max(np.abs(capacitance[inner] - (slope * overlap[inner] + offset))) / capacitance.max():.2f} % of the full-overlap value; \"\n",
    "    f\"constant edge share {1e12 * offset:.4f} pF\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The field strength in the mid-plane of the gap with the rotor at 90°, and the angular response."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "strength = lambda E, position: np.linalg.norm(E, axis=1)\n",
    "fine = np.linspace(0, 180, 181)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.section(\n",
    "    sweep[90][1],\n",
    "    plane=Plane(origin=(0.0, 0.0, 0.0), normal=(0.0, 0.0, 1.0)),\n",
    "    component=strength,\n",
    "    limits=(0, 2400),\n",
    "    contours=0,\n",
    "    subdivisions=2,\n",
    "    label=\"|E| [V/m]\",\n",
    "    title=\"Field in the mid-plane, rotor at 90°\",\n",
    "    xlimits=(-0.0075, 0.0075),\n",
    "    ylimits=(-0.0075, 0.0075),\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    fine,\n",
    "    {\"straight-line fit\": 1e12 * (slope * np.radians(180 - fine) + offset)},\n",
    "    points={\"simulation\": (angles, 1e12 * capacitance)},\n",
    "    reference={\"parallel plates\": 1e12 * ideal_slope * np.radians(180 - fine)},\n",
    "    xlabel=\"rotor angle [deg]\",\n",
    "    ylabel=\"capacitance [pF]\",\n",
    "    title=\"Angular response\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Fill the gap with a ceramic disc in `trimmer_capacitor_rotation_geometry.py` (an embedded region\n",
    "with its own permittivity) to raise the capacitance, or shape the rotor as a cardioid-like cam to\n",
    "make the response logarithmic instead of linear."
   ]
  }
 ]
}
