{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Grow a Ni-doped MoS₂ film atom by atom\n",
    "\n",
    "Deposit Mo, S and Ni atoms onto a MoS₂ substrate one at a time, then measure Ni clustering and MoS₂-like order.\n",
    "\n",
    "Paper: Modeling Sputtering Deposition of MoS₂: Effect of Ni Doping on Nanostructure and Tribological Properties\n",
    "\n",
    "Website tutorial: reproduce/nimos2-sputtering/ · Status: Example run locally · Runtime: ~7 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 deposit.py\n",
    "\"\"\"Tutorial — Grow a Ni-doped MoS2 film atom by atom.\n",
    "\n",
    "Romero Garcia, Faiyad & Martini, Comput. Mater. Sci. 244, 113229 (2024) simulated sputter\n",
    "deposition of MoS2 with 0, 2, 10 and 15 wt% Ni using reactive MD (ReaxFF), then compressed and\n",
    "sheared the films. Intermediate Ni (2 and 10 wt%) gave the lowest shear stress.\n",
    "\n",
    "This laptop/Colab version keeps the deposition idea and swaps ReaxFF for an ML potential:\n",
    "  1. start from a MoS2 monolayer substrate with its bottom row fixed\n",
    "  2. drop Mo, S and Ni atoms one at a time onto it, with a few eV of kinetic energy, at the target composition\n",
    "  3. after each impact run a short MD relaxation with a thermostat on the substrate\n",
    "  4. measure the film: Ni clustering (Ni–Ni neighbors) and MoS2-like order (Mo with 6 S neighbors)\n",
    "\n",
    "Run:   python deposit.py --ni-wt 0 10              (~10 min on a GPU for both)\n",
    "Output: out/film_<wt>.extxyz, out/film_metrics.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.constraints import FixAtoms\n",
    "from ase.io import write\n",
    "from ase.md.langevin import Langevin\n",
    "from ase.neighborlist import neighbor_list\n",
    "\n",
    "from models import get_calc  # noqa: E402\n",
    "\n",
    "OUT = Path(__file__).parent / \"out\"\n",
    "OUT.mkdir(exist_ok=True)\n",
    "MASS = {\"Mo\": 95.95, \"S\": 32.06, \"Ni\": 58.69}\n",
    "\n",
    "\n",
    "def species_sequence(n, ni_wt, rng):\n",
    "    \"\"\"Random Mo/S/Ni sequence: Mo:S = 1:2 by atoms, Ni set by weight fraction.\"\"\"\n",
    "    m_mos2 = MASS[\"Mo\"] + 2 * MASS[\"S\"]\n",
    "    x_ni = (ni_wt / MASS[\"Ni\"]) / (ni_wt / MASS[\"Ni\"] + (100 - ni_wt) / m_mos2 * 3)  # atom fraction of Ni\n",
    "    n_ni = round(n * x_ni)\n",
    "    rest = n - n_ni\n",
    "    seq = [\"Ni\"] * n_ni + [\"Mo\"] * round(rest / 3) + [\"S\"] * (rest - round(rest / 3))\n",
    "    rng.shuffle(seq)\n",
    "    return seq\n",
    "\n",
    "\n",
    "def grow(ni_wt, n_atoms, calc, seed=0, ke_eV=4.0, relax_steps=120):\n",
    "    rng = np.random.default_rng(seed)\n",
    "    film = mx2(\"MoS2\", kind=\"2H\", a=3.18, thickness=3.19, size=(4, 4, 1), vacuum=0)\n",
    "    film.cell[2] = [0, 0, 40.0]\n",
    "    film.pbc = True\n",
    "    film.set_constraint(FixAtoms(indices=[a.index for a in film if a.position[2] < film.positions[:, 2].min() + 0.5]))\n",
    "    for k, el in enumerate(species_sequence(n_atoms, ni_wt, rng)):\n",
    "        top = film.positions[:, 2].max()\n",
    "        f = rng.random(2)\n",
    "        xy = f[0] * film.cell[0] + f[1] * film.cell[1]\n",
    "        film += Atoms(el, positions=[[xy[0], xy[1], top + 4.5]])\n",
    "        v = film.get_velocities()\n",
    "        # ASE units (eV, amu, Å) make v = sqrt(2 KE / m) directly; aim straight down\n",
    "        v[-1] = [0.0, 0.0, -np.sqrt(2 * ke_eV / MASS[el])]\n",
    "        film.set_velocities(v)\n",
    "        film.calc = calc\n",
    "        Langevin(film, 1.0 * units.fs, temperature_K=300, friction=0.02, rng=rng).run(relax_steps)\n",
    "        if (k + 1) % 20 == 0:\n",
    "            print(f\"Ni {ni_wt:>4.1f} wt%: deposited {k + 1}/{n_atoms}\", flush=True)\n",
    "    return film\n",
    "\n",
    "\n",
    "def metrics(film):\n",
    "    s = np.array(film.get_chemical_symbols())\n",
    "    i, j = neighbor_list(\"ij\", film, {(\"Mo\", \"S\"): 2.8, (\"Ni\", \"Ni\"): 2.8, (\"Mo\", \"Mo\"): 0.1, (\"S\", \"S\"): 0.1,\n",
    "                                      (\"Ni\", \"S\"): 0.1, (\"Mo\", \"Ni\"): 0.1})\n",
    "    mo = np.where(s == \"Mo\")[0]\n",
    "    nS = np.array([np.sum((i == m) & (s[j] == \"S\")) for m in mo])\n",
    "    ni = np.where(s == \"Ni\")[0]\n",
    "    nNi = np.array([np.sum((i == m) & (s[j] == \"Ni\")) for m in ni]) if len(ni) else np.array([0])\n",
    "    return {\"frac_Mo_6S\": float(np.mean(nS == 6)), \"mean_Ni_Ni\": float(nNi.mean())}\n",
    "\n",
    "\n",
    "def main():\n",
    "    ap = argparse.ArgumentParser()\n",
    "    ap.add_argument(\"--ni-wt\", type=float, nargs=\"+\", default=[0, 10])\n",
    "    ap.add_argument(\"--n-atoms\", type=int, default=90)\n",
    "    ap.add_argument(\"--model\", default=\"mace-small\")\n",
    "    a = ap.parse_args()\n",
    "    calc = get_calc(a.model, dtype=\"float32\")\n",
    "    res = {}\n",
    "    for w in a.ni_wt:\n",
    "        film = grow(w, a.n_atoms, calc)\n",
    "        write(OUT / f\"film_{w:g}.extxyz\", film)\n",
    "        res[w] = metrics(film)\n",
    "        print(f\"Ni {w:g} wt%: {res[w]}\")\n",
    "\n",
    "    import matplotlib\n",
    "    matplotlib.use(\"Agg\")\n",
    "    import matplotlib.pyplot as plt\n",
    "    fig, axs = plt.subplots(1, 2, figsize=(8, 3.4))\n",
    "    ws = list(res)\n",
    "    axs[0].bar([f\"{w:g}%\" for w in ws], [res[w][\"frac_Mo_6S\"] for w in ws], color=\"#1f6fa8\")\n",
    "    axs[0].set_ylabel(\"fraction of Mo with 6 S neighbors\")\n",
    "    axs[1].bar([f\"{w:g}%\" for w in ws], [res[w][\"mean_Ni_Ni\"] for w in ws], color=\"#c2414f\")\n",
    "    axs[1].set_ylabel(\"mean Ni–Ni neighbors\")\n",
    "    for ax in axs:\n",
    "        ax.set_xlabel(\"Ni content (wt%)\")\n",
    "    fig.suptitle(\"Deposited film structure (includes the substrate)\")\n",
    "    fig.tight_layout()\n",
    "    fig.savefig(OUT / \"film_metrics.png\", dpi=160)\n",
    "    print(\"wrote\", OUT / \"film_metrics.png\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n"
   ],
   "id": "cell-4"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "!python deposit.py --ni-wt 0 10"
   ],
   "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
}