{
 "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 matrix of a touchscreen\n",
    "\n",
    "A projected-capacitive touchscreen has transmit electrodes (rows) and receive electrodes\n",
    "(columns) that cross each other in two layers. The controller drives one row at a time and\n",
    "measures the charge that flows into each column: the mutual capacitance $C_{ij}=Q_j/V_i$ of every\n",
    "crossing. A finger above a crossing takes over part of the field lines that would end on the\n",
    "column and lowers its mutual capacitance; the drop locates the touch.\n",
    "\n",
    "The model has three rows (at $y=-5$, 0 and 5 mm) and three columns (at $x=-5$, 0 and 5 mm), 1.5 mm\n",
    "wide and 0.2 mm thick, 0.2 mm apart, embedded in a polymer substrate ($\\varepsilon_r=4$) on a\n",
    "grounded display shield and covered by 0.5 mm of glass ($\\varepsilon_r=7$). The strips run across\n",
    "the whole modelled area of 20 mm × 20 mm, whose side faces carry no charge. The finger is a\n",
    "grounded conductor of 4 mm radius resting on the glass above the middle crossing. OneSimulation\n",
    "solves $-\\nabla\\cdot(\\varepsilon\\nabla V)=0$ with the driven row at 1 V and every other electrode\n",
    "grounded; the charge of each electrode is the reaction of the potential on its faces.\n",
    "\n",
    "The touchscreen is mirror-symmetric about the plane $x=0$, so half of it is modelled. The air and\n",
    "the dielectrics with the electrodes cut out come from `touchscreen_capacitance_matrix.step` and,\n",
    "with the finger, from `touchscreen_capacitance_matrix_finger.step`; the face groups are\n",
    "`tx_low`, `tx_middle`, `tx_high`, `rx_middle`, `rx_side`, `finger`, `shield`, `symmetry` and\n",
    "`outer`. The two dielectric layers come from `touchscreen_capacitance_matrix_substrate.step` and\n",
    "`touchscreen_capacitance_matrix_glass.step`. The script `touchscreen_capacitance_matrix_geometry.py`\n",
    "builds all four with the CAD objects of OneSimulation.\n",
    "\n",
    "| faces | condition |\n",
    "|---|---|\n",
    "| driven row | $V=1$ V |\n",
    "| other rows, columns, `finger`, `shield` | $V=0$ |\n",
    "| `symmetry` (the plane $x=0$), `outer` | $\\mathbf D\\cdot\\mathbf n=0$ |\n",
    "\n",
    "**Reference.** A crossing is a small parallel-plate capacitor of the overlap area $w^2$ and the\n",
    "gap $d$ between row and column, $C\\approx\\varepsilon_0\\varepsilon_rw^2/d$; the fringing field\n",
    "around the edges adds to it. The Maxwell capacitance matrix is symmetric (reciprocity), which the\n",
    "charges of the two driven rows on each other must show. The sensing principle follows\n",
    "T. Gray, *Projected Capacitive Touch*, Springer 2019."
   ]
  },
  {
   "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, 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 two variants and the dielectric layers. The layers are embedded in the mesh, the\n",
    "cells are fine on the electrodes and in the stack and grow upwards into the air."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "regions = {\n",
    "    \"without finger\": load(\"touchscreen_capacitance_matrix.step\"),\n",
    "    \"with finger\": load(\"touchscreen_capacitance_matrix_finger.step\"),\n",
    "}\n",
    "substrate, glass = load(\"touchscreen_capacitance_matrix_substrate.step\"), load(\n",
    "    \"touchscreen_capacitance_matrix_glass.step\"\n",
    ")\n",
    "electrodes = (\"tx_low\", \"tx_middle\", \"tx_high\", \"rx_middle\", \"rx_side\")\n",
    "meshes = {\n",
    "    label: TetrahedralMesher(\n",
    "        target_size=0.002,\n",
    "        embedded_regions=(substrate, glass),\n",
    "        refinements=(\n",
    "            LocalRefinement(region=substrate, target_size=0.0006),\n",
    "            LocalRefinement(region=glass, target_size=0.0008),\n",
    "            LocalRefinement(\n",
    "                region=air.select(\n",
    "                    faces=lambda face: face.id.split(\".\")[0] in electrodes\n",
    "                ),\n",
    "                target_size=0.0004,\n",
    "            ),\n",
    "        ),\n",
    "    ).generate(air)\n",
    "    for label, air in regions.items()\n",
    "}\n",
    "\n",
    "air = regions[\"with finger\"]\n",
    "view = plots.Camera(elevation=35, azimuth=-125)\n",
    "fig = plots.figure(1, 2, size=(14, 6.5))\n",
    "plots.geometry(\n",
    "    air,\n",
    "    selection={\n",
    "        \"rows\": air.boundaries.tx_low\n",
    "        | air.boundaries.tx_middle\n",
    "        | air.boundaries.tx_high,\n",
    "        \"columns\": air.boundaries.rx_middle | air.boundaries.rx_side,\n",
    "        \"finger\": air.boundaries.finger,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Half of the touchscreen with the finger\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"with finger\"],\n",
    "    groups=(\"tx_low\", \"tx_middle\", \"tx_high\", \"rx_middle\", \"rx_side\", \"finger\"),\n",
    "    camera=view,\n",
    "    title=f\"{meshes['with finger'].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The substrate and the glass get their permittivities from `regionwise`. The middle row and the\n",
    "lower row are driven in turn; the upper row follows from the lower one by symmetry. The factor\n",
    "two restores the full charge of the electrodes cut by the symmetry plane."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "eps0 = float(VacuumPermittivity().evaluate())\n",
    "layer = lambda low, high: lambda points: (points[:, 2] > low) & (points[:, 2] < high)\n",
    "permittivity = regionwise(\n",
    "    ((layer(0.0, 0.0012), 4.0 * eps0), (layer(0.0012, 0.0017), 7.0 * eps0)),\n",
    "    default=eps0,\n",
    "    unit=\"F/m\",\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "whole = {\n",
    "    \"tx_low\": 2,\n",
    "    \"tx_middle\": 2,\n",
    "    \"tx_high\": 2,\n",
    "    \"rx_middle\": 2,\n",
    "    \"rx_side\": 1,\n",
    "    \"finger\": 2,\n",
    "}\n",
    "\n",
    "\n",
    "def charges(label, driven):\n",
    "    \"\"\"Charges of all electrodes (full touchscreen) with one row at 1 V, and the solved potential.\"\"\"\n",
    "    air = regions[label]\n",
    "    grounded = [\n",
    "        name\n",
    "        for name in (*electrodes, \"finger\")\n",
    "        if name != driven and name in air.boundary_groups()\n",
    "    ]\n",
    "    model = PoissonEquation(\n",
    "        domain=air.volume, permittivity=permittivity, charge_density=0.0\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Touchscreen\",\n",
    "        geometry=air,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            FixedPotential(boundary=air.boundaries[driven], physics=model, value=1.0),\n",
    "            FixedPotential(boundary=air.boundaries.shield, physics=model, value=0.0),\n",
    "            *(\n",
    "                FixedPotential(boundary=air.boundaries[name], physics=model, value=0.0)\n",
    "                for name in grounded\n",
    "            ),\n",
    "            ZeroNormalElectricDisplacement(\n",
    "                boundary=air.boundaries.symmetry | air.boundaries.outer, physics=model\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    potential = (\n",
    "        Simulation(problem=problem, mesh=meshes[label], numerics=numerics)\n",
    "        .solve_stationary()\n",
    "        .field(model.potential)\n",
    "    )\n",
    "    return {\n",
    "        name: whole[name] * potential.reaction(air.boundaries[name])\n",
    "        for name in (*electrodes, \"finger\")\n",
    "        if name in air.boundary_groups()\n",
    "    }, potential\n",
    "\n",
    "\n",
    "runs = {\n",
    "    (label, row): charges(label, row)\n",
    "    for label in regions\n",
    "    for row in (\"tx_middle\", \"tx_low\")\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The mutual capacitances between the three rows and the three columns, the drop caused by the\n",
    "finger, reciprocity and the parallel-plate value of one crossing."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mutual = {\n",
    "    label: np.array(\n",
    "        [\n",
    "            [\n",
    "                -runs[label, row][0][column]\n",
    "                for column in (\"rx_side\", \"rx_middle\", \"rx_side\")\n",
    "            ]\n",
    "            for row in (\"tx_low\", \"tx_middle\", \"tx_low\")\n",
    "        ]\n",
    "    )\n",
    "    for label in regions\n",
    "}\n",
    "print(\"mutual capacitance row -> column [pF], columns at x = -5, 0, 5 mm\")\n",
    "for label, matrix in mutual.items():\n",
    "    print(f\"{label}:\")\n",
    "    for row, values in zip((\"y = -5 mm\", \"y =  0 mm\", \"y = +5 mm\"), matrix):\n",
    "        print(f\"   row {row}: \" + \"  \".join(f\"{1e12 * value:7.4f}\" for value in values))\n",
    "drop = 100 * (1 - mutual[\"with finger\"] / mutual[\"without finger\"])\n",
    "print(\n",
    "    \"drop by the finger [%]:\\n\"\n",
    "    + \"\\n\".join(\"   \" + \"  \".join(f\"{value:7.2f}\" for value in row) for row in drop)\n",
    ")\n",
    "for label in regions:\n",
    "    forward, backward = (\n",
    "        runs[label, \"tx_middle\"][0][\"tx_low\"],\n",
    "        runs[label, \"tx_low\"][0][\"tx_middle\"],\n",
    "    )\n",
    "    total = sum(runs[label, \"tx_middle\"][0].values())\n",
    "    print(\n",
    "        f\"{label}: reciprocity C(middle row, lower row) / C(lower row, middle row) - 1 = {forward / backward - 1:+.1e}; \"\n",
    "        f\"charge on the driven row {1e12 * runs[label, 'tx_middle'][0]['tx_middle']:.4f} pF, induced on the electrodes \"\n",
    "        f\"{-1e12 * (total - runs[label, 'tx_middle'][0]['tx_middle']):.4f} pF, rest on the shield\"\n",
    "    )\n",
    "plate = eps0 * 4.0 * 0.0015**2 / 0.0002\n",
    "print(\n",
    "    f\"parallel-plate value of one crossing: {1e12 * plate:.4f} pF; computed middle crossing {1e12 * mutual['without finger'][1, 1]:.4f} pF \"\n",
    "    f\"({100 * (mutual['without finger'][1, 1] / plate - 1):+.1f} % from fringing)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The potential in the plane $y=0$ through the middle row with the finger, and the mutual\n",
    "capacitances of the middle row to the three columns."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.section(\n",
    "    runs[\"with finger\", \"tx_middle\"][1],\n",
    "    plane=Plane(origin=(0.0, 1e-6, 0.0), normal=(0.0, 1.0, 0.0)),\n",
    "    limits=(0.0, 1.0),\n",
    "    contours=21,\n",
    "    subdivisions=2,\n",
    "    symmetry={\"planes\": [((1, 0, 0), (0, 0, 0))]},\n",
    "    label=\"potential [V]\",\n",
    "    title=\"Middle row at 1 V, finger above\",\n",
    "    xlimits=(-0.008, 0.008),\n",
    "    ylimits=(0.0, 0.004),\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.bars(\n",
    "    [\"column x = -5 mm\", \"column x = 0\", \"column x = +5 mm\"],\n",
    "    {label: 1e12 * mutual[label][1] for label in regions},\n",
    "    ylabel=\"mutual capacitance to the middle row [pF]\",\n",
    "    title=\"Touch signal\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lift the finger off the glass or move it towards a neighbouring crossing in\n",
    "`touchscreen_capacitance_matrix_geometry.py` and write the STEP files again; make the glass\n",
    "thicker to see how the touch signal fades; or drive the columns as well to obtain the full\n",
    "Maxwell capacitance matrix including the self-capacitance seen by a self-capacitive controller."
   ]
  }
 ]
}
