{
 "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": [
    "# Internal resistance of a lithium-ion cell from current pulses\n",
    "\n",
    "When a current step $I$ is applied to a cell at rest, the voltage first drops at once and then\n",
    "keeps falling while concentration gradients build up in the particles and the electrolyte. The\n",
    "pulse resistance $R(t)=\\big(U_\\mathrm{oc}-V(t)\\big)/I$ is the usual way to characterise the\n",
    "internal resistance of a cell. In the Doyle-Fuller-Newman model (equations in the\n",
    "discharge-rest-charge example) the instantaneous part comes from electronic and ionic conduction\n",
    "and from the charge-transfer reaction distributed through the porous electrodes.\n",
    "\n",
    "For a linearised Butler-Volmer law, $a\\,j = (a/r_\\mathrm{ct})\\,(\\phi_s-\\phi_e-U)$ with\n",
    "$r_\\mathrm{ct}=RT/(F\\,j_0)$, the porous electrode of thickness $L$ with conductivities $\\sigma$\n",
    "(solid) and $\\kappa$ (electrolyte) has the area resistance\n",
    "\n",
    "$$R_\\mathrm{el}=\\frac{L}{\\kappa+\\sigma}\\left[1+\\frac{2+\\big(\\frac{\\sigma}{\\kappa}+\\frac{\\kappa}{\\sigma}\\big)\\cosh\\nu}{\\nu\\,\\sinh\\nu}\\right],\\qquad\n",
    "  \\nu=L\\sqrt{\\frac{a}{r_\\mathrm{ct}}\\Big(\\frac{1}{\\kappa}+\\frac{1}{\\sigma}\\Big)} ,$$\n",
    "\n",
    "and the cell adds the separator, $R_0=R_{\\mathrm{el},-}+L_\\mathrm{sep}/\\kappa_\\mathrm{sep}+R_{\\mathrm{el},+}$.\n",
    "\n",
    "**Reference.** J. Newman and C. W. Tobias, *J. Electrochem. Soc.* 109 (1962) 1183, for the\n",
    "porous-electrode resistance; cell parameters of Chen et al., *J. Electrochem. Soc.* 167 (2020)\n",
    "080534 (LG M50, 5 Ah). The comparison uses a pulse of C/20, small enough for linear kinetics; 1C\n",
    "and 3C pulses show the nonlinear reaction resistance."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from dataclasses import replace\n",
    "\n",
    "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",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cell at 50 % state of charge"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "faraday, area, thermal = 96485.33212, 0.1027, 8.314462618 * 298.15 / 96485.33212\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.0279 + 0.5 * (0.9014 - 0.0279),\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.9077 + 0.5 * (0.2661 - 0.9077),\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": [
    "The same cell at other states of charge differs only in the initial stoichiometries; the rest\n",
    "voltage is the open-circuit voltage of those."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "socs = np.round(np.linspace(0.05, 0.95, 19), 2)\n",
    "cells = {\n",
    "    soc: replace(\n",
    "        cell,\n",
    "        negative=replace(\n",
    "            negative, initial_stoichiometry=0.0279 + soc * (0.9014 - 0.0279)\n",
    "        ),\n",
    "        positive=replace(\n",
    "            positive, initial_stoichiometry=0.9077 + soc * (0.2661 - 0.9077)\n",
    "        ),\n",
    "    )\n",
    "    for soc in socs\n",
    "}\n",
    "rest = {\n",
    "    soc: positive_ocp(c.positive.initial_stoichiometry, 0)\n",
    "    - negative_ocp(c.negative.initial_stoichiometry, 0)\n",
    "    for soc, c in cells.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Newman-Tobias resistance\n",
    "\n",
    "The closed form with the exchange current $j_0=2\\,j_{0,\\mathrm{ref}}\\sqrt{\\theta(1-\\theta)}$ of\n",
    "each electrode at its initial stoichiometry."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "newman_tobias = (\n",
    "    lambda cell: cell.separator.thickness / cell.separator.electrolyte_conductivity\n",
    "    + sum(\n",
    "        layer.thickness\n",
    "        / (k + s)\n",
    "        * (1 + (2 + (s / k + k / s) * np.cosh(nu)) / (nu * np.sinh(nu)))\n",
    "        for layer, k, s in (\n",
    "            (layer, layer.electrolyte_conductivity, layer.electronic_conductivity)\n",
    "            for layer in (cell.negative, cell.positive)\n",
    "        )\n",
    "        for nu in [\n",
    "            layer.thickness\n",
    "            * np.sqrt(\n",
    "                3\n",
    "                * layer.active_fraction\n",
    "                / layer.particle_radius\n",
    "                * 2\n",
    "                * layer.reference_exchange_current\n",
    "                * np.sqrt(\n",
    "                    layer.initial_stoichiometry * (1 - layer.initial_stoichiometry)\n",
    "                )\n",
    "                / thermal\n",
    "                * (1 / k + 1 / s)\n",
    "            )\n",
    "        ]\n",
    "    )\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Pulses\n",
    "\n",
    "The instantaneous response is the voltage at the switch-on of a C/20 step; it is computed on\n",
    "particle meshes from 10 to 320 shells. Then 10 s pulses of C/20, 1C and 3C at 50 % state of charge\n",
    "followed by 30 s of rest, and 10 s pulses of C/20 and 1C from 10 to 90 % state of charge."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "small = 0.05 * 5.0 / area\n",
    "shells = (10, 20, 40, 80, 160, 320)\n",
    "instant = {\n",
    "    n: (\n",
    "        rest[0.5]\n",
    "        - cell.solve(\n",
    "            mode=\"DFN\",\n",
    "            current_density=small,\n",
    "            final_time=1e-6,\n",
    "            radial_cells=n,\n",
    "            through_cells=(20, 10, 20),\n",
    "            output_times=(0.0,),\n",
    "        ).terminal_voltage[0]\n",
    "    )\n",
    "    / small\n",
    "    for n in shells\n",
    "}\n",
    "times = np.r_[0.0, np.geomspace(1e-3, 9.99, 80), np.linspace(10.01, 40.0, 60)]\n",
    "pulses = {\n",
    "    rate: cell.solve(\n",
    "        mode=\"DFN\",\n",
    "        current_density=lambda t, rate=rate: rate * 5.0 / area * float(t < 10.0),\n",
    "        final_time=40.0,\n",
    "        radial_cells=80,\n",
    "        through_cells=(12, 6, 12),\n",
    "        output_times=times,\n",
    "    )\n",
    "    for rate in (0.05, 1.0, 3.0)\n",
    "}\n",
    "sweep = {\n",
    "    (rate, soc): cells[soc]\n",
    "    .solve(\n",
    "        mode=\"DFN\",\n",
    "        current_density=rate * 5.0 / area,\n",
    "        final_time=10.0,\n",
    "        radial_cells=80,\n",
    "        through_cells=(12, 6, 12),\n",
    "        output_times=(0.0, 10.0),\n",
    "    )\n",
    "    .terminal_voltage\n",
    "    for rate in (0.05, 1.0)\n",
    "    for soc in socs[1:-1:2]\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "reference = newman_tobias(cell)\n",
    "extrapolated = 2 * instant[320] - instant[160]\n",
    "print(\n",
    "    f\"Newman-Tobias resistance at 50 % SOC: {1e4 * reference:.4f} Ω·cm² = {1e3 * reference / area:.3f} mΩ for the 5 Ah cell\"\n",
    ")\n",
    "for n, value in instant.items():\n",
    "    print(\n",
    "        f\"  {n:4d} particle shells: {1e4 * value:.4f} Ω·cm², deviation {100 * (value / reference - 1):+.3f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"  Richardson extrapolation of 160 and 320 shells: deviation {100 * (extrapolated / reference - 1):+.3f} %\"\n",
    ")\n",
    "for rate, run in pulses.items():\n",
    "    resistance = (rest[0.5] - run.terminal_voltage) / (rate * 5.0 / area)\n",
    "    print(\n",
    "        f\"{rate:4.2f}C pulse: R(0) = {1e3 * resistance[0] / area:.2f} mΩ, R(1 s) = {1e3 * np.interp(1.0, times, resistance) / area:.2f} mΩ, \"\n",
    "        f\"R(10 s) = {1e3 * resistance[times < 10][-1] / area:.2f} mΩ; voltage 30 s after the pulse \"\n",
    "        f\"{1e3 * (run.terminal_voltage[-1] - rest[0.5]):+.2f} mV from rest\"\n",
    "    )\n",
    "print(\n",
    "    \"SOC     R(0) at C/20   Newman-Tobias   deviation   R(10 s) at C/20   R(10 s) at 1C   [mΩ]\"\n",
    ")\n",
    "for soc in socs[1:-1:2]:\n",
    "    r0, nt = (rest[soc] - sweep[0.05, soc][0]) / (0.05 * 5.0), newman_tobias(\n",
    "        cells[soc]\n",
    "    ) / area\n",
    "    print(\n",
    "        f\"{soc:4.1f}   {1e3 * r0:12.2f}   {1e3 * nt:13.2f}   {100 * (r0 / nt - 1):+8.2f} %   {1e3 * (rest[soc] - sweep[0.05, soc][1]) / 0.25:15.2f}\"\n",
    "        f\"   {1e3 * (rest[soc] - sweep[1.0, soc][1]) / 5.0:13.2f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The pulse responses, the pulse resistance over time, the particle-mesh study of the\n",
    "instantaneous resistance and the resistance over the state of charge."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(2, 2, size=(14, 10))\n",
    "plots.line(\n",
    "    times,\n",
    "    {\n",
    "        f\"{rate:g}C\": 1e3 * (run.terminal_voltage - rest[0.5])\n",
    "        for rate, run in pulses.items()\n",
    "    },\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"V - U_oc [mV]\",\n",
    "    title=\"10 s discharge pulses at 50 % SOC\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    times[1:81],\n",
    "    {\n",
    "        f\"{rate:g}C\": 1e3 * (rest[0.5] - run.terminal_voltage[1:81]) / (rate * 5.0)\n",
    "        for rate, run in pulses.items()\n",
    "    },\n",
    "    hlines={\"Newman-Tobias R₀\": 1e3 * reference / area},\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"time after switch-on [s]\",\n",
    "    ylabel=\"pulse resistance [mΩ]\",\n",
    "    title=\"Instantaneous and growing resistance\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.convergence(\n",
    "    [1 / n for n in shells],\n",
    "    {\"|R₀ - Newman-Tobias| / R₀\": [abs(v / reference - 1) for v in instant.values()]},\n",
    "    order=1,\n",
    "    xlabel=\"particle shell width / radius\",\n",
    "    ylabel=\"relative deviation\",\n",
    "    title=\"Particle-mesh study at C/20\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    100 * socs[1:-1:2],\n",
    "    {\n",
    "        f\"{label}, {rate:g}C\": [\n",
    "            1e3 * (rest[soc] - sweep[rate, soc][k]) / (5.0 * rate)\n",
    "            for soc in socs[1:-1:2]\n",
    "        ]\n",
    "        for rate in (0.05, 1.0)\n",
    "        for k, label in ((0, \"R(0)\"), (1, \"R(10 s)\"))\n",
    "    },\n",
    "    markers=True,\n",
    "    styles={\"R(0), 1C\": \"dotted\", \"R(10 s), 1C\": \"dotted\"},\n",
    "    colors={\"R(0), 0.05C\": 0, \"R(10 s), 0.05C\": 1, \"R(0), 1C\": 0, \"R(10 s), 1C\": 1},\n",
    "    reference={\n",
    "        \"Newman-Tobias R₀\": (\n",
    "            100 * socs,\n",
    "            [1e3 * newman_tobias(c) / area for c in cells.values()],\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"state of charge [%]\",\n",
    "    ylabel=\"resistance [mΩ]\",\n",
    "    title=\"Resistance over the state of charge\",\n",
    "    legend=\"upper center\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Split the instantaneous resistance into electrode and separator parts by setting one electrode's\n",
    "exchange current very high, or fit a two-branch equivalent circuit to the pulse resistance curve."
   ]
  }
 ]
}
