{
 "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": [
    "# Monitoring a lithium-ion cell over a hybrid-vehicle drive cycle\n",
    "\n",
    "In a hybrid vehicle the battery supplies short bursts of power for acceleration and takes back\n",
    "energy during regenerative braking, while the engine keeps the state of charge in a narrow window.\n",
    "The cell sees pulses of several C in both directions. Besides voltage and state of charge, a\n",
    "battery management system cares about quantities that are only visible inside a physical model:\n",
    "the salt concentration in the electrolyte, and the potential of the negative electrode against\n",
    "lithium, $\\phi_s-\\phi_e$, at the separator. During fast charging pulses this potential drops; when\n",
    "it falls below 0 V, metallic lithium can plate on the graphite.\n",
    "\n",
    "The cell is the Doyle-Fuller-Newman model of the discharge-rest-charge example. The current profile\n",
    "is a synthetic charge-sustaining microcycle of 400 s: idle, acceleration bursts of up to 2.5C,\n",
    "cruising and regenerative braking pulses of up to 2C, then 65 s of engine charging whose current\n",
    "(about 2.6C) is set so that the net charge of the microcycle is zero. The microcycle is repeated\n",
    "three times and followed by 30 min of rest.\n",
    "\n",
    "**Reference.** Cell parameters of Chen et al., *J. Electrochem. Soc.* 167 (2020) 080534 (LG M50,\n",
    "5 Ah); model of Doyle, Fuller and Newman, *J. Electrochem. Soc.* 140 (1993) 1526. Checks: (i) the\n",
    "state of charge from coulomb counting, $s(t)=s_0-\\int I\\,dt/Q$, equals the mean stoichiometry of\n",
    "both electrodes; (ii) after a cycle with zero net charge both electrodes return to their initial\n",
    "mean stoichiometry; (iii) during the final rest the voltage relaxes to the open-circuit voltage of\n",
    "the initial state."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.physics.chemistry import (\n",
    "    BatteryElectrodeLayer,\n",
    "    BatteryElectrolyteLayer,\n",
    "    PorousElectrodeBattery,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cell at 60 % state of charge"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "faraday, area, soc0 = 96485.33212, 0.1027, 0.6\n",
    "negative_ocp = lambda x, T: (\n",
    "    1.9793 * np.exp(-39.3631 * x)\n",
    "    + 0.2482\n",
    "    - 0.0909 * np.tanh(29.8538 * (x - 0.1234))\n",
    "    - 0.04478 * np.tanh(14.9159 * (x - 0.2769))\n",
    "    - 0.0205 * np.tanh(30.4444 * (x - 0.6103))\n",
    ")\n",
    "positive_ocp = lambda y, T: (\n",
    "    4.4875\n",
    "    - 0.8090 * y\n",
    "    - 0.0428 * np.tanh(18.5138 * (y - 0.5542))\n",
    "    - 17.7326 * np.tanh(15.7890 * (y - 0.3117))\n",
    "    + 17.5842 * np.tanh(15.9308 * (y - 0.3120))\n",
    ")\n",
    "negative = BatteryElectrodeLayer(\n",
    "    thickness=85.2e-6,\n",
    "    porosity=0.25,\n",
    "    electrolyte_diffusivity=1.7694e-10 * 0.25**1.5,\n",
    "    electrolyte_conductivity=0.9487 * 0.25**1.5,\n",
    "    particle_radius=5.86e-6,\n",
    "    particle_diffusivity=3.3e-14,\n",
    "    active_fraction=0.75,\n",
    "    maximum_concentration=33133,\n",
    "    initial_stoichiometry=0.0279 + soc0 * (0.9014 - 0.0279),\n",
    "    reference_exchange_current=6.48e-7 * np.sqrt(1000) * 33133 / 2,\n",
    "    electronic_conductivity=215,\n",
    "    open_circuit_potential=negative_ocp,\n",
    ")\n",
    "positive = BatteryElectrodeLayer(\n",
    "    thickness=75.6e-6,\n",
    "    porosity=0.335,\n",
    "    electrolyte_diffusivity=1.7694e-10 * 0.335**1.5,\n",
    "    electrolyte_conductivity=0.9487 * 0.335**1.5,\n",
    "    particle_radius=5.22e-6,\n",
    "    particle_diffusivity=4e-15,\n",
    "    active_fraction=0.665,\n",
    "    maximum_concentration=63104,\n",
    "    initial_stoichiometry=0.9077 + soc0 * (0.2661 - 0.9077),\n",
    "    reference_exchange_current=3.42e-6 * np.sqrt(1000) * 63104 / 2,\n",
    "    electronic_conductivity=0.18,\n",
    "    open_circuit_potential=positive_ocp,\n",
    ")\n",
    "separator = BatteryElectrolyteLayer(\n",
    "    thickness=12e-6,\n",
    "    porosity=0.47,\n",
    "    electrolyte_diffusivity=1.7694e-10 * 0.47**1.5,\n",
    "    electrolyte_conductivity=0.9487 * 0.47**1.5,\n",
    ")\n",
    "cell = PorousElectrodeBattery(\n",
    "    negative=negative,\n",
    "    separator=separator,\n",
    "    positive=positive,\n",
    "    electrolyte_concentration=1000,\n",
    "    transference_number=0.2594,\n",
    ")\n",
    "capacity = (\n",
    "    faraday\n",
    "    * negative.active_fraction\n",
    "    * negative.thickness\n",
    "    * negative.maximum_concentration\n",
    "    * (0.9014 - 0.0279)\n",
    "    * area\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Drive cycle\n",
    "\n",
    "Segments of the microcycle as (start time in s, C-rate), positive on discharge.\n",
    "\n",
    "The switch times are passed as breakpoints, so the integrator restarts exactly at every change of\n",
    "the current; the pulse voltage window 2.5-4.3 V of the cell is set as cut-off and would stop the run if\n",
    "the cycle left it. Particles with 32 shells, layers with 20, 10 and 20 control volumes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "segments = np.array(\n",
    "    [\n",
    "        (0, 0.0),\n",
    "        (20, 2.5),\n",
    "        (35, 1.0),\n",
    "        (75, -2.0),\n",
    "        (85, 0.0),\n",
    "        (100, 2.0),\n",
    "        (112, 0.8),\n",
    "        (172, -1.5),\n",
    "        (186, 0.0),\n",
    "        (200, 1.5),\n",
    "        (230, 0.5),\n",
    "        (290, -1.0),\n",
    "        (305, -0.5),\n",
    "        (370, 0.0),\n",
    "    ]\n",
    ")\n",
    "period, cycles = 400.0, 3\n",
    "segments[-2, 1] -= (np.diff(np.r_[segments[:, 0], period]) @ segments[:, 1]) / (\n",
    "    370 - 305\n",
    ")\n",
    "profile = (\n",
    "    lambda t: 5.0\n",
    "    / area\n",
    "    * segments[np.searchsorted(segments[:, 0], t % period, side=\"right\") - 1, 1]\n",
    "    * (t < cycles * period)\n",
    ")\n",
    "end = cycles * period + 1800.0\n",
    "times = np.r_[\n",
    "    np.arange(0.0, cycles * period, 1.0), np.linspace(cycles * period, end, 181)\n",
    "]\n",
    "switches = np.r_[\n",
    "    (np.arange(cycles)[:, None] * period + segments[:, 0]).ravel(), cycles * period, end\n",
    "]\n",
    "run = cell.solve(\n",
    "    mode=\"DFN\",\n",
    "    current_density=profile,\n",
    "    final_time=end,\n",
    "    radial_cells=32,\n",
    "    through_cells=(20, 10, 20),\n",
    "    output_times=times,\n",
    "    breakpoints=switches,\n",
    "    cutoff_voltage=(2.5, 4.3),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Monitoring and checks"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "charge = np.r_[0.0, np.cumsum(np.diff(times) * run.current_density[:-1])] * area\n",
    "coulomb = soc0 - charge / capacity\n",
    "mean = [\n",
    "    np.mean(c @ np.diff(np.linspace(0, 1, 33) ** 3), axis=1)\n",
    "    / layer.maximum_concentration\n",
    "    for c, layer in zip(run.particle_concentration, (negative, positive))\n",
    "]\n",
    "soc_negative = (\n",
    "    soc0\n",
    "    - (negative.initial_stoichiometry - mean[0])\n",
    "    * faraday\n",
    "    * area\n",
    "    * 0.75\n",
    "    * 85.2e-6\n",
    "    * 33133\n",
    "    / capacity\n",
    ")\n",
    "soc_positive = (\n",
    "    soc0\n",
    "    - (mean[1] - positive.initial_stoichiometry)\n",
    "    * faraday\n",
    "    * area\n",
    "    * 0.665\n",
    "    * 75.6e-6\n",
    "    * 63104\n",
    "    / capacity\n",
    ")\n",
    "plating = run.solid_potential[:, 19] - run.electrolyte_potential[:, 19]\n",
    "relaxed = positive_ocp(positive.initial_stoichiometry, 0) - negative_ocp(\n",
    "    negative.initial_stoichiometry, 0\n",
    ")\n",
    "driving = times < cycles * period\n",
    "print(f\"run ended by: {run.termination_reason}\")\n",
    "print(\n",
    "    f\"net charge of one microcycle: {np.diff(np.r_[segments[:, 0], period]) @ segments[:, 1] * 5.0:.2e} A s; \"\n",
    "    f\"rms current {area * np.sqrt(np.mean(run.current_density[driving] ** 2)):.2f} A, peaks {area * run.current_density.max():.1f} A \"\n",
    "    f\"and {area * run.current_density.min():.1f} A\"\n",
    ")\n",
    "print(\n",
    "    f\"state of charge from the particles against coulomb counting: largest difference {np.abs(soc_negative - coulomb).max():.1e} (negative), \"\n",
    "    f\"{np.abs(soc_positive - coulomb).max():.1e} (positive)\"\n",
    ")\n",
    "print(\n",
    "    f\"after {cycles} cycles: mean stoichiometries {mean[0][-1]:.7f} and {mean[1][-1]:.7f}, start {negative.initial_stoichiometry:.7f} and \"\n",
    "    f\"{positive.initial_stoichiometry:.7f}\"\n",
    ")\n",
    "print(\n",
    "    f\"state-of-charge window while driving {coulomb[driving].min():.4f} - {coulomb[driving].max():.4f}; voltage window \"\n",
    "    f\"{run.terminal_voltage[driving].min():.3f} - {run.terminal_voltage[driving].max():.3f} V\"\n",
    ")\n",
    "print(\n",
    "    f\"lowest salt concentration {run.electrolyte_concentration.min():.0f} mol/m³; lowest negative-electrode potential at the separator \"\n",
    "    f\"{1e3 * plating.min():.1f} mV vs Li (plating below 0 mV)\"\n",
    ")\n",
    "for minutes in (1, 5, 30):\n",
    "    k = np.searchsorted(times, cycles * period + 60 * minutes)\n",
    "    print(\n",
    "        f\"{minutes:2d} min into the rest: V - U_oc(initial) = {1e3 * (run.terminal_voltage[k] - relaxed):+.2f} mV\"\n",
    "    )\n",
    "print(\n",
    "    f\"energy delivered {np.trapezoid(np.maximum(run.current_density, 0) * run.terminal_voltage, times) * area / 3600:.3f} Wh, \"\n",
    "    f\"taken back {-np.trapezoid(np.minimum(run.current_density, 0) * run.terminal_voltage, times) * area / 3600:.3f} Wh\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(2, 2, size=(15, 9.5))\n",
    "plots.line(\n",
    "    times / 60,\n",
    "    {\"terminal voltage\": run.terminal_voltage},\n",
    "    right={\"current [A]\": area * run.current_density},\n",
    "    hlines={\"open-circuit voltage at start\": relaxed},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"voltage [V]\",\n",
    "    right_label=\"current [A]\",\n",
    "    title=\"Voltage and current\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    times / 60,\n",
    "    {\"negative particles\": soc_negative},\n",
    "    reference={\"coulomb counting\": coulomb},\n",
    "    points={\"positive particles\": (times[::40] / 60, soc_positive[::40])},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"state of charge\",\n",
    "    title=\"State of charge\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    times / 60,\n",
    "    {\"lowest salt concentration\": run.electrolyte_concentration.min(axis=1)},\n",
    "    right={\"highest salt concentration\": run.electrolyte_concentration.max(axis=1)},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"lowest salt [mol/m³]\",\n",
    "    right_label=\"highest salt [mol/m³]\",\n",
    "    title=\"Electrolyte\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    times[:400],\n",
    "    {\"negative potential at the separator\": 1e3 * plating[:400]},\n",
    "    right={\"current [A]\": area * run.current_density[:400]},\n",
    "    hlines={\"plating threshold\": 0.0},\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"φs - φe [mV vs Li]\",\n",
    "    right_label=\"current [A]\",\n",
    "    title=\"Plating margin during the first microcycle\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "The engine-charging phase uses up the plating margin and nearly empties the electrolyte near the\n",
    "positive collector. Spread the same charge over a longer, gentler phase, or lower the temperature\n",
    "through the exchange current and the diffusivities, and watch both margins change."
   ]
  }
 ]
}
