{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Diagnose a foundation potential on a molten salt\n",
    "\n",
    "Melt LiCl–FeCl₂ with an off-the-shelf ML potential and compute the partial radial distribution functions that reveal whether Fe ions cluster.\n",
    "\n",
    "Paper: Elucidating Bulk Structure, Transport Properties, and Chain Formation in Molten LiCl–FeCl₂: A Temperature and Composition Analysis\n",
    "\n",
    "Website tutorial: reproduce/licl-fecl2-molten/ · 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 molten_salt_structure.py\n",
    "\"\"\"Tutorial — Check a foundation ML potential on molten LiCl–FeCl2.\n",
    "\n",
    "The paper (under review) found that universal MACE models, trained mostly on solid crystals,\n",
    "produce spurious Fe–Fe clustering in molten LiCl–FeCl2. Fine-tuning (multi-head replay + LoRA)\n",
    "on DFT data of the melt removed the artifact; the fixed model matched high-energy X-ray diffraction.\n",
    "\n",
    "This tutorial runs the diagnostic you would run first, with the off-the-shelf model:\n",
    "  1. build a random LiCl–FeCl2 melt at a realistic density\n",
    "  2. run NVT molecular dynamics at 1000 K\n",
    "  3. compute partial radial distribution functions g(r) and the Fe–Cl coordination number\n",
    "  4. inspect Fe–Fe: a sharp first peak near the Fe–Fe metal bond length (~2.5 Å) signals clustering;\n",
    "     in a well-described salt, Fe ions sit apart, separated by Cl (first Fe–Fe peak near 3.5–4 Å)\n",
    "\n",
    "Run:   python molten_salt_structure.py                     (~5 min on a GPU; set --steps lower on CPU)\n",
    "Output: out/rdf.png, out/rdf.csv, out/melt.extxyz\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.io import write\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 coordination, 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(\"--n-licl\", type=int, default=36)\n",
    "    ap.add_argument(\"--n-fecl2\", type=int, default=12)\n",
    "    ap.add_argument(\"--density\", type=float, default=1.9, help=\"g/cm^3 (between molten LiCl ~1.5 and FeCl2 ~2.3)\")\n",
    "    ap.add_argument(\"--T\", type=float, default=1000)\n",
    "    ap.add_argument(\"--steps\", type=int, default=6000, help=\"2 fs steps\")\n",
    "    args = ap.parse_args()\n",
    "\n",
    "    counts = {\"Li\": args.n_licl, \"Fe\": args.n_fecl2, \"Cl\": args.n_licl + 2 * args.n_fecl2}\n",
    "    atoms = random_melt(counts, args.density, seed=1)\n",
    "    print(f\"{len(atoms)} ions in a {atoms.cell[0, 0]:.2f} Å box\")\n",
    "    atoms.calc = get_calc(args.model, dtype=\"float32\")\n",
    "    FIRE(atoms, logfile=None).run(fmax=0.5, steps=200)  # remove bad contacts\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",
    "\n",
    "    frames = []\n",
    "    equil = args.steps // 3\n",
    "    for i in range(0, args.steps, 50):\n",
    "        dyn.run(50)\n",
    "        if i >= equil:\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",
    "    write(OUT / \"melt.extxyz\", frames)\n",
    "\n",
    "    pairs = [(\"Li\", \"Cl\"), (\"Fe\", \"Cl\"), (\"Cl\", \"Cl\"), (\"Fe\", \"Fe\")]\n",
    "    data = {p: partial_rdf(frames, *p) for p in pairs}\n",
    "    vol = frames[0].get_volume()\n",
    "    r, g = data[(\"Fe\", \"Cl\")]\n",
    "    rmin = r[np.argmax(g) + np.argmin(g[np.argmax(g):np.argmax(g) + 40])]\n",
    "    cn = coordination(r, g, counts[\"Cl\"] / vol, rmin)\n",
    "    rf, gf = data[(\"Fe\", \"Fe\")]\n",
    "    n_fefe = coordination(rf, gf, counts[\"Fe\"] / vol, 3.0)  # Fe neighbours closer than 3 Å: the clustering signal\n",
    "    print(f\"Fe–Cl first peak {r[np.argmax(g)]:.2f} Å, coordination {cn:.2f} (cutoff {rmin:.2f} Å)\")\n",
    "    print(f\"Fe–Fe neighbours within 3.0 Å: {n_fefe:.2f} per Fe -> \"\n",
    "          f\"{'Fe clustering' if n_fefe > 0.5 else 'no clustering: Fe ions stay separated by Cl'}\")\n",
    "\n",
    "    import matplotlib\n",
    "    matplotlib.use(\"Agg\")\n",
    "    import matplotlib.pyplot as plt\n",
    "    fig, ax = plt.subplots(figsize=(6.5, 4))\n",
    "    col = {(\"Li\", \"Cl\"): \"#2e7d5b\", (\"Fe\", \"Cl\"): \"#1f6fa8\", (\"Cl\", \"Cl\"): \"#d9a20b\", (\"Fe\", \"Fe\"): \"#c2414f\"}\n",
    "    for p, (rr, gg) in data.items():\n",
    "        ax.plot(rr, gg, lw=2, color=col[p], label=f\"{p[0]}–{p[1]}\")\n",
    "    ax.axvspan(2.2, 2.8, color=\"#c2414f\", alpha=0.08)\n",
    "    ax.annotate(\"clustered Fe would\\npeak here (Fe–Fe)\", xy=(2.5, 0.3), xytext=(4.3, 5.0), fontsize=8,\n",
    "                color=\"#c2414f\", arrowprops=dict(arrowstyle=\"->\", color=\"#c2414f\"))\n",
    "    ax.set_xlabel(\"r (Å)\")\n",
    "    ax.set_ylabel(\"g(r)\")\n",
    "    ax.set_title(f\"Molten LiCl–FeCl$_2$ at {args.T:.0f} K ({args.model})\")\n",
    "    ax.legend(frameon=False)\n",
    "    fig.tight_layout()\n",
    "    fig.savefig(OUT / \"rdf.png\", dpi=160)\n",
    "    np.savetxt(OUT / \"rdf.csv\", np.column_stack([r] + [data[p][1] for p in pairs]),\n",
    "               header=\"r_A \" + \" \".join(f\"g_{a}{b}\" for a, b in pairs), fmt=\"%.4f\")\n",
    "    print(\"wrote\", OUT / \"rdf.png\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n"
   ],
   "id": "cell-5"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "!python molten_salt_structure.py"
   ],
   "id": "cell-6"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Optional: Install fairchem-core, accept the UMA model terms on Hugging Face, and sign in before running this command.\n",
    "# !python molten_salt_structure.py --model uma-s-1p1"
   ],
   "id": "cell-7"
  },
  {
   "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-8"
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "accelerator": "GPU",
  "colab": {
   "provenance": []
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}