Example run locallyPython · ML potential · ~3 min (GPU)

Stretch MoS₂ until it breaks, at three temperatures

Pull a monolayer MoS₂ sheet apart at 100, 200 and 300 K with an ML potential, and measure flake tilt with a PCA method.

Download notebook

What you will learn

  • How to run strain-controlled tension with molecular dynamics
  • How to convert the ASE stress of a 2D sheet to GPa
  • How to measure flake orientation from atom positions

Set up

pip install mace-torch ase matplotlib numpy scipy

Files for this tutorial:

Put the shared files in common/, next to the mos2-low-temperature/ directory. Run the commands from mos2-low-temperature/.

How it works

  1. Build a rectangular sheet

    A rectangular cell lets you stretch along a pure crystal direction: x is zigzag, y is armchair. The sheet has 144 atoms.

  2. Thermalize, then stretch in steps

    After 400 fs at temperature, the cell grows by 1% along the pull axis. A short MD run follows every step. The stress is averaged over the second half of that run.

  3. Find the failure point

    The peak stress marks failure. The script stops when stress drops below half of its maximum.

  4. Measure flake tilt

    flake_angle.py takes one flake’s atoms, finds the direction of least spread (the flake normal) with PCA, and reports its angle to the shear plane. Run it with --demo to check it against flakes with a known tilt.

Run it

The local run used MACE-MP-0 with mace-torch 0.3.17 on an NVIDIA GeForce RTX 5080.

python fracture_temperature.py --direction zigzag
python flake_angle.py --demo

Optional

Use this command to pull along the other crystal direction. The example output below is from zigzag tension.

python fracture_temperature.py --direction armchair

What you should see

Three stress–strain curves with stars marking their peak stresses.
Output of fracture_temperature.py (MACE-MP-0 small). Stars mark failure: 24.5 GPa at 100 K, 23.6 GPa at 200 K, 22.7 GPa at 300 K. Colder sheets fail at a higher stress and strain, the same trend as the paper’s ReaxFF result.
Measured and imposed flake angles compared with a diagonal reference line.
flake_angle.py --demo: measured vs imposed tilt for small and large synthetic flakes.

How this differs from the paper

The paper used ReaxFF in LAMMPS, two independent runs per condition, and larger sheets. It also simulated water adsorption and sliding of flake films, which need ReaxFF and longer runs. This version reproduces the fracture test (paper Fig. 3) with an ML potential. Absolute strengths depend on the potential, the strain rate and the sheet size.

Full source

fracture_temperature.py (105 lines)
fracture_temperature.py
"""Tutorial — Does cold MoS2 break at a higher stress?

Faiyad et al., Friction 13, 9441020 (2025), Fig. 3: monolayer MoS2 stretched at 100, 200 and 300 K
with reactive MD (ReaxFF) fails at a higher stress when colder. That temperature dependence is one
step in the paper's explanation of why MoS2 lubricant debris is smaller in the cold.

This version repeats the test with an ML potential (MACE-MP-0 by default, no extra files needed):
  1. build a rectangular monolayer MoS2 cell (~144 atoms)
  2. thermalize at temperature T with a Langevin thermostat
  3. stretch it in small strain increments along one direction, relaxing with MD after each
  4. record the normal stress; the peak marks failure

Run:   python fracture_temperature.py --direction zigzag          (~5-10 min on a laptop CPU)
Output: out/fracture_<direction>.png, out/fracture_<direction>.csv
Stress is reported in GPa using an effective monolayer thickness of 6.15 Å (the MoS2 interlayer spacing).
"""
import argparse
import sys
from pathlib import Path

import numpy as np
from ase import units
from ase.build import make_supercell, mx2
from ase.md.langevin import Langevin
from ase.md.velocitydistribution import MaxwellBoltzmannDistribution

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "common"))
from models import get_calc  # noqa: E402

OUT = Path(__file__).parent / "out"
OUT.mkdir(exist_ok=True)
EV_A3_TO_GPA = 160.21766


def rectangular_monolayer(nx=6, ny=4, vacuum=8.0):
    hexcell = mx2("MoS2", kind="2H", a=3.18, thickness=3.19, size=(1, 1, 1), vacuum=vacuum)
    rect = make_supercell(hexcell, [[1, 0, 0], [1, 2, 0], [0, 0, 1]])  # a x a*sqrt(3): x = zigzag, y = armchair
    rect = rect.repeat((nx, ny, 1))
    rect.pbc = True
    return rect


