{
 "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": [
    "# Copper speciation in ammonia solution\n",
    "\n",
    "Cupric ions bind up to four ammonia molecules and form the deep blue tetraammine complex. The\n",
    "complexes form step by step,\n",
    "\n",
    "$$\\mathrm{Cu(NH_3)_{n-1}^{2+} + NH_3 \\;\\rightleftharpoons\\; Cu(NH_3)_n^{2+}},\\qquad\n",
    "  K_n = \\frac{[\\mathrm{Cu(NH_3)}_n]}{[\\mathrm{Cu(NH_3)}_{n-1}][\\mathrm{NH_3}]},\\quad n=1\\dots4,$$\n",
    "\n",
    "while ammonia is a weak base and water ionises,\n",
    "\n",
    "$$\\mathrm{NH_4^+ \\rightleftharpoons NH_3 + H^+}\\ (K_a),\\qquad \\mathrm{H_2O \\rightleftharpoons H^+ + OH^-}\\ (K_w).$$\n",
    "\n",
    "Every equilibrium is written as a pair of mass-action reactions whose rate constants have the\n",
    "ratio of the equilibrium constant, and the well-mixed solution (0D) is integrated with the\n",
    "implicit Euler method until all reactions balance. Hydroxo complexes and the precipitation of\n",
    "copper hydroxide at low ammonia content are left out.\n",
    "\n",
    "**Reference.** Stability constants at 25 °C: $\\log K_n = 4.04,\\ 3.43,\\ 2.80,\\ 1.48$ (Martell &\n",
    "Smith, *Critical Stability Constants*, vol. 4), $\\mathrm pK_a = 9.25$, $\\mathrm pK_w = 14.00$.\n",
    "With the cumulative constants $\\beta_n=K_1\\cdots K_n$ the fraction of copper in complex $n$ at\n",
    "the free ammonia concentration $L$ is\n",
    "\n",
    "$$\\alpha_n(L)=\\frac{\\beta_nL^n}{\\sum_{j=0}^4\\beta_jL^j},\\qquad\n",
    "  \\bar n(L)=\\sum_n n\\,\\alpha_n \\ \\text{(Bjerrum's formation function)} .$$\n",
    "\n",
    "For copper sulfate in ammonia, electroneutrality gives $[\\mathrm{H^+}]=\\sqrt{K_w/(1+L/K_a)}$, and\n",
    "the ammonia balance $N_T = L\\,(1+[\\mathrm{H^+}]/K_a) + \\mathrm{Cu}_T\\,\\bar n(L)$ fixes $L$; it is\n",
    "solved here independently with a root finder."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.geometry import LumpedDomain\n",
    "from onesim.meshing import LumpedMesh\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.discretization import LumpedParameters\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.numerics.time import BackwardEuler\n",
    "from onesim.physics.chemistry import (\n",
    "    ReactionIR,\n",
    "    ReactionKinetics,\n",
    "    ReactionNetworkIR,\n",
    "    SpeciesIR,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\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": [
    "## Reaction network\n",
    "\n",
    "Concentrations are in mol/m³ (= mmol/L), so the constants in L/mol are divided by 1000. The\n",
    "complexation steps bind with $k=1$ m³/(mol s); the proton transfers are nearly diffusion-limited,\n",
    "$10^8$ m³/(mol s) (Eigen, 1964), which makes the system very stiff, a task for the implicit\n",
    "integrator."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "complexes = [\"Cu\", \"CuNH3\", \"Cu(NH3)2\", \"Cu(NH3)3\", \"Cu(NH3)4\"]\n",
    "log_K = (4.04, 3.43, 2.80, 1.48)\n",
    "Ka, Kw, fast = 10**-9.25 * 1e3, 1e-14 * 1e6, 1e8\n",
    "reactions = [\n",
    "    ReactionIR(name, reactants, products, {\"kind\": \"constant\", \"value\": k})\n",
    "    for n, lk in enumerate(log_K, 1)\n",
    "    for name, reactants, products, k in (\n",
    "        (f\"bind_{n}\", {complexes[n - 1]: 1, \"NH3\": 1}, {complexes[n]: 1}, 1.0),\n",
    "        (\n",
    "            f\"release_{n}\",\n",
    "            {complexes[n]: 1},\n",
    "            {complexes[n - 1]: 1, \"NH3\": 1},\n",
    "            1e3 / 10**lk,\n",
    "        ),\n",
    "    )\n",
    "]\n",
    "reactions += [\n",
    "    ReactionIR(\n",
    "        \"deprotonation\",\n",
    "        {\"NH4\": 1},\n",
    "        {\"NH3\": 1, \"H\": 1},\n",
    "        {\"kind\": \"constant\", \"value\": fast * Ka},\n",
    "    ),\n",
    "    ReactionIR(\n",
    "        \"protonation\",\n",
    "        {\"NH3\": 1, \"H\": 1},\n",
    "        {\"NH4\": 1},\n",
    "        {\"kind\": \"constant\", \"value\": fast},\n",
    "    ),\n",
    "    ReactionIR(\n",
    "        \"self_ionisation\",\n",
    "        {},\n",
    "        {\"H\": 1, \"OH\": 1},\n",
    "        {\"kind\": \"constant\", \"value\": fast * Kw},\n",
    "    ),\n",
    "    ReactionIR(\n",
    "        \"neutralisation\", {\"H\": 1, \"OH\": 1}, {}, {\"kind\": \"constant\", \"value\": fast}\n",
    "    ),\n",
    "]\n",
    "species = complexes + [\"NH3\", \"NH4\", \"H\", \"OH\"]\n",
    "network = ReactionNetworkIR(\n",
    "    \"copper_ammine\",\n",
    "    \"1\",\n",
    "    species=tuple(SpeciesIR(name, 0, 1e-25) for name in species),\n",
    "    reactions=tuple(reactions),\n",
    "    strict_balance=False,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Titration series\n",
    "\n",
    "One millimole per litre of copper sulfate in ammonia solutions from 0.02 mmol/L to 2 mol/L. Each\n",
    "solution starts with all ammonia free and neutral water, and runs for 300 s in 150 implicit steps,\n",
    "far beyond the slowest release time $1/k_{-4}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "domain = LumpedDomain()\n",
    "copper = 1.0\n",
    "ammonia = np.geomspace(0.02, 2000.0, 16)\n",
    "models = [ReactionKinetics(domain=domain.system, network=network) for _ in ammonia]\n",
    "numerics = Numerics(\n",
    "    spatial=LumpedParameters(),\n",
    "    time_integrator=BackwardEuler(),\n",
    "    nonlinear_solver=Newton(\n",
    "        linear_solver=SparseDirect(),\n",
    "        jacobian=\"analytic\",\n",
    "        absolute_tolerance=1e-12,\n",
    "        relative_tolerance=1e-10,\n",
    "    ),\n",
    ")\n",
    "runs = [\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"copper in {total:.1f} mM ammonia\",\n",
    "            geometry=domain,\n",
    "            physics=(model,),\n",
    "            initial_conditions=tuple(\n",
    "                InitialValue(model.concentration(name), value)\n",
    "                for name, value in {\n",
    "                    **dict.fromkeys(species, 0.0),\n",
    "                    \"Cu\": copper,\n",
    "                    \"NH3\": total,\n",
    "                    \"H\": 1e-4,\n",
    "                    \"OH\": 1e-4,\n",
    "                }.items()\n",
    "            ),\n",
    "        ),\n",
    "        mesh=LumpedMesh(domain),\n",
    "        numerics=numerics,\n",
    "    ).run(start_time=0.0, end_time=300.0, time_step=2.0)\n",
    "    for model, total in zip(models, ammonia)\n",
    "]\n",
    "final = {\n",
    "    name: np.array(\n",
    "        [\n",
    "            run.field(model.concentration(name)).values[0]\n",
    "            for run, model in zip(runs, models)\n",
    "        ]\n",
    "    )\n",
    "    for name in species\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the equilibrium\n",
    "\n",
    "Free ammonia and pH of every solution against the root of the ammonia balance, and the copper\n",
    "fractions against $\\alpha_n$ at the simulated free ammonia."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "beta = np.cumprod([1.0] + [10**lk / 1e3 for lk in log_K])\n",
    "alpha = lambda L: beta * L ** np.arange(5) / np.sum(beta * L ** np.arange(5))\n",
    "free_ammonia = lambda total: brentq(\n",
    "    lambda L: L * (1 + np.sqrt(Kw / (1 + L / Ka)) / Ka)\n",
    "    + copper * alpha(L) @ np.arange(5)\n",
    "    - total,\n",
    "    1e-12,\n",
    "    total,\n",
    ")\n",
    "free = np.array([free_ammonia(total) for total in ammonia])\n",
    "pH = -np.log10(final[\"H\"] / 1e3)\n",
    "pH_reference = -np.log10(np.sqrt(Kw / (1 + free / Ka)) / 1e3)\n",
    "fractions = np.array(\n",
    "    [[final[name][i] / copper for name in complexes] for i in range(len(ammonia))]\n",
    ")\n",
    "print(\n",
    "    f\"largest relative deviation of free NH3 from the equilibrium: {np.max(np.abs(final['NH3'] / free - 1)):.1e}\"\n",
    ")\n",
    "print(f\"largest deviation of pH: {np.max(np.abs(pH - pH_reference)):.1e}\")\n",
    "print(\n",
    "    f\"largest deviation of a copper fraction from alpha_n: {np.max(np.abs(fractions - np.array([alpha(L) for L in final['NH3']]))):.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"copper and ammonia balances: {np.max(np.abs(fractions.sum(axis=1) - 1)):.1e}, \"\n",
    "    f\"{np.max(np.abs(final['NH3'] + final['NH4'] + fractions @ np.arange(5) * copper - ammonia) / ammonia):.1e}\"\n",
    ")\n",
    "for total, L, p, row in list(zip(ammonia, final[\"NH3\"], pH, fractions))[::2]:\n",
    "    print(\n",
    "        f\"total NH3 {total:8.2f} mM: free {L:8.3f} mM, pH {p:5.2f}, fractions \"\n",
    "        + \" \".join(f\"{value:.3f}\" for value in row)\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The species distribution over the free ammonia concentration, Bjerrum's formation function and\n",
    "the pH of the solution over the total ammonia."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "L_line = np.geomspace(1e-3, 3e3, 300)\n",
    "alpha_line = np.array([alpha(L) for L in L_line])\n",
    "total_line = np.geomspace(0.015, 2500, 200)\n",
    "free_line = np.array([free_ammonia(total) for total in total_line])\n",
    "fig = plots.figure(1, 3, size=(18, 5))\n",
    "plots.line(\n",
    "    points={\n",
    "        name: (final[\"NH3\"] / 1e3, fractions[:, n]) for n, name in enumerate(complexes)\n",
    "    },\n",
    "    reference={\n",
    "        name: (L_line / 1e3, alpha_line[:, n]) for n, name in enumerate(complexes)\n",
    "    },\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"free NH3 [mol/L]\",\n",
    "    ylabel=\"fraction of copper\",\n",
    "    title=\"Copper species, dashed: exact\",\n",
    "    legend=\"center left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"OneSimulation\": (final[\"NH3\"] / 1e3, fractions @ np.arange(5))},\n",
    "    reference={\n",
    "        \"from the stability constants\": (L_line / 1e3, alpha_line @ np.arange(5))\n",
    "    },\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"free NH3 [mol/L]\",\n",
    "    ylabel=\"mean number of bound NH3\",\n",
    "    title=\"Formation function\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"OneSimulation\": (ammonia / 1e3, pH)},\n",
    "    reference={\n",
    "        \"electroneutrality and NH3 balance\": (\n",
    "            total_line / 1e3,\n",
    "            -np.log10(np.sqrt(Kw / (1 + free_line / Ka)) / 1e3),\n",
    "        )\n",
    "    },\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"total NH3 [mol/L]\",\n",
    "    ylabel=\"pH\",\n",
    "    title=\"pH of the solution\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add ammonium sulfate to buffer the solution and watch the complexes shift to lower $n$ at the\n",
    "same total ammonia. Add the hydroxo complex $\\mathrm{CuOH^+}$ as another reversible pair, or\n",
    "replace the constant rate pairs by reversible reactions with species thermochemistry to obtain\n",
    "the temperature dependence of the stability constants."
   ]
  }
 ]
}
