What you will learn
- How dopant formation energy is defined and computed
- How to swap ML potentials (MACE-MP-0 or Meta UMA) with one argument
- How to measure dopant mobility with mean squared displacement
Set up
pip install mace-torch ase matplotlib numpy scipy # optional: pip install fairchem-core (UMA, needs a Hugging Face token)Files for this tutorial:
benchmark_dopants.py— Formation energies for 17 dopant–site combinationsheat_md.py— Heating MD of a Cu-intercalated bilayer + MSD../common/models.py— One-line model loader (MACE or UMA)
Put the shared files in common/, next to the uma-doped-mos2/ directory. Run the commands from uma-doped-mos2/.
How it works
Relax the pristine reference cells
Relax a 4×4 MoS₂ monolayer (48 atoms) and a pristine bilayer with the same potential.
Place each dopant
Metals replace one Mo atom (Nb, Re, Ta, Ti, Ru, Au, Cu). Non-metals replace one S atom (Se, Te, O, N, Cl, F). Alkali and coinage metals sit in the van der Waals gap of a bilayer (Li, Na, Cu, Ag).
Compute formation energies
For substitution, compare with a pristine monolayer and include the chemical potential of the removed host atom. For intercalation, compare with a pristine bilayer and omit the removed-host term. In both cases, subtract the dopant chemical potential. Each chemical potential is the energy per atom of the element’s relaxed reference phase, computed with the same model. A negative formation energy favors incorporation relative to the chosen elemental references. Compare formation energies for the same dopant to rank sites.
Heat a doped bilayer
heat_md.py ramps the target temperature of a Cu-intercalated bilayer from 300 K toward 1,000 K with a Langevin thermostat. It records each species’ mean squared displacement (MSD). A steep MSD curve marks a mobile species.
Run it
The local run used MACE-MP-0 with mace-torch 0.3.17 on an NVIDIA GeForce RTX 5080.
python benchmark_dopants.py
python heat_md.py --steps 3000Optional
Install fairchem-core, accept the UMA model terms on Hugging Face, and sign in before running this command.
python benchmark_dopants.py --model uma-s-1p1What you should see