def pull(T, axis, calc, d_eps=0.01, max_eps=0.45, steps=60, seed=0):
    atoms = rectangular_monolayer()
    atoms.calc = calc
    rng = np.random.default_rng(seed)
    MaxwellBoltzmannDistribution(atoms, temperature_K=T, rng=rng)
    dyn = Langevin(atoms, 1.0 * units.fs, temperature_K=T, friction=0.05, rng=rng)
    dyn.run(400)  # thermalize
    lz = atoms.cell[2, 2]
    strains, stresses = [], []
    eps = 0.0
    while eps < max_eps:
        cell = atoms.cell.array.copy()
        cell[axis] *= 1 + d_eps  # stretch by one increment; total strain eps = (1 + d_eps)^n - 1
        atoms.set_cell(cell, scale_atoms=True)
        eps = (1 + eps) * (1 + d_eps) - 1
        sig = []
        for _ in range(steps // 10):
            dyn.run(10)
            sig.append(atoms.get_stress(voigt=True)[axis])  # ASE convention: tensile stress is positive
        s = np.mean(sig[len(sig) // 2:]) * EV_A3_TO_GPA * lz / 6.15
        strains.append(eps)
        stresses.append(s)
        print(f"T={T:4.0f} K  strain={eps:5.3f}  stress={s:6.2f} GPa", flush=True)
        if len(stresses) > 4 and s < 0.5 * max(stresses):
            break  # failed: stress collapsed
    return np.array(strains), np.array(stresses)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", default="mace-small")
    ap.add_argument("--direction", choices=["zigzag", "armchair"], default="zigzag")
    ap.add_argument("--temps", type=float, nargs="+", default=[100, 200, 300])
    args = ap.parse_args()
    axis = 0 if args.direction == "zigzag" else 1
    calc = get_calc(args.model, dtype="float32")

    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots(figsize=(6, 4))
    colors = {100: "#1f6fa8", 200: "#2e7d5b", 300: "#c2414f"}
    lines = ["T_K,strain,stress_GPa"]
    for T in args.temps:
        e, s = pull(T, axis, calc)
        i = int(np.argmax(s))
        ax.plot(e, s, color=colors.get(int(T), None), lw=2, label=f"{T:.0f} K")
        ax.plot(e[i], s[i], "*", ms=14, color=colors.get(int(T), "k"))
        print(f"==> {T:.0f} K: failure stress {s[i]:.1f} GPa at strain {e[i]:.3f}")
        lines += [f"{T:.0f},{a:.4f},{b:.3f}" for a, b in zip(e, s)]
    (OUT / f"fracture_{args.direction}.csv").write_text("\n".join(lines))
    ax.set_xlabel("Engineering strain")
    ax.set_ylabel("Normal stress (GPa)")
    ax.set_title(f"Monolayer MoS$_2$, {args.direction} tension ({args.model})")
    ax.legend(frameon=False)
    fig.tight_layout()
    fig.savefig(OUT / f"fracture_{args.direction}.png", dpi=160)
    print("wrote", OUT / f"fracture_{args.direction}.png")


if __name__ == "__main__":
    main()
flake_angle.py (81 lines)
flake_angle.py
"""Tutorial — measure how much a MoS2 flake tilts away from the sliding direction.

Friction 2025, Fig. 6 defines the flake angle: the angle between a flake's basal plane and the
shear plane. Flat flakes (small angle) slide easily; tilted flakes resist sliding. The paper found
small and oxidized flakes stay tilted during sliding.

The angle comes from principal component analysis (PCA) of one flake's atom positions:
the eigenvector with the smallest eigenvalue is the flake normal.

Run:   python flake_angle.py frames.extxyz --flake-ids flake_ids.txt   (your own simulation)
       python flake_angle.py --demo                                    (synthetic flakes, < 1 s)
Output: out/flake_angles.png (demo) or printed angles per frame.
"""
import argparse
from pathlib import Path

import numpy as np

OUT = Path(__file__).parent / "out"
OUT.mkdir(exist_ok=True)


def flake_angle(positions, shear_normal=(0, 0, 1)):
    """Angle in degrees between a flake's plane and the plane whose normal is `shear_normal`."""
    x = positions - positions.mean(axis=0)
    w, v = np.linalg.eigh(x.T @ x)
    normal = v[:, 0]  # smallest-variance direction
    c = abs(normal @ np.asarray(shear_normal, float)) / np.linalg.norm(shear_normal)
    return np.degrees(np.arccos(np.clip(c, 0, 1)))


def synthetic_flake(n_side, tilt_deg, rng):
    """Flat triangular-lattice patch tilted about the y axis, with thermal noise."""
    a = 3.18
    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)])
    pts += rng.normal(0, 0.15, pts.shape)
    t = np.radians(tilt_deg)
    R = np.array([[np.cos(t), 0, np.sin(t)], [0, 1, 0], [-np.sin(t), 0, np.cos(t)]])
    return pts @ R.T


def demo():
    rng = np.random.default_rng(0)
    sizes = {"small (16 atoms)": 4, "large (144 atoms)": 12}
    true = np.linspace(0, 40, 9)
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots(figsize=(5, 4))
    for label, n in sizes.items():
        meas = [np.mean([flake_angle(synthetic_flake(n, t, rng)) for _ in range(20)]) for t in true]
        ax.plot(true, meas, "o-", label=label)
    ax.plot(true, true, "k:", lw=1, label="exact")
    ax.set_xlabel("Imposed tilt (°)")
    ax.set_ylabel("Measured flake angle (°)")
    ax.legend(frameon=False)
    ax.set_title("PCA flake-angle check")
    fig.tight_layout()
    fig.savefig(OUT / "flake_angles.png", dpi=160)
    print("wrote", OUT / "flake_angles.png")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("traj", nargs="?")
    ap.add_argument("--flake-ids", help="text file: one integer flake id per atom (same order as the trajectory)")
    ap.add_argument("--demo", action="store_true")
    a = ap.parse_args()
    if a.demo or not a.traj:
        return demo()
    from ase.io import iread
    ids = np.loadtxt(a.flake_ids, dtype=int)
    for k, frame in enumerate(iread(a.traj)):
        pos = frame.get_positions()
        angles = [flake_angle(pos[ids == f]) for f in np.unique(ids) if (ids == f).sum() >= 6]
        print(f"frame {k}: mean flake angle {np.mean(angles):.1f}° over {len(angles)} flakes")


if __name__ == "__main__":
    main()