{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Constant-current discharge of a lumped battery cell\n",
    "\n",
    "The cell is described by its state of charge $s$ and its temperature $T$. A constant current\n",
    "$I$ drains the charge capacity $Q$, the terminal voltage is the open-circuit voltage minus the\n",
    "ohmic drop, and the ohmic heat warms the cell against the cooling to the ambient:\n",
    "\n",
    "$$\\frac{ds}{dt}=-\\frac{I}{Q},\\qquad V=U_{oc}(s)-IR,\\qquad C\\,\\frac{dT}{dt}=I^2R-hA\\,(T-T_a) .$$\n",
    "\n",
    "**Reference.** With a linear open-circuit voltage and a constant resistance the solution is\n",
    "closed-form: the state of charge falls linearly, and the temperature approaches the steady rise\n",
    "$I^2R/(hA)$ exponentially with the time constant $C/(hA)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "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.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()\n",
    "\n",
    "capacity, current, resistance = 2.0 * 3600.0, 2.0, 0.05\n",
    "thermal_capacity, cooling, ambient = 60.0, 0.24, 298.15\n",
    "open_circuit = lambda soc: 3.2 + 0.8 * soc\n",
    "end_time = 0.8 * capacity / current"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The cell is a lumped model without spatial extent. It is discharged from 90 % to 10 % state of\n",
    "charge with the classical Runge-Kutta method; the outputs are collected in memory."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "cell = LumpedDomain()\n",
    "chemistry = BatteryChemistry(\n",
    "    \"linear-ocv-cell\",\n",
    "    open_circuit_voltage=lambda soc, temperature: open_circuit(soc),\n",
    "    internal_resistance=lambda soc, temperature: resistance,\n",
    ")\n",
    "model = LumpedBattery(\n",
    "    domain=cell.system,\n",
    "    chemistry=chemistry,\n",
    "    charge_capacity=capacity,\n",
    "    current=current,\n",
    "    thermal_capacity=thermal_capacity,\n",
    "    heat_transfer=cooling,\n",
    "    ambient_temperature=ambient,\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Constant-current discharge\",\n",
    "    geometry=cell,\n",
    "    physics=(model,),\n",
    "    initial_conditions=(\n",
    "        InitialValue(model.state_of_charge, 0.9),\n",
    "        InitialValue(model.temperature, ambient),\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=end_time,\n",
    "    time_step=end_time / 288,\n",
    "    output=Output(\n",
    "        fields=(model.state_of_charge, model.temperature, model.terminal_voltage),\n",
    "        interval=end_time / 288,\n",
    "        sink=record,\n",
    "    ),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "times = record.times\n",
    "soc, temperature, voltage = (\n",
    "    record.time_series(field)[1]\n",
    "    for field in (model.state_of_charge, model.temperature, model.terminal_voltage)\n",
    ")\n",
    "exact_soc = 0.9 - current * times / capacity\n",
    "exact_voltage = open_circuit(exact_soc) - current * resistance\n",
    "exact_temperature = ambient + current**2 * resistance / cooling * (\n",
    "    1 - np.exp(-times * cooling / thermal_capacity)\n",
    ")\n",
    "print(f\"largest deviation of the state of charge   {np.abs(soc - exact_soc).max():.1e}\")\n",
    "print(\n",
    "    f\"largest deviation of the terminal voltage  {np.abs(voltage - exact_voltage).max():.1e} V\"\n",
    ")\n",
    "print(\n",
    "    f\"largest deviation of the temperature       {np.abs(temperature - exact_temperature).max():.1e} K \"\n",
    "    f\"(rise {temperature[-1] - ambient:.3f} K)\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "fig = plots.figure(1, 2, size=(13, 4.8))\n",
    "plots.line(\n",
    "    times / 60,\n",
    "    {\"open-circuit voltage\": open_circuit(exact_soc)},\n",
    "    points={\"simulation\": (times[::8] / 60, voltage[::8])},\n",
    "    reference={\"closed-form terminal voltage\": exact_voltage},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"voltage [V]\",\n",
    "    title=\"Terminal voltage\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (times[::8] / 60, temperature[::8])},\n",
    "    reference={\"closed-form solution\": (times / 60, exact_temperature)},\n",
    "    hlines={\"steady temperature\": ambient + current**2 * resistance / cooling},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"cell temperature [K]\",\n",
    "    title=\"Cell temperature\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give the cell a measured open-circuit curve and a resistance that rises at low temperature, or\n",
    "replace the constant current by a drive cycle."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
