{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Let the model choose its next training data\n",
    "\n",
    "Run Pt(111)–water MD, measure where two ML potentials disagree, and select the most uncertain frames for DFT labeling.\n",
    "\n",
    "Paper: Uncertainty-Biased Active Learning of MACE Interatomic Potentials for Complex Interfaces\n",
    "\n",
    "Website tutorial: reproduce/active-learning-interfaces/ · Status: Example run locally · Runtime: ~1 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 committee_selection.py\n",
    "\"\"\"Tutorial — Let the model tell you which structures to label next.\n",
    "\n",
    "Active learning grows a training set only where the ML potential is unsure. The in-preparation\n",
    "work (HER-AL) adds a bias force that pushes MD toward high-uncertainty configurations, labels\n",
    "those with DFT, retrains, and repeats.\n",
    "\n",
    "This tutorial builds the core of that loop with two pretrained models as a \"committee\":\n",
    "  1. run short MD of water on a Pt(111) slab with MACE-MP-0 small\n",
    "  2. re-evaluate every saved frame with MACE-MP-0 medium\n",
    "  3. uncertainty = largest per-atom force disagreement between the two models\n",
    "  4. pick the most uncertain, mutually distinct frames and write them out for DFT labeling\n",
    "\n",
    "Run:   python committee_selection.py            (~3 min on a GPU)\n",
    "Output: out/uncertainty.png, out/to_label.extxyz (frames you would send to DFT)\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 fcc111, molecule\n",
    "from ase.constraints import FixAtoms\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 pt_water(n_water=10, seed=0):\n",
    "    slab = fcc111(\"Pt\", size=(3, 3, 4), vacuum=0.0, a=3.92)\n",
    "    top = slab.positions[:, 2].max()\n",
    "    slab.cell[2, 2] = top + 14.0\n",
    "    rng = np.random.default_rng(seed)\n",
    "    placed = []\n",
    "    for _ in range(n_water):\n",
    "        for _ in range(500):\n",
    "            p = rng.random(3) * [1, 1, 0] @ slab.cell + [0, 0, top + 2.3 + rng.random() * 7]\n",
    "            if all(np.linalg.norm(p - q) > 2.8 for q in placed):\n",
    "                placed.append(p)\n",
    "                break\n",
    "        w = molecule(\"H2O\")\n",
    "        w.rotate(rng.random() * 360, rng.normal(size=3))\n",
    "        w.translate(p - w.positions[0])\n",
    "        slab += w\n",
    "    slab.set_constraint(FixAtoms(indices=[a.index for a in slab if a.symbol == \"Pt\" and a.position[2] < 2.5]))\n",
    "    slab.pbc = True\n",
    "    return slab\n",
    "\n",
    "\n",
    "def main():\n",
    "    ap = argparse.ArgumentParser()\n",
    "    ap.add_argument(\"--steps\", type=int, default=3000, help=\"0.5 fs steps\")\n",
    "    ap.add_argument(\"--T\", type=float, default=350)\n",
    "    ap.add_argument(\"--n-select\", type=int, default=5)\n",
    "    args = ap.parse_args()\n",
    "\n",
    "    atoms = pt_water()\n",
    "    atoms.calc = get_calc(\"mace-small\", dtype=\"float32\")\n",
    "    MaxwellBoltzmannDistribution(atoms, temperature_K=args.T, rng=np.random.default_rng(0))\n",
    "    dyn = Langevin(atoms, 0.5 * units.fs, temperature_K=args.T, friction=0.02, rng=np.random.default_rng(1))\n",
    "    frames, f_small = [], []\n",
    "    for i in range(0, args.steps, 25):\n",
    "        dyn.run(25)\n",
    "        frames.append(atoms.copy())\n",
    "        f_small.append(atoms.get_forces().copy())\n",
    "\n",
    "    judge = get_calc(\"mace-medium\", dtype=\"float32\")\n",
    "    sigma = []\n",
    "    for fr, fs in zip(frames, f_small):\n",
    "        fr.calc = judge\n",
    "        dev = np.linalg.norm(fr.get_forces() - fs, axis=1)\n",
    "        sigma.append(dev.max())\n",
    "    sigma = np.array(sigma)\n",
    "\n",
    "    # greedy pick: most uncertain first, skipping frames within 4 saves of an earlier pick (diversity)\n",
    "    order, picked = np.argsort(sigma)[::-1], []\n",
    "    for k in order:\n",
    "        if all(abs(k - j) > 4 for j in picked):\n",
    "            picked.append(int(k))\n",
    "        if len(picked) == args.n_select:\n",
    "            break\n",
    "    for k in picked:\n",
    "        frames[k].info[\"max_force_dev_eV_A\"] = float(sigma[k])\n",
    "        frames[k].calc = None\n",
    "    write(OUT / \"to_label.extxyz\", [frames[k] for k in sorted(picked)])\n",
    "    print(\"max force disagreement (eV/Å): median %.3f, max %.3f\" % (np.median(sigma), sigma.max()))\n",
    "    print(\"frames selected for DFT labeling:\", sorted(picked))\n",
    "\n",
    "    import matplotlib\n",
    "    matplotlib.use(\"Agg\")\n",
    "    import matplotlib.pyplot as plt\n",
    "    t = np.arange(len(sigma)) * 25 * 0.5e-3\n",
    "    fig, ax = plt.subplots(figsize=(6.5, 3.6))\n",
    "    ax.plot(t, sigma, color=\"#1f6fa8\", lw=1.5)\n",
    "    ax.plot(t[picked], sigma[picked], \"o\", color=\"#c2414f\", label=\"selected for DFT\")\n",
    "    ax.set_xlabel(\"Time (ps)\")\n",
    "    ax.set_ylabel(\"max |ΔF| small vs medium (eV/Å)\")\n",
    "    ax.set_title(\"Committee disagreement along Pt(111)–water MD\")\n",
    "    ax.legend(frameon=False)\n",
    "    fig.tight_layout()\n",
    "    fig.savefig(OUT / \"uncertainty.png\", dpi=160)\n",
    "    print(\"wrote\", OUT / \"uncertainty.png\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n"
   ],
   "id": "cell-4"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "!python committee_selection.py"
   ],
   "id": "cell-5"
  },
  {
   "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-6"
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "accelerator": "GPU",
  "colab": {
   "provenance": []
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}