{
 "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": [
    "# Corrosion of iron in aerated water: Evans diagram and mixed potential\n",
    "\n",
    "A piece of iron in neutral, aerated water corrodes because two electrode reactions run on\n",
    "the same metal surface at the same potential $E$: the anodic dissolution of the metal and\n",
    "the cathodic reduction of dissolved oxygen,\n",
    "\n",
    "$$\\mathrm{Fe}\\rightarrow\\mathrm{Fe^{2+}}+2e^-,\\qquad \\mathrm{O_2}+2\\mathrm{H_2O}+4e^-\\rightarrow4\\,\\mathrm{OH^-}.$$\n",
    "\n",
    "Far from their equilibrium potentials both follow Tafel laws, and the oxygen reduction is\n",
    "limited by the diffusion of oxygen to the surface (limiting current density $i_L$):\n",
    "\n",
    "$$i_a=i_{0,a}\\,10^{(E-E_a)/b_a},\\qquad\n",
    "  |i_c|=\\frac{i_k}{1+i_k/i_L},\\quad i_k=i_{0,c}\\,10^{-(E-E_c)/b_c}.$$\n",
    "\n",
    "A freely corroding electrode carries no net current, $i_a=|i_c|$: this fixes the\n",
    "corrosion (mixed) potential $E_\\mathrm{corr}$ and the corrosion current density\n",
    "$i_\\mathrm{corr}$. OneSimulation's `ElectrodePolarization` holds the two reactions\n",
    "(`TafelReaction`, one with a transport limit); `solve_stationary()` returns the\n",
    "polarisation curve over a potential sweep, and `mixed_potential()` solves the current\n",
    "balance with a selectable nonlinear solver.\n",
    "\n",
    "**Reference.** U. R. Evans, *The Corrosion and Oxidation of Metals*, Arnold 1960;\n",
    "D. A. Jones, *Principles and Prevention of Corrosion*, 2nd ed., Prentice Hall 1996,\n",
    "ch. 3-4. Without transport limit the intersection of the two Tafel lines is closed form,\n",
    "\n",
    "$$E_\\mathrm{corr}=\\frac{\\log_{10}(i_{0,c}/i_{0,a})+E_a/b_a+E_c/b_c}{1/b_a+1/b_c},\\qquad\n",
    "  i_\\mathrm{corr}=i_{0,a}\\,10^{(E_\\mathrm{corr}-E_a)/b_a};$$\n",
    "\n",
    "when oxygen transport controls, $i_\\mathrm{corr}\\to i_L$ and\n",
    "$E_\\mathrm{corr}\\to E_a+b_a\\log_{10}(i_L/i_{0,a})$. In between, the balance is solved\n",
    "independently with a bracketing root finder. Faraday's law turns the corrosion current\n",
    "into a penetration rate $\\dot d=i_\\mathrm{corr}M/(nF\\rho)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.materials import TafelReaction\n",
    "from onesim.numerics.nonlinear import LeastSquares\n",
    "from onesim.physics.chemistry import ElectrodePolarization\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.optimize import brentq\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Electrode kinetics\n",
    "\n",
    "Potentials against the standard hydrogen electrode. Iron: $E_a=-0.44$ V, $i_{0,a}=10^{-3}$\n",
    "A/m², $b_a=60$ mV/decade. Oxygen at pH 7: $E_c=+0.80$ V, $i_{0,c}=10^{-6}$ A/m²,\n",
    "$b_c=120$ mV/decade, and a limiting current density of 0.1 A/m² for still, air-saturated\n",
    "water at room temperature (values of the order given by Jones, ch. 3)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "iron = {\"potential\": -0.44, \"exchange\": 1e-3, \"slope\": 0.06}\n",
    "oxygen = {\"potential\": 0.80, \"exchange\": 1e-6, \"slope\": 0.12}\n",
    "limiting, molar_mass, density, faraday = 0.1, 55.845e-3, 7874.0, 96485.33212\n",
    "sweep = np.linspace(-0.75, 0.30, 421)\n",
    "electrode = lambda limit: ElectrodePolarization(\n",
    "    reactions=(\n",
    "        TafelReaction(\n",
    "            reaction_id=\"iron dissolution\",\n",
    "            exchange_current_density=iron[\"exchange\"],\n",
    "            equilibrium_potential=iron[\"potential\"],\n",
    "            tafel_slope=iron[\"slope\"],\n",
    "            direction=\"anodic\",\n",
    "        ),\n",
    "        TafelReaction(\n",
    "            reaction_id=\"oxygen reduction\",\n",
    "            exchange_current_density=oxygen[\"exchange\"],\n",
    "            equilibrium_potential=oxygen[\"potential\"],\n",
    "            tafel_slope=oxygen[\"slope\"],\n",
    "            direction=\"cathodic\",\n",
    "            limiting_current_density=limit,\n",
    "        ),\n",
    "    ),\n",
    "    potential_sweep=sweep,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mixed potential\n",
    "\n",
    "The current balance is solved with Levenberg-Marquardt between -0.8 V and +0.3 V; the\n",
    "independent reference is a bracketing root of the same balance written out by hand."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solver = LeastSquares(method=\"levenberg_marquardt\")\n",
    "corrosion = electrode(limiting).mixed_potential(\n",
    "    bounds=(-0.8, 0.3), solver=solver, current_tolerance=1e-12\n",
    ")\n",
    "balance = lambda E, limit: (\n",
    "    iron[\"exchange\"] * 10 ** ((E - iron[\"potential\"]) / iron[\"slope\"])\n",
    "    - 1\n",
    "    / (\n",
    "        1 / (oxygen[\"exchange\"] * 10 ** (-(E - oxygen[\"potential\"]) / oxygen[\"slope\"]))\n",
    "        + 1 / limit\n",
    "    )\n",
    ")\n",
    "reference = brentq(balance, -0.8, 0.3, args=(limiting,), xtol=1e-14)\n",
    "tafel_potential = (\n",
    "    np.log10(oxygen[\"exchange\"] / iron[\"exchange\"])\n",
    "    + iron[\"potential\"] / iron[\"slope\"]\n",
    "    + oxygen[\"potential\"] / oxygen[\"slope\"]\n",
    ") / (1 / iron[\"slope\"] + 1 / oxygen[\"slope\"])\n",
    "current = corrosion.reaction_current_densities[\"iron dissolution\"]\n",
    "print(\n",
    "    f\"corrosion potential {corrosion.potential:.6f} V (independent root {reference:.6f} V, \"\n",
    "    f\"transport-limit estimate {iron['potential'] + iron['slope'] * np.log10(limiting / iron['exchange']):.6f} V)\"\n",
    ")\n",
    "print(\n",
    "    f\"corrosion current density {current:.6f} A/m² (limiting current {limiting} A/m²), balance residual {corrosion.balance_residual:.1e} A/m², \"\n",
    "    f\"{corrosion.evaluations} evaluations\"\n",
    ")\n",
    "print(\n",
    "    f\"penetration rate of iron: {current * molar_mass / (2 * faraday * density) * 1e3 * 3.15576e7:.3f} mm/year\"\n",
    ")\n",
    "print(\n",
    "    f\"without transport limit the Tafel lines would cross at {tafel_potential:.4f} V and \"\n",
    "    f\"{iron['exchange'] * 10 ** ((tafel_potential - iron['potential']) / iron['slope']):.1f} A/m²\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Oxygen supply\n",
    "\n",
    "The limiting current density grows with stirring, flow and oxygen content. Over seven\n",
    "decades of $i_L$ the corrosion current moves from transport control ($i_\\mathrm{corr}=i_L$)\n",
    "to activation control (the Tafel intersection)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "limits = np.logspace(-3, 4, 29)\n",
    "points = [\n",
    "    electrode(limit).mixed_potential(\n",
    "        bounds=(-0.8, 0.3), solver=solver, current_tolerance=1e-12\n",
    "    )\n",
    "    for limit in limits\n",
    "]\n",
    "potentials = np.array([p.potential for p in points])\n",
    "currents = np.array([p.reaction_current_densities[\"iron dissolution\"] for p in points])\n",
    "roots = np.array(\n",
    "    [brentq(balance, -0.8, 0.3, args=(limit,), xtol=1e-14) for limit in limits]\n",
    ")\n",
    "print(\n",
    "    f\"largest deviation of the corrosion potential from the independent root over the sweep: {np.abs(potentials - roots).max():.1e} V\"\n",
    ")\n",
    "print(\n",
    "    f\"i_corr / i_L at i_L = 1e-3 A/m²: {currents[0] / limits[0]:.4f};  i_corr at i_L = 1e4 A/m²: {currents[-1]:.2f} A/m² \"\n",
    "    f\"(Tafel intersection {iron['exchange'] * 10 ** ((tafel_potential - iron['potential']) / iron['slope']):.2f} A/m²)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The Evans diagram (potential against the logarithm of the current density of each branch,\n",
    "with the net polarisation curve), and the corrosion current and potential against the oxygen\n",
    "limiting current with their two closed-form limits."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "curve = electrode(limiting).solve_stationary()\n",
    "tafel_current = iron[\"exchange\"] * 10 ** (\n",
    "    (tafel_potential - iron[\"potential\"]) / iron[\"slope\"]\n",
    ")\n",
    "fig = plots.figure(1, 3, size=(18, 5.5))\n",
    "plots.line(\n",
    "    y={\n",
    "        \"iron dissolution\": (\n",
    "            np.abs(curve.reaction_current_densities[\"iron dissolution\"]),\n",
    "            curve.potential,\n",
    "        ),\n",
    "        \"oxygen reduction\": (\n",
    "            np.abs(curve.reaction_current_densities[\"oxygen reduction\"]),\n",
    "            curve.potential,\n",
    "        ),\n",
    "        \"net current |i|\": (np.abs(curve.current_density), curve.potential),\n",
    "    },\n",
    "    points={\"corrosion point\": (np.array([current]), np.array([corrosion.potential]))},\n",
    "    vlines={\"limiting current\": limiting},\n",
    "    colors={\"net current |i|\": 6},\n",
    "    styles={\"net current |i|\": \"dashed\"},\n",
    "    scale=\"logx\",\n",
    "    xlimits=(1e-5, 1e3),\n",
    "    ylimits=(-0.75, 0.3),\n",
    "    xlabel=\"current density |i| [A/m²]\",\n",
    "    ylabel=\"potential E [V vs SHE]\",\n",
    "    title=\"Evans diagram\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"OneSimulation\": (limits, currents)},\n",
    "    reference={\n",
    "        \"transport control i = i_L\": (limits, limits),\n",
    "        \"Tafel intersection\": (limits, np.full_like(limits, tafel_current)),\n",
    "    },\n",
    "    scale=\"loglog\",\n",
    "    ylimits=(5e-4, 3e2),\n",
    "    xlabel=\"oxygen limiting current i_L [A/m²]\",\n",
    "    ylabel=\"corrosion current i_corr [A/m²]\",\n",
    "    title=\"Corrosion current against oxygen supply\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"OneSimulation\": (limits, potentials)},\n",
    "    reference={\n",
    "        \"independent root\": (limits, roots),\n",
    "        \"E_a + b_a log(i_L / i_0a)\": (\n",
    "            limits,\n",
    "            iron[\"potential\"] + iron[\"slope\"] * np.log10(limits / iron[\"exchange\"]),\n",
    "        ),\n",
    "    },\n",
    "    hlines={\"Tafel intersection\": tafel_potential},\n",
    "    scale=\"logx\",\n",
    "    ylimits=(-0.65, -0.05),\n",
    "    xlabel=\"oxygen limiting current i_L [A/m²]\",\n",
    "    ylabel=\"corrosion potential E_corr [V vs SHE]\",\n",
    "    title=\"Corrosion potential\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a second cathodic reaction, hydrogen evolution, and lower the pH: below about pH 4 it\n",
    "overtakes oxygen reduction and the corrosion current no longer follows the oxygen supply.\n",
    "Couple the iron to zinc in a galvanic pair by adding the zinc dissolution branch: the mixed\n",
    "potential drops and the iron current falls (cathodic protection). Measured polarisation\n",
    "data can be fitted for the Tafel parameters with the least-squares `fit` of a\n",
    "`SimulationStudyService` built on the same model."
   ]
  }
 ]
}
