{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Benchmark a universal ML potential on doped MoS₂\n",
    "\n",
    "Build doped MoS₂ cells, relax them with an ML potential, compute dopant formation energies, then heat a doped bilayer and watch the dopants move.\n",
    "\n",
    "Paper: Machine Learning Interatomic Potentials Enable Molecular Dynamics Simulations of Doped MoS₂\n",
    "\n",
    "Website tutorial: reproduce/uma-doped-mos2/ · Status: Example run locally · Runtime: ~1 min + ~1 min MD (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 benchmark_dopants.py\n",
    "\"\"\"Tutorial 1 — Benchmark a universal ML potential on doped MoS2.\n",
    "\n",
    "Reproduces the workflow of Faiyad & Martini, JCTC 2026 at laptop scale:\n",
    "  1. build a pristine MoS2 monolayer supercell\n",
    "  2. put one dopant on a Mo site, an S site, or between layers (intercalated, bilayer)\n",
    "  3. relax every structure with the ML potential\n",
    "  4. compute the dopant formation energy\n",
    "         E_f = E(doped) - E(pristine) + mu(removed host atom) - mu(dopant)\n",
    "     with chemical potentials mu from each element's relaxed reference phase\n",
    "  5. plot E_f per dopant and site\n",
    "\n",
    "Run:   python benchmark_dopants.py                    (MACE-MP-0 small, ~3 min on a laptop CPU)\n",
    "       python benchmark_dopants.py --model uma-s-1p1  (the model used in the paper; needs HF token)\n",
    "Output: out/formation_energies.csv, out/formation_energies.png\n",
    "\"\"\"\n",
    "import argparse\n",
    "import csv\n",
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "import numpy as np\n",
    "from ase import Atoms\n",
    "from ase.build import bulk, molecule, mx2\n",
    "from ase.constraints import FixSymmetry\n",
    "from ase.filters import FrechetCellFilter\n",
    "from ase.optimize import BFGS\n",
    "\n",
    "from models import get_calc  # noqa: E402\n",
    "\n",
    "OUT = Path(__file__).parent / \"out\"\n",
    "OUT.mkdir(exist_ok=True)\n",
    "\n",
    "# Elemental reference phases for chemical potentials (lattice constants are starting guesses; cells are relaxed).\n",
    "REF = {\n",
    "    \"Mo\": lambda: bulk(\"Mo\", \"bcc\", a=3.15),\n",
    "    \"S\": lambda: Atoms(\"S2\", positions=[[0, 0, 0], [0, 0, 1.89]]),  # S2 molecule (a simple, common reference)\n",
    "    \"Nb\": lambda: bulk(\"Nb\", \"bcc\", a=3.30),\n",
    "    \"Re\": lambda: bulk(\"Re\", \"hcp\", a=2.76, c=4.46),\n",
    "    \"Ta\": lambda: bulk(\"Ta\", \"bcc\", a=3.30),\n",
    "    \"Ti\": lambda: bulk(\"Ti\", \"hcp\", a=2.95, c=4.68),\n",
    "    \"Ru\": lambda: bulk(\"Ru\", \"hcp\", a=2.71, c=4.28),\n",
    "    \"Au\": lambda: bulk(\"Au\", \"fcc\", a=4.08),\n",
    "    \"Cu\": lambda: bulk(\"Cu\", \"fcc\", a=3.61),\n",
    "    \"Ag\": lambda: bulk(\"Ag\", \"fcc\", a=4.09),\n",
    "    \"Li\": lambda: bulk(\"Li\", \"bcc\", a=3.44),\n",
    "    \"Na\": lambda: bulk(\"Na\", \"bcc\", a=4.23),\n",
    "    \"Se\": lambda: Atoms(\"Se2\", positions=[[0, 0, 0], [0, 0, 2.17]]),\n",
    "    \"Te\": lambda: Atoms(\"Te2\", positions=[[0, 0, 0], [0, 0, 2.56]]),\n",
    "    \"O\": lambda: molecule(\"O2\"),\n",
    "    \"N\": lambda: molecule(\"N2\"),\n",
    "    \"Cl\": lambda: molecule(\"Cl2\"),\n",
    "    \"F\": lambda: molecule(\"F2\"),\n",
    "}\n",
    "MO_SITE = [\"Nb\", \"Re\", \"Ta\", \"Ti\", \"Ru\", \"Au\", \"Cu\"]\n",
    "S_SITE = [\"Se\", \"Te\", \"O\", \"N\", \"Cl\", \"F\"]\n",
    "INTERCAL = [\"Li\", \"Na\", \"Cu\", \"Ag\"]\n",
    "\n",
    "\n",
    "def relax(atoms, calc, cell=False, fmax=0.05, steps=300):\n",
    "    atoms = atoms.copy()\n",
    "    atoms.calc = calc\n",
    "    target = FrechetCellFilter(atoms) if cell else atoms\n",
    "    BFGS(target, logfile=None).run(fmax=fmax, steps=steps)\n",
    "    return atoms\n",
    "\n",
    "\n",
    "def mu(el, calc, cache={}):\n",
    "    \"\"\"Chemical potential = energy per atom of the relaxed elemental reference.\"\"\"\n",
    "    if el not in cache:\n",
    "        ref = REF[el]()\n",
    "        periodic = ref.pbc.any()\n",
    "        if not periodic:\n",
    "            ref.center(vacuum=8.0)\n",
    "            ref.pbc = True\n",
    "        r = relax(ref, calc, cell=periodic)\n",
    "        cache[el] = r.get_potential_energy() / len(r)\n",
    "    return cache[el]\n",
    "\n",
    "\n",
    "def monolayer(n=4):\n",
    "    a = mx2(\"MoS2\", kind=\"2H\", a=3.18, thickness=3.19, size=(n, n, 1), vacuum=8.0)\n",
    "    a.pbc = True\n",
    "    return a\n",
    "\n",
    "\n",
    "def bilayer(n=4, gap=6.15):\n",
    "    top = monolayer(n)\n",
    "    bot = top.copy()\n",
    "    top.translate([0, 0, gap])\n",
    "    both = bot + top\n",
    "    both.cell[2, 2] = top.positions[:, 2].max() + 8.0\n",
    "    both.center(axis=2)\n",
    "    return both\n",
    "\n",
    "\n",
    "def main():\n",
    "    ap = argparse.ArgumentParser()\n",
    "    ap.add_argument(\"--model\", default=\"mace-small\")\n",
    "    ap.add_argument(\"--size\", type=int, default=4, help=\"n x n supercell\")\n",
    "    args = ap.parse_args()\n",
    "    calc = get_calc(args.model)\n",
    "\n",
    "    rows = []\n",
    "    # --- pristine monolayer and substitutions -------------------------------------------\n",
    "    pristine = relax(monolayer(args.size), calc)\n",
    "    E0 = pristine.get_potential_energy()\n",
    "    mo_idx = next(i for i, s in enumerate(pristine.get_chemical_symbols()) if s == \"Mo\")\n",
    "    s_idx = next(i for i, s in enumerate(pristine.get_chemical_symbols()) if s == \"S\")\n",
    "    for site, idx, host, dopants in ((\"Mo-sub\", mo_idx, \"Mo\", MO_SITE), (\"S-sub\", s_idx, \"S\", S_SITE)):\n",
    "        for el in dopants:\n",
    "            d = pristine.copy()\n",
    "            d[idx].symbol = el\n",
    "            d = relax(d, calc)\n",
    "            Ef = d.get_potential_energy() - E0 + mu(host, calc) - mu(el, calc)\n",
    "            rows.append((el, site, Ef))\n",
    "            print(f\"{site:9s} {el:3s}  E_f = {Ef:7.3f} eV\", flush=True)\n",
    "\n",
    "    # --- intercalation in a bilayer --------------------------------------------------------\n",
    "    bil = relax(bilayer(args.size), calc)\n",
    "    Eb = bil.get_potential_energy()\n",
    "    z_mid = bil.positions[:, 2].mean()\n",
    "    xy = bil.cell[0, :2] * 0.5 + bil.cell[1, :2] * 0.5 / 3\n",
    "    for el in INTERCAL:\n",
    "        d = bil + Atoms(el, positions=[[xy[0], xy[1], z_mid]])\n",
    "        d = relax(d, calc)\n",
    "        Ef = d.get_potential_energy() - Eb - mu(el, calc)\n",
    "        rows.append((el, \"intercalated\", Ef))\n",
    "        print(f\"{'intercal':9s} {el:3s}  E_f = {Ef:7.3f} eV\", flush=True)\n",
    "\n",
    "    with open(OUT / \"formation_energies.csv\", \"w\", newline=\"\") as f:\n",
    "        w = csv.writer(f)\n",
    "        w.writerow([\"dopant\", \"site\", \"E_f_eV\", \"model\"])\n",
    "        for r in rows:\n",
    "            w.writerow([*r[:2], f\"{r[2]:.4f}\", args.model])\n",
    "\n",
    "    import matplotlib\n",
    "    matplotlib.use(\"Agg\")\n",
    "    import matplotlib.pyplot as plt\n",
    "    colors = {\"Mo-sub\": \"#1f6fa8\", \"S-sub\": \"#d9a20b\", \"intercalated\": \"#c2414f\"}\n",
    "    fig, ax = plt.subplots(figsize=(9, 4))\n",
    "    labels = [f\"{e}\\n{s.split('-')[0] if s != 'intercalated' else 'int'}\" for e, s, _ in rows]\n",
    "    ax.bar(range(len(rows)), [r[2] for r in rows], color=[colors[r[1]] for r in rows])\n",
    "    ax.set_xticks(range(len(rows)), labels, fontsize=8)\n",
    "    ax.axhline(0, color=\"k\", lw=0.8)\n",
    "    ax.set_ylabel(\"Formation energy (eV)\")\n",
    "    ax.set_title(f\"Dopant formation energies in MoS$_2$ ({args.model})\")\n",
    "    for k, c in colors.items():\n",
    "        ax.bar([], [], color=c, label=k)\n",
    "    ax.legend(frameon=False, fontsize=8)\n",
    "    fig.tight_layout()\n",
    "    fig.savefig(OUT / \"formation_energies.png\", dpi=160)\n",
    "    print(\"wrote\", OUT / \"formation_energies.png\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n"
   ],
   "id": "cell-4"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "%%writefile heat_md.py\n",
    "\"\"\"Tutorial 1, part 2 — heat a doped MoS2 bilayer and watch the dopants move.\n",
    "\n",
    "The paper heated 3,111-atom supercells from 300 K to 1000 K over 20 ps (NPT, UMA small) and\n",
    "tracked clustering, interlayer diffusion and compound formation. This laptop version heats a\n",
    "small Cu-intercalated bilayer with a Langevin thermostat and reports each species' mean\n",
    "squared displacement (MSD). Fast-moving dopants show up as a steep MSD curve.\n",
    "\n",
    "Run:   python heat_md.py --dopant Cu --n-dopant 4          (~2-4 min CPU with MACE small)\n",
    "Output: out/heat_<dopant>.extxyz (open in OVITO or ase gui), out/msd_<dopant>.png\n",
    "\"\"\"\n",
    "import argparse\n",
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "import numpy as np\n",
    "from ase import Atoms, units\n",
    "from ase.build import mx2\n",
    "from ase.io import write\n",
    "from ase.md.langevin import Langevin\n",
    "from ase.md.velocitydistribution import MaxwellBoltzmannDistribution\n",
    "\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 doped_bilayer(n, dopant, k, seed=0, gap=7.0, dmin=2.2):\n",
    "    \"\"\"Two MoS2 layers `gap` Å apart (pristine 2H spacing is 6.15 Å; intercalants push it open),\n",
    "    periodic along z, with `k` dopant atoms placed at random in the gap at least `dmin` Å from any atom.\"\"\"\n",
    "    layer = mx2(\"MoS2\", kind=\"2H\", a=3.18, thickness=3.19, size=(n, n, 1), vacuum=0)\n",
    "    top = layer.copy()\n",
    "    top.translate([0, 0, gap])\n",
    "    sys_ = layer + top\n",
    "    sys_.cell[2] = [0, 0, 2 * gap]  # periodic stack of bilayers\n",
    "    sys_.pbc = True\n",
    "    rng = np.random.default_rng(seed)\n",
    "    z = layer.positions[:, 2].max() + (gap - 3.19) / 2  # middle of the van der Waals gap\n",
    "    placed = 0\n",
    "    for _ in range(5000):\n",
    "        if placed == k:\n",
    "            break\n",
    "        f = rng.random(2)\n",
    "        p = f[0] * sys_.cell[0] + f[1] * sys_.cell[1] + [0, 0, z]\n",
    "        trial = sys_ + Atoms(dopant, positions=[p])\n",
    "        if trial.get_distances(len(trial) - 1, range(len(trial) - 1), mic=True).min() >= dmin:\n",
    "            sys_ = trial\n",
    "            placed += 1\n",
    "    sys_.wrap()\n",
    "    return sys_\n",
    "\n",
    "\n",
    "def main():\n",
    "    ap = argparse.ArgumentParser()\n",
    "    ap.add_argument(\"--model\", default=\"mace-small\")\n",
    "    ap.add_argument(\"--dopant\", default=\"Cu\")\n",
    "    ap.add_argument(\"--n-dopant\", type=int, default=4)\n",
    "    ap.add_argument(\"--size\", type=int, default=4)\n",
    "    ap.add_argument(\"--steps\", type=int, default=3000, help=\"1 fs steps\")\n",
    "    ap.add_argument(\"--t0\", type=float, default=300)\n",
    "    ap.add_argument(\"--t1\", type=float, default=1000)\n",
    "    args = ap.parse_args()\n",
    "\n",
    "    atoms = doped_bilayer(args.size, args.dopant, args.n_dopant)\n",
    "    atoms.calc = get_calc(args.model, dtype=\"float32\")\n",
    "    MaxwellBoltzmannDistribution(atoms, temperature_K=args.t0, rng=np.random.default_rng(1))\n",
    "    dyn = Langevin(atoms, 1.0 * units.fs, temperature_K=args.t0, friction=0.02, rng=np.random.default_rng(2))\n",
    "\n",
    "    ref = atoms.get_positions().copy()\n",
    "    prev = ref.copy()\n",
    "    unwrapped = ref.copy()\n",
    "    sym = np.array(atoms.get_chemical_symbols())\n",
    "    kinds = sorted(set(sym), key=lambda s: {\"Mo\": 0, \"S\": 1}.get(s, 2))\n",
    "    msd = {k: [] for k in kinds}\n",
    "    times, temps, frames = [], [], []\n",
    "    every = 30\n",
    "\n",
    "    def record():\n",
    "        nonlocal prev, unwrapped\n",
    "        pos = atoms.get_positions()\n",
    "        d = pos - prev\n",
    "        frac = np.linalg.solve(atoms.cell.T, d.T).T\n",
    "        frac -= np.round(frac)\n",
    "        unwrapped = unwrapped + frac @ atoms.cell\n",
    "        prev = pos.copy()\n",
    "        for k in kinds:\n",
    "            m = sym == k\n",
    "            msd[k].append(np.mean(np.sum((unwrapped[m] - ref[m]) ** 2, axis=1)))\n",
    "        times.append(dyn.get_number_of_steps() * 1e-3)\n",
    "        temps.append(atoms.get_temperature())\n",
    "        frames.append(atoms.copy())\n",
    "\n",
    "    for step in range(0, args.steps, every):\n",
    "        dyn.set_temperature(temperature_K=args.t0 + (args.t1 - args.t0) * step / args.steps)\n",
    "        dyn.run(every)\n",
    "        record()\n",
    "        if len(times) % 10 == 0:\n",
    "            print(f\"t = {times[-1]:5.2f} ps   T = {temps[-1]:6.0f} K   MSD({args.dopant}) = {msd[args.dopant][-1]:6.2f} A^2\", flush=True)\n",
    "\n",
    "    write(OUT / f\"heat_{args.dopant}.extxyz\", frames)\n",
    "    import matplotlib\n",
    "    matplotlib.use(\"Agg\")\n",
    "    import matplotlib.pyplot as plt\n",
    "    col = {\"Mo\": \"#1f6fa8\", \"S\": \"#d9a20b\"}\n",
    "    fig, ax = plt.subplots(figsize=(6, 4))\n",
    "    for k in kinds:\n",
    "        ax.plot(times, msd[k], label=k, color=col.get(k, \"#c2414f\"), lw=2)\n",
    "    ax.set_xlabel(\"Time (ps)\")\n",
    "    ax.set_ylabel(\"MSD (Å$^2$)\")\n",
    "    ax.set_title(f\"{args.dopant}-intercalated MoS$_2$ bilayer, {args.t0:.0f}→{args.t1:.0f} K\")\n",
    "    ax.legend(frameon=False)\n",
    "    fig.tight_layout()\n",
    "    fig.savefig(OUT / f\"msd_{args.dopant}.png\", dpi=160)\n",
    "    print(\"wrote\", OUT / f\"msd_{args.dopant}.png\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n"
   ],
   "id": "cell-5"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "!python benchmark_dopants.py"
   ],
   "id": "cell-6"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "!python heat_md.py --steps 3000"
   ],
   "id": "cell-7"
  },
  {
   "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 benchmark_dopants.py --model uma-s-1p1"
   ],
   "id": "cell-8"
  },
  {
   "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-9"
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "accelerator": "GPU",
  "colab": {
   "provenance": []
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}