{
 "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": [
    "# Pacemaker electrodes: current distribution and pair resistance\n",
    "\n",
    "A bipolar pacing lead stimulates the heart through two electrodes in contact with the tissue. The\n",
    "pacing voltage drives an ionic current through the tissue (conductivity $\\sigma=0.2$ S/m); the\n",
    "resistance between the electrodes sets the current, and with it the battery drain and the\n",
    "stimulation threshold. The electrodes are modelled as two hemispheres of radius $a=1$ mm on the\n",
    "insulating surface of a half-space of tissue, at the centre distance $d$. The potential obeys\n",
    "\n",
    "$$\\nabla\\cdot(\\sigma\\nabla V)=0,\\qquad \\mathbf J=-\\sigma\\nabla V ,$$\n",
    "\n",
    "the same equation as electrostatics with the conductivity in place of the permittivity; the\n",
    "\"charge\" on an electrode becomes the current through it.\n",
    "\n",
    "The pair is symmetric about the plane through both centres and antisymmetric about the mid-plane\n",
    "between them, where the potential is zero. One quarter of the tissue, a quarter of a half ball of\n",
    "radius 100 mm, comes from the CAD file `pacing_electrode_pair_resistance.step` ($d=8$ mm) and\n",
    "from `..._4mm.step` and `..._16mm.step`. The script `pacing_electrode_pair_resistance_geometry.py`\n",
    "builds them with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `electrode` | $V=U/2$, half the pacing voltage $U=1$ V |\n",
    "| `midplane` | $V=0$ (antisymmetry) |\n",
    "| `symmetry`, `surface` | no current, $\\mathbf J\\cdot\\mathbf n=0$ |\n",
    "| `outer` | no current (far away) |\n",
    "\n",
    "**Reference.** Two hemispheres on an insulating half-space carry half the current of two whole\n",
    "spheres in an unbounded medium. The two-sphere problem is solved exactly in bispherical\n",
    "coordinates (Smythe, *Static and Dynamic Electricity*, 3rd ed., Sec. 5.08); with\n",
    "$\\cosh\\beta=d/(2a)$ the resistance between the hemispheres is\n",
    "\n",
    "$$R=\\frac{1}{\\pi\\sigma a\\,\\sinh\\beta\\,\\sum_{n=1}^{\\infty}1/\\sinh(n\\beta)} ,$$\n",
    "\n",
    "which tends to $2/(2\\pi\\sigma a)$, two single electrodes in series, when they are far apart."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\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 (\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 quarter of the tissue with its named faces. The tetrahedra grow from the\n",
    "electrode outwards; the distance of 8 mm is meshed three times, from 0.2 to 0.1 mm at the electrode."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "tissues = {\n",
    "    0.004: load(\"pacing_electrode_pair_resistance_4mm.step\"),\n",
    "    0.008: load(\"pacing_electrode_pair_resistance.step\"),\n",
    "    0.016: load(\"pacing_electrode_pair_resistance_16mm.step\"),\n",
    "}\n",
    "radius = 1.0e-3\n",
    "cases = [\n",
    "    (0.008, 0.20e-3),\n",
    "    (0.008, 0.14e-3),\n",
    "    (0.008, 0.10e-3),\n",
    "    (0.004, 0.10e-3),\n",
    "    (0.016, 0.10e-3),\n",
    "]\n",
    "meshes = [\n",
    "    TetrahedralMesher(\n",
    "        target_size=0.02,\n",
    "        minimum_size=size,\n",
    "        size_field=lambda points, d=d, h=size: np.clip(\n",
    "            h + 0.3 * (np.linalg.norm(points - (d / 2, 0.0, 0.0), axis=1) - radius),\n",
    "            h,\n",
    "            0.02,\n",
    "        ),\n",
    "    ).generate(tissues[d])\n",
    "    for d, size in cases\n",
    "]\n",
    "\n",
    "faces = tissues[0.008].boundaries\n",
    "view = plots.Camera(elevation=35, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    tissues[0.008],\n",
    "    selection={\n",
    "        \"electrode\": faces.electrode,\n",
    "        \"mid-plane\": faces.midplane,\n",
    "        \"surface\": faces.surface,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Quarter of the tissue around one electrode\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{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",
    "The conductivity takes the place of the permittivity; the current leaving the electrode is the\n",
    "`reaction` of its fixed potential. The quarter holds half of one electrode."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "conductivity, voltage = 0.2, 1.0\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "models = [\n",
    "    PoissonEquation(\n",
    "        domain=tissues[d].volume,\n",
    "        permittivity=regionwise((), default=conductivity, unit=\"S/m\"),\n",
    "        charge_density=0.0,\n",
    "    )\n",
    "    for d, _ in cases\n",
    "]\n",
    "results = [\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Pacing electrodes\",\n",
    "            geometry=tissues[d],\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                FixedPotential(\n",
    "                    boundary=tissues[d].boundaries.electrode,\n",
    "                    physics=model,\n",
    "                    value=voltage / 2,\n",
    "                ),\n",
    "                FixedPotential(\n",
    "                    boundary=tissues[d].boundaries.midplane, physics=model, value=0.0\n",
    "                ),\n",
    "                ZeroNormalElectricDisplacement(\n",
    "                    boundary=tissues[d].boundaries.symmetry\n",
    "                    | tissues[d].boundaries.surface\n",
    "                    | tissues[d].boundaries.outer,\n",
    "                    physics=model,\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary()\n",
    "    for model, mesh, (d, _) in zip(models, meshes, cases)\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The resistance $R=U/I$ with the current $I$ of the whole electrode, against the exact two-sphere\n",
    "series, for three meshes at 8 mm and for the three distances."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "beta = lambda d: np.arccosh(d / (2 * radius))\n",
    "exact = lambda d: 1 / (\n",
    "    np.pi\n",
    "    * conductivity\n",
    "    * radius\n",
    "    * np.sinh(beta(d))\n",
    "    * np.sum(1 / np.sinh(np.arange(1, 150) * beta(d)))\n",
    ")\n",
    "resistances = [\n",
    "    voltage\n",
    "    / (2 * result.field(model.potential).reaction(tissues[d].boundaries.electrode))\n",
    "    for model, result, (d, _) in zip(models, results, cases)\n",
    "]\n",
    "print(\"distance   cell size   tetrahedra   R [Ω]        exact [Ω]    deviation\")\n",
    "for (d, size), mesh, value in zip(cases, meshes, resistances):\n",
    "    print(\n",
    "        f\"{1e3 * d:5.0f} mm {1e3 * size:8.2f} mm {mesh.cell_count:12d} {value:12.3f} {exact(d):12.3f} {100 * (value / exact(d) - 1):+10.3f} %\"\n",
    "    )\n",
    "study = convergence(resistances[:3], [size for _, size in cases[:3]])\n",
    "print(\n",
    "    f\"8 mm: observed order {study.order:.2f}, extrapolated {study.extrapolated:.3f} Ω ({100 * (study.extrapolated / exact(0.008) - 1):+.3f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"two single electrodes in series, 2/(2 pi sigma a) = {2 / (2 * np.pi * conductivity * radius):.3f} Ω\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The potential on the tissue surface, the current density on the electrode surface around its\n",
    "equator (from the side facing the other electrode to the far side) for the three distances, and\n",
    "the resistance against the distance."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "angle = np.linspace(0.0, np.pi, 61)\n",
    "equator = lambda d: np.column_stack(\n",
    "    (\n",
    "        d / 2 - 1.001 * radius * np.cos(angle),\n",
    "        1.001 * radius * np.sin(angle),\n",
    "        np.full_like(angle, -1e-6),\n",
    "    )\n",
    ")\n",
    "crowding = {\n",
    "    f\"d = {1e3 * d:.0f} mm\": conductivity\n",
    "    * np.linalg.norm(result.field(model.electric_field).evaluate(equator(d)), axis=1)\n",
    "    for model, result, (d, size) in zip(models, results, cases)\n",
    "    if size == 0.10e-3\n",
    "}\n",
    "distances = np.geomspace(2.2e-3, 0.03, 200)\n",
    "fig = plots.figure(1, 3, size=(18, 5.5))\n",
    "plots.surface(\n",
    "    results[2].field(models[2].potential),\n",
    "    boundary=tissues[0.008].boundaries.surface,\n",
    "    limits=(0, 0.5),\n",
    "    contours=11,\n",
    "    subdivisions=2,\n",
    "    label=\"potential [V]\",\n",
    "    xlimits=(0, 0.012),\n",
    "    ylimits=(0, 0.008),\n",
    "    title=\"Surface potential, d = 8 mm\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    np.degrees(angle),\n",
    "    crowding,\n",
    "    hlines={\"single electrode, uniform\": conductivity * voltage / (2 * radius)},\n",
    "    xlabel=\"angle from the side facing the other electrode [deg]\",\n",
    "    ylabel=\"current density [A/m²]\",\n",
    "    title=\"Current crowding on the electrode\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * distances,\n",
    "    {\"exact two-sphere series\": [exact(d) for d in distances]},\n",
    "    points={\n",
    "        \"simulation\": (\n",
    "            [1e3 * d for d, size in cases if size == 0.10e-3],\n",
    "            [r for r, (d, size) in zip(resistances, cases) if size == 0.10e-3],\n",
    "        )\n",
    "    },\n",
    "    hlines={\"far apart\": 2 / (2 * np.pi * conductivity * radius)},\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"centre distance d [mm]\",\n",
    "    ylabel=\"resistance between the electrodes [Ω]\",\n",
    "    title=\"Pair resistance\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the electrode radius in `pacing_electrode_pair_resistance_geometry.py` to see the\n",
    "resistance fall roughly with $1/a$; replace one hemisphere by a ring electrode on an insulating\n",
    "lead body; or add a thin layer of fibrous tissue of lower conductivity around the tip, which\n",
    "raises the pacing impedance over the weeks after implantation."
   ]
  }
 ]
}
