{
 "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": [
    "# Rate capability of a lithium-ion cell\n",
    "\n",
    "The faster a cell is discharged, the larger its polarisation, the earlier it reaches the cut-off\n",
    "voltage and the less capacity and energy it delivers. In a cell with thick, dense electrodes the\n",
    "electrolyte is often the bottleneck: lithium salt is produced in the negative electrode and\n",
    "consumed in the positive one, and the salt concentration near the positive collector falls.\n",
    "\n",
    "For a uniform reaction rate the steady salt balance $-D_e\\,c_e'=(1-t_+)\\,i_e/F$ with an ionic\n",
    "current rising linearly from zero to $I$ in the negative electrode, constant in the separator and\n",
    "falling back to zero in the positive electrode gives\n",
    "\n",
    "$$c_e(x)=c_0+\\frac{(1-t_+)\\,I}{F}\\big(\\bar g-g(x)\\big),\\qquad g(x)=\\int_0^x\\frac{i_e/I}{D_e}\\,dx,$$\n",
    "\n",
    "where $\\bar g$ is the porosity-weighted mean of $g$ that conserves the salt. The concentration\n",
    "reaches zero at the positive collector at the limiting current\n",
    "$I_\\mathrm{lim}=F c_0/\\big((1-t_+)(g(L)-\\bar g)\\big)$, so the minimum concentration falls as\n",
    "$c_0(1-I/I_\\mathrm{lim})$.\n",
    "\n",
    "**Reference.** Cell parameters of Chen et al., *J. Electrochem. Soc.* 167 (2020) 080534 (LG M50,\n",
    "5 Ah); model of Doyle, Fuller and Newman, *J. Electrochem. Soc.* 140 (1993) 1526. Checks: (i) at\n",
    "low rate the delivered capacity approaches the stoichiometric capacity of the limiting electrode;\n",
    "(ii) the electrolyte follows the steady salt balance and the limiting current above; (iii) the\n",
    "capacity-rate data are summarised by Peukert's law $Q\\propto I^{1-k}$."
   ]
  },
  {
   "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",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cell"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "faraday, area, transference = 96485.33212, 0.1027, 0.2594\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=transference,\n",
    ")\n",
    "stoichiometric = faraday * 0.75 * 85.2e-6 * 33133 * (0.9014 - 0.0279) * area / 3600"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Discharges\n",
    "\n",
    "Each discharge starts from the full cell and runs a little past the 2.5 V cut-off (the end time is\n",
    "given as a fraction of the nominal hour count); the capacity is read at the cut-off."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "rates = {0.1: 1.02, 0.2: 1.02, 0.5: 1.01, 1.0: 0.995, 1.25: 0.985, 1.5: 0.972}\n",
    "runs = {\n",
    "    rate: cell.solve(\n",
    "        mode=\"DFN\",\n",
    "        current_density=5.0 * rate / area,\n",
    "        final_time=end * 3600 / rate,\n",
    "        radial_cells=12,\n",
    "        through_cells=(8, 4, 8),\n",
    "        output_times=np.linspace(0, end * 3600 / rate, 800),\n",
    "    )\n",
    "    for rate, end in rates.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "layers = (\n",
    "    (negative, 0.0),\n",
    "    (separator, negative.thickness),\n",
    "    (positive, negative.thickness + separator.thickness),\n",
    ")\n",
    "x = np.linspace(0, negative.thickness + separator.thickness + positive.thickness, 4001)\n",
    "g = lambda x: np.where(\n",
    "    x < negative.thickness,\n",
    "    x**2 / (2 * negative.thickness * negative.electrolyte_diffusivity),\n",
    "    np.where(\n",
    "        x < layers[2][1],\n",
    "        negative.thickness / (2 * negative.electrolyte_diffusivity)\n",
    "        + (x - negative.thickness) / separator.electrolyte_diffusivity,\n",
    "        g_end\n",
    "        - (x[-1] - x) ** 2\n",
    "        / (2 * positive.thickness * positive.electrolyte_diffusivity),\n",
    "    ),\n",
    ")\n",
    "g_end = (\n",
    "    negative.thickness / (2 * negative.electrolyte_diffusivity)\n",
    "    + separator.thickness / separator.electrolyte_diffusivity\n",
    "    + positive.thickness / (2 * positive.electrolyte_diffusivity)\n",
    ")\n",
    "porosity = np.select(\n",
    "    [x < negative.thickness, x < layers[2][1]],\n",
    "    [negative.porosity, separator.porosity],\n",
    "    positive.porosity,\n",
    ")\n",
    "g_mean = np.trapezoid(porosity * g(x), x) / np.trapezoid(porosity, x)\n",
    "limiting = faraday * 1000 / ((1 - transference) * (g_end - g_mean))\n",
    "results = {}\n",
    "for rate, run in runs.items():\n",
    "    capacity = 5.0 * rate * run.times / 3600\n",
    "    cut = np.argmax(run.terminal_voltage < 2.5)\n",
    "    q = np.interp(\n",
    "        2.5, run.terminal_voltage[cut : cut - 2 : -1], capacity[cut : cut - 2 : -1]\n",
    "    )\n",
    "    keep = capacity <= q\n",
    "    results[rate] = dict(\n",
    "        q=q,\n",
    "        energy=np.trapezoid(run.terminal_voltage[keep], capacity[keep]),\n",
    "        salt=run.electrolyte_concentration[keep].min(),\n",
    "        profile=run.electrolyte_concentration[np.flatnonzero(keep)[-1]],\n",
    "    )\n",
    "peukert = (\n",
    "    1\n",
    "    - np.polyfit(\n",
    "        np.log(list(rates)[2:]), np.log([results[r][\"q\"] for r in list(rates)[2:]]), 1\n",
    "    )[0]\n",
    ")\n",
    "print(\n",
    "    f\"stoichiometric capacity of the negative electrode {stoichiometric:.4f} Ah; limiting current of the steady salt balance \"\n",
    "    f\"{limiting:.1f} A/m² = {limiting * area:.2f} A = {limiting * area / 5:.2f}C\"\n",
    ")\n",
    "print(\n",
    "    \"C-rate   capacity [Ah]  of stoichiometric   energy [Wh]   mean voltage [V]   min salt [mol/m³]   steady balance c0(1-I/I_lim)\"\n",
    ")\n",
    "for rate, r in results.items():\n",
    "    print(\n",
    "        f\"{rate:6.2f}   {r['q']:12.4f}   {100 * r['q'] / stoichiometric:13.1f} %   {r['energy']:11.3f}   {r['energy'] / r['q']:15.4f}\"\n",
    "        f\"   {r['salt']:17.1f}   {1000 * (1 - 5 * rate / area / limiting):17.1f}\"\n",
    "    )\n",
    "print(f\"Peukert exponent from C/2 to 1.5C: k = {peukert:.4f}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Discharge curves, capacity and energy over the rate, the salt profile at the cut-off against the\n",
    "steady balance, and the minimum salt concentration on its way to the limiting current."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(2, 2, size=(14, 10))\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"{rate:g}C\": (5.0 * rate * run.times / 3600, run.terminal_voltage)\n",
    "        for rate, run in runs.items()\n",
    "    },\n",
    "    hlines={\"cut-off\": 2.5},\n",
    "    xlimits=(0, 5.3),\n",
    "    ylimits=(2.4, 4.25),\n",
    "    xlabel=\"discharged capacity [Ah]\",\n",
    "    ylabel=\"terminal voltage [V]\",\n",
    "    title=\"Discharge curves from C/10 to 1.5C\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    list(rates),\n",
    "    {\"capacity [Ah]\": [r[\"q\"] for r in results.values()]},\n",
    "    right={\"energy [Wh]\": [r[\"energy\"] for r in results.values()]},\n",
    "    hlines={\"stoichiometric capacity\": stoichiometric},\n",
    "    ylimits=(4.82, 5.12),\n",
    "    markers=True,\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"C-rate\",\n",
    "    ylabel=\"capacity to 2.5 V [Ah]\",\n",
    "    right_label=\"energy to 2.5 V [Wh]\",\n",
    "    title=\"Rate capability\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    1e6 * runs[0.1].electrolyte_positions,\n",
    "    {f\"{rate:g}C\": r[\"profile\"] for rate, r in results.items() if rate >= 0.5},\n",
    "    reference={\n",
    "        f\"{rate:g}C\": (\n",
    "            1e6 * x,\n",
    "            1000 + (1 - transference) * 5 * rate / area / faraday * (g_mean - g(x)),\n",
    "        )\n",
    "        for rate in results\n",
    "        if rate >= 0.5\n",
    "    },\n",
    "    vlines=[1e6 * negative.thickness, 1e6 * layers[2][1]],\n",
    "    xlabel=\"x [µm]\",\n",
    "    ylabel=\"salt concentration [mol/m³]\",\n",
    "    title=\"Salt at the cut-off, dashed: steady balance\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"simulation\": (\n",
    "            5 * np.array(list(rates)) / area,\n",
    "            [r[\"salt\"] for r in results.values()],\n",
    "        )\n",
    "    },\n",
    "    reference={\n",
    "        \"steady balance c₀(1 - I/I_lim)\": (\n",
    "            np.linspace(0, limiting, 50),\n",
    "            1000 * (1 - np.linspace(0, limiting, 50) / limiting),\n",
    "        )\n",
    "    },\n",
    "    vlines={\"limiting current\": limiting},\n",
    "    xlabel=\"current density [A/m²]\",\n",
    "    ylabel=\"minimum salt concentration [mol/m³]\",\n",
    "    title=\"Towards the limiting current\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Thinner or more porous electrodes raise the limiting current: change the thickness and porosity\n",
    "and see the rate capability improve at the expense of the stored energy per area."
   ]
  }
 ]
}
