{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# From g(r) to thermodynamics: Kirkwood–Buff integrals\n",
    "\n",
    "Simulate the LiCl–KCl eutectic melt and compute running Kirkwood–Buff integrals, the bridge from structure to activity coefficients and phase diagrams.\n",
    "\n",
    "Paper: Thermodynamic Properties and Phase Diagram of Molten LiCl–KCl from ML Interatomic Potentials and Kirkwood–Buff Theory\n",
    "\n",
    "Website tutorial: reproduce/licl-kcl-thermo/ · Status: Example run locally · Runtime: ~2 min (GPU). In Colab choose *Runtime → Change runtime type → GPU*."
   ],
   "id": "cell-1"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "!pip install mace-torch ase matplotlib numpy scipy"
   ],
   "id": "cell-2"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "%%writefile models.py\n",
    "\"\"\"One place to pick an ML interatomic potential for every tutorial.\n",
    "\n",
    "    from models import get_calc\n",
    "    calc = get_calc(\"mace-small\")      # default, no account needed\n",
    "    calc = get_calc(\"uma-s-1p1\")       # Meta UMA via fairchem (needs a Hugging Face token)\n",
    "\n",
    "MACE-MP-0 downloads its weights on first use (about 20-90 MB).\n",
    "UMA is gated: accept the license at https://huggingface.co/facebook/UMA and run\n",
    "`huggingface-cli login` (or set HF_TOKEN) before using it.\n",
    "\"\"\"\n",
    "import os\n",
    "\n",
    "\n",
    "def device():\n",
    "    try:\n",
    "        import torch\n",
    "        return \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
    "    except ImportError:\n",
    "        return \"cpu\"\n",
    "\n",
    "\n",
    "def get_calc(name: str = \"mace-small\", task: str = \"omat\", dtype: str = \"float64\"):\n",
    "    \"\"\"dtype: float64 for geometry optimisation, float32 (about 2x faster) for molecular dynamics.\"\"\"\n",
    "    if os.path.exists(name):  # a fine-tuned MACE model file\n",
    "        from mace.calculators import MACECalculator\n",
    "        return MACECalculator(model_paths=name, device=device(), default_dtype=dtype)\n",
    "    name = name.lower()\n",
    "    if name.startswith(\"mace\"):\n",
    "        from mace.calculators import mace_mp\n",
    "        size = name.split(\"-\", 1)[1] if \"-\" in name else \"small\"\n",
    "        return mace_mp(model=size, device=device(), default_dtype=dtype)\n",
    "    if name.startswith(\"uma\"):\n",
    "        from fairchem.core import pretrained_mlip, FAIRChemCalculator\n",
    "        predictor = pretrained_mlip.get_predict_unit(name, device=device())\n",
    "        return FAIRChemCalculator(predictor, task_name=task)\n",
    "    raise ValueError(f\"unknown model {name!r}; use mace-small, mace-medium or uma-s-1p1\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    print(\"device:\", device(), \"| HF_TOKEN set:\", bool(os.environ.get(\"HF_TOKEN\")))\n"
   ],
   "id": "cell-3"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "%%writefile melt.py\n",
    "\"\"\"Helpers shared by the molten-salt tutorials: random melt builder, RDFs, Kirkwood–Buff integrals.\"\"\"\n",
    "import numpy as np\n",
    "from ase import Atoms\n",
    "\n",
    "MASS = {\"Li\": 6.94, \"K\": 39.098, \"Na\": 22.99, \"Fe\": 55.845, \"Cl\": 35.45}\n",
    "\n",
    "\n",
    "def random_melt(counts: dict, density_g_cm3: float, seed=0, dmin=2.0):\n",
    "    \"\"\"Place ions randomly in a cubic box at the target density, keeping a minimum separation.\"\"\"\n",
    "    rng = np.random.default_rng(seed)\n",
    "    syms = [s for s, n in counts.items() for _ in range(n)]\n",
    "    mass = sum(MASS[s] for s in syms) / 6.02214076e23  # g\n",
    "    L = (mass / density_g_cm3) ** (1 / 3) * 1e8  # Å\n",
    "    pos = []\n",
    "    for s in syms:\n",
    "        for _ in range(20000):\n",
    "            p = rng.random(3) * L\n",
    "            if all(np.linalg.norm((p - q) - L * np.round((p - q) / L)) > dmin for q in pos):\n",
    "                pos.append(p)\n",
    "                break\n",
    "        else:\n",
    "            raise RuntimeError(\"could not place ion; lower density or dmin\")\n",
    "    order = rng.permutation(len(syms))\n",
    "    return Atoms([syms[i] for i in order], positions=np.array(pos)[order], cell=[L] * 3, pbc=True)\n",
    "\n",
    "\n",
    "def partial_rdf(frames, a, b, rmax=None, nbins=200):\n",
    "    \"\"\"g_ab(r) averaged over frames (cubic or orthorhombic cells, minimum image).\"\"\"\n",
    "    L = frames[0].cell.lengths()\n",
    "    rmax = rmax or 0.5 * L.min()\n",
    "    edges = np.linspace(0, rmax, nbins + 1)\n",
    "    hist = np.zeros(nbins)\n",
    "    na = nb = 0\n",
    "    for f in frames:\n",
    "        s = np.array(f.get_chemical_symbols())\n",
    "        A, B = f.positions[s == a], f.positions[s == b]\n",
    "        d = A[:, None, :] - B[None, :, :]\n",
    "        d -= f.cell.lengths() * np.round(d / f.cell.lengths())\n",
    "        r = np.linalg.norm(d, axis=-1)\n",
    "        if a == b:\n",
    "            r = r[np.triu_indices(len(A), 1)]\n",
    "        hist += np.histogram(r.ravel(), edges)[0]\n",
    "        na, nb, vol = len(A), len(B), f.get_volume()\n",
    "    pairs = na * (na - 1) / 2 if a == b else na * nb\n",
    "    shell = 4 / 3 * np.pi * (edges[1:] ** 3 - edges[:-1] ** 3)\n",
    "    g = hist / len(frames) / (pairs / vol * shell)\n",
    "    return 0.5 * (edges[1:] + edges[:-1]), g\n",
    "\n",
    "\n",
    "def coordination(r, g, rho_b, rcut):\n",
    "    m = r <= rcut\n",
    "    return 4 * np.pi * rho_b * np.trapezoid(g[m] * r[m] ** 2, r[m])\n",
    "\n",
    "\n",
    "def kb_running(r, g):\n",
    "    \"\"\"Running Kirkwood–Buff integral G(R) = 4 pi ∫_0^R (g(r) - 1) r^2 dr  (Å^3).\"\"\"\n",
    "    integrand = 4 * np.pi * (g - 1) * r ** 2\n",
    "    return np.concatenate([[0], np.cumsum(0.5 * (integrand[1:] + integrand[:-1]) * np.diff(r))])\n"
   ],
   "id": "cell-4"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "%%writefile kirkwood_buff.py\n",
    "\"\"\"Tutorial — From molten-salt structure to thermodynamics with Kirkwood–Buff integrals.\n",
    "\n",
    "Kirkwood–Buff (KB) theory links pair structure to thermodynamics. The KB integral\n",
    "      G_ij = 4π ∫ (g_ij(r) − 1) r² dr\n",
    "measures how many extra j particles surround an i particle compared with a random mixture.\n",
    "Combinations of G_ij give activity-coefficient derivatives, partial molar volumes and,\n",
    "integrated over composition, excess Gibbs energies — and from those a phase diagram.\n",
    "\n",
    "The in-preparation work does this for molten LiCl–KCl with ML-potential MD. This tutorial runs\n",
    "one composition and shows the key practical issue: the running integral G(R) must reach a plateau,\n",
    "and finite boxes make that hard. Production work uses large boxes and finite-size corrections\n",
    "(e.g. Krüger et al., J. Phys. Chem. Lett. 4, 235 (2013)).\n",
    "\n",
    "Run:   python kirkwood_buff.py --x-licl 0.58          (eutectic composition; ~5 min on a GPU)\n",
    "Output: out/kb_running.png, out/rdf_licl_kcl.png\n",
    "\"\"\"\n",
    "import argparse\n",
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "import numpy as np\n",
    "from ase import units\n",
    "from ase.md.langevin import Langevin\n",
    "from ase.md.velocitydistribution import MaxwellBoltzmannDistribution\n",
    "from ase.optimize import FIRE\n",
    "\n",
    "from melt import kb_running, partial_rdf, random_melt  # noqa: E402\n",
    "from models import get_calc  # noqa: E402\n",
    "\n",
    "OUT = Path(__file__).parent / \"out\"\n",
    "OUT.mkdir(exist_ok=True)\n",
    "\n",
    "\n",
    "def main():\n",
    "    ap = argparse.ArgumentParser()\n",
    "    ap.add_argument(\"--model\", default=\"mace-small\")\n",
    "    ap.add_argument(\"--x-licl\", type=float, default=0.58)\n",
    "    ap.add_argument(\"--n-pairs\", type=int, default=64, help=\"total cation-anion pairs\")\n",
    "    ap.add_argument(\"--density\", type=float, default=1.63, help=\"g/cm^3, approx. eutectic melt near 800 K\")\n",
    "    ap.add_argument(\"--T\", type=float, default=800)\n",
    "    ap.add_argument(\"--steps\", type=int, default=6000)\n",
    "    args = ap.parse_args()\n",
    "\n",
    "    n_li = round(args.x_licl * args.n_pairs)\n",
    "    counts = {\"Li\": n_li, \"K\": args.n_pairs - n_li, \"Cl\": args.n_pairs}\n",
    "    atoms = random_melt(counts, args.density, seed=3, dmin=2.2)\n",
    "    atoms.calc = get_calc(args.model, dtype=\"float32\")\n",
    "    FIRE(atoms, logfile=None).run(fmax=0.5, steps=200)\n",
    "    MaxwellBoltzmannDistribution(atoms, temperature_K=args.T, rng=np.random.default_rng(0))\n",
    "    dyn = Langevin(atoms, 2.0 * units.fs, temperature_K=args.T, friction=0.01, rng=np.random.default_rng(1))\n",
    "    frames = []\n",
    "    for i in range(0, args.steps, 40):\n",
    "        dyn.run(40)\n",
    "        if i >= args.steps // 3:\n",
    "            frames.append(atoms.copy())\n",
    "        if i % 1000 == 0:\n",
    "            print(f\"step {i:6d}  T = {atoms.get_temperature():6.0f} K\", flush=True)\n",
    "\n",
    "    pairs = [(\"Li\", \"Li\"), (\"K\", \"K\"), (\"Li\", \"K\"), (\"Li\", \"Cl\"), (\"K\", \"Cl\")]\n",
    "    import matplotlib\n",
    "    matplotlib.use(\"Agg\")\n",
    "    import matplotlib.pyplot as plt\n",
    "    fig1, ax1 = plt.subplots(figsize=(6, 4))\n",
    "    fig2, ax2 = plt.subplots(figsize=(6, 4))\n",
    "    for p in pairs:\n",
    "        r, g = partial_rdf(frames, *p)\n",
    "        G = kb_running(r, g)\n",
    "        ax1.plot(r, g, lw=1.8, label=f\"{p[0]}–{p[1]}\")\n",
    "        ax2.plot(r, G, lw=1.8, label=f\"{p[0]}–{p[1]}\")\n",
    "        tail = G[int(0.75 * len(G)):]\n",
    "        print(f\"G_{p[0]}{p[1]}(R) over last quarter: {tail.mean():8.1f} ± {tail.std():5.1f} Å^3\")\n",
    "    for ax, y in ((ax1, \"g(r)\"), (ax2, \"running G(R) (Å$^3$)\")):\n",
    "        ax.set_xlabel(\"r (Å)\" if ax is ax1 else \"R (Å)\")\n",
    "        ax.set_ylabel(y)\n",
    "        ax.legend(frameon=False, fontsize=8)\n",
    "    ax2.axhline(0, color=\"k\", lw=0.6)\n",
    "    ax1.set_title(f\"Li$_{{{args.x_licl:.2f}}}$K$_{{{1 - args.x_licl:.2f}}}$Cl melt, {args.T:.0f} K\")\n",
    "    ax2.set_title(\"Kirkwood–Buff running integrals (look for a plateau)\")\n",
    "    for f, n in ((fig1, \"rdf_licl_kcl.png\"), (fig2, \"kb_running.png\")):\n",
    "        f.tight_layout()\n",
    "        f.savefig(OUT / n, dpi=160)\n",
    "    print(\"wrote\", OUT / \"kb_running.png\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n"
   ],
   "id": "cell-5"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "!python kirkwood_buff.py"
   ],
   "id": "cell-6"
  },
  {
   "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-7"
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "accelerator": "GPU",
  "colab": {
   "provenance": []
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}