{
 "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": [
    "# Isothermal sodium-ion cell in 1D\n",
    "\n",
    "Sodium-ion cells work like lithium-ion cells: Na⁺ ions shuttle through a liquid electrolyte\n",
    "between a negative electrode that stores sodium, here hard carbon, and a positive host, here the\n",
    "polyanionic Na₃V₂(PO₄)₂F₃ (NVPF). The porous-electrode equations of Doyle, Fuller and Newman hold\n",
    "unchanged for the monovalent Na⁺ (equations in the lithium-ion discharge-rest-charge example):\n",
    "solid diffusion in spherical particles, salt diffusion and migration in the electrolyte, Ohm's law\n",
    "in both phases and Butler-Volmer kinetics.\n",
    "\n",
    "The two electrodes give the cell its typical voltage curve. Hard carbon has a sloping region at\n",
    "low sodium content and a low-voltage plateau when filled; NVPF has two plateaus, near 4.2 V and\n",
    "3.7 V, separated at two sodium ions per formula unit:\n",
    "\n",
    "| electrode | stoichiometry at full / empty cell | open-circuit potential |\n",
    "|---|---|---|\n",
    "| hard carbon | $x=0.85$ / $x=0.02$ (2.0 V) | slope from about 1 V to 0.1 V, then plateau near 0.05 V |\n",
    "| NVPF | $y=0.36$ / $y\\approx0.88$ | plateaus at 4.2 V ($y<2/3$) and 3.7 V ($y>2/3$) |\n",
    "\n",
    "**Reference.** Model structure and electrode chemistry after K. Chayambuka, G. Mulder,\n",
    "D. L. Danilov and P. H. L. Notten, *Adv. Energy Mater.* 10 (2020) 2001310 and their\n",
    "physics-based sodium-ion model (2022); the parameters and open-circuit curves here are\n",
    "representative values of that cell type, not a fit. Checks: (i) sodium in particles and\n",
    "electrolyte is conserved; (ii) coulomb counting: the stoichiometric capacity of the hard carbon\n",
    "window equals the low-rate capacity; (iii) at C/10 the voltage follows the open-circuit voltage\n",
    "and its differential capacity $dQ/dV$ shows the high-voltage plateau of NVPF at the voltage the\n",
    "open-circuit curves predict."
   ]
  },
  {
   "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",
    "1 M NaPF₆ in EC:PC with Bruggeman tortuosity (exponent 1.5)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "faraday, x100, y100, x0 = 96485.33212, 0.85, 0.36, 0.02\n",
    "hard_carbon = (\n",
    "    lambda x, T: 0.06 + 0.9 * np.exp(-9 * x) + 1.6 * np.exp(-35 * x) - 0.04 * x\n",
    ")\n",
    "nvpf = lambda y, T: (\n",
    "    3.95\n",
    "    - 0.25 * np.tanh((y - 0.667) / 0.02)\n",
    "    - 0.15 * (y - 0.667)\n",
    "    + 0.4 * np.exp(-(y - 0.333) / 0.012)\n",
    "    - 1.2 * np.exp(-(1 - y) / 0.03)\n",
    ")\n",
    "negative = BatteryElectrodeLayer(\n",
    "    thickness=64e-6,\n",
    "    porosity=0.51,\n",
    "    electrolyte_diffusivity=2.5e-10 * 0.51**1.5,\n",
    "    electrolyte_conductivity=0.8 * 0.51**1.5,\n",
    "    particle_radius=3.5e-6,\n",
    "    particle_diffusivity=5e-15,\n",
    "    active_fraction=0.44,\n",
    "    maximum_concentration=14540,\n",
    "    initial_stoichiometry=x100,\n",
    "    reference_exchange_current=1.0,\n",
    "    electronic_conductivity=256,\n",
    "    open_circuit_potential=hard_carbon,\n",
    ")\n",
    "positive = BatteryElectrodeLayer(\n",
    "    thickness=68e-6,\n",
    "    porosity=0.23,\n",
    "    electrolyte_diffusivity=2.5e-10 * 0.23**1.5,\n",
    "    electrolyte_conductivity=0.8 * 0.23**1.5,\n",
    "    particle_radius=0.6e-6,\n",
    "    particle_diffusivity=1e-16,\n",
    "    active_fraction=0.62,\n",
    "    maximum_concentration=15320,\n",
    "    initial_stoichiometry=y100,\n",
    "    reference_exchange_current=0.5,\n",
    "    electronic_conductivity=50,\n",
    "    open_circuit_potential=nvpf,\n",
    ")\n",
    "separator = BatteryElectrolyteLayer(\n",
    "    thickness=25e-6,\n",
    "    porosity=0.55,\n",
    "    electrolyte_diffusivity=2.5e-10 * 0.55**1.5,\n",
    "    electrolyte_conductivity=0.8 * 0.55**1.5,\n",
    ")\n",
    "cell = PorousElectrodeBattery(\n",
    "    negative=negative,\n",
    "    separator=separator,\n",
    "    positive=positive,\n",
    "    electrolyte_concentration=1000,\n",
    "    transference_number=0.45,\n",
    ")\n",
    "c_minus, c_plus = (\n",
    "    faraday * layer.active_fraction * layer.thickness * layer.maximum_concentration\n",
    "    for layer in (negative, positive)\n",
    ")\n",
    "capacity = c_minus * (x100 - x0)\n",
    "open_circuit = lambda q: nvpf(y100 + q / c_plus, 0) - hard_carbon(x100 - q / c_minus, 0)\n",
    "print(\n",
    "    f\"stoichiometric capacity of the hard carbon window {capacity / 3600 / 10:.4f} mAh/cm² (1C = {capacity / 3600 / 10:.3f} mA/cm²); \"\n",
    "    f\"the positive electrode is then at y = {y100 + capacity / c_plus:.3f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Discharges\n",
    "\n",
    "C/10, C/2 and 1C from the charged cell to a little past the 2.0 V cut-off (end time as a fraction\n",
    "of the nominal hour count); at 1C also on a coarser mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "rates = {0.1: 1.0, 0.5: 0.98, 1.0: 0.96}\n",
    "runs = {\n",
    "    rate: cell.solve(\n",
    "        mode=\"DFN\",\n",
    "        current_density=rate * capacity / 3600,\n",
    "        final_time=end * 3600 / rate,\n",
    "        radial_cells=16,\n",
    "        through_cells=(10, 5, 10),\n",
    "        output_times=np.linspace(0, end * 3600 / rate, 1200),\n",
    "    )\n",
    "    for rate, end in rates.items()\n",
    "}\n",
    "coarse = cell.solve(\n",
    "    mode=\"DFN\",\n",
    "    current_density=capacity / 3600,\n",
    "    final_time=rates[1.0] * 3600,\n",
    "    radial_cells=8,\n",
    "    through_cells=(5, 3, 5),\n",
    "    output_times=np.linspace(0, rates[1.0] * 3600, 1200),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "delivered = {rate: rate * capacity * run.times / 3600 for rate, run in runs.items()}\n",
    "cutoff = {\n",
    "    rate: np.interp(2.0, run.terminal_voltage[::-1], delivered[rate][::-1])\n",
    "    for rate, run in runs.items()\n",
    "}\n",
    "coarse_cutoff = np.interp(2.0, coarse.terminal_voltage[::-1], delivered[1.0][::-1])\n",
    "print(\n",
    "    f\"sodium inventory: largest relative drift {max(np.ptp(r.lithium_inventory) / r.lithium_inventory[0] for r in runs.values()):.1e}\"\n",
    ")\n",
    "print(\n",
    "    \"C-rate   capacity to 2.0 V [mAh/cm²]   of stoichiometric   mean voltage [V]   energy [mWh/cm²]\"\n",
    ")\n",
    "for rate, run in runs.items():\n",
    "    keep = delivered[rate] <= cutoff[rate]\n",
    "    energy = np.trapezoid(run.terminal_voltage[keep], delivered[rate][keep])\n",
    "    print(\n",
    "        f\"{rate:6.1f}   {cutoff[rate] / 36000:27.4f}   {100 * cutoff[rate] / capacity:15.2f} %   {energy / cutoff[rate]:16.4f}   {energy / 36000:16.4f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"1C on the coarse mesh (5, 3, 5 cells, 8 shells): {coarse_cutoff / 36000:.4f} mAh/cm², difference {100 * (coarse_cutoff / cutoff[1.0] - 1):+.2f} %\"\n",
    ")\n",
    "slow, q = runs[0.1], delivered[0.1]\n",
    "inside = (q > 0.05 * capacity) & (q < cutoff[0.1])\n",
    "print(\n",
    "    f\"C/10: mean V - U_oc = {1e3 * np.mean(slow.terminal_voltage[inside] - open_circuit(q[inside])):+.1f} mV\"\n",
    ")\n",
    "grid = np.linspace(0.05 * capacity, 0.95 * capacity, 1801)\n",
    "peak_ocv = open_circuit(grid)[np.argmax(-np.gradient(grid, open_circuit(grid)))]\n",
    "peak_sim = np.interp(grid, q, slow.terminal_voltage)[\n",
    "    np.argmax(-np.gradient(grid, np.interp(grid, q, slow.terminal_voltage)))\n",
    "]\n",
    "print(\n",
    "    f\"high-voltage NVPF plateau as dQ/dV peak: open-circuit {peak_ocv:.4f} V, C/10 discharge {peak_sim:.4f} V \"\n",
    "    f\"(polarisation {1e3 * (peak_ocv - peak_sim):.1f} mV)\"\n",
    ")\n",
    "print(\n",
    "    \"negative particle at 1C when the cell reaches 2.0 V: surface stoichiometry \"\n",
    "    f\"{np.interp(cutoff[1.0], delivered[1.0], runs[1.0].particle_surface_concentration[0].min(axis=1)) / negative.maximum_concentration:.3f}, \"\n",
    "    f\"mean {x100 - cutoff[1.0] / c_minus:.3f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(2, 2, size=(14, 10))\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"{rate:g}C\": (delivered[rate] / 36000, run.terminal_voltage)\n",
    "        for rate, run in runs.items()\n",
    "    },\n",
    "    reference={\"open-circuit voltage\": (grid / 36000, open_circuit(grid))},\n",
    "    hlines={\"cut-off 2.0 V\": 2.0},\n",
    "    ylimits=(1.8, 4.4),\n",
    "    xlabel=\"discharged capacity [mAh/cm²]\",\n",
    "    ylabel=\"terminal voltage [V]\",\n",
    "    title=\"Discharge of the sodium-ion cell\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    np.interp(grid, q, slow.terminal_voltage),\n",
    "    {\n",
    "        \"C/10 discharge\": -np.gradient(grid, np.interp(grid, q, slow.terminal_voltage))\n",
    "        / 36000\n",
    "    },\n",
    "    reference={\n",
    "        \"open-circuit voltage\": (\n",
    "            open_circuit(grid),\n",
    "            -np.gradient(grid, open_circuit(grid)) / 36000,\n",
    "        )\n",
    "    },\n",
    "    xlimits=(3.2, 4.3),\n",
    "    xlabel=\"voltage [V]\",\n",
    "    ylabel=\"dQ/dV [mAh/(cm² V)]\",\n",
    "    title=\"Differential capacity\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"{rate:g}C, hard carbon surface\": (\n",
    "            delivered[rate] / 36000,\n",
    "            run.particle_surface_concentration[0].min(axis=1)\n",
    "            / negative.maximum_concentration,\n",
    "        )\n",
    "        for rate, run in runs.items()\n",
    "    },\n",
    "    reference={\"mean (coulomb counting)\": (grid / 36000, x100 - grid / c_minus)},\n",
    "    xlabel=\"discharged capacity [mAh/cm²]\",\n",
    "    ylabel=\"sodium stoichiometry x\",\n",
    "    title=\"Hard carbon empties from the surface\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    1e6 * runs[1.0].electrolyte_positions,\n",
    "    {\n",
    "        f\"{f:.0%} of the 1C discharge\": runs[1.0].electrolyte_concentration[\n",
    "            int(f * 1199)\n",
    "        ]\n",
    "        for f in (0.05, 0.3, 0.6, 0.9)\n",
    "    },\n",
    "    vlines=[1e6 * negative.thickness, 1e6 * (negative.thickness + separator.thickness)],\n",
    "    xlabel=\"x [µm]\",\n",
    "    ylabel=\"salt concentration [mol/m³]\",\n",
    "    title=\"Electrolyte at 1C\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the representative curves by measured half-cell data, add a sodium-plating check on the\n",
    "hard-carbon plateau during fast charge, or compare with the lithium-ion cell of the rate-capability\n",
    "example at the same current per area."
   ]
  }
 ]
}
