{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Stretch MoS₂ until it breaks, at three temperatures\n",
    "\n",
    "Pull a monolayer MoS₂ sheet apart at 100, 200 and 300 K with an ML potential, and measure flake tilt with a PCA method.\n",
    "\n",
    "Paper: Mechanisms of MoS₂ Dry Film Lubricant Behavior at Low Temperatures\n",
    "\n",
    "Website tutorial: reproduce/mos2-low-temperature/ · Status: Example run locally · Runtime: ~3 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 fracture_temperature.py\n",
    "\"\"\"Tutorial — Does cold MoS2 break at a higher stress?\n",
    "\n",
    "Faiyad et al., Friction 13, 9441020 (2025), Fig. 3: monolayer MoS2 stretched at 100, 200 and 300 K\n",
    "with reactive MD (ReaxFF) fails at a higher stress when colder. That temperature dependence is one\n",
    "step in the paper's explanation of why MoS2 lubricant debris is smaller in the cold.\n",
    "\n",
    "This version repeats the test with an ML potential (MACE-MP-0 by default, no extra files needed):\n",
    "  1. build a rectangular monolayer MoS2 cell (~144 atoms)\n",
    "  2. thermalize at temperature T with a Langevin thermostat\n",
    "  3. stretch it in small strain increments along one direction, relaxing with MD after each\n",
    "  4. record the normal stress; the peak marks failure\n",
    "\n",
    "Run:   python fracture_temperature.py --direction zigzag          (~5-10 min on a laptop CPU)\n",
    "Output: out/fracture_<direction>.png, out/fracture_<direction>.csv\n",
    "Stress is reported in GPa using an effective monolayer thickness of 6.15 Å (the MoS2 interlayer spacing).\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.build import make_supercell, mx2\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",
    "EV_A3_TO_GPA = 160.21766\n",
    "\n",
    "\n",
    "def rectangular_monolayer(nx=6, ny=4, vacuum=8.0):\n",
    "    hexcell = mx2(\"MoS2\", kind=\"2H\", a=3.18, thickness=3.19, size=(1, 1, 1), vacuum=vacuum)\n",
    "    rect = make_supercell(hexcell, [[1, 0, 0], [1, 2, 0], [0, 0, 1]])  # a x a*sqrt(3): x = zigzag, y = armchair\n",
    "    rect = rect.repeat((nx, ny, 1))\n",
    "    rect.pbc = True\n",
    "    return rect\n",
    "\n",
    "\n",
    "def pull(T, axis, calc, d_eps=0.01, max_eps=0.45, steps=60, seed=0):\n",
    "    atoms = rectangular_monolayer()\n",
    "    atoms.calc = calc\n",
    "    rng = np.random.default_rng(seed)\n",
    "    MaxwellBoltzmannDistribution(atoms, temperature_K=T, rng=rng)\n",
    "    dyn = Langevin(atoms, 1.0 * units.fs, temperature_K=T, friction=0.05, rng=rng)\n",
    "    dyn.run(400)  # thermalize\n",
    "    lz = atoms.cell[2, 2]\n",
    "    strains, stresses = [], []\n",
    "    eps = 0.0\n",
    "    while eps < max_eps:\n",
    "        cell = atoms.cell.array.copy()\n",
    "        cell[axis] *= 1 + d_eps  # stretch by one increment; total strain eps = (1 + d_eps)^n - 1\n",
    "        atoms.set_cell(cell, scale_atoms=True)\n",
    "        eps = (1 + eps) * (1 + d_eps) - 1\n",
    "        sig = []\n",
    "        for _ in range(steps // 10):\n",
    "            dyn.run(10)\n",
    "            sig.append(atoms.get_stress(voigt=True)[axis])  # ASE convention: tensile stress is positive\n",
    "        s = np.mean(sig[len(sig) // 2:]) * EV_A3_TO_GPA * lz / 6.15\n",
    "        strains.append(eps)\n",
    "        stresses.append(s)\n",
    "        print(f\"T={T:4.0f} K  strain={eps:5.3f}  stress={s:6.2f} GPa\", flush=True)\n",
    "        if len(stresses) > 4 and s < 0.5 * max(stresses):\n",
    "            break  # failed: stress collapsed\n",
    "    return np.array(strains), np.array(stresses)\n",
    "\n",
    "\n",
    "def main():\n",
    "    ap = argparse.ArgumentParser()\n",
    "    ap.add_argument(\"--model\", default=\"mace-small\")\n",
    "    ap.add_argument(\"--direction\", choices=[\"zigzag\", \"armchair\"], default=\"zigzag\")\n",
    "    ap.add_argument(\"--temps\", type=float, nargs=\"+\", default=[100, 200, 300])\n",
    "    args = ap.parse_args()\n",
    "    axis = 0 if args.direction == \"zigzag\" else 1\n",
    "    calc = get_calc(args.model, dtype=\"float32\")\n",
    "\n",
    "    import matplotlib\n",
    "    matplotlib.use(\"Agg\")\n",
    "    import matplotlib.pyplot as plt\n",
    "    fig, ax = plt.subplots(figsize=(6, 4))\n",
    "    colors = {100: \"#1f6fa8\", 200: \"#2e7d5b\", 300: \"#c2414f\"}\n",
    "    lines = [\"T_K,strain,stress_GPa\"]\n",
    "    for T in args.temps:\n",
    "        e, s = pull(T, axis, calc)\n",
    "        i = int(np.argmax(s))\n",
    "        ax.plot(e, s, color=colors.get(int(T), None), lw=2, label=f\"{T:.0f} K\")\n",
    "        ax.plot(e[i], s[i], \"*\", ms=14, color=colors.get(int(T), \"k\"))\n",
    "        print(f\"==> {T:.0f} K: failure stress {s[i]:.1f} GPa at strain {e[i]:.3f}\")\n",
    "        lines += [f\"{T:.0f},{a:.4f},{b:.3f}\" for a, b in zip(e, s)]\n",
    "    (OUT / f\"fracture_{args.direction}.csv\").write_text(\"\\n\".join(lines))\n",
    "    ax.set_xlabel(\"Engineering strain\")\n",
    "    ax.set_ylabel(\"Normal stress (GPa)\")\n",
    "    ax.set_title(f\"Monolayer MoS$_2$, {args.direction} tension ({args.model})\")\n",
    "    ax.legend(frameon=False)\n",
    "    fig.tight_layout()\n",
    "    fig.savefig(OUT / f\"fracture_{args.direction}.png\", dpi=160)\n",
    "    print(\"wrote\", OUT / f\"fracture_{args.direction}.png\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n"
   ],
   "id": "cell-4"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "%%writefile flake_angle.py\n",
    "\"\"\"Tutorial — measure how much a MoS2 flake tilts away from the sliding direction.\n",
    "\n",
    "Friction 2025, Fig. 6 defines the flake angle: the angle between a flake's basal plane and the\n",
    "shear plane. Flat flakes (small angle) slide easily; tilted flakes resist sliding. The paper found\n",
    "small and oxidized flakes stay tilted during sliding.\n",
    "\n",
    "The angle comes from principal component analysis (PCA) of one flake's atom positions:\n",
    "the eigenvector with the smallest eigenvalue is the flake normal.\n",
    "\n",
    "Run:   python flake_angle.py frames.extxyz --flake-ids flake_ids.txt   (your own simulation)\n",
    "       python flake_angle.py --demo                                    (synthetic flakes, < 1 s)\n",
    "Output: out/flake_angles.png (demo) or printed angles per frame.\n",
    "\"\"\"\n",
    "import argparse\n",
    "from pathlib import Path\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "OUT = Path(__file__).parent / \"out\"\n",
    "OUT.mkdir(exist_ok=True)\n",
    "\n",
    "\n",
    "def flake_angle(positions, shear_normal=(0, 0, 1)):\n",
    "    \"\"\"Angle in degrees between a flake's plane and the plane whose normal is `shear_normal`.\"\"\"\n",
    "    x = positions - positions.mean(axis=0)\n",
    "    w, v = np.linalg.eigh(x.T @ x)\n",
    "    normal = v[:, 0]  # smallest-variance direction\n",
    "    c = abs(normal @ np.asarray(shear_normal, float)) / np.linalg.norm(shear_normal)\n",
    "    return np.degrees(np.arccos(np.clip(c, 0, 1)))\n",
    "\n",
    "\n",
    "def synthetic_flake(n_side, tilt_deg, rng):\n",
    "    \"\"\"Flat triangular-lattice patch tilted about the y axis, with thermal noise.\"\"\"\n",
    "    a = 3.18\n",
    "    pts = np.array([[i * a + 0.5 * j * a, j * a * np.sqrt(3) / 2, 0.0] for i in range(n_side) for j in range(n_side)])\n",
    "    pts += rng.normal(0, 0.15, pts.shape)\n",
    "    t = np.radians(tilt_deg)\n",
    "    R = np.array([[np.cos(t), 0, np.sin(t)], [0, 1, 0], [-np.sin(t), 0, np.cos(t)]])\n",
    "    return pts @ R.T\n",
    "\n",
    "\n",
    "def demo():\n",
    "    rng = np.random.default_rng(0)\n",
    "    sizes = {\"small (16 atoms)\": 4, \"large (144 atoms)\": 12}\n",
    "    true = np.linspace(0, 40, 9)\n",
    "    import matplotlib\n",
    "    matplotlib.use(\"Agg\")\n",
    "    import matplotlib.pyplot as plt\n",
    "    fig, ax = plt.subplots(figsize=(5, 4))\n",
    "    for label, n in sizes.items():\n",
    "        meas = [np.mean([flake_angle(synthetic_flake(n, t, rng)) for _ in range(20)]) for t in true]\n",
    "        ax.plot(true, meas, \"o-\", label=label)\n",
    "    ax.plot(true, true, \"k:\", lw=1, label=\"exact\")\n",
    "    ax.set_xlabel(\"Imposed tilt (°)\")\n",
    "    ax.set_ylabel(\"Measured flake angle (°)\")\n",
    "    ax.legend(frameon=False)\n",
    "    ax.set_title(\"PCA flake-angle check\")\n",
    "    fig.tight_layout()\n",
    "    fig.savefig(OUT / \"flake_angles.png\", dpi=160)\n",
    "    print(\"wrote\", OUT / \"flake_angles.png\")\n",
    "\n",
    "\n",
    "def main():\n",
    "    ap = argparse.ArgumentParser()\n",
    "    ap.add_argument(\"traj\", nargs=\"?\")\n",
    "    ap.add_argument(\"--flake-ids\", help=\"text file: one integer flake id per atom (same order as the trajectory)\")\n",
    "    ap.add_argument(\"--demo\", action=\"store_true\")\n",
    "    a = ap.parse_args()\n",
    "    if a.demo or not a.traj:\n",
    "        return demo()\n",
    "    from ase.io import iread\n",
    "    ids = np.loadtxt(a.flake_ids, dtype=int)\n",
    "    for k, frame in enumerate(iread(a.traj)):\n",
    "        pos = frame.get_positions()\n",
    "        angles = [flake_angle(pos[ids == f]) for f in np.unique(ids) if (ids == f).sum() >= 6]\n",
    "        print(f\"frame {k}: mean flake angle {np.mean(angles):.1f}° over {len(angles)} flakes\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n"
   ],
   "id": "cell-5"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "!python fracture_temperature.py --direction zigzag"
   ],
   "id": "cell-6"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "!python flake_angle.py --demo"
   ],
   "id": "cell-7"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Optional: Use this command to pull along the other crystal direction. The example output below is from zigzag tension.\n",
    "# !python fracture_temperature.py --direction armchair"
   ],
   "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
}