How this differs from the paper
The paper used Meta’s UMA (small and medium), DFT references from Quantum ESPRESSO, 25 dopants at three sites, and 3,111-atom NPT simulations over 20 ps. This version defaults to MACE-MP-0 so it runs without an account, uses simple elemental references, and heats about 100 atoms. Expect the same workflow and qualitatively similar trends, not the paper’s numbers. Known MACE-MP-0 weakness: O₂ and other molecular references are poorly described, so O and F energies are less reliable.
Full source
benchmark_dopants.py (158 lines)
"""Tutorial 1 — Benchmark a universal ML potential on doped MoS2.
Reproduces the workflow of Faiyad & Martini, JCTC 2026 at laptop scale:
1. build a pristine MoS2 monolayer supercell
2. put one dopant on a Mo site, an S site, or between layers (intercalated, bilayer)
3. relax every structure with the ML potential
4. compute the dopant formation energy
E_f = E(doped) - E(pristine) + mu(removed host atom) - mu(dopant)
with chemical potentials mu from each element's relaxed reference phase
5. plot E_f per dopant and site
Run: python benchmark_dopants.py (MACE-MP-0 small, ~3 min on a laptop CPU)
python benchmark_dopants.py --model uma-s-1p1 (the model used in the paper; needs HF token)
Output: out/formation_energies.csv, out/formation_energies.png
"""
import argparse
import csv
import sys
from pathlib import Path
import numpy as np
from ase import Atoms
from ase.build import bulk, molecule, mx2
from ase.constraints import FixSymmetry
from ase.filters import FrechetCellFilter
from ase.optimize import BFGS
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)
# Elemental reference phases for chemical potentials (lattice constants are starting guesses; cells are relaxed).
REF = {
"Mo": lambda: bulk("Mo", "bcc", a=3.15),
"S": lambda: Atoms("S2", positions=[[0, 0, 0], [0, 0, 1.89]]), # S2 molecule (a simple, common reference)
"Nb": lambda: bulk("Nb", "bcc", a=3.30),
"Re": lambda: bulk("Re", "hcp", a=2.76, c=4.46),
"Ta": lambda: bulk("Ta", "bcc", a=3.30),
"Ti": lambda: bulk("Ti", "hcp", a=2.95, c=4.68),
"Ru": lambda: bulk("Ru", "hcp", a=2.71, c=4.28),
"Au": lambda: bulk("Au", "fcc", a=4.08),
"Cu": lambda: bulk("Cu", "fcc", a=3.61),
"Ag": lambda: bulk("Ag", "fcc", a=4.09),
"Li": lambda: bulk("Li", "bcc", a=3.44),
"Na": lambda: bulk("Na", "bcc", a=4.23),
"Se": lambda: Atoms("Se2", positions=[[0, 0, 0], [0, 0, 2.17]]),
"Te": lambda: Atoms("Te2", positions=[[0, 0, 0], [0, 0, 2.56]]),
"O": lambda: molecule("O2"),
"N": lambda: molecule("N2"),
"Cl": lambda: molecule("Cl2"),
"F": lambda: molecule("F2"),
}
MO_SITE = ["Nb", "Re", "Ta", "Ti", "Ru", "Au", "Cu"]
S_SITE = ["Se", "Te", "O", "N", "Cl", "F"]
INTERCAL = ["Li", "Na", "Cu", "Ag"]
def relax(atoms, calc, cell=False, fmax=0.05, steps=300):
atoms = atoms.copy()
atoms.calc = calc
target = FrechetCellFilter(atoms) if cell else atoms
BFGS(target, logfile=None).run(fmax=fmax, steps=steps)
return atoms
def mu(el, calc, cache={}):
"""Chemical potential = energy per atom of the relaxed elemental reference."""
if el not in cache:
ref = REF[el]()
periodic = ref.pbc.any()
if not periodic:
ref.center(vacuum=8.0)
ref.pbc = True
r = relax(ref, calc, cell=periodic)
cache[el] = r.get_potential_energy() / len(r)
return cache[el]
def monolayer(n=4):
a = mx2("MoS2", kind="2H", a=3.18, thickness=3.19, size=(n, n, 1), vacuum=8.0)
a.pbc = True
return a
def bilayer(n=4, gap=6.15):
top = monolayer(n)
bot = top.copy()
top.translate([0, 0, gap])
both = bot + top
both.cell[2, 2] = top.positions[:, 2].max() + 8.0
both.center(axis=2)
return both
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", default="mace-small")
ap.add_argument("--size", type=int, default=4, help="n x n supercell")
args = ap.parse_args()
calc = get_calc(args.model)
rows = []
# --- pristine monolayer and substitutions -------------------------------------------
pristine = relax(monolayer(args.size), calc)
E0 = pristine.get_potential_energy()
mo_idx = next(i for i, s in enumerate(pristine.get_chemical_symbols()) if s == "Mo")
s_idx = next(i for i, s in enumerate(pristine.get_chemical_symbols()) if s == "S")
for site, idx, host, dopants in (("Mo-sub", mo_idx, "Mo", MO_SITE), ("S-sub", s_idx, "S", S_SITE)):
for el in dopants:
d = pristine.copy()
d[idx].symbol = el
d = relax(d, calc)
Ef = d.get_potential_energy() - E0 + mu(host, calc) - mu(el, calc)
rows.append((el, site, Ef))
print(f"{site:9s} {el:3s} E_f = {Ef:7.3f} eV", flush=True)
# --- intercalation in a bilayer --------------------------------------------------------
bil = relax(bilayer(args.size), calc)
Eb = bil.get_potential_energy()
z_mid = bil.positions[:, 2].mean()
xy = bil.cell[0, :2] * 0.5 + bil.cell[1, :2] * 0.5 / 3
for el in INTERCAL:
d = bil + Atoms(el, positions=[[xy[0], xy[1], z_mid]])
d = relax(d, calc)
Ef = d.get_potential_energy() - Eb - mu(el, calc)
rows.append((el, "intercalated", Ef))
print(f"{'intercal':9s} {el:3s} E_f = {Ef:7.3f} eV", flush=True)
with open(OUT / "formation_energies.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["dopant", "site", "E_f_eV", "model"])
for r in rows:
w.writerow([*r[:2], f"{r[2]:.4f}", args.model])
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
colors = {"Mo-sub": "#1f6fa8", "S-sub": "#d9a20b", "intercalated": "#c2414f"}
fig, ax = plt.subplots(figsize=(9, 4))
labels = [f"{e}\n{s.split('-')[0] if s != 'intercalated' else 'int'}" for e, s, _ in rows]
ax.bar(range(len(rows)), [r[2] for r in rows], color=[colors[r[1]] for r in rows])
ax.set_xticks(range(len(rows)), labels, fontsize=8)
ax.axhline(0, color="k", lw=0.8)
ax.set_ylabel("Formation energy (eV)")
ax.set_title(f"Dopant formation energies in MoS$_2$ ({args.model})")
for k, c in colors.items():
ax.bar([], [], color=c, label=k)
ax.legend(frameon=False, fontsize=8)
fig.tight_layout()
fig.savefig(OUT / "formation_energies.png", dpi=160)
print("wrote", OUT / "formation_energies.png")
if __name__ == "__main__":
main()
heat_md.py (120 lines)
"""Tutorial 1, part 2 — heat a doped MoS2 bilayer and watch the dopants move.
The paper heated 3,111-atom supercells from 300 K to 1000 K over 20 ps (NPT, UMA small) and
tracked clustering, interlayer diffusion and compound formation. This laptop version heats a
small Cu-intercalated bilayer with a Langevin thermostat and reports each species' mean
squared displacement (MSD). Fast-moving dopants show up as a steep MSD curve.
Run: python heat_md.py --dopant Cu --n-dopant 4 (~2-4 min CPU with MACE small)
Output: out/heat_<dopant>.extxyz (open in OVITO or ase gui), out/msd_<dopant>.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.io import write
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)
def doped_bilayer(n, dopant, k, seed=0, gap=7.0, dmin=2.2):
"""Two MoS2 layers `gap` Å apart (pristine 2H spacing is 6.15 Å; intercalants push it open),
periodic along z, with `k` dopant atoms placed at random in the gap at least `dmin` Å from any atom."""
layer = mx2("MoS2", kind="2H", a=3.18, thickness=3.19, size=(n, n, 1), vacuum=0)
top = layer.copy()
top.translate([0, 0, gap])
sys_ = layer + top
sys_.cell[2] = [0, 0, 2 * gap] # periodic stack of bilayers
sys_.pbc = True
rng = np.random.default_rng(seed)
z = layer.positions[:, 2].max() + (gap - 3.19) / 2 # middle of the van der Waals gap
placed = 0
for _ in range(5000):
if placed == k:
break
f = rng.random(2)
p = f[0] * sys_.cell[0] + f[1] * sys_.cell[1] + [0, 0, z]
trial = sys_ + Atoms(dopant, positions=[p])
if trial.get_distances(len(trial) - 1, range(len(trial) - 1), mic=True).min() >= dmin:
sys_ = trial
placed += 1
sys_.wrap()
return sys_
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", default="mace-small")
ap.add_argument("--dopant", default="Cu")
ap.add_argument("--n-dopant", type=int, default=4)
ap.add_argument("--size", type=int, default=4)
ap.add_argument("--steps", type=int, default=3000, help="1 fs steps")
ap.add_argument("--t0", type=float, default=300)
ap.add_argument("--t1", type=float, default=1000)
args = ap.parse_args()
atoms = doped_bilayer(args.size, args.dopant, args.n_dopant)
atoms.calc = get_calc(args.model, dtype="float32")
MaxwellBoltzmannDistribution(atoms, temperature_K=args.t0, rng=np.random.default_rng(1))
dyn = Langevin(atoms, 1.0 * units.fs, temperature_K=args.t0, friction=0.02, rng=np.random.default_rng(2))
ref = atoms.get_positions().copy()
prev = ref.copy()
unwrapped = ref.copy()
sym = np.array(atoms.get_chemical_symbols())
kinds = sorted(set(sym), key=lambda s: {"Mo": 0, "S": 1}.get(s, 2))
msd = {k: [] for k in kinds}
times, temps, frames = [], [], []
every = 30
def record():
nonlocal prev, unwrapped
pos = atoms.get_positions()
d = pos - prev
frac = np.linalg.solve(atoms.cell.T, d.T).T
frac -= np.round(frac)
unwrapped = unwrapped + frac @ atoms.cell
prev = pos.copy()
for k in kinds:
m = sym == k
msd[k].append(np.mean(np.sum((unwrapped[m] - ref[m]) ** 2, axis=1)))
times.append(dyn.get_number_of_steps() * 1e-3)
temps.append(atoms.get_temperature())
frames.append(atoms.copy())
for step in range(0, args.steps, every):
dyn.set_temperature(temperature_K=args.t0 + (args.t1 - args.t0) * step / args.steps)
dyn.run(every)
record()
if len(times) % 10 == 0:
print(f"t = {times[-1]:5.2f} ps T = {temps[-1]:6.0f} K MSD({args.dopant}) = {msd[args.dopant][-1]:6.2f} A^2", flush=True)
write(OUT / f"heat_{args.dopant}.extxyz", frames)
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
col = {"Mo": "#1f6fa8", "S": "#d9a20b"}
fig, ax = plt.subplots(figsize=(6, 4))
for k in kinds:
ax.plot(times, msd[k], label=k, color=col.get(k, "#c2414f"), lw=2)
ax.set_xlabel("Time (ps)")
ax.set_ylabel("MSD (Å$^2$)")
ax.set_title(f"{args.dopant}-intercalated MoS$_2$ bilayer, {args.t0:.0f}→{args.t1:.0f} K")
ax.legend(frameon=False)
fig.tight_layout()
fig.savefig(OUT / f"msd_{args.dopant}.png", dpi=160)
print("wrote", OUT / f"msd_{args.dopant}.png")
if __name__ == "__main__":
main()