{
 "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": [
    "# Estimating a lumped battery model from a load cycle\n",
    "\n",
    "A lumped battery model needs no knowledge of the electrode design or materials. It\n",
    "describes the cell by a handful of parameters: the capacity $Q$, the open-circuit voltage\n",
    "$U_\\mathrm{OCV}(s)$ as a function of the state of charge $s$, an internal resistance $R$\n",
    "that collects ohmic, kinetic and transport losses, and one thermal mass with heat capacity\n",
    "$C_\\mathrm{th}$ that exchanges heat with the surroundings through the conductance $hA$:\n",
    "\n",
    "$$\\frac{ds}{dt}=-\\frac{I}{Q},\\qquad U=U_\\mathrm{OCV}(s)-R\\,I,\\qquad\n",
    "  C_\\mathrm{th}\\frac{dT}{dt}=R\\,I^2-hA\\,(T-T_\\infty).$$\n",
    "\n",
    "Over a load cycle the terminal voltage carries the information on $Q$ (through the drift\n",
    "of $U_\\mathrm{OCV}$) and on $R$ (through the jumps at every load change); the temperature\n",
    "carries the information on $C_\\mathrm{th}$ and $hA$ (rise rate and level).\n",
    "\n",
    "OneSimulation solves the model with `LumpedBattery` and the classical Runge-Kutta method.\n",
    "The `SimulationStudyService` turns it into a least-squares problem: `fit` varies the four\n",
    "parameters, runs the battery simulation for every trial point, forms the residuals of\n",
    "voltage and temperature divided by their noise levels and minimises their sum of squares\n",
    "with the Levenberg-Marquardt method. It returns the estimates with their linearised\n",
    "covariance in physical units.\n",
    "\n",
    "**Reference.** The data are synthetic: generated by the same model from the \"true\" values\n",
    "$Q=2.5$ Ah, $R=40$ mΩ, $C_\\mathrm{th}=45$ J/K, $hA=0.12$ W/K with normally distributed\n",
    "noise of 2 mV on the voltage and 0.05 K on the temperature. A correct estimation recovers\n",
    "them within the standard errors that this noise allows and leaves residuals of the size\n",
    "of the noise (D. Bernardi, E. Pawlikowski and J. Newman, *A general energy balance for\n",
    "battery systems*, J. Electrochem. Soc. 132, 5-12 (1985); G. L. Plett, *Battery Management\n",
    "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 BatteryChemistry, LumpedBattery\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\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 load cycle\n",
    "\n",
    "A cylindrical lithium-ion cell at 25 °C ambient, starting at 95 % state of charge. A\n",
    "ten-minute pattern of discharge at 0.5C to 2C, a short charge pulse (regenerative\n",
    "braking) and rests is repeated for one hour; voltage and temperature are sampled every\n",
    "10 s."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ambient, start, noise_voltage, noise_temperature = 298.15, 0.95, 2e-3, 0.05\n",
    "open_circuit = lambda s: 3.0 + 1.1 * s - 0.35 * s**2 + 0.05 * np.log(s / (1.0 - s))\n",
    "pattern = np.array(\n",
    "    [\n",
    "        (0, 1.25),\n",
    "        (120, 5.0),\n",
    "        (180, 2.5),\n",
    "        (300, -2.5),\n",
    "        (330, 0.0),\n",
    "        (390, 3.75),\n",
    "        (510, 0.0),\n",
    "    ]\n",
    ")\n",
    "load = lambda t: pattern[np.searchsorted(pattern[:, 0], t % 600.0, side=\"right\") - 1, 1]\n",
    "times = np.arange(0.0, 3601.0, 10.0)\n",
    "cell = LumpedDomain()\n",
    "print(\n",
    "    f\"charge drawn in one hour {np.mean([load(t) for t in np.arange(0.0, 3600.0)]):.3f} Ah, \"\n",
    "    f\"rms current {np.sqrt(np.mean([load(t) ** 2 for t in np.arange(0.0, 3600.0)])):.2f} A\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`cycle(values)` builds the battery simulation for one parameter set (capacity in Ah,\n",
    "resistance in mΩ, heat capacity in J/K, conductance in W/K); the study runs it with steps\n",
    "of 2 s and reads voltage and temperature at the sampling times."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cycle = lambda values: (\n",
    "    model := LumpedBattery(\n",
    "        domain=cell.system,\n",
    "        charge_capacity=3600.0 * values[\"capacity\"],\n",
    "        current=load,\n",
    "        thermal_capacity=values[\"heat_capacity\"],\n",
    "        heat_transfer=values[\"conductance\"],\n",
    "        ambient_temperature=ambient,\n",
    "        chemistry=BatteryChemistry(\n",
    "            \"lumped cell\",\n",
    "            open_circuit_voltage=lambda s, T: open_circuit(s),\n",
    "            internal_resistance=lambda s, T: 1e-3 * values[\"resistance\"],\n",
    "        ),\n",
    "    ),\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Load cycle\",\n",
    "            geometry=cell,\n",
    "            physics=(model,),\n",
    "            initial_conditions=(\n",
    "                InitialValue(model.state_of_charge, start),\n",
    "                InitialValue(model.temperature, ambient),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=LumpedMesh(cell),\n",
    "        numerics=Numerics(\n",
    "            spatial=LumpedParameters(), time_integrator=ClassicalRungeKutta4()\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "names = (\"capacity\", \"resistance\", \"heat_capacity\", \"conductance\")\n",
    "study = SimulationStudyService(\n",
    "    (\n",
    "        StudyParameter(\"capacity\", 1.5, 4.0),\n",
    "        StudyParameter(\"resistance\", 10.0, 100.0),\n",
    "        StudyParameter(\"heat_capacity\", 10.0, 150.0),\n",
    "        StudyParameter(\"conductance\", 0.02, 0.5),\n",
    "    ),\n",
    "    cycle,\n",
    "    lambda run: {\n",
    "        f\"{quantity}_{i}\": value\n",
    "        for quantity, field in (\n",
    "            (\"voltage\", run[0].terminal_voltage),\n",
    "            (\"temperature\", run[0].temperature),\n",
    "        )\n",
    "        for i, value in enumerate(np.interp(times, *run[1].field(field).time_series()))\n",
    "    },\n",
    "    solve=lambda built: (\n",
    "        built[0],\n",
    "        built[1].run(start_time=0.0, end_time=3600.0, time_step=2.0),\n",
    "    ),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Synthetic measurements\n",
    "\n",
    "The true parameters are run once and normally distributed noise is added (fixed seed)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "true = {\"capacity\": 2.5, \"resistance\": 40.0, \"heat_capacity\": 45.0, \"conductance\": 0.12}\n",
    "clean = study.sweep(combinations=[true]).runs[0].measurements\n",
    "rng = np.random.default_rng(2026)\n",
    "voltage = np.array([clean[f\"voltage_{i}\"] for i in range(times.size)]) + rng.normal(\n",
    "    0.0, noise_voltage, times.size\n",
    ")\n",
    "temperature = np.array(\n",
    "    [clean[f\"temperature_{i}\"] for i in range(times.size)]\n",
    ") + rng.normal(0.0, noise_temperature, times.size)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Least-squares fit\n",
    "\n",
    "Residuals of voltage and temperature, each divided by its noise level; Levenberg-Marquardt\n",
    "from a start far from the truth: 2.0 Ah, 70 mΩ, 90 J/K, 0.25 W/K."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "initial = {\n",
    "    \"capacity\": 2.0,\n",
    "    \"resistance\": 70.0,\n",
    "    \"heat_capacity\": 90.0,\n",
    "    \"conductance\": 0.25,\n",
    "}\n",
    "fit = study.fit(\n",
    "    residuals=lambda m: np.r_[\n",
    "        [(m[f\"voltage_{i}\"] - voltage[i]) / noise_voltage for i in range(times.size)],\n",
    "        [\n",
    "            (m[f\"temperature_{i}\"] - temperature[i]) / noise_temperature\n",
    "            for i in range(times.size)\n",
    "        ],\n",
    "    ],\n",
    "    start=initial,\n",
    "    method=\"levenberg_marquardt\",\n",
    "    maximum_runs=150,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the true values"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"{fit.run_count} battery simulations (including the data run), converged: {fit.converged}, rank {fit.rank} of {len(names)}, \"\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 zip(names, (\"Ah\", \"mΩ\", \"J/K\", \"W/K\")):\n",
    "    print(\n",
    "        f\"{name:14s} {fit.parameters[name]:10.4f} ± {fit.standard_errors[name]:.4f} {unit:3s} {true[name]:9.3f}   \"\n",
    "        f\"{(fit.parameters[name] - true[name]) / fit.standard_errors[name]:+6.2f} σ\"\n",
    "    )\n",
    "print(\n",
    "    f\"correlation capacity-resistance {fit.covariance[0, 1] / np.sqrt(fit.covariance[0, 0] * fit.covariance[1, 1]):+.2f}, \"\n",
    "    f\"heat capacity-conductance {fit.covariance[2, 3] / np.sqrt(fit.covariance[2, 2] * fit.covariance[3, 3]):+.2f}\"\n",
    ")\n",
    "print(\n",
    "    f\"rms residuals: voltage {1e3 * noise_voltage * np.sqrt(np.mean(fit.residuals[:times.size] ** 2)):.2f} mV (noise 2 mV), \"\n",
    "    f\"temperature {noise_temperature * np.sqrt(np.mean(fit.residuals[times.size:] ** 2)):.3f} K (noise 0.05 K)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Terminal voltage and temperature: data, fitted model and the model at the start values."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "final, first = (\n",
    "    study.sweep(combinations=[dict(values)]).runs[0].measurements\n",
    "    for values in (fit.parameters, initial)\n",
    ")\n",
    "series = lambda m, quantity: np.array([m[f\"{quantity}_{i}\"] for i in range(times.size)])\n",
    "fig = plots.figure(1, 2, size=(15, 5))\n",
    "plots.line(\n",
    "    times / 60,\n",
    "    {\"fitted model\": series(final, \"voltage\")},\n",
    "    points={\"data\": (times[::3] / 60, voltage[::3])},\n",
    "    reference={\"start values\": series(first, \"voltage\")},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"terminal voltage [V]\",\n",
    "    title=\"Terminal voltage over the load cycle\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    times / 60,\n",
    "    {\"fitted model\": series(final, \"temperature\") - 273.15},\n",
    "    points={\"data\": (times[::3] / 60, temperature[::3] - 273.15)},\n",
    "    reference={\"start values\": series(first, \"temperature\") - 273.15},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"cell temperature [°C]\",\n",
    "    title=\"Cell temperature\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Fit only the voltage and the thermal parameters become unidentifiable: the fit reports a\n",
    "reduced rank and no covariance. Let the resistance depend on temperature through an\n",
    "Arrhenius factor and add its activation energy as a fifth parameter; the electrical and\n",
    "thermal parts then couple, and the correlations in the covariance show how well the data\n",
    "separate them. Measured cycler data replace the synthetic `voltage` and `temperature`\n",
    "arrays directly."
   ]
  }
 ]
}
