{
 "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": [
    "# Battery overdischarge protection using shunt resistances\n",
    "\n",
    "A string of two identical 12 Ah lithium-ion cells is discharged by a current source\n",
    "$I_\\mathrm{app}=C_\\mathrm{rate}\\times 12$ A. From $t=50$ s cell 1 develops a small internal\n",
    "short (conductance $G_\\mathrm{short}$), so it drains faster than cell 2. Without protection the\n",
    "string ends with cell 1 overdischarged and cell 2 under-used. With protection, a shunt resistor\n",
    "parallel to each cell is switched from $10^8\\,\\Omega$ to about $2\\cdot10^{-8}\\,\\Omega$ the moment\n",
    "that cell's state of charge reaches 0.2: the cell is bypassed and empties into its shunt. This is\n",
    "the cell balancing idea of G. L. Plett's battery-management lectures.\n",
    "\n",
    "**Cell.** The state of charge follows coulomb counting, $Q\\,d\\mathrm{SOC}/dt=-I_\\mathrm{int}$,\n",
    "with the internal current $I_\\mathrm{int}$ (discharge positive). The terminal voltage is\n",
    "\n",
    "$$V = E_\\mathrm{OCV}(\\mathrm{SOC}_\\mathrm{surf})\n",
    "     - \\eta_{IR,1C}\\,\\frac{I_\\mathrm{int}}{I_{1C}}\n",
    "     - \\frac{2R_gT}{F}\\,\\operatorname{asinh}\\frac{I_\\mathrm{int}}{2J_0I_{1C}} ,$$\n",
    "\n",
    "where the surface state of charge belongs to a spherical diffusion particle with time constant\n",
    "$\\tau$: $\\partial s/\\partial t=\\tau^{-1}x^{-2}\\partial_x(x^2\\partial_x s)$ on $0\\le x\\le1$ with\n",
    "$\\tau^{-1}\\partial_x s=-I_\\mathrm{int}/(3Q)$ at the surface. The particle is divided into equal\n",
    "spherical shells (finite volumes).\n",
    "\n",
    "**Circuit.** The source forces $I_\\mathrm{app}$ through each cell-shunt pair, so\n",
    "$I_\\mathrm{int}=I_\\mathrm{app}+V/R_\\mathrm{shunt}+G_\\mathrm{short}(t)\\,V$. Together with the\n",
    "voltage equation this is an algebraic equation for $I_\\mathrm{int}$, solved by Newton's method.\n",
    "\n",
    "**Time integration.** OneSimulation's variable-step BDF2 and, for comparison, the adaptive\n",
    "Dormand-Prince Runge-Kutta 5(4) method. The shunt switching is an event on\n",
    "$\\mathrm{SOC}-0.2$; the integrator locates it, and the run continues from there with the shunt\n",
    "switched and a small first step.\n",
    "\n",
    "**Reference.** (i) Charge conservation: the particle average must equal\n",
    "$1-\\int I_\\mathrm{int}dt/Q$. (ii) Cell 2 carries the constant source current until it switches,\n",
    "so $t_2=0.8\\,Q/I_\\mathrm{app}$ (up to the leakage through $10^8\\,\\Omega$), and its surface state\n",
    "of charge has the exact series solution of a sphere with constant flux (Crank, *The Mathematics\n",
    "of Diffusion*). (iii) A bypassed cell relaxes to $V=-I_\\mathrm{app}R_\\mathrm{on}$. (iv) The\n",
    "published behaviour: the shunts fire near 4400 s and 5800 s at 0.5C and near 1350 s and 1450 s\n",
    "at 2C; without shunts cell 1 ends at a state of charge of about $-0.1$ and cell 2 at about 0.07."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from time import perf_counter\n",
    "\n",
    "import numpy as np\n",
    "from onesim.numerics.time import AdaptiveBDF, AdaptiveRungeKutta45, EventDefinition\n",
    "from onesim.simulation import smooth_step\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 circuit\n",
    "\n",
    "Capacity, short and shunts follow the published model; the open-circuit curve and the loss\n",
    "parameters are representative of a lithium-ion cell, with a voltage that collapses to 0 V at an\n",
    "empty cell and continues linearly below."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "capacity, one_c, ohmic_1c, exchange_ratio, diffusion_time = (\n",
    "    12.0 * 3600.0,\n",
    "    12.0,\n",
    "    0.02,\n",
    "    0.85,\n",
    "    1000.0,\n",
    ")\n",
    "shunt_off, shunt_on, threshold = 1.0e8, 1.0e8 * np.finfo(float).eps, 0.2\n",
    "plateau, slope, knee, tafel = 3.55, 0.6, 0.025, 2 * 8.314462618 * 298.15 / 96485.33212\n",
    "short = smooth_step(49.5, 50.5, low=0.0, high=0.5)\n",
    "open_circuit = lambda s: np.where(\n",
    "    s >= 0,\n",
    "    plateau + slope * s - plateau * np.exp(-np.maximum(s, 0) / knee),\n",
    "    (slope + plateau / knee) * s,\n",
    ")\n",
    "open_circuit_slope = lambda s: slope + plateau / knee * np.exp(-np.maximum(s, 0) / knee)\n",
    "losses = lambda current: ohmic_1c * current / one_c + tafel * np.arcsinh(\n",
    "    current / (2 * exchange_ratio * one_c)\n",
    ")\n",
    "loss_slope = lambda current: ohmic_1c / one_c + tafel / np.hypot(\n",
    "    1.0, current / (2 * exchange_ratio * one_c)\n",
    ") / (2 * exchange_ratio * one_c)\n",
    "\n",
    "\n",
    "def simulate(rate, shunts, end_time, solver, shells=20):\n",
    "    \"\"\"Discharge the string at the C-rate `rate` with or without shunts; history of both cells.\"\"\"\n",
    "    source, faces = rate * one_c, np.linspace(0.0, 1.0, shells + 1)\n",
    "    volume, link = np.diff(faces**3) / 3, faces[1:-1] ** 2 * shells / diffusion_time\n",
    "    diffusion = (\n",
    "        np.diag(link, 1)\n",
    "        + np.diag(link, -1)\n",
    "        - np.diag(np.r_[link, 0.0] + np.r_[0.0, link])\n",
    "    ) / volume[:, None]\n",
    "    lever, sink, bypassed = (\n",
    "        diffusion_time / (6 * capacity * shells),\n",
    "        np.eye(shells)[-1] / (3 * capacity * volume[-1]),\n",
    "        np.zeros(2, dtype=bool),\n",
    "    )\n",
    "    conductance = lambda time: shunts / np.where(\n",
    "        bypassed, shunt_on, shunt_off\n",
    "    ) + np.array([float(short(time)), 0.0])\n",
    "    surface = lambda state, current: state[:, -1] - lever * current\n",
    "\n",
    "    def current(time, state):\n",
    "        \"\"\"Internal currents of both cells: Newton solution of the circuit equation.\"\"\"\n",
    "        g, i = conductance(time), np.full(2, source)\n",
    "        for _ in range(100):\n",
    "            update = (\n",
    "                i - source - g * (open_circuit(surface(state, i)) - losses(i))\n",
    "            ) / (\n",
    "                1 + g * (open_circuit_slope(surface(state, i)) * lever + loss_slope(i))\n",
    "            )\n",
    "            i = i - update\n",
    "            if np.all(np.abs(update) <= 1e-13 * (1 + np.abs(i))):\n",
    "                break\n",
    "        return i\n",
    "\n",
    "    feedback = lambda time, state, i: (\n",
    "        conductance(time)\n",
    "        * open_circuit_slope(surface(state, i))\n",
    "        / (\n",
    "            1\n",
    "            + conductance(time)\n",
    "            * (open_circuit_slope(surface(state, i)) * lever + loss_slope(i))\n",
    "        )\n",
    "    )\n",
    "    rate_of_change = lambda time, y: (\n",
    "        y.reshape(2, shells) @ diffusion.T\n",
    "        - np.outer(current(time, y.reshape(2, shells)), sink)\n",
    "    ).ravel()\n",
    "    jacobian = lambda time, y: np.kron(np.eye(2), diffusion) - np.diag(\n",
    "        np.kron(\n",
    "            feedback(time, y.reshape(2, shells), current(time, y.reshape(2, shells))),\n",
    "            sink,\n",
    "        )\n",
    "    )\n",
    "    events = (\n",
    "        [\n",
    "            EventDefinition(\n",
    "                f\"shunt {cell + 1} on\",\n",
    "                lambda time, y, cell=cell: (\n",
    "                    -1.0\n",
    "                    if bypassed[cell]\n",
    "                    else 3 * y.reshape(2, shells)[cell] @ volume - threshold\n",
    "                ),\n",
    "                direction=-1,\n",
    "                terminal=True,\n",
    "            )\n",
    "            for cell in range(2)\n",
    "        ]\n",
    "        if shunts\n",
    "        else ()\n",
    "    )\n",
    "    options = {\"jacobian\": jacobian} if isinstance(solver, AdaptiveBDF) else {}\n",
    "    time, state, first_step, parts, fired, steps, start = (\n",
    "        0.0,\n",
    "        np.ones(2 * shells),\n",
    "        0.1,\n",
    "        [],\n",
    "        {},\n",
    "        0,\n",
    "        perf_counter(),\n",
    "    )\n",
    "    while time < end_time:\n",
    "        segment = solver.integrate(\n",
    "            rate_of_change,\n",
    "            state,\n",
    "            time,\n",
    "            end_time,\n",
    "            initial_step=first_step,\n",
    "            events=events,\n",
    "            **options,\n",
    "        )\n",
    "        states = np.array(segment.states).reshape(-1, 2, shells)\n",
    "        parts.append(\n",
    "            (\n",
    "                np.array(segment.times),\n",
    "                states,\n",
    "                np.array([current(t, s) for t, s in zip(segment.times, states)]),\n",
    "            )\n",
    "        )\n",
    "        for event in segment.events:\n",
    "            fired[event.event_id] = event.time\n",
    "            bypassed[int(event.event_id.split()[1]) - 1] = True\n",
    "        time, state, first_step, steps = (\n",
    "            segment.times[-1],\n",
    "            segment.states[-1],\n",
    "            1e-3,\n",
    "            steps + segment.accepted_steps,\n",
    "        )\n",
    "    times, states, currents = (np.concatenate(part) for part in zip(*parts))\n",
    "    voltage = open_circuit(states[:, :, -1] - lever * currents) - losses(currents)\n",
    "    return dict(\n",
    "        times=times,\n",
    "        soc=3 * states @ volume,\n",
    "        current=currents,\n",
    "        surface=states[:, :, -1] - lever * currents,\n",
    "        voltage=voltage,\n",
    "        events=fired,\n",
    "        steps=steps,\n",
    "        seconds=perf_counter() - start,\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation\n",
    "\n",
    "Both C-rates without and with shunts (BDF2, 20 shells), a Dormand-Prince reference at a\n",
    "tolerance of $10^{-10}$, and at 0.5C with shunts both integrators on 10, 20 and 40 shells and\n",
    "for tolerances from $10^{-4}$ to $10^{-7}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "methods = {\n",
    "    \"BDF2\": lambda tolerance: AdaptiveBDF(\n",
    "        order=2,\n",
    "        relative_tolerance=tolerance,\n",
    "        absolute_tolerance=tolerance,\n",
    "        maximum_step=25.0,\n",
    "    ),\n",
    "    \"RK45\": lambda tolerance: AdaptiveRungeKutta45(\n",
    "        relative_tolerance=tolerance, absolute_tolerance=tolerance, maximum_step=25.0\n",
    "    ),\n",
    "}\n",
    "cases = {\n",
    "    (0.5, False): 6700.0,\n",
    "    (0.5, True): 10000.0,\n",
    "    (2.0, False): 1700.0,\n",
    "    (2.0, True): 10000.0,\n",
    "}\n",
    "runs = {\n",
    "    case: simulate(*case, end, methods[\"BDF2\"](1e-6)) for case, end in cases.items()\n",
    "}\n",
    "reference = simulate(0.5, True, 10000.0, methods[\"RK45\"](1e-10))\n",
    "study = {\n",
    "    (shells, name, tolerance): simulate(0.5, True, 10000.0, method(tolerance), shells)\n",
    "    for name, method in methods.items()\n",
    "    for shells, tolerance in (\n",
    "        (10, 1e-6),\n",
    "        (20, 1e-6),\n",
    "        (40, 1e-6),\n",
    "        (20, 1e-4),\n",
    "        (20, 1e-5),\n",
    "        (20, 1e-7),\n",
    "    )\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison\n",
    "\n",
    "Before its shunt fires, cell 2 carries the constant source current. For a sphere with a constant\n",
    "surface flux the surface value lies below the average by\n",
    "$(I\\tau/3Q)\\,[\\,1/5-2\\sum_n e^{-\\lambda_n^2t/\\tau}/\\lambda_n^2\\,]$ with $\\tan\\lambda_n=\\lambda_n$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "roots = np.array(\n",
    "    [\n",
    "        brentq(lambda x: np.sin(x) - x * np.cos(x), n * np.pi, (n + 0.5) * np.pi)\n",
    "        for n in range(1, 400)\n",
    "    ]\n",
    ")\n",
    "exact_lag = lambda time: -(6.0 * diffusion_time / (3 * capacity)) * (\n",
    "    0.2\n",
    "    - 2 * np.sum(np.exp(-np.outer(time, roots**2) / diffusion_time) / roots**2, axis=1)\n",
    ")\n",
    "probe = np.linspace(20.0, 5700.0, 300)\n",
    "lag = {\n",
    "    shells: np.interp(\n",
    "        probe,\n",
    "        study[shells, \"BDF2\", 1e-6][\"times\"],\n",
    "        (study[shells, \"BDF2\", 1e-6][\"surface\"] - study[shells, \"BDF2\", 1e-6][\"soc\"])[\n",
    "            :, 1\n",
    "        ],\n",
    "    )\n",
    "    for shells in (10, 20, 40)\n",
    "}\n",
    "mesh_error = {\n",
    "    shells: np.abs(values - exact_lag(probe)).max() for shells, values in lag.items()\n",
    "}\n",
    "\n",
    "print(\n",
    "    \"C-rate  shunts   shunt 1 fires   shunt 2 fires   final state of charge (cell 1, cell 2)\"\n",
    ")\n",
    "for (rate, shunts), run in runs.items():\n",
    "    fired = \"\".join(\n",
    "        f\"{run['events'].get(name, np.nan):13.2f} s \"\n",
    "        for name in (\"shunt 1 on\", \"shunt 2 on\")\n",
    "    )\n",
    "    print(\n",
    "        f\"{rate:5.1f}   {'on ' if shunts else 'off'}   {fired}  {run['soc'][-1, 0]:+.4f}, {run['soc'][-1, 1]:+.4f}\"\n",
    "    )\n",
    "print(\n",
    "    \"published: about 4400 s and 5800 s at 0.5C, 1350 s and 1450 s at 2C; without shunts at 0.5C about -0.1 and 0.07\"\n",
    ")\n",
    "for rate in (0.5, 2.0):\n",
    "    run, source = runs[rate, True], rate * one_c\n",
    "    before = run[\"times\"] <= run[\"events\"][\"shunt 2 on\"]\n",
    "    switching = (\n",
    "        0.8 * capacity\n",
    "        - np.trapezoid(run[\"voltage\"][before, 1] / shunt_off, run[\"times\"][before])\n",
    "    ) / source\n",
    "    print(\n",
    "        f\"{rate}C: cell 2 switches at {run['events']['shunt 2 on']:.6f} s, closed form {switching:.6f} s; bypassed cells end at \"\n",
    "        f\"{run['voltage'][-1, 0]:.3e} V and {run['voltage'][-1, 1]:.3e} V, closed form {-source * shunt_on:.3e} V\"\n",
    "    )\n",
    "balance = max(\n",
    "    np.abs(\n",
    "        run[\"soc\"][-1]\n",
    "        - 1\n",
    "        + np.trapezoid(run[\"current\"], run[\"times\"], axis=0) / capacity\n",
    "    ).max()\n",
    "    for run in (*runs.values(), reference)\n",
    ")\n",
    "print(f\"charge balance, largest |SOC - (1 - ∫I dt / Q)| over all runs: {balance:.1e}\")\n",
    "print(\n",
    "    \"particle against the exact series, largest error of surface minus average: \"\n",
    "    + \", \".join(\n",
    "        f\"{error:.2e} ({shells} shells)\" for shells, error in mesh_error.items()\n",
    "    )\n",
    "    + f\"; observed order {np.log2(mesh_error[10] / mesh_error[20]):.2f} and {np.log2(mesh_error[20] / mesh_error[40]):.2f}\"\n",
    ")\n",
    "print(\n",
    "    \"shells  tolerance  method   accepted steps   run time [s]   |t1 - reference| [s]\"\n",
    ")\n",
    "for (shells, name, tolerance), run in sorted(study.items()):\n",
    "    print(\n",
    "        f\"{shells:6d}  {tolerance:9.0e}  {name:6s} {run['steps']:16d} {run['seconds']:14.1f} \"\n",
    "        f\"{abs(run['events']['shunt 1 on'] - reference['events']['shunt 1 on']):22.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The 0.5C case: terminal voltages and states of charge without and with shunts, and the bypass\n",
    "transient of cell 1. Below: the particle of cell 2 against the exact series, and the number of\n",
    "steps both integrators need when the particle mesh or the tolerance changes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "curves = lambda key: {\n",
    "    f\"cell {cell + 1}\"\n",
    "    + (\", shunts\" if shunts else \"\"): (\n",
    "        runs[0.5, shunts][\"times\"],\n",
    "        runs[0.5, shunts][key][:, cell],\n",
    "    )\n",
    "    for shunts in (False, True)\n",
    "    for cell in (0, 1)\n",
    "}\n",
    "dashed = {\"cell 1, shunts\": \"dashed\", \"cell 2, shunts\": \"dashed\"}\n",
    "colours = {\"cell 1\": 0, \"cell 2\": 1, \"cell 1, shunts\": 0, \"cell 2, shunts\": 1}\n",
    "fired = reference[\"events\"][\"shunt 1 on\"]\n",
    "near = lambda run: (run[\"times\"] > fired - 20) & (run[\"times\"] < fired + 300)\n",
    "shells_axis, tolerances = [10, 20, 40], [1e-4, 1e-5, 1e-6, 1e-7]\n",
    "fig = plots.figure(2, 3, size=(17, 10))\n",
    "plots.line(\n",
    "    y=curves(\"voltage\"),\n",
    "    colors=colours,\n",
    "    styles=dashed,\n",
    "    xlimits=(0, 7000),\n",
    "    ylimits=(-11, 5),\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"terminal voltage [V]\",\n",
    "    title=\"Cell voltages at 0.5C\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y=curves(\"soc\"),\n",
    "    colors=colours,\n",
    "    styles=dashed,\n",
    "    hlines={\"shunt threshold\": threshold},\n",
    "    xlimits=(0, 7000),\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"state of charge\",\n",
    "    title=\"State of charge at 0.5C\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        \"current, RK45 reference\": (\n",
    "            reference[\"times\"][near(reference)] - fired,\n",
    "            np.maximum(reference[\"current\"][near(reference), 0], 1e-2),\n",
    "        )\n",
    "    },\n",
    "    points={\n",
    "        \"current, BDF2 steps\": (\n",
    "            (runs[0.5, True][\"times\"] - fired)[near(runs[0.5, True])][::12],\n",
    "            np.maximum(runs[0.5, True][\"current\"][near(runs[0.5, True]), 0], 1e-2)[\n",
    "                ::12\n",
    "            ],\n",
    "        )\n",
    "    },\n",
    "    right={\n",
    "        \"surface state of charge\": (\n",
    "            reference[\"times\"][near(reference)] - fired,\n",
    "            reference[\"surface\"][near(reference), 0],\n",
    "        ),\n",
    "        \"average state of charge\": (\n",
    "            reference[\"times\"][near(reference)] - fired,\n",
    "            reference[\"soc\"][near(reference), 0],\n",
    "        ),\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    xlabel=\"time after shunt 1 fires [s]\",\n",
    "    ylabel=\"current of cell 1 [A]\",\n",
    "    right_label=\"state of charge\",\n",
    "    title=\"Bypass transient of cell 1\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    y={f\"{shells} shells\": (probe, 1e3 * values) for shells, values in lag.items()},\n",
    "    reference={\"exact series\": (probe, 1e3 * exact_lag(probe))},\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"surface - average state of charge [10⁻³]\",\n",
    "    title=\"Particle of cell 2 and the exact series\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.line(\n",
    "    shells_axis,\n",
    "    {\n",
    "        name: [study[shells, name, 1e-6][\"steps\"] for shells in shells_axis]\n",
    "        for name in methods\n",
    "    },\n",
    "    markers=True,\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"particle shells\",\n",
    "    ylabel=\"accepted steps over 10000 s\",\n",
    "    title=\"Explicit steps grow with the particle mesh\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[4],\n",
    ")\n",
    "plots.line(\n",
    "    tolerances,\n",
    "    {\n",
    "        name: [study[20, name, tolerance][\"steps\"] for tolerance in tolerances]\n",
    "        for name in methods\n",
    "    },\n",
    "    markers=True,\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"relative tolerance, 20 shells\",\n",
    "    ylabel=\"accepted steps over 10000 s\",\n",
    "    title=\"... and do not follow the tolerance\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[5],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the representative open-circuit curve by measured data and the near-short by a balancing\n",
    "resistor of a few ohms: the bypassed cell then drains slowly and a second event on rising state\n",
    "of charge can switch the shunt off again. Several cells in series only add blocks to the state\n",
    "vector. The step counts show the classic stiffness signature: the explicit method's step is set\n",
    "by the fastest diffusion mode, which grows with the square of the shell count, while BDF2 follows\n",
    "the accuracy of the slow dynamics."
   ]
  }
 ]
}
