{
 "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": [
    "# Discharge, rest and recharge of a lithium-ion cell\n",
    "\n",
    "The cell is a sandwich of a porous negative electrode, a separator and a porous positive electrode\n",
    "between two current collectors. The Doyle-Fuller-Newman (DFN) model resolves the thickness\n",
    "coordinate $x$ and, at every $x$ in the electrodes, a spherical active particle with radius\n",
    "coordinate $r$:\n",
    "\n",
    "$$\\frac{\\partial c_s}{\\partial t}=\\frac{D_s}{r^2}\\frac{\\partial}{\\partial r}\\Big(r^2\\frac{\\partial c_s}{\\partial r}\\Big),\\qquad\n",
    "  \\varepsilon\\frac{\\partial c_e}{\\partial t}=\\frac{\\partial}{\\partial x}\\Big(D_e\\frac{\\partial c_e}{\\partial x}\\Big)+\\frac{(1-t_+)\\,a\\,j}{F},$$\n",
    "\n",
    "$$\\frac{\\partial i_e}{\\partial x}=a\\,j,\\qquad i_e=-\\kappa\\frac{\\partial\\phi_e}{\\partial x}+\\frac{2(1-t_+)RT\\kappa}{F}\\frac{\\partial\\ln c_e}{\\partial x},\\qquad\n",
    "  i_s=-\\sigma\\frac{\\partial\\phi_s}{\\partial x},\\qquad j=2j_0\\sinh\\frac{F(\\phi_s-\\phi_e-U(c_s^\\mathrm{surf}))}{2RT}.$$\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| current collectors | $i_s=I$, $i_e=0$, no salt flux |\n",
    "| separator | $i_e=I$, no electrode phase |\n",
    "| particle centre / surface | symmetry / $-D_s\\,\\partial_r c_s = j/F$ |\n",
    "\n",
    "The cell starts at 90 % state of charge. The current program is 45 min at 1C (5 A), one hour at\n",
    "rest, 45 min of 1C charge and half an hour of rest. The cell is isothermal at 25 °C.\n",
    "\n",
    "**Reference.** Parameters, open-circuit curves and stoichiometry limits of the LG M50 cell are\n",
    "those of Chen et al., *J. Electrochem. Soc.* 167 (2020) 080534; the model is that of Doyle,\n",
    "Fuller and Newman, *J. Electrochem. Soc.* 140 (1993) 1526. Independent checks: (i) lithium in\n",
    "particles and electrolyte is conserved; (ii) coulomb counting fixes the mean stoichiometry of each\n",
    "electrode, $\\Delta\\bar\\theta=-\\int I\\,dt/(F\\varepsilon_sLc_{s,\\max}A)$; (iii) at rest the terminal\n",
    "voltage relaxes to the open-circuit voltage of the mean stoichiometries,\n",
    "$U_+(\\bar\\theta_+)-U_-(\\bar\\theta_-)$; (iv) the voltage converges under mesh refinement."
   ]
  },
  {
   "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\n",
    "\n",
    "Effective electrolyte transport follows Bruggeman's relation with exponent 1.5; the electrode area\n",
    "is 0.1027 m², so 1C is 48.7 A/m²."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "faraday, area = 96485.33212, 0.1027\n",
    "one_c = 5.0 / area\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 + 0.9 * (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 + 0.9 * (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": [
    "## Simulation\n",
    "\n",
    "The current density is a function of time (positive on discharge); its switch times are passed as\n",
    "breakpoints, so the integrator restarts exactly at every switch. The particles are divided into 32\n",
    "spherical shells, the layers into 20, 10 and 20 control volumes. A mesh study repeats the 45 min\n",
    "discharge with 8 to 64 particle shells and with 5 to 40 control volumes in each electrode."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "program = lambda t: one_c * (float(t < 2700) - float(6300 <= t < 9000))\n",
    "times = np.linspace(0.0, 10800.0, 1081)\n",
    "run = cell.solve(\n",
    "    mode=\"DFN\",\n",
    "    current_density=program,\n",
    "    final_time=10800.0,\n",
    "    radial_cells=32,\n",
    "    through_cells=(20, 10, 20),\n",
    "    output_times=times,\n",
    "    breakpoints=(0.0, 2700.0, 6300.0, 9000.0, 10800.0),\n",
    ")\n",
    "radial = {\n",
    "    n: cell.solve(\n",
    "        mode=\"DFN\",\n",
    "        current_density=one_c,\n",
    "        final_time=2700.0,\n",
    "        radial_cells=n,\n",
    "        through_cells=(20, 10, 20),\n",
    "        output_times=(0.0, 2700.0),\n",
    "    ).terminal_voltage[-1]\n",
    "    for n in (8, 16, 32, 64)\n",
    "}\n",
    "layered = {\n",
    "    n: cell.solve(\n",
    "        mode=\"DFN\",\n",
    "        current_density=one_c,\n",
    "        final_time=2700.0,\n",
    "        radial_cells=32,\n",
    "        through_cells=(n, n // 2, n),\n",
    "        output_times=(0.0, 2700.0),\n",
    "    ).terminal_voltage[-1]\n",
    "    for n in (5, 10, 20, 40)\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "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",
    "relaxed = positive_ocp(mean[1], 0) - negative_ocp(mean[0], 0)\n",
    "counted = (\n",
    "    one_c\n",
    "    * 2700\n",
    "    / (\n",
    "        faraday\n",
    "        * np.array(\n",
    "            [\n",
    "                layer.active_fraction * layer.thickness * layer.maximum_concentration\n",
    "                for layer in (negative, positive)\n",
    "            ]\n",
    "        )\n",
    "    )\n",
    ")\n",
    "ends = {\n",
    "    \"end of discharge\": 269,\n",
    "    \"end of first rest\": 629,\n",
    "    \"end of charge\": 899,\n",
    "    \"end of program\": 1080,\n",
    "}\n",
    "print(\n",
    "    f\"lithium inventory: largest relative drift {np.ptp(run.lithium_inventory) / run.lithium_inventory[0]:.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"coulomb counting after 45 min at 1C: mean stoichiometry change negative {mean[0][0] - mean[0][270]:.6f} \"\n",
    "    f\"(exact {counted[0]:.6f}), positive {mean[1][270] - mean[1][0]:.6f} (exact {counted[1]:.6f})\"\n",
    ")\n",
    "print(\n",
    "    f\"after the full program: mean stoichiometries {mean[0][-1]:.6f} and {mean[1][-1]:.6f} (start {negative.initial_stoichiometry:.6f} and {positive.initial_stoichiometry:.6f})\"\n",
    ")\n",
    "for name, k in ends.items():\n",
    "    print(\n",
    "        f\"{name:18s} t = {times[k] / 60:5.0f} min   V = {run.terminal_voltage[k]:.4f} V   \"\n",
    "        f\"open-circuit voltage of the mean stoichiometries {relaxed[k]:.4f} V   difference {1e3 * (run.terminal_voltage[k] - relaxed[k]):+.2f} mV\"\n",
    "    )\n",
    "errors = {\n",
    "    \"particle shells\": {\n",
    "        1 / n: abs(v - radial[64]) for n, v in radial.items() if n < 64\n",
    "    },\n",
    "    \"electrode cells\": {\n",
    "        1 / n: abs(v - layered[40]) for n, v in layered.items() if n < 40\n",
    "    },\n",
    "}\n",
    "print(\n",
    "    \"voltage at the end of discharge: \"\n",
    "    + \", \".join(f\"{v:.5f} V ({n} shells)\" for n, v in radial.items())\n",
    "    + \"; \"\n",
    "    + \", \".join(f\"{v:.5f} V ({n} cells)\" for n, v in layered.items())\n",
    ")\n",
    "for name, e in errors.items():\n",
    "    h = sorted(e)\n",
    "    print(\n",
    "        f\"observed order in the {name}: {np.log2(e[h[2]] / e[h[1]]):.2f}, {np.log2(e[h[1]] / e[h[0]]):.2f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Terminal voltage against the relaxed open-circuit voltage; salt concentration and reaction\n",
    "current through the cell at five moments; the radial lithium profile in the positive particle next\n",
    "to the separator; and the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "moments = {\n",
    "    \"5 min\": 30,\n",
    "    \"25 min\": 150,\n",
    "    \"45 min (end of discharge)\": 269,\n",
    "    \"after 1 h rest\": 629,\n",
    "    \"end of charge\": 899,\n",
    "}\n",
    "x = 1e6 * run.electrolyte_positions\n",
    "fig = plots.figure(2, 3, size=(17, 9.5))\n",
    "plots.line(\n",
    "    times / 60,\n",
    "    {\"terminal voltage\": run.terminal_voltage},\n",
    "    reference={\"open-circuit voltage of mean stoichiometries\": relaxed},\n",
    "    right={\"current [A]\": area * run.current_density},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"voltage [V]\",\n",
    "    right_label=\"current [A]\",\n",
    "    title=\"Discharge, rest and charge at 1C\",\n",
    "    legend=\"upper center\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    x,\n",
    "    {name: run.electrolyte_concentration[k] for name, k in moments.items()},\n",
    "    vlines=[1e6 * negative.thickness, 1e6 * (negative.thickness + separator.thickness)],\n",
    "    xlabel=\"x [µm]\",\n",
    "    ylabel=\"salt concentration [mol/m³]\",\n",
    "    title=\"Electrolyte through the cell\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    1e6 * run.interfacial_positions,\n",
    "    {name: run.interfacial_current_density[k] for name, k in moments.items()},\n",
    "    vlines=[1e6 * negative.thickness, 1e6 * (negative.thickness + separator.thickness)],\n",
    "    xlabel=\"x [µm]\",\n",
    "    ylabel=\"reaction current density j [A/m²]\",\n",
    "    title=\"Where the reaction takes place\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    1e6 * run.radii[1],\n",
    "    {\n",
    "        name: run.particle_concentration[1][k, 0] / positive.maximum_concentration\n",
    "        for name, k in moments.items()\n",
    "    },\n",
    "    xlabel=\"radius [µm]\",\n",
    "    ylabel=\"stoichiometry θ₊\",\n",
    "    title=\"Positive particle next to the separator\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.line(\n",
    "    times / 60,\n",
    "    {\"negative\": mean[0], \"positive\": mean[1]},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"mean stoichiometry\",\n",
    "    title=\"Lithium between the electrodes\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[4],\n",
    ")\n",
    "plots.convergence(\n",
    "    None,\n",
    "    {name: (list(e), list(e.values())) for name, e in errors.items()},\n",
    "    order=(1, 2),\n",
    "    xlabel=\"relative cell size (1 / number of cells)\",\n",
    "    ylabel=\"voltage error at end of discharge [V]\",\n",
    "    title=\"Mesh study\",\n",
    "    ax=fig[5],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the program to a constant-current constant-voltage charge, give the electrolyte\n",
    "concentration-dependent transport, or compare the full model with the single-particle model at the\n",
    "same current."
   ]
  }
 ]
}
