{
 "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": [
    "# Lithium-ion cell with a single-ion conducting electrolyte\n",
    "\n",
    "Liquid electrolytes carry the current with both ions; the anions pile up at one electrode and\n",
    "deplete at the other, and the salt gradient limits the rate. Polymer and ceramic single-ion\n",
    "conductors fix the anions to the host, so the lithium transference number is $t_+=1$. In the\n",
    "porous electrode (Doyle-Fuller-Newman) model the salt balance then has no source,\n",
    "\n",
    "$$\\varepsilon\\frac{\\partial c_e}{\\partial t}=\\nabla\\cdot\\big(D_\\mathrm{eff}\\nabla c_e\\big)+(1-t_+)\\frac{a\\,j}{F}\n",
    "  \\quad\\Rightarrow\\quad c_e=c_{e,0},$$\n",
    "\n",
    "and the ionic current obeys Ohm's law, $i_e=-\\kappa_\\mathrm{eff}\\nabla\\phi_e$, without the diffusion\n",
    "potential $\\propto(1-t_+)\\nabla\\ln c_e$. The electrodes, particles and kinetics are those of the\n",
    "LG M50 cell (graphite-SiOx | NMC811, 5 Ah, 25 °C) of Chen et al., *J. Electrochem. Soc.* 167\n",
    "(2020) 080534; the electrolyte is replaced by a single-ion conductor of bulk conductivity\n",
    "$\\kappa$ = 1, 0.3 and 0.1 S/m with the Bruggeman correction $\\kappa_\\mathrm{eff}=\\kappa\\varepsilon^{1.5}$.\n",
    "\n",
    "**Reference.** (i) The salt concentration must stay at its initial value. (ii) For very high\n",
    "ionic and electronic conductivities the reaction is uniform through each electrode and the model\n",
    "reduces exactly to the single-particle model (SPM). (iii) If the reaction stayed uniform through\n",
    "the electrodes, lowering the conductivity would shift the voltage by the ohmic drop\n",
    "$\\Delta V=i\\,\\Delta R$ with $R=\\frac{L_-}{3\\kappa_{\\mathrm{eff},-}}+\\frac{L_s}{\\kappa_{\\mathrm{eff},s}}+\\frac{L_+}{3\\kappa_{\\mathrm{eff},+}}$,\n",
    "the classical one-third rule of a porous electrode with uniform reaction (J. Newman, K.E.\n",
    "Thomas-Alyea, *Electrochemical Systems*, 3rd ed., Wiley 2004, §22). It is the limit for a weak\n",
    "resistance and an upper bound otherwise, because a poorer conductor pulls the reaction towards\n",
    "the separator and shortens the ionic path."
   ]
  },
  {
   "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",
    "The layers of the LG M50 cell; only the electrolyte conductivity changes. The salt diffusivity\n",
    "no longer matters at $t_+=1$ and is kept at the liquid value."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "faraday, area = 96485.33212, 0.1027\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",
    "porosity = {\"negative\": 0.25, \"separator\": 0.47, \"positive\": 0.335}\n",
    "thickness = {\"negative\": 85.2e-6, \"separator\": 12e-6, \"positive\": 75.6e-6}\n",
    "cell = lambda kappa, sigma=None: PorousElectrodeBattery(\n",
    "    negative=BatteryElectrodeLayer(\n",
    "        thickness=thickness[\"negative\"],\n",
    "        porosity=porosity[\"negative\"],\n",
    "        electrolyte_diffusivity=1.7694e-10 * 0.25**1.5,\n",
    "        electrolyte_conductivity=kappa * 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.9014,\n",
    "        reference_exchange_current=6.48e-7 * np.sqrt(1000) * 33133 / 2,\n",
    "        electronic_conductivity=sigma or 215,\n",
    "        open_circuit_potential=negative_ocp,\n",
    "    ),\n",
    "    separator=BatteryElectrolyteLayer(\n",
    "        thickness=thickness[\"separator\"],\n",
    "        porosity=porosity[\"separator\"],\n",
    "        electrolyte_diffusivity=1.7694e-10 * 0.47**1.5,\n",
    "        electrolyte_conductivity=kappa * 0.47**1.5,\n",
    "    ),\n",
    "    positive=BatteryElectrodeLayer(\n",
    "        thickness=thickness[\"positive\"],\n",
    "        porosity=porosity[\"positive\"],\n",
    "        electrolyte_diffusivity=1.7694e-10 * 0.335**1.5,\n",
    "        electrolyte_conductivity=kappa * 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.2661,\n",
    "        reference_exchange_current=3.42e-6 * np.sqrt(1000) * 63104 / 2,\n",
    "        electronic_conductivity=sigma or 0.18,\n",
    "        open_circuit_potential=positive_ocp,\n",
    "    ),\n",
    "    electrolyte_concentration=1000,\n",
    "    transference_number=1.0,\n",
    ")\n",
    "resistance = lambda kappa: sum(\n",
    "    thickness[n] / ((1 if n == \"separator\" else 3) * kappa * porosity[n] ** 1.5)\n",
    "    for n in thickness\n",
    ")\n",
    "print(\n",
    "    \"ohmic resistance of the electrolyte, uniform reaction: \"\n",
    "    + \", \".join(\n",
    "        f\"kappa = {k:g} S/m: {resistance(k) * 1e4:.2f} Ohm cm²\" for k in (1.0, 0.3, 0.1)\n",
    "    )\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Discharges\n",
    "\n",
    "Each discharge covers 80 % of the nominal capacity at 0.5C and 1C, for the three conductivities,\n",
    "with the full porous electrode model. A fourth run at 1C with conductivities of $10^3$ S/m in\n",
    "both phases is compared with the single-particle model."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "one_c = 5.0 / area\n",
    "runs = {\n",
    "    (kappa, rate): cell(kappa).solve(\n",
    "        mode=\"DFN\",\n",
    "        current_density=rate * one_c,\n",
    "        final_time=0.8 * 3600 / rate,\n",
    "        radial_cells=16,\n",
    "        through_cells=(10, 5, 10),\n",
    "        output_times=np.linspace(0, 0.8 * 3600 / rate, 241),\n",
    "    )\n",
    "    for kappa in (1.0, 0.3, 0.1)\n",
    "    for rate in (0.5, 1.0)\n",
    "}\n",
    "ideal = cell(1e3, sigma=1e3)\n",
    "limit = {\n",
    "    mode: ideal.solve(\n",
    "        mode=mode,\n",
    "        current_density=one_c,\n",
    "        final_time=0.8 * 3600,\n",
    "        radial_cells=16,\n",
    "        through_cells=(10, 5, 10),\n",
    "        output_times=np.linspace(0, 0.8 * 3600, 241),\n",
    "    )\n",
    "    for mode in (\"DFN\", \"SPM\")\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the references\n",
    "\n",
    "The largest relative deviation of the salt concentration from 1000 mol/m³, the high-conductivity\n",
    "model against the SPM, and the voltage shift at the first output time (12 s at 1C) against the\n",
    "ohmic estimate."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"largest |c_e - c_e0| / c_e0 over all runs: {max(np.abs(run.electrolyte_concentration / 1000 - 1).max() for run in runs.values()):.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"high conductivities: largest |V_DFN - V_SPM| = {1e3 * np.abs(limit['DFN'].terminal_voltage - limit['SPM'].terminal_voltage).max():.3f} mV over the 1C discharge\"\n",
    ")\n",
    "print(\n",
    "    f\"{'C-rate':>6s} {'kappa':>6s} {'V(t1) [V]':>10s} {'V_end [V]':>10s} {'shift vs 1 S/m [mV]':>20s} {'one-third rule [mV]':>20s} {'ratio':>6s}\"\n",
    ")\n",
    "for (kappa, rate), run in runs.items():\n",
    "    shift = 1e3 * (runs[1.0, rate].terminal_voltage[1] - run.terminal_voltage[1])\n",
    "    estimate = 1e3 * rate * one_c * (resistance(kappa) - resistance(1.0))\n",
    "    print(\n",
    "        f\"{rate:6.1f} {kappa:6.1f} {run.terminal_voltage[1]:10.4f} {run.terminal_voltage[-1]:10.4f} {shift:20.1f} {estimate:20.1f} \"\n",
    "        f\"{shift / estimate if estimate else 1.0:6.2f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The discharge curves of all runs, and the ionic potential through the cell at the end of the 1C\n",
    "discharge for the three conductivities."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "capacity = lambda rate, run: 5.0 * rate * run.times / 3600\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"{rate:g}C, κ = {kappa:g} S/m\": (capacity(rate, run), run.terminal_voltage)\n",
    "        for (kappa, rate), run in runs.items()\n",
    "    },\n",
    "    reference={\n",
    "        \"1C, SPM limit\": (capacity(1.0, limit[\"SPM\"]), limit[\"SPM\"].terminal_voltage)\n",
    "    },\n",
    "    xlabel=\"discharged capacity [Ah]\",\n",
    "    ylabel=\"terminal voltage [V]\",\n",
    "    title=\"Discharge with a single-ion conductor\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"κ = {kappa:g} S/m\": (\n",
    "            runs[kappa, 1.0].electrolyte_positions * 1e6,\n",
    "            1e3\n",
    "            * (\n",
    "                runs[kappa, 1.0].electrolyte_potential[-1]\n",
    "                - runs[kappa, 1.0].electrolyte_potential[-1][0]\n",
    "            ),\n",
    "        )\n",
    "        for kappa in (1.0, 0.3, 0.1)\n",
    "    },\n",
    "    xlabel=\"position through the cell [µm]\",\n",
    "    ylabel=\"φ_e - φ_e(0) [mV]\",\n",
    "    title=\"Ionic potential at the end of the 1C discharge\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Set $t_+$ back to the liquid value 0.26 at the same conductivity: the salt gradient adds the\n",
    "concentration overpotential and cuts the capacity at high rates. Thicker electrodes show where\n",
    "the low conductivity of solid electrolytes concentrates the reaction near the separator."
   ]
  }
 ]
}
