{
 "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": [
    "# Capacitive position sensor\n",
    "\n",
    "Capacitive sensors find a conductive object without touching it. Four square copper pads\n",
    "(8 mm, 2 mm apart) sit on an FR-4 circuit board ($\\varepsilon_r=4.4$, 1.6 mm thick) inside a\n",
    "grounded metal box of 40 x 40 x 20 mm. A metal cube of 10 mm, the target, hovers 2 mm above the\n",
    "pads. The five conductors (four pads and the target) and the grounded box form a five-terminal\n",
    "system; in the charge-free space between them the potential obeys\n",
    "\n",
    "$$\\nabla\\cdot(\\varepsilon\\nabla V)=0 .$$\n",
    "\n",
    "The charges and potentials of the terminals are linked by the Maxwell capacitance matrix,\n",
    "$Q_i=\\sum_j C_{ij}V_j$. Column $j$ is found by holding terminal $j$ at 1 V and all others at 0 V.\n",
    "When the target moves sideways, its coupling capacitance $-C_{i,\\mathrm{target}}$ grows for the\n",
    "pads it moves towards; differences of these four numbers give its position.\n",
    "\n",
    "The air comes from the CAD file `capacitive_position_sensor.step` (target centred) and from\n",
    "`..._x2.step`, `..._x4.step`, `..._x2y2.step` and `..._x4y3.step` (target moved by those millimetres);\n",
    "its faces form the groups `pad_1` ... `pad_4` (pads in the four quadrants, counter-clockwise from\n",
    "$+x,+y$), `target` and `ground`. The board is `capacitive_position_sensor_board.step`. The script\n",
    "`capacitive_position_sensor_geometry.py` builds them with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** Reciprocity requires a symmetric matrix, $C_{ij}=C_{ji}$, and with a closed\n",
    "grounded box each row of the pads and the target plus the charge on the box sums to zero\n",
    "(Smythe, *Static and Dynamic Electricity*, 3rd ed., Sec. 2.15). The centred target must couple\n",
    "equally to all four pads by symmetry. The position estimate\n",
    "\n",
    "$$\\hat x=g\\,\\frac{(C_1+C_4)-(C_2+C_3)}{C_1+C_2+C_3+C_4},\\qquad\n",
    "  \\hat y=g\\,\\frac{(C_1+C_2)-(C_3+C_4)}{C_1+C_2+C_3+C_4}$$\n",
    "\n",
    "(with $C_i$ the coupling capacitance of pad $i$) is calibrated once at $x=2$ mm and then compared\n",
    "with the true positions."
   ]
  },
  {
   "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 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 FixedPotential, PoissonEquation\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 board is embedded in the mesh of the air. The cells are 2 mm between the pads and the\n",
    "target and grow towards the walls of the box."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mm = 1e-3\n",
    "positions = {(0, 0): \"\", (2, 0): \"_x2\", (4, 0): \"_x4\", (2, 2): \"_x2y2\", (4, 3): \"_x4y3\"}\n",
    "airs = {\n",
    "    position: load(f\"capacitive_position_sensor{suffix}.step\")\n",
    "    for position, suffix in positions.items()\n",
    "}\n",
    "board = load(\"capacitive_position_sensor_board.step\")\n",
    "meshes = {\n",
    "    position: TetrahedralMesher(\n",
    "        target_size=6 * mm,\n",
    "        minimum_size=0.5 * mm,\n",
    "        embedded_regions=(board,),\n",
    "        size_field=lambda points: np.clip(\n",
    "            2 * mm\n",
    "            + 0.5 * np.maximum(np.max(np.abs(points[:, :2]), axis=1) - 11 * mm, 0)\n",
    "            + 0.5 * np.maximum(points[:, 2] - 16 * mm, 0),\n",
    "            2 * mm,\n",
    "            6 * mm,\n",
    "        ),\n",
    "    ).generate(air)\n",
    "    for position, air in airs.items()\n",
    "}\n",
    "\n",
    "faces = airs[(2, 2)].boundaries\n",
    "terminals = (\"pad_1\", \"pad_2\", \"pad_3\", \"pad_4\", \"target\")\n",
    "view = plots.Camera(elevation=40, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    airs[(2, 2)],\n",
    "    selection={name: faces[name] for name in terminals},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Pads and target inside the shielding box (target at 2, 2 mm)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[(2, 2)],\n",
    "    groups=terminals,\n",
    "    camera=view,\n",
    "    title=f\"{meshes[(2, 2)].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One simulation per excited terminal: the full matrix at the centred position, the target column\n",
    "at every position. The charge on each terminal is the `reaction` of its fixed potential."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "eps0 = float(VacuumPermittivity().evaluate())\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "runs = [((0, 0), excited) for excited in terminals] + [\n",
    "    (position, \"target\") for position in positions if position != (0, 0)\n",
    "]\n",
    "models = [\n",
    "    PoissonEquation(\n",
    "        domain=airs[position].volume,\n",
    "        permittivity=regionwise(((board, 4.4 * eps0),), default=eps0, unit=\"F/m\"),\n",
    "        charge_density=0.0,\n",
    "    )\n",
    "    for position, _ in runs\n",
    "]\n",
    "potentials = [\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Capacitive sensor\",\n",
    "            geometry=airs[position],\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                *(\n",
    "                    FixedPotential(\n",
    "                        boundary=airs[position].boundaries[name],\n",
    "                        physics=model,\n",
    "                        value=float(name == excited),\n",
    "                    )\n",
    "                    for name in terminals\n",
    "                ),\n",
    "                FixedPotential(\n",
    "                    boundary=airs[position].boundaries.ground, physics=model, value=0.0\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=meshes[position],\n",
    "        numerics=numerics,\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(model.potential)\n",
    "    for model, (position, excited) in zip(models, runs)\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The capacitance matrix at the centre, its asymmetry and the charge balance, then the position of\n",
    "the target recovered from the four coupling capacitances."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "matrix = np.array(\n",
    "    [\n",
    "        [\n",
    "            potential.reaction(airs[(0, 0)].boundaries[name])\n",
    "            for potential in potentials[:5]\n",
    "        ]\n",
    "        for name in terminals\n",
    "    ]\n",
    ")\n",
    "print(\"Maxwell capacitance matrix at the centred position [pF]\")\n",
    "print(\"          \" + \"\".join(f\"{name:>11s}\" for name in terminals))\n",
    "for name, row in zip(terminals, matrix):\n",
    "    print(f\"{name:10s}\" + \"\".join(f\"{1e12 * value:11.4f}\" for value in row))\n",
    "print(\n",
    "    f\"largest asymmetry |C_ij - C_ji| / |C_ij|: {np.max(np.abs(matrix - matrix.T)) / np.max(np.abs(matrix - np.diag(np.diag(matrix)))):.1e}\"\n",
    ")\n",
    "box = [\n",
    "    potential.reaction(airs[(0, 0)].boundaries.ground) for potential in potentials[:5]\n",
    "]\n",
    "print(\n",
    "    f\"charge balance (terminals + box) / excited charge: {np.max(np.abs((matrix.sum(axis=0) + box) / np.diag(matrix))):.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"coupling of the centred target to the four pads [pF]: {', '.join(f'{-1e12 * value:.4f}' for value in matrix[:4, 4])}\"\n",
    ")\n",
    "\n",
    "coupling = {\n",
    "    (0, 0): -matrix[:4, 4],\n",
    "    **{\n",
    "        position: -np.array(\n",
    "            [\n",
    "                potential.reaction(airs[position].boundaries[name])\n",
    "                for name in terminals[:4]\n",
    "            ]\n",
    "        )\n",
    "        for (position, _), potential in zip(runs[5:], potentials[5:])\n",
    "    },\n",
    "}\n",
    "signal = {\n",
    "    position: np.array([(c[0] + c[3] - c[1] - c[2]), (c[0] + c[1] - c[2] - c[3])])\n",
    "    / c.sum()\n",
    "    for position, c in coupling.items()\n",
    "}\n",
    "gain = 2 * mm / signal[(2, 0)][0]\n",
    "print(\"true position [mm]   estimated [mm]        error [mm]\")\n",
    "for position, value in signal.items():\n",
    "    estimate = gain * value / mm\n",
    "    print(\n",
    "        f\"({position[0]:4.1f}, {position[1]:4.1f})        ({estimate[0]:6.3f}, {estimate[1]:6.3f})     {np.hypot(*(estimate - position)):.3f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The potential in a vertical cut through two pads when the target is driven, and the four coupling\n",
    "capacitances for the five positions."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.section(\n",
    "    potentials[7],\n",
    "    plane=Plane(origin=(0, 5 * mm, 0), normal=(0, 1, 0)),\n",
    "    limits=(0, 1),\n",
    "    contours=11,\n",
    "    subdivisions=2,\n",
    "    label=\"potential [V]\",\n",
    "    xlimits=(-20 * mm, 20 * mm),\n",
    "    ylimits=(0, 20 * mm),\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Target at (2, 2) mm driven at 1 V, cut through pads 1 and 2\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.bars(\n",
    "    [f\"pad {i}\" for i in range(1, 5)],\n",
    "    {f\"target at ({x}, {y}) mm\": 1e12 * coupling[(x, y)] for x, y in positions},\n",
    "    ylabel=\"coupling capacitance [pF]\",\n",
    "    title=\"Coupling of the target to the four pads\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the target in `capacitive_position_sensor_geometry.py` to see the sensitivity fall with\n",
    "the gap; add a guard ring around the pads; or replace the cube by a finger-shaped dielectric\n",
    "body to model a touch sensor."
   ]
  }
 ]
}
