{
 "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": [
    "# Identifying an equivalent-circuit battery model from a pulse test\n",
    "\n",
    "Equivalent-circuit models describe a battery cell without any knowledge of its\n",
    "internal chemistry: a voltage source for the open-circuit voltage $U_\\mathrm{OCV}(s)$\n",
    "as a function of the state of charge $s$, a series resistance $R_0$ for the\n",
    "instantaneous (ohmic) response, and resistor-capacitor branches for the slower\n",
    "polarisation. With one branch,\n",
    "\n",
    "$$U=U_\\mathrm{OCV}(s)-R_0\\,I-u_1,\\qquad\n",
    "  \\frac{du_1}{dt}=\\frac{I}{C_1}-\\frac{u_1}{R_1C_1},\\qquad\n",
    "  \\frac{ds}{dt}=-\\frac{I}{Q},$$\n",
    "\n",
    "with the current $I$ positive on discharge, the capacity $Q$ and the relaxation time\n",
    "$\\tau_1=R_1C_1$. A pulse test (current pulses with rests in between) separates the\n",
    "parameters: the voltage jumps at the pulse edges give $R_0$, the slow relaxation after\n",
    "them $R_1$ and $\\tau_1$.\n",
    "\n",
    "OneSimulation solves the circuit (voltage source, $R_0$, the $R_1C_1$ branch, current\n",
    "load) with its circuit solver. The `SimulationStudyService` turns it into a least-squares\n",
    "problem: `fit` runs the circuit for trial values of $(R_0,R_1,\\tau_1)$, forms the voltage\n",
    "residuals divided by the noise level and minimises their sum of squares with the\n",
    "Levenberg-Marquardt method. It returns the estimates with their linearised covariance in\n",
    "physical units.\n",
    "\n",
    "**Reference.** G. L. Plett, *Battery Management Systems, Vol. I: Battery Modeling*,\n",
    "Artech House 2015, ch. 2; the pulse test follows the hybrid pulse power\n",
    "characterisation idea of the *FreedomCAR Battery Test Manual* (INL 2003). The data are\n",
    "synthetic: generated by the same circuit from the \"true\" values $R_0=15$ mΩ,\n",
    "$R_1=10$ mΩ, $\\tau_1=30$ s with normally distributed noise of 1 mV. A correct\n",
    "identification recovers these values within the uncertainty the noise allows and\n",
    "leaves residuals of the size of the noise."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.physics.systems import (\n",
    "    Circuit,\n",
    "    CircuitCapacitor,\n",
    "    CircuitCurrentSource,\n",
    "    CircuitResistor,\n",
    "    CircuitVoltageSource,\n",
    ")\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": [
    "## Cell and pulse test\n",
    "\n",
    "A 3 Ah cell, starting at 80 % state of charge. The test applies a 10 s discharge pulse\n",
    "at 2C (6 A), 40 s rest, a 10 s charge pulse at 1.5C, 40 s rest, then the same at a\n",
    "lower state of charge after a 300 s discharge at 1C; the voltage is sampled every\n",
    "second. The open-circuit voltage curve is taken as known (measured beforehand)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "capacity, start, noise = 3.0 * 3600.0, 0.80, 1e-3\n",
    "open_circuit = lambda s: 3.45 + 0.55 * s + 0.08 * np.log(s / (1.0 - s)) / 4.0\n",
    "steps = np.array(\n",
    "    [\n",
    "        (0, 6.0),\n",
    "        (10, 0.0),\n",
    "        (50, -4.5),\n",
    "        (60, 0.0),\n",
    "        (100, 3.0),\n",
    "        (400, 0.0),\n",
    "        (500, 6.0),\n",
    "        (510, 0.0),\n",
    "        (550, -4.5),\n",
    "        (560, 0.0),\n",
    "    ]\n",
    ")\n",
    "load = lambda t: steps[np.searchsorted(steps[:, 0], t, side=\"right\") - 1, 1]\n",
    "times = np.arange(0.0, 661.0, 1.0)\n",
    "state = start - np.r_[0.0, np.cumsum([load(t) for t in times[:-1]])] / capacity\n",
    "print(\n",
    "    f\"state of charge from {state[0]:.3f} to {state[-1]:.3f}, open-circuit voltage from {open_circuit(state[0]):.4f} V to {open_circuit(state[-1]):.4f} V\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Circuit model\n",
    "\n",
    "`pulse_test(values)` builds the circuit for one parameter set; the voltage source\n",
    "follows the open-circuit voltage along the coulomb-counted state of charge."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "pulse_test = lambda values: Circuit(\n",
    "    components=(\n",
    "        CircuitVoltageSource(\n",
    "            name=\"ocv\",\n",
    "            positive=\"p\",\n",
    "            negative=\"0\",\n",
    "            voltage=lambda t: open_circuit(np.interp(t, times, state)),\n",
    "        ),\n",
    "        CircuitResistor(\n",
    "            name=\"r0\", positive=\"p\", negative=\"a\", resistance=1e-3 * values[\"r0\"]\n",
    "        ),\n",
    "        CircuitResistor(\n",
    "            name=\"r1\", positive=\"a\", negative=\"t\", resistance=1e-3 * values[\"r1\"]\n",
    "        ),\n",
    "        CircuitCapacitor(\n",
    "            name=\"c1\",\n",
    "            positive=\"a\",\n",
    "            negative=\"t\",\n",
    "            capacitance=values[\"tau1\"] / (1e-3 * values[\"r1\"]),\n",
    "            initial_voltage=0.0,\n",
    "        ),\n",
    "        CircuitCurrentSource(name=\"load\", positive=\"t\", negative=\"0\", current=load),\n",
    "    )\n",
    ")\n",
    "study = SimulationStudyService(\n",
    "    (\n",
    "        StudyParameter(\"r0\", 1.0, 50.0),\n",
    "        StudyParameter(\"r1\", 1.0, 50.0),\n",
    "        StudyParameter(\"tau1\", 2.0, 200.0),\n",
    "    ),\n",
    "    pulse_test,\n",
    "    lambda circuit: {f\"u_{i}\": u for i, u in enumerate(circuit.voltages[\"t\"])},\n",
    "    solve=lambda circuit: circuit.solve(times=times, max_step=0.25),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Synthetic measurements\n",
    "\n",
    "The true circuit is run once and normally distributed noise of 1 mV is added (fixed seed)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "true = {\"r0\": 15.0, \"r1\": 10.0, \"tau1\": 30.0}\n",
    "rng = np.random.default_rng(2026)\n",
    "clean = study.sweep(combinations=[true]).runs[0].measurements\n",
    "data = np.array([clean[f\"u_{i}\"] for i in range(times.size)]) + rng.normal(\n",
    "    0.0, noise, times.size\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Identification\n",
    "\n",
    "Bounds: resistances between 1 and 50 mΩ, relaxation time between 2 and 200 s.\n",
    "Levenberg-Marquardt starts at $R_0=30$ mΩ, $R_1=4$ mΩ, $\\tau_1=80$ s."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "start_values = {\"r0\": 30.0, \"r1\": 4.0, \"tau1\": 80.0}\n",
    "fit = study.fit(\n",
    "    residuals=lambda m: np.array(\n",
    "        [(m[f\"u_{i}\"] - data[i]) / noise for i in range(times.size)]\n",
    "    ),\n",
    "    start=start_values,\n",
    "    method=\"levenberg_marquardt\",\n",
    "    maximum_runs=100,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the true values\n",
    "\n",
    "Standard errors from the linearised covariance, scaled with the residual variance."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"{fit.run_count} circuit simulations (including the data run), converged: {fit.converged}, rank {fit.rank}, \"\n",
    "    f\"χ² = {fit.residuals @ fit.residuals:.1f} for {fit.degrees_of_freedom} degrees of freedom\"\n",
    ")\n",
    "print(\"parameter   estimate ± standard error    true    deviation\")\n",
    "for name, unit in ((\"r0\", \"mΩ\"), (\"r1\", \"mΩ\"), (\"tau1\", \"s\")):\n",
    "    print(\n",
    "        f\"{name:8s} {fit.parameters[name]:10.4f} ± {fit.standard_errors[name]:.4f} {unit:2s} {true[name]:8.2f}   \"\n",
    "        f\"{(fit.parameters[name] - true[name]) / fit.standard_errors[name]:+6.2f} σ\"\n",
    "    )\n",
    "correlation = fit.covariance / np.sqrt(\n",
    "    np.outer(np.diag(fit.covariance), np.diag(fit.covariance))\n",
    ")\n",
    "print(\n",
    "    f\"correlations: R0-R1 {correlation[0, 1]:+.2f}, R0-τ1 {correlation[0, 2]:+.2f}, R1-τ1 {correlation[1, 2]:+.2f}; \"\n",
    "    f\"rms voltage residual {1e3 * noise * np.sqrt(np.mean(fit.residuals ** 2)):.3f} mV (noise {1e3 * noise:.1f} mV)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The measured and fitted terminal voltage with the current profile; a close-up of one\n",
    "pulse, where the instantaneous jump ($R_0$) and the relaxation ($R_1$, $\\tau_1$)\n",
    "separate; and the residuals (dotted: ± the noise level)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fitted, first = (\n",
    "    np.array([run.measurements[f\"u_{i}\"] for i in range(times.size)])\n",
    "    for run in study.sweep(combinations=[dict(fit.parameters), start_values]).runs\n",
    ")\n",
    "fig = plots.figure(1, 3, size=(17, 5))\n",
    "plots.line(\n",
    "    times / 60,\n",
    "    {\"fitted model\": fitted},\n",
    "    points={\"pulse-test data\": (times[::4] / 60, data[::4])},\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] (discharge > 0)\",\n",
    "    title=\"Pulse test\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "window = (times >= 490) & (times <= 600)\n",
    "plots.line(\n",
    "    times[window],\n",
    "    {\"fitted model\": fitted[window]},\n",
    "    points={\"pulse-test data\": (times[window], data[window])},\n",
    "    reference={\"start values\": first[window]},\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"terminal voltage [V]\",\n",
    "    title=\"Second pulse pair, close-up\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"data - model\": (times / 60, 1e3 * (data - fitted))},\n",
    "    hlines=[1e3 * noise, -1e3 * noise],\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"voltage residual [mV]\",\n",
    "    title=\"Residuals\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a second RC branch with a longer relaxation time and refit: with these data its\n",
    "parameters stay poorly determined, which the covariance shows at once. Make the\n",
    "resistances functions of the state of charge, or fit the open-circuit voltage curve as\n",
    "well from a slow (C/20) discharge. Real cycler data replace the synthetic `data`\n",
    "array directly."
   ]
  }
 ]
}
