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

Grow a Ni-doped MoS₂ film atom by atom

Deposit Mo, S and Ni atoms onto a MoS₂ substrate one at a time, then measure Ni clustering and MoS₂-like order.

Download notebook

What you will learn

  • How deposition simulations work (insert, impact, relax)
  • How to set composition by weight percent
  • Simple structure metrics from neighbor lists

Set up

pip install mace-torch ase matplotlib numpy scipy

Files for this tutorial:

Put the shared files in common/, next to the nimos2-sputtering/ directory. Run the commands from nimos2-sputtering/.

How it works

  1. Prepare the substrate

    A 4×4 MoS₂ monolayer with its bottom S layer fixed, in a tall periodic cell.

  2. Deposit

    Each new atom starts 4.5 Å above the surface with 4 eV of kinetic energy, aimed straight down. 120 fs of thermostatted MD follows each impact.

  3. Measure

    Fraction of Mo with six S neighbors (MoS₂-like order) and mean Ni–Ni neighbor count (clustering).

Run it

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

python deposit.py --ni-wt 0 10

What you should see

Two bar charts comparing local structure metrics for films with two nickel contents.
Output of deposit.py (7 min for both films). With 90 deposited atoms the metrics are dominated by the substrate; they show how to measure the film, not the paper’s result.

How this differs from the paper

The paper used ReaxFF in LAMMPS, thousands of deposited atoms, two substrate temperatures (300 and 670 K), and then compressed and sheared the films to measure friction. This version deposits about 90 atoms with an ML potential to show the method.

Full source

deposit.py (113 lines)
deposit.py
"""Tutorial — Grow a Ni-doped MoS2 film atom by atom.

Romero Garcia, Faiyad & Martini, Comput. Mater. Sci. 244, 113229 (2024) simulated sputter
deposition of MoS2 with 0, 2, 10 and 15 wt% Ni using reactive MD (ReaxFF), then compressed and
sheared the films. Intermediate Ni (2 and 10 wt%) gave the lowest shear stress.

This laptop/Colab version keeps the deposition idea and swaps ReaxFF for an ML potential:
  1. start from a MoS2 monolayer substrate with its bottom row fixed
  2. drop Mo, S and Ni atoms one at a time onto it, with a few eV of kinetic energy, at the target composition
  3. after each impact run a short MD relaxation with a thermostat on the substrate
  4. measure the film: Ni clustering (Ni–Ni neighbors) and MoS2-like order (Mo with 6 S neighbors)

Run:   python deposit.py --ni-wt 0 10              (~10 min on a GPU for both)
Output: out/film_<wt>.extxyz, out/film_metrics.png
"""
import argparse
import sys
from pathlib import Path

import numpy as np
from ase import Atoms, units
from ase.build import mx2
from ase.constraints import FixAtoms
from ase.io import write
from ase.md.langevin import Langevin
from ase.neighborlist import neighbor_list

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)
MASS = {"Mo": 95.95, "S": 32.06, "Ni": 58.69}


def species_sequence(n, ni_wt, rng):
    """Random Mo/S/Ni sequence: Mo:S = 1:2 by atoms, Ni set by weight fraction."""
    m_mos2 = MASS["Mo"] + 2 * MASS["S"]
    x_ni = (ni_wt / MASS["Ni"]) / (ni_wt / MASS["Ni"] + (100 - ni_wt) / m_mos2 * 3)  # atom fraction of Ni
    n_ni = round(n * x_ni)
    rest = n - n_ni
    seq = ["Ni"] * n_ni + ["Mo"] * round(rest / 3) + ["S"] * (rest - round(rest / 3))
    rng.shuffle(seq)
    return seq


def grow(ni_wt, n_atoms, calc, seed=0, ke_eV=4.0, relax_steps=120):
    rng = np.random.default_rng(seed)
    film = mx2("MoS2", kind="2H", a=3.18, thickness=3.19, size=(4, 4, 1), vacuum=0)
    film.cell[2] = [0, 0, 40.0]
    film.pbc = True
    film.set_constraint(FixAtoms(indices=[a.index for a in film if a.position[2] < film.positions[:, 2].min() + 0.5]))
    for k, el in enumerate(species_sequence(n_atoms, ni_wt, rng)):
        top = film.positions[:, 2].max()
        f = rng.random(2)
        xy = f[0] * film.cell[0] + f[1] * film.cell[1]
        film += Atoms(el, positions=[[xy[0], xy[1], top + 4.5]])
        v = film.get_velocities()
        # ASE units (eV, amu, Å) make v = sqrt(2 KE / m) directly; aim straight down
        v[-1] = [0.0, 0.0, -np.sqrt(2 * ke_eV / MASS[el])]
        film.set_velocities(v)
        film.calc = calc
        Langevin(film, 1.0 * units.fs, temperature_K=300, friction=0.02, rng=rng).run(relax_steps)
        if (k + 1) % 20 == 0:
            print(f"Ni {ni_wt:>4.1f} wt%: deposited {k + 1}/{n_atoms}", flush=True)
    return film


def metrics(film):
    s = np.array(film.get_chemical_symbols())
    i, j = neighbor_list("ij", film, {("Mo", "S"): 2.8, ("Ni", "Ni"): 2.8, ("Mo", "Mo"): 0.1, ("S", "S"): 0.1,
                                      ("Ni", "S"): 0.1, ("Mo", "Ni"): 0.1})
    mo = np.where(s == "Mo")[0]
    nS = np.array([np.sum((i == m) & (s[j] == "S")) for m in mo])
    ni = np.where(s == "Ni")[0]
    nNi = np.array([np.sum((i == m) & (s[j] == "Ni")) for m in ni]) if len(ni) else np.array([0])
    return {"frac_Mo_6S": float(np.mean(nS == 6)), "mean_Ni_Ni": float(nNi.mean())}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ni-wt", type=float, nargs="+", default=[0, 10])
    ap.add_argument("--n-atoms", type=int, default=90)
    ap.add_argument("--model", default="mace-small")
    a = ap.parse_args()
    calc = get_calc(a.model, dtype="float32")
    res = {}
    for w in a.ni_wt:
        film = grow(w, a.n_atoms, calc)
        write(OUT / f"film_{w:g}.extxyz", film)
        res[w] = metrics(film)
        print(f"Ni {w:g} wt%: {res[w]}")

    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    fig, axs = plt.subplots(1, 2, figsize=(8, 3.4))
    ws = list(res)
    axs[0].bar([f"{w:g}%" for w in ws], [res[w]["frac_Mo_6S"] for w in ws], color="#1f6fa8")
    axs[0].set_ylabel("fraction of Mo with 6 S neighbors")
    axs[1].bar([f"{w:g}%" for w in ws], [res[w]["mean_Ni_Ni"] for w in ws], color="#c2414f")
    axs[1].set_ylabel("mean Ni–Ni neighbors")
    for ax in axs:
        ax.set_xlabel("Ni content (wt%)")
    fig.suptitle("Deposited film structure (includes the substrate)")
    fig.tight_layout()
    fig.savefig(OUT / "film_metrics.png", dpi=160)
    print("wrote", OUT / "film_metrics.png")


if __name__ == "__main__":
    main()