{
 "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": [
    "# Power losses of a lithium-ion cell in a hybrid pulse power test\n",
    "\n",
    "The hybrid pulse power characterisation (HPPC) test probes a cell with a 10 s discharge pulse,\n",
    "40 s rest and a 10 s regenerative charge pulse at 75 % of the discharge current, repeated at\n",
    "several states of charge. Every watt the cell does not deliver is turned into heat somewhere\n",
    "inside it. With the Doyle-Fuller-Newman model (equations in the discharge-rest-charge example) the\n",
    "loss of terminal power against the reversible power of the mean electrode stoichiometries splits\n",
    "exactly into five parts:\n",
    "\n",
    "$$I\\big(U_+(\\bar\\theta_+)-U_-(\\bar\\theta_-)\\big)-IV=\n",
    "  \\underbrace{\\int\\frac{i_e^2}{\\kappa}dx}_{\\text{electrolyte conduction}}\n",
    "  \\underbrace{-\\int i_e\\frac{2(1-t_+)RT}{F}\\frac{\\partial\\ln c_e}{\\partial x}dx}_{\\text{salt concentration}}\n",
    "  +\\underbrace{\\int\\frac{i_s^2}{\\sigma}dx}_{\\text{electrode conduction}}\n",
    "  +\\underbrace{\\int a\\,j\\,\\eta\\,dx}_{\\text{reaction}}\n",
    "  +\\underbrace{\\int a\\,j\\,\\big(U(\\theta^\\mathrm{surf})-U(\\bar\\theta)\\big)dx}_{\\text{particle diffusion}},$$\n",
    "\n",
    "with the overpotential $\\eta=\\phi_s-\\phi_e-U(\\theta^\\mathrm{surf})$. The identity follows from\n",
    "charge conservation, $\\partial i_e/\\partial x=a\\,j$ and $i_s+i_e=I$, by integration by parts; on\n",
    "the finite-volume mesh the same summation by parts holds face by face.\n",
    "\n",
    "**Reference.** Test protocol of the *FreedomCAR Battery Test Manual for Power-Assist Hybrid\n",
    "Electric Vehicles* (INL, 2003); model of Doyle, Fuller and Newman, *J. Electrochem. Soc.* 140\n",
    "(1993) 1526; cell parameters of Chen et al., *J. Electrochem. Soc.* 167 (2020) 080534 (LG M50,\n",
    "5 Ah). Check: the five loss parts add up to the terminal power loss at every output time, and\n",
    "their time integrals to the terminal energy loss of every pulse."
   ]
  },
  {
   "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",
    "from scipy.integrate import solve_ivp\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cell at 80 % state of charge"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "faraday, area, soc0 = 96485.33212, 0.1027, 0.8\n",
    "thermal = 8.314462618 * 298.15 / faraday\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",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## HPPC test\n",
    "\n",
    "Pulses of 1.5C (7.5 A) discharge and 1.125C charge at 80, 50 and 20 % state of charge; between the\n",
    "blocks the cell is discharged by 30 % at 1C and rests for 15 minutes.\n",
    "\n",
    "The current switches abruptly. The stiff BDF integrator (the default of the model) gets a maximum\n",
    "step of 2 s through the `time_solver` port, so that no pulse can fall between two steps."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "one_c, step = 5.0 / area, 0.3 * 5.0904 / 5.0 * 3600\n",
    "starts = np.array([0.0, 100 + step + 900, 2 * (100 + step + 900)])\n",
    "table = np.array(\n",
    "    sorted(\n",
    "        [\n",
    "            (s + offset, rate)\n",
    "            for s in starts\n",
    "            for offset, rate in ((0, 1.5), (10, 0), (50, -1.125), (60, 0))\n",
    "        ]\n",
    "        + [\n",
    "            (s + offset, rate)\n",
    "            for s in starts[:2]\n",
    "            for offset, rate in ((100, 1.0), (100 + step, 0))\n",
    "        ]\n",
    "    )\n",
    ")\n",
    "program = lambda t: one_c * table[np.searchsorted(table[:, 0], t, side=\"right\") - 1, 1]\n",
    "end = starts[2] + 100\n",
    "times = np.unique(\n",
    "    np.r_[\n",
    "        np.linspace(0, end, 1500),\n",
    "        np.concatenate([s + np.linspace(0, 100, 501) for s in starts]),\n",
    "    ]\n",
    ")\n",
    "counts = (10, 5, 10)\n",
    "stepping = lambda rhs, span, start, output_times, jacobian_sparsity: solve_ivp(\n",
    "    rhs,\n",
    "    span,\n",
    "    start,\n",
    "    method=\"BDF\",\n",
    "    t_eval=output_times,\n",
    "    jac_sparsity=jacobian_sparsity,\n",
    "    rtol=1e-8,\n",
    "    atol=1e-9,\n",
    "    max_step=2.0,\n",
    ")\n",
    "run = cell.solve(\n",
    "    mode=\"DFN\",\n",
    "    current_density=program,\n",
    "    final_time=end,\n",
    "    radial_cells=16,\n",
    "    through_cells=counts,\n",
    "    output_times=times,\n",
    "    time_solver=stepping,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loss parts\n",
    "\n",
    "All parts are evaluated on the finite-volume faces and cells of the solution, in W per m² of\n",
    "electrode."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "nn, ns, nq = counts\n",
    "current, ionic, phi_e, salt = (\n",
    "    run.current_density,\n",
    "    run.electrolyte_current_density,\n",
    "    run.electrolyte_potential,\n",
    "    run.electrolyte_concentration,\n",
    ")\n",
    "concentration_loss = -(\n",
    "    ionic[:, 1:-1]\n",
    "    * 2\n",
    "    * (1 - cell.transference_number)\n",
    "    * thermal\n",
    "    * np.diff(np.log(salt), axis=1)\n",
    ").sum(axis=1)\n",
    "conduction_loss = (\n",
    "    -(ionic[:, 1:-1] * np.diff(phi_e, axis=1)).sum(axis=1) - concentration_loss\n",
    ")\n",
    "electrode_loss = (\n",
    "    -(\n",
    "        (current[:, None] - ionic[:, 1:nn])\n",
    "        * np.diff(run.solid_potential[:, :nn], axis=1)\n",
    "    ).sum(axis=1)\n",
    "    - (\n",
    "        (current[:, None] - ionic[:, nn + ns + 1 : -1])\n",
    "        * np.diff(run.solid_potential[:, nn:], axis=1)\n",
    "    ).sum(axis=1)\n",
    "    + current**2\n",
    "    * (\n",
    "        negative.thickness / nn / negative.electronic_conductivity\n",
    "        + positive.thickness / nq / positive.electronic_conductivity\n",
    "    )\n",
    "    / 2\n",
    ")\n",
    "width = np.repeat([negative.thickness / nn, positive.thickness / nq], (nn, nq))\n",
    "surface_area = np.repeat(\n",
    "    [\n",
    "        3 * negative.active_fraction / negative.particle_radius,\n",
    "        3 * positive.active_fraction / positive.particle_radius,\n",
    "    ],\n",
    "    (nn, nq),\n",
    ")\n",
    "surface_potential = np.c_[\n",
    "    negative_ocp(\n",
    "        run.particle_surface_concentration[0] / negative.maximum_concentration, 0\n",
    "    ),\n",
    "    positive_ocp(\n",
    "        run.particle_surface_concentration[1] / positive.maximum_concentration, 0\n",
    "    ),\n",
    "]\n",
    "mean = [\n",
    "    np.mean(c @ np.diff(np.linspace(0, 1, 17) ** 3), axis=1)\n",
    "    / layer.maximum_concentration\n",
    "    for c, layer in zip(run.particle_concentration, (negative, positive))\n",
    "]\n",
    "mean_potential = np.repeat(\n",
    "    np.c_[negative_ocp(mean[0], 0), positive_ocp(mean[1], 0)], (nn, nq), axis=1\n",
    ")\n",
    "reaction = width * surface_area * run.interfacial_current_density\n",
    "reaction_loss = (\n",
    "    reaction\n",
    "    * (\n",
    "        run.solid_potential\n",
    "        - np.c_[phi_e[:, :nn], phi_e[:, nn + ns :]]\n",
    "        - surface_potential\n",
    "    )\n",
    ").sum(axis=1)\n",
    "particle_loss = (reaction * (surface_potential - mean_potential)).sum(axis=1)\n",
    "parts = {\n",
    "    \"electrolyte conduction\": conduction_loss,\n",
    "    \"salt concentration\": concentration_loss,\n",
    "    \"electrode conduction\": electrode_loss,\n",
    "    \"reaction\": reaction_loss,\n",
    "    \"particle diffusion\": particle_loss,\n",
    "}\n",
    "terminal_loss = current * (\n",
    "    positive_ocp(mean[1], 0) - negative_ocp(mean[0], 0) - run.terminal_voltage\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"largest |terminal power loss - sum of the five parts| over the test: {np.abs(terminal_loss - sum(parts.values())).max():.1e} W/m² \"\n",
    "    f\"(largest loss {terminal_loss.max():.1f} W/m²)\"\n",
    ")\n",
    "pulses = {\n",
    "    f\"{label}\\n{soc:.0%}\": (s + offset, s + offset + 10)\n",
    "    for s, soc in zip(starts, (0.8, 0.5, 0.2))\n",
    "    for label, offset in ((\"discharge\", 0.0), (\"charge\", 50.0))\n",
    "}\n",
    "energy = {\n",
    "    name: {\n",
    "        part: area\n",
    "        * np.trapezoid(\n",
    "            values[(times >= a) & (times <= b - 1e-9)],\n",
    "            times[(times >= a) & (times <= b - 1e-9)],\n",
    "        )\n",
    "        for part, values in {**parts, \"terminal\": terminal_loss}.items()\n",
    "    }\n",
    "    for name, (a, b) in pulses.items()\n",
    "}\n",
    "print(\n",
    "    \"pulse                 terminal loss [J]   sum of parts [J]   \"\n",
    "    + \"   \".join(f\"{part:>11.11s}\" for part in parts)\n",
    ")\n",
    "for name, e in energy.items():\n",
    "    print(\n",
    "        f\"{name.replace('\\n', ' at '):20s} {e['terminal']:15.4f} {sum(e[p] for p in parts):18.4f}   \"\n",
    "        + \"   \".join(f\"{100 * e[p] / e['terminal']:9.1f} %\" for p in parts)\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "block = (times >= starts[1] - 5) & (times <= starts[1] + 95)\n",
    "fig = plots.figure(1, 3, size=(19, 5.4))\n",
    "plots.line(\n",
    "    times / 60,\n",
    "    {\"terminal voltage\": run.terminal_voltage},\n",
    "    right={\"current [A]\": area * current},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"voltage [V]\",\n",
    "    right_label=\"current [A]\",\n",
    "    title=\"HPPC test at 80, 50 and 20 % SOC\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    times[block] - starts[1],\n",
    "    {part: area * values[block] for part, values in parts.items()},\n",
    "    reference={\n",
    "        \"terminal power loss\": (times[block] - starts[1], area * terminal_loss[block])\n",
    "    },\n",
    "    xlabel=\"time in the 50 % block [s]\",\n",
    "    ylabel=\"power loss [W]\",\n",
    "    title=\"Where the power goes\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.bars(\n",
    "    list(pulses),\n",
    "    {part: [energy[name][part] for name in pulses] for part in parts},\n",
    "    reference=[energy[name][\"terminal\"] for name in pulses],\n",
    "    ylabel=\"energy loss in the 10 s pulse [J]\",\n",
    "    title=\"Loss parts per 10 s pulse\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "The loss parts are the local heat sources of a thermal model: add them per layer to find where a\n",
    "cell heats up during fast charging, or repeat the test at lower temperature with smaller exchange\n",
    "currents and diffusivities."
   ]
  }
 ]
}
