{
 "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": [
    "# Single-particle model against the full porous-electrode model\n",
    "\n",
    "When the electrolyte conducts well and the current is moderate, every particle in an electrode\n",
    "sees almost the same reaction rate. The single-particle model then replaces each electrode by one\n",
    "representative sphere that carries the mean reaction current $j_\\pm=\\pm I/(a_\\pm L_\\pm)$:\n",
    "\n",
    "$$\\frac{\\partial c_s}{\\partial t}=\\frac{D_s}{r^2}\\frac{\\partial}{\\partial r}\\Big(r^2\\frac{\\partial c_s}{\\partial r}\\Big),\\qquad\n",
    "  -D_s\\frac{\\partial c_s}{\\partial r}\\Big|_{R}=\\frac{j}{F},\\qquad\n",
    "  V=U_+(\\theta_+^\\mathrm{surf})-U_-(\\theta_-^\\mathrm{surf})-\\frac{2RT}{F}\\Big(\\operatorname{asinh}\\frac{|j_+|}{2j_{0,+}}+\\operatorname{asinh}\\frac{j_-}{2j_{0,-}}\\Big) .$$\n",
    "\n",
    "The SPMe adds the salt diffusion and the ohmic and concentration losses of the electrolyte, still\n",
    "with a uniform reaction; the DFN resolves the reaction distribution through both electrodes.\n",
    "\n",
    "**Reference.** For a constant current the surface concentration of a sphere follows the exact\n",
    "series (Crank, *The Mathematics of Diffusion*, 1975, eq. 6.62)\n",
    "\n",
    "$$c_s(R,t)=c_0-\\frac{jR}{FD_s}\\Big[3\\tau+\\frac15-2\\sum_{n}\\frac{e^{-\\lambda_n^2\\tau}}{\\lambda_n^2}\\Big],\\qquad \\tau=\\frac{D_st}{R^2},\\quad\\tan\\lambda_n=\\lambda_n .$$\n",
    "\n",
    "Marquis, Sulzer, Timms, Please and Chapman, *J. Electrochem. Soc.* 166 (2019) A3693, derive the SPM\n",
    "and the SPMe as asymptotic limits of the DFN for well-conducting electrodes: the voltage error of the\n",
    "SPM grows linearly with the C-rate; the SPMe adds the electrolyte correction and leaves a much\n",
    "smaller error. In this cell the positive electrode conducts poorly (0.18 S/m), so the reaction\n",
    "spreads unevenly through it and the SPMe error grows more slowly than the quadratic law of the\n",
    "ideal case, but stays several times below the SPM error. Cell parameters of Chen et al., *J. Electrochem. Soc.* 167\n",
    "(2020) 080534 (LG M50, 5 Ah)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.physics.chemistry import (\n",
    "    BatteryElectrodeLayer,\n",
    "    BatteryElectrolyteLayer,\n",
    "    PorousElectrodeBattery,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.optimize import brentq\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cell"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "faraday, area = 96485.33212, 0.1027\n",
    "negative_ocp = lambda x, T: (\n",
    "    1.9793 * np.exp(-39.3631 * x)\n",
    "    + 0.2482\n",
    "    - 0.0909 * np.tanh(29.8538 * (x - 0.1234))\n",
    "    - 0.04478 * np.tanh(14.9159 * (x - 0.2769))\n",
    "    - 0.0205 * np.tanh(30.4444 * (x - 0.6103))\n",
    ")\n",
    "positive_ocp = lambda y, T: (\n",
    "    4.4875\n",
    "    - 0.8090 * y\n",
    "    - 0.0428 * np.tanh(18.5138 * (y - 0.5542))\n",
    "    - 17.7326 * np.tanh(15.7890 * (y - 0.3117))\n",
    "    + 17.5842 * np.tanh(15.9308 * (y - 0.3120))\n",
    ")\n",
    "negative = BatteryElectrodeLayer(\n",
    "    thickness=85.2e-6,\n",
    "    porosity=0.25,\n",
    "    electrolyte_diffusivity=1.7694e-10 * 0.25**1.5,\n",
    "    electrolyte_conductivity=0.9487 * 0.25**1.5,\n",
    "    particle_radius=5.86e-6,\n",
    "    particle_diffusivity=3.3e-14,\n",
    "    active_fraction=0.75,\n",
    "    maximum_concentration=33133,\n",
    "    initial_stoichiometry=0.9014,\n",
    "    reference_exchange_current=6.48e-7 * np.sqrt(1000) * 33133 / 2,\n",
    "    electronic_conductivity=215,\n",
    "    open_circuit_potential=negative_ocp,\n",
    ")\n",
    "positive = BatteryElectrodeLayer(\n",
    "    thickness=75.6e-6,\n",
    "    porosity=0.335,\n",
    "    electrolyte_diffusivity=1.7694e-10 * 0.335**1.5,\n",
    "    electrolyte_conductivity=0.9487 * 0.335**1.5,\n",
    "    particle_radius=5.22e-6,\n",
    "    particle_diffusivity=4e-15,\n",
    "    active_fraction=0.665,\n",
    "    maximum_concentration=63104,\n",
    "    initial_stoichiometry=0.2661,\n",
    "    reference_exchange_current=3.42e-6 * np.sqrt(1000) * 63104 / 2,\n",
    "    electronic_conductivity=0.18,\n",
    "    open_circuit_potential=positive_ocp,\n",
    ")\n",
    "separator = BatteryElectrolyteLayer(\n",
    "    thickness=12e-6,\n",
    "    porosity=0.47,\n",
    "    electrolyte_diffusivity=1.7694e-10 * 0.47**1.5,\n",
    "    electrolyte_conductivity=0.9487 * 0.47**1.5,\n",
    ")\n",
    "cell = PorousElectrodeBattery(\n",
    "    negative=negative,\n",
    "    separator=separator,\n",
    "    positive=positive,\n",
    "    electrolyte_concentration=1000,\n",
    "    transference_number=0.2594,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Particle against the exact series\n",
    "\n",
    "50 minutes at 1C, the SPM on particle meshes of 8 to 64 shells; the exact series with 200 roots. The\n",
    "surface value is extrapolated from the outer shell, so the error falls at first order."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "one_c = 5.0 / area\n",
    "probe = np.linspace(0, 3000, 61)\n",
    "spm_meshes = {\n",
    "    n: cell.solve(\n",
    "        mode=\"SPM\",\n",
    "        current_density=one_c,\n",
    "        final_time=3000,\n",
    "        radial_cells=n,\n",
    "        output_times=probe,\n",
    "    )\n",
    "    for n in (8, 16, 32, 64)\n",
    "}\n",
    "roots = np.array(\n",
    "    [\n",
    "        brentq(lambda z: np.sin(z) - z * np.cos(z), n * np.pi, (n + 0.5) * np.pi - 1e-9)\n",
    "        for n in range(1, 201)\n",
    "    ]\n",
    ")\n",
    "series = (\n",
    "    lambda layer, j, t: layer.initial_stoichiometry * layer.maximum_concentration\n",
    "    - j\n",
    "    * layer.particle_radius\n",
    "    / (faraday * layer.particle_diffusivity)\n",
    "    * (\n",
    "        3 * layer.particle_diffusivity * t / layer.particle_radius**2\n",
    "        + 0.2\n",
    "        - 2\n",
    "        * np.sum(\n",
    "            np.exp(\n",
    "                -np.outer(\n",
    "                    layer.particle_diffusivity * t / layer.particle_radius**2, roots**2\n",
    "                )\n",
    "            )\n",
    "            / roots**2,\n",
    "            axis=1,\n",
    "        )\n",
    "    )\n",
    ")\n",
    "exact = [\n",
    "    series(\n",
    "        layer,\n",
    "        sign\n",
    "        * one_c\n",
    "        / (3 * layer.active_fraction / layer.particle_radius * layer.thickness),\n",
    "        probe,\n",
    "    )\n",
    "    for layer, sign in ((negative, 1), (positive, -1))\n",
    "]\n",
    "errors = {\n",
    "    n: [\n",
    "        np.abs(run.particle_surface_concentration[k][:, 0] - exact[k]).max()\n",
    "        / layer.maximum_concentration\n",
    "        for k, layer in enumerate((negative, positive))\n",
    "    ]\n",
    "    for n, run in spm_meshes.items()\n",
    "}\n",
    "print(\n",
    "    \"particle shells   largest error of the surface stoichiometry (negative, positive)\"\n",
    ")\n",
    "for n, (en, ep) in errors.items():\n",
    "    print(f\"{n:15d}   {en:.3e}   {ep:.3e}\")\n",
    "print(\n",
    "    f\"observed orders 32 -> 64 shells: {np.log2(errors[32][0] / errors[64][0]):.2f} (negative), {np.log2(errors[32][1] / errors[64][1]):.2f} (positive)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Three models over the rate\n",
    "\n",
    "Each discharge covers 90 % of the nominal capacity, so all three models stay away from the steep end\n",
    "of the voltage curve."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "rates = (0.1, 0.2, 0.5, 1.0)\n",
    "runs = {\n",
    "    (mode, rate): cell.solve(\n",
    "        mode=mode,\n",
    "        current_density=rate * one_c,\n",
    "        final_time=0.9 * 3600 / rate,\n",
    "        radial_cells=16,\n",
    "        through_cells=(10, 5, 10),\n",
    "        output_times=np.linspace(0, 0.9 * 3600 / rate, 300),\n",
    "    )\n",
    "    for mode in (\"SPM\", \"SPMe\", \"DFN\")\n",
    "    for rate in rates\n",
    "}\n",
    "deviation = {\n",
    "    (mode, rate): runs[mode, rate].terminal_voltage - runs[\"DFN\", rate].terminal_voltage\n",
    "    for mode in (\"SPM\", \"SPMe\")\n",
    "    for rate in rates\n",
    "}\n",
    "print(\"C-rate   largest |V_SPM - V_DFN|   largest |V_SPMe - V_DFN|   [mV]\")\n",
    "for rate in rates:\n",
    "    print(\n",
    "        f\"{rate:6.1f}   {1e3 * np.abs(deviation['SPM', rate]).max():20.2f}   {1e3 * np.abs(deviation['SPMe', rate]).max():23.2f}\"\n",
    "    )\n",
    "slopes = {\n",
    "    mode: np.polyfit(\n",
    "        np.log(rates),\n",
    "        np.log([np.abs(deviation[mode, rate]).max() for rate in rates]),\n",
    "        1,\n",
    "    )[0]\n",
    "    for mode in (\"SPM\", \"SPMe\")\n",
    "}\n",
    "print(\n",
    "    f\"growth of the error with the C-rate: SPM ~ C^{slopes['SPM']:.2f}, SPMe ~ C^{slopes['SPMe']:.2f} (ideal asymptotic limits: 1 and 2)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "capacity = lambda rate: 5.0 * rate * runs[\"DFN\", rate].times / 3600\n",
    "fig = plots.figure(2, 2, size=(14, 10))\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"DFN {rate:g}C\": (capacity(rate), runs[\"DFN\", rate].terminal_voltage)\n",
    "        for rate in (0.1, 0.5, 1.0)\n",
    "    },\n",
    "    reference={\n",
    "        f\"DFN {rate:g}C\": (capacity(rate), runs[\"SPM\", rate].terminal_voltage)\n",
    "        for rate in (0.1, 0.5, 1.0)\n",
    "    },\n",
    "    xlabel=\"discharged capacity [Ah]\",\n",
    "    ylabel=\"terminal voltage [V]\",\n",
    "    title=\"DFN (solid) and SPM (dashed)\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"{mode} {rate:g}C\": (capacity(rate), 1e3 * deviation[mode, rate])\n",
    "        for mode in (\"SPM\", \"SPMe\")\n",
    "        for rate in (0.5, 1.0)\n",
    "    },\n",
    "    styles={\"SPMe 0.5C\": \"dashed\", \"SPMe 1C\": \"dashed\"},\n",
    "    colors={\"SPM 0.5C\": 0, \"SPM 1C\": 1, \"SPMe 0.5C\": 0, \"SPMe 1C\": 1},\n",
    "    xlabel=\"discharged capacity [Ah]\",\n",
    "    ylabel=\"V - V_DFN [mV]\",\n",
    "    title=\"Voltage error of the reduced models\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    rates,\n",
    "    {\n",
    "        mode: [1e3 * np.abs(deviation[mode, rate]).max() for rate in rates]\n",
    "        for mode in (\"SPM\", \"SPMe\")\n",
    "    },\n",
    "    markers=True,\n",
    "    slope=1,\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"C-rate\",\n",
    "    ylabel=\"largest |V - V_DFN| [mV]\",\n",
    "    title=\"Error over the C-rate\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.convergence(\n",
    "    [1 / n for n in errors],\n",
    "    {\n",
    "        \"negative particle\": [e[0] for e in errors.values()],\n",
    "        \"positive particle\": [e[1] for e in errors.values()],\n",
    "    },\n",
    "    order=1,\n",
    "    xlabel=\"shell width / particle radius\",\n",
    "    ylabel=\"largest error of the surface stoichiometry\",\n",
    "    title=\"SPM particle against the exact series\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "The SPM runs in a fraction of the DFN time: use it for long cycling studies or state estimation,\n",
    "and switch to the SPMe or the DFN where the electrolyte limits the cell, as in the rate-capability\n",
    "example."
   ]
  }
 ]
}
