{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# The first few nanometres of an electrolyte\n",
    "\n",
    "A positively biased metal repels cations and attracts anions. How much charge\n",
    "accumulates when its potential rises from 1 to 10 mV? The one-dimensional\n",
    "Poisson–Nernst–Planck model includes diffusion, electrical migration and a charge-free\n",
    "compact layer at the electrode. Both ions are blocked at the metal.\n",
    "\n",
    "The solvent is water at 25 °C. The bulk contains 1 mol/m³ of each monovalent ion\n",
    "(1 mM). The compact layer is 0.3 nm thick, with a relative permittivity of 10.\n",
    "Its potential drop is $\\sigma/C_S$, where $C_S=\\epsilon_S/d_S$."
   ],
   "id": "d23a57c00520"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d1 import Line\n",
    "from onesim.meshing import cartesian\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.linear import GMRES\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.numerics.time import BDF, BackwardEuler\n",
    "from onesim.physics.chemistry import (\n",
    "    PoissonNernstPlanck,\n",
    "    ScharfetterGummelFiniteVolume,\n",
    "    SternLayer,\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",
    "from scipy.constants import epsilon_0\n",
    "from scipy.optimize import brentq\n",
    "\n",
    "theme.set()\n",
    "faraday, gas_constant, temperature = 96485.33212, 8.314462618, 298.15\n",
    "bulk, diffusivity = 1.0, 1e-9\n",
    "epsilon, capacitance = 78.5 * epsilon_0, 10 * epsilon_0 / 0.3e-9\n",
    "thermal = gas_constant * temperature / faraday\n",
    "debye = np.sqrt(epsilon * thermal / (2 * faraday * bulk))\n",
    "stern = epsilon / capacitance\n",
    "half_length = 8 * debye\n",
    "line = Line(start=(0, 0, 0), end=(2 * half_length, 0, 0))\n",
    "numerics = Numerics(\n",
    "    spatial=ScharfetterGummelFiniteVolume(),\n",
    "    time_integrator=BDF(order=2, startup=BackwardEuler()),\n",
    "    nonlinear_solver=Newton(\n",
    "        linear_solver=GMRES(relative_tolerance=1e-7, restart=220, maximum_iterations=650),\n",
    "        absolute_tolerance=1e-8,\n",
    "    ),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "830c15583927"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Establish the bulk and sweep the metal potential\n",
    "\n",
    "Two identical electrodes at $+V$ and $-V$ place the zero of potential at the cell\n",
    "midpoint by symmetry. Here both ion concentrations are equal. For each voltage,\n",
    "a first charging run measures the small amount of salt removed from the middle.\n",
    "A second run adds this amount to the initial inventory to recover the specified\n",
    "bulk concentration. Only the positive half-cell is plotted.\n",
    "\n",
    "Each run starts from a uniform electrolyte. The zero-flux blocking walls conserve\n",
    "each ion separately. The compact-layer Robin condition uses the effective thickness\n",
    "$\\epsilon/C_S$ in the solvent permittivity convention."
   ],
   "id": "c8509607f2a0"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "bias = np.arange(1, 11) * 1e-3\n",
    "species = (TransportSpecies(\"cation\", diffusivity), TransportSpecies(\"anion\", diffusivity))\n",
    "tau = debye**2 / diffusivity\n",
    "def equilibrium(voltage, mesh, cells):\n",
    "    half = cells // 2\n",
    "    walls = (\n",
    "        SternLayer(potential=voltage, thickness=stern),\n",
    "        SternLayer(potential=-voltage, thickness=stern),\n",
    "    )\n",
    "    model = PoissonNernstPlanck(\n",
    "        domain=line.line,\n",
    "        species=species,\n",
    "        charge_numbers=(1, -1),\n",
    "        temperature=temperature,\n",
    "        permittivity=epsilon,\n",
    "        potential_boundaries=(walls,),\n",
    "    )\n",
    "    start = bulk\n",
    "    for _ in range(2):\n",
    "        initial = tuple(InitialValue(model.concentration(ion.species_id), start) for ion in species)\n",
    "        problem = Problem(\n",
    "            name=\"Blocking electrodes\", geometry=line, physics=(model,), initial_conditions=initial\n",
    "        )\n",
    "        result = Simulation(problem=problem, mesh=mesh, numerics=numerics).run(\n",
    "            start_time=0, end_time=256 * tau, time_step=4 * tau\n",
    "        )\n",
    "        cp, cm = (\n",
    "            np.asarray(result.field(model.concentration(ion.species_id)).values) for ion in species\n",
    "        )\n",
    "        measured = 0.5 * (cp[half - 1] + cp[half])\n",
    "        start += bulk - measured\n",
    "    field = result.field(model.electric_potential)\n",
    "    phi = np.asarray(field.values)\n",
    "    x = np.asarray(field.space.dof_coordinates)[:half, 0]\n",
    "    width = 2 * half_length / cells\n",
    "    charge = epsilon * (voltage - phi[0]) / (stern + width / 2)\n",
    "    ionic_charge = -faraday * width * np.sum(cp[:half] - cm[:half])\n",
    "    residual = np.max(np.abs(phi - np.asarray(field.at(224 * tau).values)))\n",
    "    return charge, ionic_charge, measured, residual, x, phi, cp, cm\n",
    "\n",
    "\n",
    "def line_mesh(cells):\n",
    "    return cartesian(shape=(cells,), extents=(2 * half_length,), geometry=line, periodic=False).build()\n",
    "\n",
    "\n",
    "coarse_cells, fine_cells = 80, 160\n",
    "coarse_mesh, mesh = line_mesh(coarse_cells), line_mesh(fine_cells)\n",
    "coarse_charge = equilibrium(bias[-1], coarse_mesh, coarse_cells)[0]\n",
    "charge, charge_from_ions, centre, drift = [], [], [], []\n",
    "half = fine_cells // 2\n",
    "for voltage in bias:\n",
    "    sigma, ions, measured, residual, x, phi, cp, cm = equilibrium(voltage, mesh, fine_cells)\n",
    "    charge.append(sigma)\n",
    "    charge_from_ions.append(ions)\n",
    "    centre.append(measured)\n",
    "    drift.append(residual)\n",
    "print(f\"Refinement from {coarse_cells} to {len(phi)} potential cells: charge at 10 mV changes from {1000 * coarse_charge:.5f} to {1000 * charge[-1]:.5f} mC/m²\")"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "2623e268f5af"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Compare against Gouy–Chapman–Stern theory\n",
    "\n",
    "In an unbounded reservoir the surface charge is\n",
    "$\\sigma=2\\epsilon V_T\\sinh(\\phi_d/(2V_T))/\\lambda_D$ and $V=\\phi_d+\\sigma/C_S$.\n",
    "Solving this scalar relation gives the independent reference. At low voltage\n",
    "the capacitance tends to $\\epsilon/(\\lambda_D+\\epsilon/C_S)$.\n",
    "Reference: O. Stern, *Zur Theorie der elektrolytischen Doppelschicht* (1924);\n",
    "A. J. Bard and L. R. Faulkner, *Electrochemical Methods*, 2nd ed. (2001)."
   ],
   "id": "28a917e5d25a"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "gouy = lambda v: 2 * epsilon * thermal / debye * np.sinh(v / (2 * thermal))\n",
    "surface = np.array(\n",
    "    [brentq(lambda v: v + gouy(v) / capacitance - applied, 0, applied) for applied in bias]\n",
    ")\n",
    "theory = gouy(surface)\n",
    "exact_phi = 4 * thermal * np.arctanh(np.tanh(surface[-1] / (4 * thermal)) * np.exp(-x / debye))\n",
    "print(\n",
    "    f\"Debye length {debye*1e9:.2f} nm. Largest bulk concentration error: {np.max(np.abs(np.array(centre)-bulk)):.2g} mol/m³.\"\n",
    ")\n",
    "print(\n",
    "    f\"Wall charge at 10 mV: {1000*charge[-1]:.4f} mC/m². Largest relative error over all ten biases: {max(abs(charge/theory-1)):.2%}.\"\n",
    ")\n",
    "print(\n",
    "    f\"Half-cell ionic charge differs from wall charge by at most {max(abs(np.array(charge_from_ions)/charge-1)):.2%}; the finite midpoint also carries electric displacement.\"\n",
    ")\n",
    "print(f\"Maximum potential change during the final 32 Debye times: {max(drift)*1e6:.3f} µV.\")"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "066c237d66fd"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Profiles at 10 mV and the charging curve\n",
    "\n",
    "Charge in the compact layer lowers the potential at the first accessible point\n",
    "of the liquid. Both concentrations approach the bulk level several Debye lengths away."
   ],
   "id": "dae77768c336"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(17, 4.8))\n",
    "plots.line(\n",
    "    points={\"Liquid\": (x * 1e9, phi[:half] * 1e3)},\n",
    "    reference={\"GCS\": (x * 1e9, exact_phi * 1e3)},\n",
    "    hlines={\"Metal\": 10},\n",
    "    xlabel=\"Distance [nm]\",\n",
    "    ylabel=\"Potential [mV]\",\n",
    "    title=\"Screening at 10 mV\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"Cation\": (x * 1e9, cp[:half]), \"Anion\": (x * 1e9, cm[:half])},\n",
    "    reference={\n",
    "        \"Cation\": (x * 1e9, bulk * np.exp(-exact_phi / thermal)),\n",
    "        \"Anion\": (x * 1e9, bulk * np.exp(exact_phi / thermal)),\n",
    "    },\n",
    "    xlabel=\"Distance [nm]\",\n",
    "    ylabel=\"Concentration [mol/m³]\",\n",
    "    title=\"Cation depletion and anion uptake\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"OneSimulation\": (bias * 1e3, 1e3 * np.array(charge))},\n",
    "    reference={\"GCS\": (bias * 1e3, 1e3 * theory)},\n",
    "    xlabel=\"Metal potential [mV]\",\n",
    "    ylabel=\"Charge [mC/m²]\",\n",
    "    title=\"Charge stored by the electrode\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "caf94d6f1ef5"
  }
 ]
}
