{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# How force fields and mixing rules change gold–ion interactions\n",
    "\n",
    "Recompute the Au–ion Lennard-Jones cross terms for the four ion force fields in the paper’s Table I, and see how far they disagree.\n",
    "\n",
    "Paper: Deriving Effective Electrode–Ion Interactions from Free-Energy Profiles at Electrochemical Interfaces\n",
    "\n",
    "Website tutorial: reproduce/electrode-ion-interactions/ · Status: Example run locally · Runtime: < 2 s."
   ],
   "id": "cell-1"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "!pip install numpy matplotlib"
   ],
   "id": "cell-2"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "%%writefile lj_mixing.py\n",
    "\"\"\"Tutorial — Why mixing rules can flip the sign of ion adsorption on gold.\n",
    "\n",
    "Roncoroni, Faiyad et al., J. Chem. Phys. 164, 084702 (2026), Table I lists four popular ion\n",
    "force fields. Au is modeled with Heinz et al. (2008) parameters. Classical MD never fits the\n",
    "Au–ion cross term directly: it is built from the pure terms with a mixing rule.\n",
    "\n",
    "  Lorentz–Berthelot:  sigma_ij = (sigma_i + sigma_j)/2,   eps_ij = sqrt(eps_i eps_j)\n",
    "  Geometric:          sigma_ij = sqrt(sigma_i sigma_j),    eps_ij = sqrt(eps_i eps_j)\n",
    "\n",
    "This script computes the Au–ion 12-6 Lennard-Jones well for every force field and both rules.\n",
    "Well depths vary across force fields. For a given force field, the two mixing rules can shift\n",
    "the position of the minimum. The paper tested both effects using adsorption free-energy profiles.\n",
    "The final fit adjusted both eps_ij and sigma_ij to approximate the UMA-S(OMat) profiles.\n",
    "\n",
    "Run:   python lj_mixing.py            (pure NumPy, < 2 s)\n",
    "Output: out/au_ion_wells.csv, out/au_ion_lj.png\n",
    "\"\"\"\n",
    "from pathlib import Path\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "OUT = Path(__file__).parent / \"out\"\n",
    "OUT.mkdir(exist_ok=True)\n",
    "\n",
    "AU = (5.29000, 2.6290)  # eps [kcal/mol], sigma [Å]  (Heinz et al. 2008, as used in the paper)\n",
    "# Table I of the paper: (eps, sigma) for Na+, Cl-, F- and the mixing rule each force field was built with.\n",
    "FF = {\n",
    "    \"Jorgensen\": {\"Na+\": (0.0005, 4.0700), \"Cl-\": (0.7100, 4.0200), \"F-\": (0.7100, 3.0500), \"rule\": \"geometric\"},\n",
    "    \"Cheatham\":  {\"Na+\": (0.0874, 2.4393), \"Cl-\": (0.0356, 4.4777), \"F-\": (0.0034, 4.1035), \"rule\": \"LB\"},\n",
    "    \"Merz\":      {\"Na+\": (0.0276, 2.5996), \"Cl-\": (0.6380, 4.0981), \"F-\": (0.2414, 3.2678), \"rule\": \"LB\"},\n",
    "    \"Dang\":      {\"Na+\": (0.1300, 2.3500), \"Cl-\": (0.1000, 4.4500), \"F-\": (0.2000, 3.1680), \"rule\": \"LB\"},\n",
    "}\n",
    "\n",
    "\n",
    "def mix(a, b, rule):\n",
    "    eps = np.sqrt(a[0] * b[0])\n",
    "    sig = 0.5 * (a[1] + b[1]) if rule == \"LB\" else np.sqrt(a[1] * b[1])\n",
    "    return eps, sig\n",
    "\n",
    "\n",
    "def lj(r, eps, sig):\n",
    "    x = (sig / r) ** 6\n",
    "    return 4 * eps * (x * x - x)\n",
    "\n",
    "\n",
    "rows = []\n",
    "for ff, d in FF.items():\n",
    "    for ion in (\"Na+\", \"Cl-\", \"F-\"):\n",
    "        for rule in (\"LB\", \"geometric\"):\n",
    "            eps, sig = mix(AU, d[ion], rule)\n",
    "            rows.append((ff, ion, rule, eps, sig, 2 ** (1 / 6) * sig, rule == d[\"rule\"]))\n",
    "\n",
    "with open(OUT / \"au_ion_wells.csv\", \"w\") as f:\n",
    "    f.write(\"force_field,ion,mixing_rule,eps_kcal_mol,sigma_A,r_min_A,native_rule\\n\")\n",
    "    for r in rows:\n",
    "        f.write(f\"{r[0]},{r[1]},{r[2]},{r[3]:.4f},{r[4]:.4f},{r[5]:.3f},{r[6]}\\n\")\n",
    "\n",
    "print(f\"{'force field':10s} {'ion':4s} {'rule':9s}  well depth (kcal/mol)  r_min (Å)\")\n",
    "for r in rows:\n",
    "    print(f\"{r[0]:10s} {r[1]:4s} {r[2]:9s}  {r[3]:8.3f}{'  <- native' if r[6] else '':12s}  {r[5]:6.2f}\")\n",
    "\n",
    "# Spread of the native-rule Au–Cl well depth across force fields (the headline of the comparison)\n",
    "cl = [r[3] for r in rows if r[1] == \"Cl-\" and r[6]]\n",
    "print(f\"\\nAu–Cl- well depth across force fields (native rules): {min(cl):.2f} to {max(cl):.2f} kcal/mol \"\n",
    "      f\"({max(cl) / min(cl):.0f}x spread)\")\n",
    "\n",
    "import matplotlib\n",
    "matplotlib.use(\"Agg\")\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "r = np.linspace(2.2, 9, 600)\n",
    "fig, axes = plt.subplots(1, 3, figsize=(12, 3.8), sharey=True)\n",
    "colors = {\"Jorgensen\": \"#1f6fa8\", \"Cheatham\": \"#d9a20b\", \"Merz\": \"#c2414f\", \"Dang\": \"#2e7d5b\"}\n",
    "for ax, ion in zip(axes, (\"Na+\", \"Cl-\", \"F-\")):\n",
    "    for ff, d in FF.items():\n",
    "        for rule, ls in ((\"LB\", \"-\"), (\"geometric\", \":\")):\n",
    "            eps, sig = mix(AU, d[ion], rule)\n",
    "            ax.plot(r, lj(r, eps, sig), ls, color=colors[ff], lw=2 if rule == d[\"rule\"] else 1.2,\n",
    "                    label=f\"{ff} ({'LB' if rule == 'LB' else 'geom.'})\")\n",
    "    ax.axhline(0, color=\"k\", lw=0.6)\n",
    "    ax.set_ylim(-2.2, 1.5)\n",
    "    ax.set_xlabel(\"Au–ion distance (Å)\")\n",
    "    ax.set_title(f\"Au–{ion}\")\n",
    "axes[0].set_ylabel(\"LJ energy (kcal/mol)\")\n",
    "axes[2].legend(fontsize=7, frameon=False, ncol=1, loc=\"lower right\")\n",
    "fig.suptitle(\"Same ions, same gold, different force fields and mixing rules\", y=1.02)\n",
    "fig.tight_layout()\n",
    "fig.savefig(OUT / \"au_ion_lj.png\", dpi=160, bbox_inches=\"tight\")\n",
    "print(\"wrote\", OUT / \"au_ion_lj.png\")\n",
    "\n",
    "\n",
    "def rescale_eps(eps0, target_scale):\n",
    "    \"\"\"Illustrate the paper's initial gold–sodium well-depth sweep at fixed sigma_ij.\"\"\"\n",
    "    return eps0 * target_scale\n"
   ],
   "id": "cell-3"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "!python lj_mixing.py"
   ],
   "id": "cell-4"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "from IPython.display import Image, display\n",
    "import glob\n",
    "for f in sorted(glob.glob('out/*.png') + glob.glob('*.png')):\n",
    "    print(f); display(Image(f))"
   ],
   "id": "cell-5"
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "colab": {
   "provenance": []
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}