{
 "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": [
    "# Voltammetry at a microdisk electrode\n",
    "\n",
    "Microelectrodes reach a steady current within seconds because the diffusion field around them\n",
    "becomes hemispherical: the supply no longer decays as $t^{-1/2}$ as at a large electrode. For a\n",
    "disk of radius $a$ in an insulating plane the species diffuse in the axisymmetric meridian plane\n",
    "$(r,z)$,\n",
    "\n",
    "$$\\frac{\\partial c_i}{\\partial t}=D\\left[\\frac1r\\frac{\\partial}{\\partial r}\\Big(r\\frac{\\partial c_i}{\\partial r}\\Big)\n",
    "  +\\frac{\\partial^2 c_i}{\\partial z^2}\\right],\\qquad i=\\mathrm O,\\mathrm R,$$\n",
    "\n",
    "and the oxidation $\\mathrm R\\to\\mathrm O+e^-$ on the disk follows Butler-Volmer kinetics,\n",
    "$r=k^0\\big[c_\\mathrm R e^{(1-\\alpha)f(E-E^0)}-c_\\mathrm O e^{-\\alpha f(E-E^0)}\\big]$ with $f=F/RT$.\n",
    "\n",
    "| boundary | O | R |\n",
    "|---|---|---|\n",
    "| `disk`, $r<a$ (electrode) | produced at the rate $r$ | consumed at the rate $r$ |\n",
    "| `disk`, $r>a$ (insulating plane), axis | no flux | no flux |\n",
    "| `outer` hemisphere, 2 mm | $c_\\mathrm O=0$ | $c_\\mathrm R=c^\\infty$ |\n",
    "\n",
    "**Setup.** 1 mM of R, $D=10^{-9}$ m²/s, fast kinetics ($k^0=0.1$ m/s, $\\alpha=0.5$), 25 °C. The\n",
    "electrolyte, a hemisphere of 2 mm radius, comes from the CAD file\n",
    "`microdisk_electrode_voltammetry.step`, written by `microdisk_electrode_voltammetry_geometry.py`\n",
    "with the CAD objects of OneSimulation; at 200 disk radii the bulk boundary changes the steady\n",
    "current by about $2a/(\\pi\\cdot 200a)=0.3$ %.\n",
    "\n",
    "**Reference.** The steady limiting current $i_\\mathrm{ss}=4FDc^\\infty a$ (Y. Saito, *Rev.\n",
    "Polarogr. Jpn.* 15 (1968) 177); its approach after the wave has passed follows\n",
    "$i/i_\\mathrm{ss}=0.7854+0.8862\\,\\tau^{-1/2}+0.2146\\,e^{-0.7823\\,\\tau^{-1/2}}$, $\\tau=4Dt/a^2$\n",
    "(D. Shoup, A. Szabo, *J. Electroanal. Chem.* 140 (1982) 237); and for a\n",
    "reversible couple with equal diffusivities the steady sigmoid\n",
    "$i=i_\\mathrm{ss}/\\big(1+e^{-f(E-E^0)}\\big)$ (Bard and Faulkner, *Electrochemical Methods*, §5.3)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, RevolvedH1SpaceFactory\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.numerics.time import BDF, BackwardEuler\n",
    "from onesim.physics.chemistry import (\n",
    "    FixedConcentration,\n",
    "    SpeciesTransport,\n",
    "    SurfaceReaction,\n",
    "    TransportSpecies,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\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",
    "`section` with the plane $y=0$ returns the meridian quarter disc; the faces keep their names.\n",
    "The 10 µm wide disk face does not survive the STEP round trip as a face of its own (it comes\n",
    "back merged with the insulating plane as `disk`), so the reaction below is declared on all walls\n",
    "except the outer hemisphere and switched on for $r<a$, $z=0$; the mesh embeds the small core\n",
    "cylinder to place a vertex exactly on the rim.\n",
    "The triangles shrink to 0.25 µm over the disk, so that the early depletion layer and the\n",
    "singular flux at its rim are resolved."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "electrolyte = load(\"microdisk_electrode_voltammetry.step\")\n",
    "plane = electrolyte.section((0, 1, 0))\n",
    "core = load(\"microdisk_electrode_voltammetry_core.step\").section((0, 1, 0))\n",
    "side = plane.boundaries\n",
    "radius, outer = 10e-6, plane.size[0]\n",
    "mesh = TriangularMesher(\n",
    "    target_size=outer / 20,\n",
    "    embedded_regions=(core,),\n",
    "    size_field=lambda p: np.minimum(\n",
    "        outer / 20,\n",
    "        radius / 40 + 0.3 * np.hypot(np.maximum(p[:, 0] - radius, 0.0), p[:, 1]),\n",
    "    ),\n",
    ").generate(plane)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(15, 6.5))\n",
    "plots.geometry(\n",
    "    electrolyte,\n",
    "    selection={\n",
    "        \"bottom plane (disk for r < a)\": electrolyte.boundaries.disk,\n",
    "        \"outer hemisphere\": electrolyte.boundaries.outer,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=25, azimuth=-150),\n",
    "    title=\"Half of the electrolyte (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian plane: {mesh.cell_count} triangles, graded to the disk rim\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model and voltammograms\n",
    "\n",
    "Quadratic axisymmetric elements (`RevolvedH1SpaceFactory`, weight $2\\pi r$) for both species and\n",
    "the Butler-Volmer rate as a `SurfaceReaction` on the walls, active on the disk $r<a$, $z=0$ (the\n",
    "rate law receives the boundary points). The potential sweeps from\n",
    "$E^0-0.3$ V to $E^0+0.3$ V and back at 0.01 V/s (dimensionless scan rate $a^2fv/D=0.04$, nearly\n",
    "steady) and at 1 V/s ($a^2fv/D=4$, transient), with 2 mV steps. The current is $F$ times the flux\n",
    "of R into the disk, `boundary_flux` of the recorded states. On this micrometre mesh the residuals\n",
    "are tiny (the disk current is $4\\cdot10^{-14}$ mol/s), so Newton's absolute tolerance is set to\n",
    "$10^{-24}$ mol/s."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "faraday, gas_constant, temperature = 96485.33212, 8.314462618, 298.15\n",
    "f = faraday / (gas_constant * temperature)\n",
    "diffusivity, bulk, k0, alpha, formal = 1.0e-9, 1.0, 0.1, 0.5, 0.0\n",
    "limiting = 4 * faraday * diffusivity * bulk * radius\n",
    "print(\n",
    "    f\"Saito limiting current 4 F D c a = {limiting * 1e9:.4f} nA; k0 a / D = {k0 * radius / diffusivity:.0f}\"\n",
    ")\n",
    "\n",
    "sweep = lambda rate_of_scan: (\n",
    "    lambda t: formal\n",
    "    - 0.3\n",
    "    + rate_of_scan * (0.6 / rate_of_scan - np.abs(np.asarray(t) - 0.6 / rate_of_scan))\n",
    ")\n",
    "programmes = {\"0.01 V/s\": (sweep(0.01), 120.0, 0.2), \"1 V/s\": (sweep(1.0), 1.2, 0.002)}\n",
    "currents, fields = {}, {}\n",
    "for name, (potential, end_time, time_step) in programmes.items():\n",
    "    model = SpeciesTransport(\n",
    "        domain=plane.domain(),\n",
    "        species=(\n",
    "            TransportSpecies(\"O\", diffusivity=diffusivity),\n",
    "            TransportSpecies(\"R\", diffusivity=diffusivity),\n",
    "        ),\n",
    "    )\n",
    "    rate = (\n",
    "        lambda c, t, points: ((points[:, 0] < radius) & (points[:, 1] < 1e-3 * radius))\n",
    "        * k0\n",
    "        * (\n",
    "            c[\"R\"] * np.exp((1 - alpha) * f * (potential(t) - formal))\n",
    "            - c[\"O\"] * np.exp(-alpha * f * (potential(t) - formal))\n",
    "        )\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Microdisk voltammetry\",\n",
    "        geometry=plane,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            SurfaceReaction(\n",
    "                physics=model,\n",
    "                boundary=side.all - side.outer,\n",
    "                rate=rate,\n",
    "                stoichiometry={\"R\": -1, \"O\": 1},\n",
    "            ),\n",
    "            FixedConcentration(\n",
    "                physics=model, boundary=side.outer, value={\"O\": 0.0, \"R\": bulk}\n",
    "            ),\n",
    "        ),\n",
    "        initial_conditions=(\n",
    "            InitialValue(model.field(\"O\"), 0.0),\n",
    "            InitialValue(model.field(\"R\"), bulk),\n",
    "        ),\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=problem,\n",
    "        mesh=mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(\n",
    "                element=Lagrange(order=2), provider=RevolvedH1SpaceFactory()\n",
    "            ),\n",
    "            nonlinear_solver=Newton(\n",
    "                linear_solver=SparseDirect(),\n",
    "                absolute_tolerance=1e-24,\n",
    "                relative_tolerance=1e-8,\n",
    "            ),\n",
    "            time_integrator=BDF(order=2, startup=BackwardEuler()),\n",
    "        ),\n",
    "    ).run(start_time=0.0, end_time=end_time, time_step=time_step)\n",
    "    reduced = result.field(model.field(\"R\"))\n",
    "    times = np.asarray(reduced.times)[1:]\n",
    "    currents[name] = (\n",
    "        times,\n",
    "        potential(times),\n",
    "        faraday\n",
    "        * np.array(\n",
    "            [reduced.boundary_flux(side.all - side.outer, time=t) for t in times]\n",
    "        ),\n",
    "    )\n",
    "    fields[name] = result.field(model.field(\"O\"))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the references\n",
    "\n",
    "The forward slow sweep: half-wave potential $E_{1/2}=E^0$, the Tomeš criterion\n",
    "$E_{3/4}-E_{1/4}=(RT/F)\\ln 9=56.4$ mV, and the plateau at $E^0+0.3$ V against Saito's current.\n",
    "The plateau is reached 30 s after the wave ($\\tau\\approx1200$); Shoup and Szabo give the\n",
    "remaining excess of the decaying transient."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "shoup_szabo = (\n",
    "    lambda tau: 0.7854 + 0.8862 / np.sqrt(tau) + 0.2146 * np.exp(-0.7823 / np.sqrt(tau))\n",
    ")\n",
    "times, E, current = currents[\"0.01 V/s\"]\n",
    "forward = times <= 60.0\n",
    "quarter, half, three_quarter = (\n",
    "    E[forward][np.argmin(np.abs(current[forward] - level * current[forward].max()))]\n",
    "    for level in (0.25, 0.5, 0.75)\n",
    ")\n",
    "expected = shoup_szabo(4 * diffusivity * 30.0 / radius**2)\n",
    "print(\n",
    "    f\"slow sweep: plateau current at E0 + 0.3 V = {current[forward][-1] * 1e9:.4f} nA = {current[forward][-1] / limiting:.4f} i_ss \"\n",
    "    f\"(Saito with the Shoup-Szabo excess at tau = 1200: {expected:.4f} i_ss, deviation {current[forward][-1] / limiting / expected - 1:.2%})\"\n",
    ")\n",
    "print(\n",
    "    f\"slow sweep: E1/2 - E0 = {(half - formal) * 1e3:.1f} mV (reversible: 0), E3/4 - E1/4 = {(three_quarter - quarter) * 1e3:.1f} mV (reversible: {np.log(9) / f * 1e3:.1f} mV)\"\n",
    ")\n",
    "print(\n",
    "    f\"slow sweep: largest gap between forward and reverse current {np.abs(np.interp(E[forward], E[~forward][::-1], current[~forward][::-1]) - current[forward]).max() / limiting:.2%} of i_ss\"\n",
    ")\n",
    "times, E, current = currents[\"1 V/s\"]\n",
    "peak = np.argmax(np.where(times <= 0.6, current, -np.inf))\n",
    "print(\n",
    "    f\"fast sweep: forward peak {current[peak] / limiting:.3f} i_ss at E - E0 = {(E[peak] - formal) * 1e3:.0f} mV; \"\n",
    "    f\"planar Randles-Sevcik part alone {0.4463 * faraday * bulk * np.sqrt(f * 1.0 * diffusivity) * np.pi * radius**2 / limiting:.3f} i_ss\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The voltammograms at both scan rates against the steady sigmoid, and the concentration of O\n",
    "around the disk at the end of the forward slow sweep."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "scan = np.linspace(-0.3, 0.3, 300)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    y={\n",
    "        name: ((E - formal) * 1e3, current * 1e9)\n",
    "        for name, (times, E, current) in currents.items()\n",
    "    },\n",
    "    reference={\n",
    "        \"steady sigmoid\": (scan * 1e3, limiting / (1 + np.exp(-f * scan)) * 1e9)\n",
    "    },\n",
    "    xlabel=\"E - E⁰ [mV]\",\n",
    "    ylabel=\"current [nA]\",\n",
    "    title=\"Cyclic voltammograms\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.surface(\n",
    "    fields[\"0.01 V/s\"],\n",
    "    time=currents[\"0.01 V/s\"][0][np.argmin(np.abs(currents[\"0.01 V/s\"][0] - 60.0))],\n",
    "    limits=(0, bulk),\n",
    "    xlimits=(0, 6 * radius),\n",
    "    ylimits=(0, 4 * radius),\n",
    "    length_unit=\"um\",\n",
    "    contours=8,\n",
    "    subdivisions=2,\n",
    "    xlabel=\"r [µm]\",\n",
    "    ylabel=\"z [µm]\",\n",
    "    label=\"c_O [mol/m³]\",\n",
    "    title=\"O around the disk at E⁰ + 0.3 V (0.01 V/s)\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lower $k^0$ until $k^0a/D\\approx1$: the steady wave flattens and shifts, the microelectrode\n",
    "way of measuring fast kinetics without high scan rates. Shrink the disk to 1 µm and the\n",
    "steady state is reached a hundred times faster. A recessed or hemispherical electrode only\n",
    "needs a different profile in the geometry script."
   ]
  }
 ]
}
