{
 "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": [
    "# Capacity and power fade of a lumped battery\n",
    "\n",
    "Most of the calendar ageing of a lithium-ion cell comes from a parasitic reaction at the negative\n",
    "electrode: solvent molecules diffuse through the solid-electrolyte interphase (SEI) and react at\n",
    "the graphite surface. The film thickens, every mole of film product consumes two moles of\n",
    "cyclable lithium, and the film resistance grows:\n",
    "\n",
    "$$\\frac{dL}{dt}=\\bar V\\,\\frac{c_\\mathrm{sol}D(T)}{L},\\qquad\n",
    "  Q_\\mathrm{loss}=\\frac{2F\\,A_s}{\\bar V}\\,(L-L_0),\\qquad\n",
    "  R=R_0+\\frac{L}{\\kappa_\\mathrm{SEI}A_s},\\qquad D(T)=D_\\mathrm{ref}\\,e^{-\\frac{E_a}{R_g}\\left(\\frac1T-\\frac1{T_\\mathrm{ref}}\\right)},$$\n",
    "\n",
    "with the partial molar volume $\\bar V$ of the film, the solvent concentration $c_\\mathrm{sol}$ and the\n",
    "active surface $A_s$ of the negative electrode. Cycling adds an empirical fade of the capacity,\n",
    "$Q_\\mathrm{cyc}(n)=Q_0\\,e^{-k\\,\\max(n-n_0,0)}$ after $n$ equivalent full cycles; the cell does one\n",
    "cycle per day, and $Q=Q_\\mathrm{cyc}(n)-Q_\\mathrm{loss}$. The aged cell is a lumped electrothermal\n",
    "battery (the model of the constant-current example) with capacity $Q$ and resistance $R$.\n",
    "\n",
    "**Reference.** The film law has the closed form $L(t)=\\sqrt{L_0^2+2\\bar Vc_\\mathrm{sol}D\\,t}$, so the\n",
    "calendar loss grows with $\\sqrt t$ (M. B. Pinson and M. Z. Bazant, *J. Electrochem. Soc.* 160 (2013)\n",
    "A243; H. J. Ploehn, P. Ramadass and R. E. White, *J. Electrochem. Soc.* 151 (2004) A456). The end of\n",
    "life, 80 % of the initial capacity, follows from the closed forms by root finding. For a constant\n",
    "current $I$ the lumped cell delivers $E=Q\\int_{s_1}^{s_0}U_\\mathrm{oc}\\,ds-I^2R\\,t$ between the states\n",
    "of charge $s_0$ and $s_1$. The open-circuit curve and the fresh cell (5 Ah, 30 mΩ) follow the LG M50\n",
    "cell of Chen et al., *J. Electrochem. Soc.* 167 (2020) 080534."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.geometry import LumpedDomain\n",
    "from onesim.meshing import LumpedMesh\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.discretization import LumpedParameters\n",
    "from onesim.numerics.time import AdaptiveBDF, ClassicalRungeKutta4, EventDefinition\n",
    "from onesim.physics.chemistry import (\n",
    "    BatteryChemistry,\n",
    "    BatteryCycleCapacityFade,\n",
    "    LumpedBattery,\n",
    "    sei_area_resistance,\n",
    "    sei_thickness_rate,\n",
    "    solvent_limited_sei_flux,\n",
    ")\n",
    "from onesim.results.storage import MemoryOutputSink, Output\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.optimize import brentq\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cell and ageing parameters"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "faraday, gas, year = 96485.33212, 8.314462618, 365.25 * 86400\n",
    "q0, r0, surface = 5.0 * 3600, 0.030, 3.36\n",
    "solvent, molar_volume, film0, kappa_film = 4541.0, 9.585e-5, 5e-9, 5e-6\n",
    "d_ref, activation = 5e-22, 40e3\n",
    "cycling = BatteryCycleCapacityFade(\n",
    "    initial_capacity=q0, fade_rate=4e-5, induction_cycles=200\n",
    ")\n",
    "diffusivity = lambda T: d_ref * np.exp(-activation / gas * (1 / T - 1 / 298.15))\n",
    "open_circuit = lambda s: (\n",
    "    4.4875\n",
    "    - 0.8090 * (y := 0.2661 + (1 - s) * 0.5829)\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",
    "    - 1.9793 * np.exp(-39.3631 * (x := 0.0279 + s * 0.8735))\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",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Ten years at 25, 35 and 45 °C\n",
    "\n",
    "The film thickness (in nm, over time in years) is integrated with OneSimulation's adaptive BDF2\n",
    "method, using the library's film laws; an event marks the end of life at 80 % of the initial\n",
    "capacity."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "capacity = lambda years, film: cycling.remaining_capacity(\n",
    "    365.25 * years\n",
    ") - 2 * faraday * surface / molar_volume * (1e-9 * film - film0)\n",
    "ageing = {}\n",
    "for celsius in (25, 35, 45):\n",
    "    D = diffusivity(273.15 + celsius)\n",
    "    growth = (\n",
    "        lambda t, y: year\n",
    "        * 1e9\n",
    "        * sei_thickness_rate(\n",
    "            solvent_limited_sei_flux(solvent, D, 1e-9 * y), molar_volume\n",
    "        )\n",
    "    )\n",
    "    end_of_life = EventDefinition(\n",
    "        \"end of life\", lambda t, y: capacity(t, y[0]) - 0.8 * q0, direction=-1\n",
    "    )\n",
    "    run = AdaptiveBDF(\n",
    "        order=2, relative_tolerance=1e-6, absolute_tolerance=1e-6, maximum_step=0.05\n",
    "    ).integrate(\n",
    "        growth,\n",
    "        np.array([1e9 * film0]),\n",
    "        0.0,\n",
    "        10.0,\n",
    "        initial_step=1e-6,\n",
    "        events=(end_of_life,),\n",
    "    )\n",
    "    times, film = np.array(run.times), np.array(run.states)[:, 0]\n",
    "    exact = lambda t, D=D: 1e9 * np.sqrt(\n",
    "        film0**2 + 2 * molar_volume * solvent * D * t * year\n",
    "    )\n",
    "    ageing[celsius] = dict(\n",
    "        times=times,\n",
    "        film=film,\n",
    "        exact=exact(times),\n",
    "        capacity=capacity(times, film),\n",
    "        life=[event.time for event in run.events],\n",
    "        exact_life=brentq(lambda t: capacity(t, exact(t)) - 0.8 * q0, 1e-6, 50.0),\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Discharge of aged cells\n",
    "\n",
    "The cell aged at 25 °C, taken after 0, 3, 6 and 9 years, discharged at 5 A from full to 2 % state of\n",
    "charge (the fresh cell's 1C)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cell = LumpedDomain()\n",
    "numerics = Numerics(spatial=LumpedParameters(), time_integrator=ClassicalRungeKutta4())\n",
    "discharges = {}\n",
    "for age in (0, 3, 6, 9):\n",
    "    film = np.interp(age, ageing[25][\"times\"], ageing[25][\"film\"])\n",
    "    q, resistance = (\n",
    "        capacity(age, film),\n",
    "        r0 + float(sei_area_resistance(1e-9 * film, kappa_film)) / surface,\n",
    "    )\n",
    "    model = LumpedBattery(\n",
    "        domain=cell.system,\n",
    "        chemistry=BatteryChemistry(\n",
    "            \"aged\",\n",
    "            open_circuit_voltage=lambda s, T: open_circuit(s),\n",
    "            internal_resistance=lambda s, T: resistance,\n",
    "        ),\n",
    "        charge_capacity=q,\n",
    "        current=5.0,\n",
    "        thermal_capacity=70.0,\n",
    "        heat_transfer=0.3,\n",
    "        ambient_temperature=298.15,\n",
    "    )\n",
    "    record = MemoryOutputSink()\n",
    "    end = 0.98 * q / 5.0\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"aged discharge\",\n",
    "            geometry=cell,\n",
    "            physics=(model,),\n",
    "            initial_conditions=(\n",
    "                InitialValue(model.state_of_charge, 1.0),\n",
    "                InitialValue(model.temperature, 298.15),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=LumpedMesh(cell),\n",
    "        numerics=numerics,\n",
    "    ).run(\n",
    "        start_time=0.0,\n",
    "        end_time=end,\n",
    "        time_step=end / 1000,\n",
    "        output=Output(\n",
    "            fields=(model.terminal_voltage, model.temperature),\n",
    "            interval=end / 1000,\n",
    "            sink=record,\n",
    "        ),\n",
    "    )\n",
    "    s = np.linspace(0.02, 1.0, 4001)\n",
    "    discharges[age] = dict(\n",
    "        times=record.times,\n",
    "        voltage=record.time_series(model.terminal_voltage)[1],\n",
    "        q=q,\n",
    "        resistance=resistance,\n",
    "        energy=5.0\n",
    "        * np.trapezoid(record.time_series(model.terminal_voltage)[1], record.times),\n",
    "        exact=q * np.trapezoid(open_circuit(s), s) - 25.0 * resistance * end,\n",
    "        heating=record.time_series(model.temperature)[1].max() - 298.15,\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "for celsius, a in ageing.items():\n",
    "    print(\n",
    "        f\"{celsius} °C: film after 10 years {a['film'][-1]:.2f} nm (closed form {a['exact'][-1]:.2f} nm, largest deviation \"\n",
    "        f\"{np.abs(a['film'] - a['exact']).max():.1e} nm); capacity {a['capacity'][-1] / q0:.2%}; end of life after \"\n",
    "        + (\n",
    "            f\"{a['life'][0]:.4f} years (closed form {a['exact_life']:.4f})\"\n",
    "            if a[\"life\"]\n",
    "            else f\"more than 10 years (closed form {a['exact_life']:.2f})\"\n",
    "        )\n",
    "    )\n",
    "print(\n",
    "    \"age [y]   capacity [Ah]   resistance [mΩ]   energy [Wh]   closed form [Wh]   deviation   heating [K]\"\n",
    ")\n",
    "for age, d in discharges.items():\n",
    "    print(\n",
    "        f\"{age:7d}   {d['q'] / 3600:13.3f}   {1e3 * d['resistance']:15.2f}   {d['energy'] / 3600:11.4f}   {d['exact'] / 3600:16.4f}\"\n",
    "        f\"   {100 * (d['energy'] / d['exact'] - 1):+8.3f} %   {d['heating']:11.2f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(19, 5.4))\n",
    "plots.line(\n",
    "    y={f\"{c} °C\": (a[\"times\"], a[\"film\"]) for c, a in ageing.items()},\n",
    "    reference={f\"{c} °C\": (a[\"times\"], a[\"exact\"]) for c, a in ageing.items()},\n",
    "    xlabel=\"time [years]\",\n",
    "    ylabel=\"SEI thickness [nm]\",\n",
    "    title=\"Film growth (dashed: closed form)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={f\"{c} °C\": (a[\"times\"], 100 * a[\"capacity\"] / q0) for c, a in ageing.items()},\n",
    "    reference={\n",
    "        \"cycling only\": (\n",
    "            ageing[25][\"times\"],\n",
    "            100 * cycling.remaining_capacity(365.25 * ageing[25][\"times\"]) / q0,\n",
    "        )\n",
    "    },\n",
    "    hlines={\"end of life\": 80.0},\n",
    "    xlabel=\"time [years], one cycle per day\",\n",
    "    ylabel=\"capacity [% of initial]\",\n",
    "    title=\"Capacity fade\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"after {age} years\": (5.0 * d[\"times\"] / 3600, d[\"voltage\"])\n",
    "        for age, d in discharges.items()\n",
    "    },\n",
    "    xlabel=\"discharged capacity [Ah]\",\n",
    "    ylabel=\"terminal voltage [V]\",\n",
    "    title=\"5 A discharge of the cell aged at 25 °C\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the film growth depend on the state of charge through the negative-electrode potential, add\n",
    "lithium plating at low temperature, or fit the cycle fade to measured capacity checks."
   ]
  }
 ]
}
