{
 "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": [
    "# Equivalent-circuit model of a nickel-metal hydride cell\n",
    "\n",
    "Equivalent-circuit models describe a cell by what is measured at its terminals. Here a voltage\n",
    "source $U_\\mathrm{oc}(s)$ that depends on the state of charge $s$, a series resistance $R_0$ and\n",
    "one RC branch for the charge-transfer and diffusion polarisation $u_1$:\n",
    "\n",
    "$$Q\\frac{ds}{dt}=-I-I_\\mathrm{sd}(T),\\qquad C_1\\frac{du_1}{dt}=I-\\frac{u_1}{R_1},\\qquad V=U_\\mathrm{oc}(s)-R_0I-u_1 .$$\n",
    "\n",
    "NiMH cells lose charge on the shelf through internal side reactions; the self-discharge current\n",
    "follows an Arrhenius law $I_\\mathrm{sd}=k_\\mathrm{ref}\\,Q\\,\\exp\\!\\big[-\\tfrac{E_a}{R}\\big(\\tfrac1T-\\tfrac1{T_\\mathrm{ref}}\\big)\\big]$.\n",
    "The open-circuit curve is a Nernst-type curve around 1.28 V.\n",
    "\n",
    "In OneSimulation the cell is a lumped battery (state of charge, voltage source, series resistance,\n",
    "self-discharge as internal charge loss) and the RC branch is an electrical circuit driven by the\n",
    "same current; the branch voltage enters the cell as an additional voltage drop. The small-signal\n",
    "impedance of the same parameters is a battery impedance model.\n",
    "\n",
    "**Reference.** The closed-form solution of the linear circuit: for a piecewise constant current\n",
    "with steps $\\Delta I_k$ at $t_k$, $u_1(t)=\\sum_k\\Delta I_kR_1\\big(1-e^{-(t-t_k)/\\tau_1}\\big)$ with\n",
    "$\\tau_1=R_1C_1$; the impedance $Z(\\omega)=R_0+R_1/(1+i\\omega\\tau_1)$; and the linear loss of state of\n",
    "charge $I_\\mathrm{sd}t/Q$ in storage. Model structure and parameter ranges as in G. L. Plett,\n",
    "*Battery Management Systems, Vol. I: Battery Modeling* (Artech House, 2015)."
   ]
  },
  {
   "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 ClassicalRungeKutta4\n",
    "from onesim.physics.chemistry import (\n",
    "    BatteryChemistry,\n",
    "    BatteryImpedance,\n",
    "    BatteryRelaxationBranch,\n",
    "    LumpedBattery,\n",
    ")\n",
    "from onesim.physics.systems import (\n",
    "    Circuit,\n",
    "    CircuitCapacitor,\n",
    "    CircuitCurrentSource,\n",
    "    CircuitResistor,\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",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cell parameters\n",
    "\n",
    "A 2.5 Ah cell; self-discharge of 20 % per month at 25 °C with an activation energy of 35 kJ/mol."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "capacity, r0, r1, tau1 = 2.5 * 3600, 0.020, 0.015, 40.0\n",
    "k_ref, activation, gas = 0.20 / (30 * 86400), 35e3, 8.314462618\n",
    "open_circuit = lambda s: 1.28 + 0.08 * (s - 0.5) + 0.012 * np.log(s / (1 - s))\n",
    "self_discharge = (\n",
    "    lambda T: k_ref * capacity * np.exp(-activation / gas * (1 / T - 1 / 298.15))\n",
    ")\n",
    "chemistry = BatteryChemistry(\n",
    "    \"nimh\",\n",
    "    open_circuit_voltage=lambda s, T: open_circuit(s),\n",
    "    internal_resistance=lambda s, T: r0,\n",
    ")\n",
    "impedance = BatteryImpedance(\n",
    "    series_resistance=r0,\n",
    "    branches=(BatteryRelaxationBranch(resistance=r1, relaxation_time=tau1),),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Pulse discharge\n",
    "\n",
    "From 90 % state of charge: 10 min at 1C, 10 min rest, 5 min at 2C, 15 min rest, 2 min of 1C charge\n",
    "and 8 min rest, at 25 °C. The circuit is integrated with the trapezoidal rule at 0.1 s steps."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "steps = np.array(\n",
    "    [(0, 2.5), (600, 0.0), (1200, 5.0), (1500, 0.0), (2400, -2.5), (2520, 0.0)]\n",
    ")\n",
    "load = lambda t: steps[np.searchsorted(steps[:, 0], t, side=\"right\") - 1, 1]\n",
    "times = np.arange(0.0, 3001.0, 1.0)\n",
    "branch = Circuit(\n",
    "    components=(\n",
    "        CircuitCurrentSource(name=\"load\", positive=\"0\", negative=\"rc\", current=load),\n",
    "        CircuitResistor(name=\"r1\", positive=\"rc\", negative=\"0\", resistance=r1),\n",
    "        CircuitCapacitor(\n",
    "            name=\"c1\",\n",
    "            positive=\"rc\",\n",
    "            negative=\"0\",\n",
    "            capacitance=tau1 / r1,\n",
    "            initial_voltage=0.0,\n",
    "        ),\n",
    "    )\n",
    ").solve(times=times, max_step=0.1)\n",
    "polarisation = branch.voltages[\"rc\"]\n",
    "\n",
    "cell = LumpedDomain()\n",
    "model = LumpedBattery(\n",
    "    domain=cell.system,\n",
    "    chemistry=chemistry,\n",
    "    charge_capacity=capacity,\n",
    "    current=load,\n",
    "    thermal_capacity=40.0,\n",
    "    heat_transfer=0.05,\n",
    "    ambient_temperature=298.15,\n",
    "    effects={\n",
    "        \"internal_charge_loss\": self_discharge(298.15),\n",
    "        \"additional_voltage_drop\": lambda t: np.interp(t, times, polarisation),\n",
    "    },\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"NiMH pulse test\",\n",
    "    geometry=cell,\n",
    "    physics=(model,),\n",
    "    initial_conditions=(\n",
    "        InitialValue(model.state_of_charge, 0.9),\n",
    "        InitialValue(model.temperature, 298.15),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(spatial=LumpedParameters(), time_integrator=ClassicalRungeKutta4())\n",
    "record = MemoryOutputSink()\n",
    "Simulation(problem=problem, mesh=LumpedMesh(cell), numerics=numerics).run(\n",
    "    start_time=0.0,\n",
    "    end_time=3000.0,\n",
    "    time_step=1.0,\n",
    "    output=Output(\n",
    "        fields=(model.state_of_charge, model.terminal_voltage, model.temperature),\n",
    "        interval=1.0,\n",
    "        sink=record,\n",
    "    ),\n",
    ")\n",
    "soc, voltage, temperature = (\n",
    "    record.time_series(field)[1]\n",
    "    for field in (model.state_of_charge, model.terminal_voltage, model.temperature)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Impedance spectrum and storage\n",
    "\n",
    "The circuit is driven by a sinusoidal current of 0.1 A at five frequencies, starting on the\n",
    "periodic solution; amplitude and phase of the response give the impedance. The storage test keeps\n",
    "the cell at rest for 30 days at 0, 25 and 45 °C."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "frequencies = np.array([1e-3, 4e-3, 1e-2, 4e-2, 1e-1])\n",
    "sine = {\n",
    "    f: Circuit(\n",
    "        components=(\n",
    "            CircuitCurrentSource(\n",
    "                name=\"load\",\n",
    "                positive=\"0\",\n",
    "                negative=\"rc\",\n",
    "                current=lambda t, f=f: 0.1 * np.cos(2 * np.pi * f * t),\n",
    "            ),\n",
    "            CircuitResistor(name=\"r1\", positive=\"rc\", negative=\"0\", resistance=r1),\n",
    "            CircuitCapacitor(\n",
    "                name=\"c1\",\n",
    "                positive=\"rc\",\n",
    "                negative=\"0\",\n",
    "                capacitance=tau1 / r1,\n",
    "                initial_voltage=(0.1 * r1 / (1 + 2j * np.pi * f * tau1)).real,\n",
    "            ),\n",
    "        )\n",
    "    ).solve(times=np.linspace(0, 1 / f, 401), max_step=1 / (400 * f))\n",
    "    for f in frequencies\n",
    "}\n",
    "measured = {\n",
    "    f: r0\n",
    "    + 2\n",
    "    * np.mean(run.voltages[\"rc\"][:-1] * np.exp(-2j * np.pi * f * run.times[:-1]))\n",
    "    / 0.1\n",
    "    for f, run in sine.items()\n",
    "}\n",
    "storage = {}\n",
    "for celsius in (0, 25, 45):\n",
    "    shelf = LumpedBattery(\n",
    "        domain=cell.system,\n",
    "        chemistry=chemistry,\n",
    "        charge_capacity=capacity,\n",
    "        current=0.0,\n",
    "        thermal_capacity=40.0,\n",
    "        heat_transfer=0.05,\n",
    "        ambient_temperature=273.15 + celsius,\n",
    "        effects={\"internal_charge_loss\": self_discharge(273.15 + celsius)},\n",
    "    )\n",
    "    shelf_record = MemoryOutputSink()\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"NiMH storage\",\n",
    "            geometry=cell,\n",
    "            physics=(shelf,),\n",
    "            initial_conditions=(\n",
    "                InitialValue(shelf.state_of_charge, 0.9),\n",
    "                InitialValue(shelf.temperature, 273.15 + celsius),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=LumpedMesh(cell),\n",
    "        numerics=numerics,\n",
    "    ).run(\n",
    "        start_time=0.0,\n",
    "        end_time=30 * 86400.0,\n",
    "        time_step=3600.0,\n",
    "        output=Output(\n",
    "            fields=(shelf.state_of_charge, shelf.terminal_voltage),\n",
    "            interval=86400.0,\n",
    "            sink=shelf_record,\n",
    "        ),\n",
    "    )\n",
    "    storage[celsius] = (\n",
    "        shelf_record.times,\n",
    "        shelf_record.time_series(shelf.state_of_charge)[1],\n",
    "        shelf_record.time_series(shelf.terminal_voltage)[1],\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "exact_rc = sum(\n",
    "    np.where(times >= t_k, dI * r1 * (1 - np.exp(-(times - t_k) / tau1)), 0.0)\n",
    "    for t_k, dI in zip(steps[:, 0], np.diff(np.r_[0.0, steps[:, 1]]))\n",
    ")\n",
    "charge = np.r_[0.0, np.cumsum([load(t) for t in times[:-1]])]\n",
    "exact_soc = 0.9 - (charge + self_discharge(298.15) * times) / capacity\n",
    "exact_voltage = (\n",
    "    open_circuit(exact_soc) - r0 * np.array([load(t) for t in times]) - exact_rc\n",
    ")\n",
    "print(\n",
    "    f\"branch voltage against the closed form: largest deviation {1e3 * np.abs(polarisation - exact_rc).max():.3f} mV \"\n",
    "    f\"(peak {1e3 * polarisation.max():.1f} mV); KCL residual {np.abs(branch.kcl_residual).max():.1e} A\"\n",
    ")\n",
    "print(\n",
    "    f\"state of charge against coulomb counting: {np.abs(soc - exact_soc[record.times.astype(int)]).max():.1e}; \"\n",
    "    f\"terminal voltage against the closed form: {1e3 * np.abs(voltage - exact_voltage[record.times.astype(int)]).max():.3f} mV\"\n",
    ")\n",
    "print(f\"temperature rise in the 2C pulse {temperature.max() - 298.15:.3f} K\")\n",
    "print(\n",
    "    \"frequency [Hz]   Z from the circuit [mΩ]      Z of the impedance model [mΩ]   |difference| [mΩ]\"\n",
    ")\n",
    "for f, z in measured.items():\n",
    "    exact = impedance.spectrum(f)\n",
    "    print(\n",
    "        f\"{f:14.3g}   {1e3 * z.real:8.3f} {1e3 * z.imag:+8.3f}i       {1e3 * exact.real:8.3f} {1e3 * exact.imag:+8.3f}i   {1e3 * abs(z - exact):12.2e}\"\n",
    "    )\n",
    "for celsius, (t, s, v) in storage.items():\n",
    "    print(\n",
    "        f\"storage at {celsius:2d} °C: state of charge after 30 days {s[-1]:.4f}, closed form {0.9 - self_discharge(273.15 + celsius) * t[-1] / capacity:.4f}, \"\n",
    "        f\"open-circuit voltage {v[0]:.4f} -> {v[-1]:.4f} V\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(2, 2, size=(14, 10))\n",
    "plots.line(\n",
    "    times / 60,\n",
    "    {\"simulation\": voltage},\n",
    "    reference={\"closed form\": exact_voltage},\n",
    "    right={\"current [A]\": np.array([load(t) for t in times])},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"terminal voltage [V]\",\n",
    "    right_label=\"current [A]\",\n",
    "    title=\"Pulse test at 25 °C\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    times / 60,\n",
    "    {\"circuit\": 1e3 * polarisation},\n",
    "    reference={\"closed form\": 1e3 * exact_rc},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"RC-branch voltage u₁ [mV]\",\n",
    "    title=\"Polarisation of the RC branch\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "spectrum = impedance.spectrum(np.geomspace(1e-4, 10, 300))\n",
    "plots.line(\n",
    "    1e3 * spectrum.real,\n",
    "    {\"impedance model\": -1e3 * spectrum.imag},\n",
    "    points={\n",
    "        \"time-domain circuit\": (\n",
    "            1e3 * np.array([z.real for z in measured.values()]),\n",
    "            -1e3 * np.array([z.imag for z in measured.values()]),\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"Re Z [mΩ]\",\n",
    "    ylabel=\"-Im Z [mΩ]\",\n",
    "    title=\"Impedance (Nyquist)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"{celsius} °C\": (t[::2] / 86400, s[::2])\n",
    "        for celsius, (t, s, v) in storage.items()\n",
    "    },\n",
    "    reference={\n",
    "        f\"{celsius} °C\": (\n",
    "            t / 86400,\n",
    "            0.9 - self_discharge(273.15 + celsius) * t / capacity,\n",
    "        )\n",
    "        for celsius, (t, s, v) in storage.items()\n",
    "    },\n",
    "    xlabel=\"storage time [days]\",\n",
    "    ylabel=\"state of charge\",\n",
    "    title=\"Self-discharge on the shelf (dashed: closed form)\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a second RC branch for the slow diffusion, let the self-discharge depend on the state of\n",
    "charge, or fit $R_0$, $R_1$ and $\\tau_1$ to a measured spectrum with the impedance model."
   ]
  }
 ]
}
