{
 "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": [
    "# Electrode balancing of a lithium-ion cell\n",
    "\n",
    "Ageing changes a lithium-ion cell in two ways that the terminal voltage alone cannot tell apart:\n",
    "lithium is lost to side reactions, and active material of one electrode stops taking part. Both\n",
    "shift the **balance** of the electrodes, the stoichiometry (degree of lithiation) $x$ of the\n",
    "negative and $y$ of the positive electrode at 0 % and at 100 % state of charge. Between the\n",
    "limits both change linearly with the state of charge $s$,\n",
    "\n",
    "$$x(s)=x_0+s\\,(x_{100}-x_0),\\qquad y(s)=y_0+s\\,(y_{100}-y_0),$$\n",
    "\n",
    "and the open-circuit voltage of the cell is the difference of the two half-cell potentials,\n",
    "\n",
    "$$U_\\mathrm{oc}(s)=U_+\\big(y(s)\\big)-U_-\\big(x(s)\\big).$$\n",
    "\n",
    "With the half-cell curves $U_\\pm$ known from coin-cell measurements, the four limits follow from\n",
    "a least-squares fit of $U_\\mathrm{oc}(s)$ to the measured cell curve. There is no transport, no\n",
    "current and no geometry: the model is zero-dimensional.\n",
    "\n",
    "**Reference.** C.-H. Chen, F. Brosa Planella, K. O'Regan, D. Gastol, W. D. Widanage and\n",
    "E. Kendrick, *J. Electrochem. Soc.* 167 (2020) 080534: half-cell potentials of the graphite-SiOx\n",
    "negative and the NMC811 positive electrode of the LG M50 cell, and its balance $x_0=0.0279$,\n",
    "$x_{100}=0.9014$, $y_0=0.9077$, $y_{100}=0.2661$. The open-circuit voltage curve used here is\n",
    "**synthetic**: it is generated from these four values at 101 states of charge, with normally\n",
    "distributed noise of 2 mV as a measurement would have. A correct fit recovers the four values\n",
    "within the uncertainty that the noise leaves."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.simulation.studies import SimulationStudyService, StudyParameter\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Half-cell potentials and the measured curve\n",
    "\n",
    "The two half-cell potentials of Chen et al. as functions of the stoichiometry, the open-circuit\n",
    "voltage of a balance as the difference of the two along the state of charge, and the synthetic\n",
    "measurement. The charge windows of the electrodes follow from their loading (active volume\n",
    "times maximum lithium concentration times Faraday's constant): 5.83 Ah for the negative and\n",
    "8.73 Ah for the positive electrode of the 0.1027 m² electrode pair."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "negative_ocp = lambda x: (\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: (\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",
    "soc = np.linspace(0.0, 1.0, 101)\n",
    "open_circuit = lambda b: (\n",
    "    positive_ocp(b[\"y0\"] + soc * (b[\"y100\"] - b[\"y0\"]))\n",
    "    - negative_ocp(b[\"x0\"] + soc * (b[\"x100\"] - b[\"x0\"]))\n",
    ")\n",
    "names = (\"x0\", \"x100\", \"y0\", \"y100\")\n",
    "true = dict(zip(names, (0.0279, 0.9014, 0.9077, 0.2661)))\n",
    "noise = 2e-3\n",
    "measured = open_circuit(true) + np.random.default_rng(2026).normal(0.0, noise, soc.size)\n",
    "capacity_negative, capacity_positive = (\n",
    "    96485.33212 * fraction * thickness * concentration * 0.1027 / 3600\n",
    "    for fraction, thickness, concentration in (\n",
    "        (0.75, 85.2e-6, 33133),\n",
    "        (0.665, 75.6e-6, 63104),\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    f\"measured open-circuit voltage from {measured[0]:.3f} V at 0 % to {measured[-1]:.3f} V at 100 % state of charge\"\n",
    ")\n",
    "print(\n",
    "    f\"electrode charge windows: negative {capacity_negative:.3f} Ah, positive {capacity_positive:.3f} Ah\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fit of the four limits\n",
    "\n",
    "`SimulationStudyService` evaluates the open-circuit voltage for trial balances and measures the\n",
    "mean squared deviation from the data in mV²; its projected-gradient optimizer (forward\n",
    "differences of $10^{-6}$ of each interval, backtracking line search) minimises it within the\n",
    "bounds $0\\le x_0\\le0.2$, $0.7\\le x_{100}\\le1$, $0.75\\le y_0\\le1$, $0.1\\le y_{100}\\le0.45$. It\n",
    "starts from a guess several per cent off: $x_0=0.06$, $x_{100}=0.85$, $y_0=0.85$, $y_{100}=0.32$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "bounds = {\"x0\": (0.0, 0.2), \"x100\": (0.7, 1.0), \"y0\": (0.75, 1.0), \"y100\": (0.1, 0.45)}\n",
    "start = {\"x0\": 0.06, \"x100\": 0.85, \"y0\": 0.85, \"y100\": 0.32}\n",
    "study = SimulationStudyService(\n",
    "    tuple(StudyParameter(name, *bounds[name]) for name in names),\n",
    "    lambda balance: balance,\n",
    "    lambda curve: {\"msd\": float(np.mean((1e3 * (curve - measured)) ** 2))},\n",
    "    solve=open_circuit,\n",
    ")\n",
    "best = study.optimize(\n",
    "    (\"msd\",),\n",
    "    start=start,\n",
    "    step=1e-6,\n",
    "    tolerance=1e-5,\n",
    "    maximum_iterations=3000,\n",
    "    maximum_runs=400000,\n",
    ")\n",
    "fitted = open_circuit(best.parameters)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the generating values\n",
    "\n",
    "The uncertainty of each limit follows from the Gauss-Newton covariance $(J^TJ)^{-1}$ of the\n",
    "residuals divided by the noise, with the sensitivities $J$ from one more evaluation per limit.\n",
    "From the fitted windows follow the charge the cell can deliver, $C_-\\,(x_{100}-x_0)$, and the\n",
    "excess of the positive electrode."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sensitivity = np.column_stack(\n",
    "    [\n",
    "        (\n",
    "            open_circuit(dict(best.parameters) | {name: best.parameters[name] + 1e-6})\n",
    "            - fitted\n",
    "        )\n",
    "        / (1e-6 * noise)\n",
    "        for name in names\n",
    "    ]\n",
    ")\n",
    "sigma = dict(zip(names, np.sqrt(np.diag(np.linalg.inv(sensitivity.T @ sensitivity)))))\n",
    "print(\n",
    "    f\"optimizer: {best.iterations} iterations, {best.run_count} evaluations of the open-circuit voltage, \"\n",
    "    f\"χ² = N·MSD/s² = {soc.size * best.objectives['msd'] / (1e3 * noise) ** 2:.1f} for {soc.size - 4} degrees of freedom\"\n",
    ")\n",
    "print(\"limit      start     fitted     ± 1 σ       true   deviation\")\n",
    "for name in names:\n",
    "    print(\n",
    "        f\"{name:5s} {start[name]:10.4f} {best.parameters[name]:10.5f} {sigma[name]:9.5f} {true[name]:10.4f}\"\n",
    "        f\"   {(best.parameters[name] - true[name]) / sigma[name]:+5.2f} σ\"\n",
    "    )\n",
    "cell = {\n",
    "    label: (\n",
    "        capacity_negative * (b[\"x100\"] - b[\"x0\"]),\n",
    "        capacity_positive * (b[\"y0\"] - b[\"y100\"]),\n",
    "    )\n",
    "    for label, b in ((\"fitted\", best.parameters), (\"true\", true))\n",
    "}\n",
    "for label, (negative, positive) in cell.items():\n",
    "    print(\n",
    "        f\"{label:6s} cell capacity {negative:.4f} Ah (negative window), positive window {positive:.4f} Ah, \"\n",
    "        f\"excess of the positive {100 * (positive / negative - 1):.1f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"rms voltage residual {1e3 * np.sqrt(np.mean((fitted - measured) ** 2)):.3f} mV (noise {1e3 * noise:.1f} mV), \"\n",
    "    f\"largest deviation of the fitted from the true curve {1e3 * np.max(np.abs(fitted - open_circuit(true))):.2f} mV\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the measured curve with the start guess and the fit. Middle: the residuals against the\n",
    "noise level. Right: the balancing diagram, both half-cell potentials over the state of charge\n",
    "of the cell with the fitted limits; the cell voltage is their difference."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(17, 5))\n",
    "plots.line(\n",
    "    soc,\n",
    "    {\"fitted balance\": fitted},\n",
    "    points={\"measured (synthetic)\": (soc[::2], measured[::2])},\n",
    "    reference={\"start guess\": open_circuit(start)},\n",
    "    xlabel=\"state of charge\",\n",
    "    ylabel=\"open-circuit voltage [V]\",\n",
    "    title=\"Cell open-circuit voltage\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    soc,\n",
    "    {\"measured - fitted\": 1e3 * (measured - fitted)},\n",
    "    hlines=[1e3 * noise, -1e3 * noise],\n",
    "    ylimits=(-8, 8),\n",
    "    xlabel=\"state of charge\",\n",
    "    ylabel=\"voltage residual [mV]\",\n",
    "    title=\"Residuals (dotted: ± noise)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    soc,\n",
    "    {\n",
    "        \"positive electrode U₊(y)\": positive_ocp(\n",
    "            best.parameters[\"y0\"]\n",
    "            + soc * (best.parameters[\"y100\"] - best.parameters[\"y0\"])\n",
    "        )\n",
    "    },\n",
    "    right={\n",
    "        \"negative electrode U₋(x)\": negative_ocp(\n",
    "            best.parameters[\"x0\"]\n",
    "            + soc * (best.parameters[\"x100\"] - best.parameters[\"x0\"])\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"state of charge of the cell\",\n",
    "    ylabel=\"positive potential vs Li [V]\",\n",
    "    right_label=\"negative potential vs Li [V]\",\n",
    "    title=\"Balancing diagram with the fitted limits\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Shift both $y$ limits by the same amount to mimic loss of lithium inventory, or shrink one window\n",
    "to mimic loss of active material, generate the curve again and fit it: the fit tells the two\n",
    "ageing modes apart. Fitting the derivative $\\mathrm dU_\\mathrm{oc}/\\mathrm ds$ as well sharpens the\n",
    "graphite limits, whose plateaus leave the voltage itself nearly flat."
   ]
  }
 ]
}
