Examples
Practical, end-to-end examples for the most common workflows. Every script shown here is a real file in the repository, checked by the test suite so it cannot silently drift out of sync with the API.
They come in two flavours:
The runnable local example below needs no cluster and no ML stack – it runs on any machine with just the core install and is executed end-to-end in CI (
test/test_local_emt_example.py). Start here.The cluster workflows (Examples 1–2) orchestrate remote work (SSH + SLURM, GPUs, VASP), so they are not executed in CI – only checked for API-currency (
test/test_examples.py). They assume you have registered the referenced clusters withremote_handler configure cluster(see Command-Line Interface); adapt the aliases, paths and resources to your own setup before running.
The conceptual roles (sampler / selector / evaluator / trainer) and the
StagedActiveLearningHandler
that wires them together are explained in Active Learning Loops.
Run it now: a full loop with no cluster
A complete active-learning cycle for bulk Cu that runs on your laptop in a few seconds:
sample (ASE MD) -> select (stride) -> label (EMT) -> train (Morse fit) -> loop
Everything goes through the package’s real task machinery, but over the
scheduler-free direct executor on a
LocalFileSystem – so there is no
SSH, no SLURM and no ML framework. Ground truth is ASE’s EMT calculator (the
shipped EMTEvaluator); the
“trained model” is a pairwise Morse potential fitted with scipy, standing
in for a heavy MLFF trainer. Iteration 0 bootstraps under EMT; from then on the
MD is driven by the potential fitted in the previous iteration.
The point is orchestration, not accuracy: it shows that anything can be cast
as a RemoteTask, and that moving the same
loop onto a real cluster is a single change to the ClusterConfig
(executor="slurm" with a remote_machine and conda_env).
Run it from the environment the package is installed in:
cd examples/local_emt_AL
python run_al.py
The driver wires four actors into the staged handler and runs the loop:
"""Self-contained active-learning loop that runs on *any* machine, no cluster.
A minimal but complete AL cycle for bulk Cu:
sample (ASE MD) -> select (stride) -> label (EMT) -> train (Morse fit)
Every actor executes through the package's real task machinery, but over the
scheduler-free ``direct`` executor on a ``LocalFileSystem`` -- so there is no
SSH, no SLURM and no ML stack. Ground truth is ASE's EMT calculator (a shipped
preset); the "trained model" is a pairwise Morse potential fitted with scipy,
standing in for a heavy MLFF trainer. Dependencies: only ``ase``, ``numpy`` and
``scipy`` (the core install).
The point is orchestration, not accuracy: it demonstrates that *anything* can
be cast as a ``RemoteTask`` and that swapping the ``ClusterConfig`` is all it
takes to move the same loop onto a real cluster.
Run it from the environment the package is installed in (``direct`` launches a
bare ``python``, resolved from ``PATH``):
python run_al.py
"""
from pathlib import Path
from actors import MorseMDSampler, MorseTrainer
from ase.build import bulk
from remote_handler import configure_logging
from remote_handler.core.cluster_handler import ClusterConfig
from remote_handler.core.file_handler import LocalFileSystem
from remote_handler.workflows import EMTEvaluator
from remote_handler.workflows.selectors import StrideSelector
from remote_handler.workflows.staged_active_learning import (
StagedActiveLearningHandler,
)
configure_logging()
HERE = Path(__file__).resolve().parent
def main(run_dir=None, num_iterations=3):
"""Run the local AL loop.
Args:
run_dir: Where to write the ``calchome/`` tree and scratch files.
Defaults to ``al_run/`` next to this script. A test can point it
at a tmp dir.
num_iterations: Number of active-learning iterations.
Returns:
Path to the ``calchome/`` directory.
"""
run_dir = Path(run_dir) if run_dir is not None else HERE / "al_run"
run_dir.mkdir(parents=True, exist_ok=True)
scratch = run_dir / "scratch"
scratch.mkdir(exist_ok=True)
remote_fs = LocalFileSystem()
# A local, scheduler-free "cluster": empty conda fields -> the ambient
# python from PATH runs each payload. Swap executor="slurm" + a real
# remote_machine/conda_env to move the identical loop onto a cluster.
cluster_config = ClusterConfig(
remote_machine="local",
partition="none",
conda_env="",
conda_source="",
savepath=str(scratch),
template="unused.sh.j2",
executor="direct",
)
# A small periodic Cu cell (EMT supports Cu); MD explores from here.
seed_atoms = bulk("Cu", "fcc", a=3.61, cubic=True) * (2, 2, 2)
sampler = MorseMDSampler(
remote_fs=remote_fs,
cluster_config=cluster_config,
seed_atoms=seed_atoms,
temperature_K=400.0,
n_steps=200,
sample_every=40,
)
selector = StrideSelector(n_configs=3)
evaluator = EMTEvaluator(
remote_fs=remote_fs,
cluster_config=cluster_config,
num_parallel=3,
remote_savepath=scratch / "eval",
loop_time=0.3,
)
trainer = MorseTrainer(remote_fs=remote_fs, cluster_config=cluster_config)
handler = StagedActiveLearningHandler.from_actors(
sampler=sampler,
selector=selector,
evaluator=evaluator,
trainer=trainer,
calchome=run_dir / "calchome",
num_iterations=num_iterations,
cycle_exit_point="training", # every iteration ends with a fit
initial_trainer_out=HERE / "inputs" / "seed_model.json",
trainer_output_extension="json",
)
handler.run()
calchome = run_dir / "calchome"
print("\nActive learning finished. Fitted models per iteration:")
for model in sorted(calchome.glob("trainer_output/trainer_it*_0.json")):
print(f" {model.name}: {model.read_text().strip()}")
return calchome
if __name__ == "__main__":
main()
The custom actors are thin wrappers that cast an ordinary Python payload as
a SingleScriptTask. The sampler and trainer
here are external code plugged into the loop – exactly how a production
sampler or trainer is integrated:
"""Example-local AL actors: an MD sampler and a Morse trainer.
Both are thin wrappers that cast an ordinary Python payload as a
``SingleScriptTask`` and run it through whatever executor the ``ClusterConfig``
selects -- here the scheduler-free ``direct`` backend on a ``LocalFileSystem``,
so the whole loop runs on one machine with no cluster. Point the same
``ClusterConfig`` at a real cluster (``executor="slurm"``) and the identical
actor code submits to SLURM instead.
They implement the ``Sampler`` / ``ModelTrainer`` getter contract
(``get_sampled_configs`` / ``get_trained_model``) so they drop straight into
``StagedActiveLearningHandler.from_actors``.
"""
import json
import os
from pathlib import Path
from remote_handler.core.tasks import SingleScriptTask
_SCRIPTS = Path(__file__).resolve().parent / "scripts"
def _run_task(
remote_fs,
cluster_config,
script,
input_file,
workdir,
jobname,
additional_files=(),
loop_time=0.3,
):
"""Allocate + submit one ``SingleScriptTask`` and return its calcdir.
Reads results in place (local disk), so no separate collection step is
needed -- ``task.calcdir`` holds the payload's outputs once ``submit``
returns.
"""
remote_fs.makedirs(workdir, exist_ok=True)
task = SingleScriptTask(
script_file=script,
input_file=input_file,
local_savepath=Path(workdir) / "collected",
cluster_config=cluster_config,
remote_fs=remote_fs,
remote_savepath=str(workdir),
jobname=jobname,
loop_time=loop_time,
additional_files=list(additional_files),
write_manifest_on_submit=False,
)
task.allocate_data()
task.submit()
if not task.finish_check():
raise RuntimeError(
f"payload {script} did not finish in {task.calcdir}"
)
return Path(task.calcdir)
class MorseMDSampler:
"""Run short ASE Langevin MD driven by the current model."""
def __init__(
self,
remote_fs,
cluster_config,
seed_atoms,
temperature_K=300.0,
n_steps=200,
sample_every=40,
timestep_fs=1.0,
rattle=0.05,
loop_time=0.3,
):
self.remote_fs = remote_fs
self.cluster_config = cluster_config
self.seed_atoms = seed_atoms
self.temperature_K = temperature_K
self.n_steps = n_steps
self.sample_every = sample_every
self.timestep_fs = timestep_fs
self.rattle = rattle
self.loop_time = loop_time
self._out = None
def update(self, calcdir, sampler_input, **kwargs):
calcdir = Path(calcdir)
model_path = (
sampler_input[0]
if isinstance(sampler_input, (list, tuple))
else sampler_input
)
model = json.loads(Path(model_path).read_text())
at = self.seed_atoms
payload_input = {
"model": model,
"structure": {
"numbers": at.get_atomic_numbers().tolist(),
"positions": at.get_positions().tolist(),
"cell": at.get_cell().tolist(),
"pbc": at.get_pbc().tolist(),
},
"temperature_K": self.temperature_K,
"timestep_fs": self.timestep_fs,
"n_steps": self.n_steps,
"sample_every": self.sample_every,
"rattle": self.rattle,
"seed": int(Path(calcdir).name)
if Path(calcdir).name.isdigit()
else 0,
"output": "sampled.extxyz",
}
input_file = calcdir / "sampler_input.json"
input_file.write_text(json.dumps(payload_input, indent=2))
result_dir = _run_task(
self.remote_fs,
self.cluster_config,
script=_SCRIPTS / "md_sample.py",
input_file=input_file,
workdir=calcdir / "sampler_work",
jobname="sample",
loop_time=self.loop_time,
)
self._out = result_dir / "sampled.extxyz"
def get_sampled_configs(self):
return self._out
class MorseTrainer:
"""Fit a pairwise Morse potential to the accumulated labelled data."""
def __init__(
self,
remote_fs,
cluster_config,
init_params=None,
force_weight=1.0,
rc=6.0,
loop_time=0.3,
):
self.remote_fs = remote_fs
self.cluster_config = cluster_config
self.init_params = init_params or {"D": 0.5, "alpha": 1.5, "r0": 2.5}
self.force_weight = force_weight
self.rc = rc
self.loop_time = loop_time
self._out = None
def update(self, calcdir, trainer_input, **kwargs):
calcdir = Path(calcdir)
data = (
list(trainer_input)
if isinstance(trainer_input, (list, tuple))
else [trainer_input]
)
data = [Path(p) for p in data]
payload_input = {
"data": [f"additional_files/{p.name}" for p in data],
"energy_key": "REF_energy",
"forces_key": "REF_forces",
"force_weight": self.force_weight,
"rc": self.rc,
"init": self.init_params,
"output": "model.json",
}
input_file = calcdir / "trainer_input.json"
input_file.write_text(json.dumps(payload_input, indent=2))
result_dir = _run_task(
self.remote_fs,
self.cluster_config,
script=_SCRIPTS / "fit_morse.py",
input_file=input_file,
workdir=calcdir / "trainer_work",
jobname="train",
additional_files=data,
loop_time=self.loop_time,
)
self._out = result_dir / "model.json"
def get_trained_model(self):
return self._out
The payloads run on the target (here, locally). The sampler payload is a
short ASE Langevin-MD run under the current model; the trainer payload fits the
Morse parameters to the labelled data. Neither imports remote_handler – a
payload is just a script the executor ships and runs:
"""Sampler payload: ASE Langevin MD, run *on the target* by a RemoteTask.
Contract (see ``DirectSingleExecutor``): invoked as ``python md_sample.py
<input.json>`` with the working directory set to the task's calcdir. Reads the
input JSON, runs a short NVT trajectory driven by the *current* model
(bootstrap EMT on the first iteration, the fitted Morse afterwards), writes the
sampled frames as ``sampled.extxyz`` in the cwd, and drops the
``is_finished.info`` success marker.
Pure ASE + numpy -- no ML stack, no external binary -- so it runs anywhere ASE
is installed. This is the deliberately-external sampling step cast as a
``RemoteTask``: swap this script for LAMMPS/torch_sim/... without touching the
rest of the loop.
"""
import json
import sys
from pathlib import Path
import ase.io
import numpy as np
from ase import Atoms, units
from ase.calculators.calculator import Calculator, all_changes
from ase.md.langevin import Langevin
from ase.md.velocitydistribution import MaxwellBoltzmannDistribution
from ase.neighborlist import neighbor_list
class Morse(Calculator):
"""Minimal pairwise Morse potential with a hard cutoff (PBC-correct).
``E = sum_{i<j} D (e^2 - 2 e)`` with ``e = exp(-alpha (r - r0))``. Uses
ASE's neighbour list so periodic images are handled correctly -- the same
calculator the trainer fits, kept identical on both sides of the loop.
"""
implemented_properties = ["energy", "forces"]
def __init__(self, D, alpha, r0, rc=6.0, **kwargs):
super().__init__(**kwargs)
self.D, self.alpha, self.r0, self.rc = D, alpha, r0, rc
def calculate(
self, atoms=None, properties=("energy",), system_changes=all_changes
):
super().calculate(atoms, properties, system_changes)
i, j, d, Dvec = neighbor_list("ijdD", atoms, self.rc)
e = np.exp(-self.alpha * (d - self.r0))
energy = 0.5 * np.sum(self.D * (e**2 - 2.0 * e))
# du/dd = 2 D alpha (e - e^2); force on i = -(du/dd) * (-Dvec/d).
du_dd = 2.0 * self.D * self.alpha * (e - e**2)
fpair = (du_dd / d)[:, None] * Dvec
forces = np.zeros((len(atoms), 3))
np.add.at(forces, i, fpair)
self.results["energy"] = energy
self.results["forces"] = forces
def build_calculator(model: dict):
"""Instantiate the sampling calculator from a small model dict."""
kind = model.get("type", "morse").lower()
if kind == "emt":
from ase.calculators.emt import EMT
return EMT()
if kind == "morse":
return Morse(
D=model["D"],
alpha=model["alpha"],
r0=model["r0"],
rc=model.get("rc", 6.0),
)
raise ValueError(f"unknown model type {kind!r}")
def main(input_path: Path) -> None:
cfg = json.loads(Path(input_path).read_text())
s = cfg["structure"]
atoms = Atoms(
numbers=s["numbers"],
positions=s["positions"],
cell=s["cell"],
pbc=s["pbc"],
)
rng = np.random.default_rng(cfg.get("seed", 0))
atoms.rattle(stdev=cfg.get("rattle", 0.0), seed=int(rng.integers(1 << 30)))
atoms.calc = build_calculator(cfg["model"])
MaxwellBoltzmannDistribution(
atoms, temperature_K=cfg["temperature_K"], rng=rng
)
dyn = Langevin(
atoms,
timestep=cfg["timestep_fs"] * units.fs,
temperature_K=cfg["temperature_K"],
friction=cfg.get("friction", 0.01),
rng=rng,
)
frames = []
every = cfg["sample_every"]
def grab():
frames.append(atoms.copy())
dyn.attach(grab, interval=every)
dyn.run(cfg["n_steps"])
ase.io.write(cfg.get("output", "sampled.extxyz"), frames)
Path("is_finished.info").write_text("sampling finished")
if __name__ == "__main__":
main(Path(sys.argv[1]))
"""Trainer payload: fit a pairwise Morse potential to the labelled data.
Contract (see ``DirectSingleExecutor``): invoked as ``python fit_morse.py
<input.json>`` with the working directory set to the task's calcdir. Reads the
accumulated labelled configurations, fits the three Morse parameters
(``D, alpha, r0``) to the reference energies and forces with
``scipy.optimize``, and writes the model as ``model.json`` in the cwd plus the
``is_finished.info`` marker.
This is the "simplest trainable model" stand-in for a heavy MLFF trainer: no
GPU, no ML framework, fits in milliseconds -- yet it exercises the exact same
``ModelTrainer`` -> ``RemoteTask`` path a real trainer uses.
"""
import json
import sys
from pathlib import Path
import ase.io
import numpy as np
from ase.neighborlist import neighbor_list
from scipy.optimize import least_squares
def _energy_forces(atoms, D, alpha, r0, rc):
"""Morse energy + forces (matches ``md_sample.Morse``)."""
i, j, d, Dvec = neighbor_list("ijdD", atoms, rc)
e = np.exp(-alpha * (d - r0))
energy = 0.5 * np.sum(D * (e**2 - 2.0 * e))
du_dd = 2.0 * D * alpha * (e - e**2)
fpair = (du_dd / d)[:, None] * Dvec
forces = np.zeros((len(atoms), 3))
np.add.at(forces, i, fpair)
return energy, forces
def main(input_path: Path) -> None:
cfg = json.loads(Path(input_path).read_text())
rc = cfg.get("rc", 6.0)
ekey = cfg.get("energy_key", "REF_energy")
fkey = cfg.get("forces_key", "REF_forces")
fw = cfg.get("force_weight", 1.0)
configs = []
for rel in cfg["data"]:
configs.extend(ase.io.read(rel, index=":"))
if not configs:
raise RuntimeError("no training configurations found")
def residuals(params):
D, alpha, r0 = params
res = []
for at in configs:
e_pred, f_pred = _energy_forces(at, D, alpha, r0, rc)
n = len(at)
res.append((e_pred - at.info[ekey]) / n) # per-atom energy
res.extend((fw * (f_pred - at.arrays[fkey]) / np.sqrt(n)).ravel())
return np.asarray(res)
x0 = [cfg["init"]["D"], cfg["init"]["alpha"], cfg["init"]["r0"]]
sol = least_squares(
residuals,
x0=x0,
bounds=([1e-3, 0.3, 1.5], [10.0, 5.0, 3.5]),
max_nfev=cfg.get("max_nfev", 200),
)
model = {
"type": "morse",
"D": float(sol.x[0]),
"alpha": float(sol.x[1]),
"r0": float(sol.x[2]),
"rc": rc,
"n_train": len(configs),
"rms_residual": float(np.sqrt(np.mean(sol.fun**2))),
}
out = Path(cfg.get("output", "model.json"))
out.write_text(json.dumps(model, indent=2))
Path("is_finished.info").write_text("training finished")
if __name__ == "__main__":
main(Path(sys.argv[1]))
Cluster workflows
The remaining examples orchestrate work on remote clusters. Adapt the cluster aliases and paths to your own setup before running.
Example 1: DFT single-point labelling
Run VASP single-point calculations on a set of structures as a SLURM array job, then collect the labelled configurations back to the host:
"""Example 1 -- DFT single-point labelling with VASP.
Run VASP single-point calculations on a set of structures as a SLURM array job
on a remote cluster, then collect the labelled configurations.
remote_handler does not ship VASP itself (a licensed, external code) -- it
must already be installed on the target cluster, and ``vasp_binary``/the
cluster's ``environment["vasp"]`` entry must point at it.
Included verbatim by ``docs/source/examples.rst`` and signature-checked by
``test/test_examples.py``.
"""
from remote_handler.core import ClusterConfig
from remote_handler.core.file_handler import RemoteFileSystem
from remote_handler.workflows.dft_runner import VASPHandler
if __name__ == "__main__":
config = ClusterConfig.from_name("dirona")
remote_fs = RemoteFileSystem(remote_alias="dirona")
handler = VASPHandler(
traj_files=["selected_structures.extxyz"],
cluster_config=config,
remote_fs=remote_fs,
savepath="/scratch/me/vasp",
num_parallel=10,
n_processors=16,
incar_kwargs={
"xc": "PBE",
"encut": 400,
"ediff": 1e-6,
"ismear": 0,
"sigma": 0.05,
"kpts": [3, 3, 1],
},
)
# Stage inputs, submit the array, wait, and collect the labelled configs.
handler.run()
Example 2: Training a MACE force field
Configure a MaceModelTrainer and run
a training step. The trainer is an active-learning actor: in a full run an
ActiveLearningHandler
loop drives it, but you can also call update / get_trained_model
directly:
"""Example 2 -- Training a MACE force field.
Configure a ``MaceModelTrainer`` and run one training step. In a full run the
``StagedActiveLearningHandler`` calls ``update`` / ``get_trained_model`` for
you each iteration; here we drive a single step directly.
MACE (``mace-torch``) must be installed in the *remote* conda env this
trainer targets (``convert_to_jax=True`` additionally needs ``mace-jax``
there). ``training_script`` and ``remote_mace_train_runner`` are both
optional and left unset below -- they default to the shipped payload script
and are auto-discovered by probing that remote env, respectively.
Included verbatim by ``docs/source/examples.rst`` and signature-checked by
``test/test_examples.py``.
"""
from pathlib import Path
from remote_handler.core import ClusterConfig
from remote_handler.core.file_handler import RemoteFileSystem
from remote_handler.workflows.trainers import MaceModelTrainer
# See mace_config.yaml (next to this script) for a minimal config.
CONFIG_FILE = Path(__file__).parent / "mace_config.yaml"
if __name__ == "__main__":
config = ClusterConfig.from_name("datalab")
remote_fs = RemoteFileSystem(remote_alias="datalab")
trainer = MaceModelTrainer(
remote_fs=remote_fs,
cluster_config=config,
config_file=CONFIG_FILE,
num_models=3,
validation_fraction=0.1,
)
# Train on DFT-labelled configs; calcdir is this iteration's work dir.
trainer.update(Path("mace_run/0/training"), ["dft_labelled.extxyz"])
model_paths = trainer.get_trained_model()
Example 3: Standalone submit/collect
Submit a DFT array and a MACE training array in one run and exit at once
(detach/submit_detached), then reconstruct and collect both from a
later, separate run – e.g. an active-learning driver that submits before a
laptop goes to sleep and collects the next morning. Like Examples 1–2, this
is statically validated only (API-currency, no live cluster):
"""Example 3 -- Standalone submit/collect across two separate runs.
Long remote jobs do not need the launching process to stay alive: submit in
one invocation of this script, then come back later (a different process, a
different day) and collect. This shows the pattern for both a DFT array task
(:class:`~remote_handler.workflows.dft_runner.VASPHandler`, which exposes its
own ``collect_only=True`` constructor) and a MACE training array
(:class:`~remote_handler.workflows.trainers.MaceModelTrainer`, which
reconstructs its array task via
:meth:`~remote_handler.core.tasks.ArrayScriptTask.from_manifest` under the
hood).
Run ``python example_3_standalone.py submit`` to fire both jobs and exit
immediately, then ``python example_3_standalone.py collect`` (any time after,
even from a fresh shell) to check on them and fetch results once finished.
Included verbatim by ``docs/source/examples.rst`` and signature-checked by
``test/test_examples.py``.
"""
import sys
from pathlib import Path
from remote_handler.core import ClusterConfig
from remote_handler.core.file_handler import RemoteFileSystem
from remote_handler.workflows.dft_runner import VASPHandler
from remote_handler.workflows.trainers import MaceModelTrainer
MACE_CALCDIR = Path("mace_run/0/training")
def submit(dft_kwargs: dict, mace_kwargs: dict) -> None:
"""Fire both array jobs and return at once -- no waiting."""
dft_handler = VASPHandler(**dft_kwargs, collect_only=False)
dft_manifest = dft_handler.detach()
print(f"DFT array submitted; manifest at {dft_manifest}")
mace_trainer = MaceModelTrainer(**mace_kwargs, collect_only=False)
mace_trainer.update(MACE_CALCDIR, ["dft_labelled.extxyz"])
mace_manifest = mace_trainer.training_task.submit_detached()
print(f"MACE training submitted; manifest at {mace_manifest}")
def collect(dft_kwargs: dict, mace_kwargs: dict) -> None:
"""Reconstruct both tasks and collect whatever has finished."""
dft_handler = VASPHandler(**dft_kwargs, collect_only=True)
if dft_handler.finish_check():
dft_handler.collect_and_harvest()
print("DFT results collected.")
else:
print("DFT array still running.")
mace_trainer = MaceModelTrainer(**mace_kwargs, collect_only=True)
mace_trainer.update(MACE_CALCDIR, None)
if mace_trainer.training_task.finish_check():
model_paths = mace_trainer.get_trained_model()
print(f"MACE models collected: {model_paths}")
else:
print("MACE training still running.")
if __name__ == "__main__":
config = ClusterConfig.from_name("dirona")
remote_fs = RemoteFileSystem(remote_alias="dirona")
# Identical construction args for both runs -- only ``collect_only``
# differs between the process that submits and the one that collects
# later.
dft_kwargs = dict(
traj_files=["selected_structures.extxyz"],
cluster_config=config,
remote_fs=remote_fs,
savepath="/scratch/me/vasp",
num_parallel=10,
n_processors=16,
incar_kwargs={
"xc": "PBE",
"encut": 400,
"ediff": 1e-6,
"ismear": 0,
"sigma": 0.05,
"kpts": [3, 3, 1],
},
)
mace_kwargs = dict(
remote_fs=remote_fs,
cluster_config=config,
config_file="config/mace_config.yaml",
num_models=3,
)
if sys.argv[1:] == ["submit"]:
submit(dft_kwargs, mace_kwargs)
elif sys.argv[1:] == ["collect"]:
collect(dft_kwargs, mace_kwargs)
else:
raise SystemExit(f"Usage: {sys.argv[0]} submit|collect")
Example 4: Ground-truth labelling with ORCA
The same evaluator shape as Example 1, swapping VASP for ORCA:
"""Example 4 -- Ground-truth labelling with ORCA.
Run ORCA single-point calculations on a set of structures as a SLURM array
job on a remote cluster, then collect the labelled configurations -- the
same actor shape as Example 1 (VASP), swapping the DFT code.
remote_handler does not ship ORCA itself -- it must already be installed on
the target cluster, and ``orca_binary``/the cluster's ``environment["orca"]``
entry must point at it.
Included verbatim by ``docs/source/examples.rst`` and signature-checked by
``test/test_examples.py``.
"""
from pathlib import Path
from remote_handler.core import ClusterConfig
from remote_handler.core.file_handler import RemoteFileSystem
from remote_handler.workflows.evaluators import ORCAEvaluator
if __name__ == "__main__":
config = ClusterConfig.from_name("dirona")
remote_fs = RemoteFileSystem(remote_alias="dirona")
evaluator = ORCAEvaluator(
cluster_config=config,
remote_fs=remote_fs,
num_parallel=10,
orcasimpleinput="PBE def2-SVP",
n_processors=8,
)
# Label the sampler's candidate configs; calcdir is this iteration's
# work dir.
evaluator.update(Path("al_run/0/dft"), Path("sampled_configs.extxyz"))
labelled = evaluator.get_evaluated_configs()
Example 5: Training a NeuralIL model
The same trainer shape as Example 2, for the JAXNEST-based NeuralIL model:
"""Example 5 -- Training a NeuralIL model.
Configure a ``NeuralilILTrainer`` and run one training step -- the same
actor shape as Example 2 (MACE), for the JAXNEST-based NeuralIL model.
Hyperparameters layer built-in defaults < ``config_file`` < ``training_kwargs``.
The NeuralIL/JAXNEST stack must be installed in the *remote* conda env this
trainer targets (see the ``neuralil`` extra for the pieces needed to test
this locally).
Included verbatim by ``docs/source/examples.rst`` and signature-checked by
``test/test_examples.py``.
"""
from pathlib import Path
from remote_handler.core import ClusterConfig
from remote_handler.core.file_handler import RemoteFileSystem
from remote_handler.workflows.trainers import NeuralilILTrainer
if __name__ == "__main__":
config = ClusterConfig.from_name("datalab")
remote_fs = RemoteFileSystem(remote_alias="datalab")
trainer = NeuralilILTrainer(
remote_fs=remote_fs,
cluster_config=config,
training_kwargs={"n_epochs": 200, "n_ensemble": 10},
)
# Train on DFT-labelled configs; calcdir is this iteration's work dir.
trainer.update(Path("neuralil_run/0/training"), ["dft_labelled.extxyz"])
model_paths = trainer.get_trained_model()
Example 6: Training an ACE force field
The same ensemble-array trainer shape as Example 2, fitting an ACE
potential (pacemaker) instead of MACE:
"""Example 6 -- Training an ACE force field.
Configure an ``AceModelTrainer`` -- the same ensemble-array actor shape as
``MaceModelTrainer`` (Example 2), fitting a classical ACE potential with
``pacemaker`` instead of MACE.
``pacemaker`` must be installed in the *remote* conda env this trainer
targets (see the ``ace`` extra for the pieces needed to test this locally
-- it cannot coexist with the ``grace`` extra in one environment, see their
comments in ``pyproject.toml``).
Included verbatim by ``docs/source/examples.rst`` and signature-checked by
``test/test_examples.py``.
"""
from pathlib import Path
from remote_handler.core import ClusterConfig
from remote_handler.core.file_handler import RemoteFileSystem
from remote_handler.workflows.trainers import AceModelTrainer
# See ace_config.yaml (next to this script) for a minimal config.
CONFIG_FILE = Path(__file__).parent / "ace_config.yaml"
if __name__ == "__main__":
config = ClusterConfig.from_name("datalab")
remote_fs = RemoteFileSystem(remote_alias="datalab")
trainer = AceModelTrainer(
remote_fs=remote_fs,
cluster_config=config,
config_file=CONFIG_FILE,
num_models=3,
validation_fraction=0.1,
)
trainer.update(Path("ace_run/0/training"), ["dft_labelled.extxyz"])
model_paths = trainer.get_trained_model()
Example 7: Training a GRACE force field
The same ensemble-array trainer shape as Example 2, fitting a GRACE
potential (gracemaker) instead of MACE:
"""Example 7 -- Training a GRACE force field.
Configure a ``GraceModelTrainer`` -- the same ensemble-array actor shape as
``MaceModelTrainer`` (Example 2), fitting a GRACE potential with
``gracemaker`` instead of MACE.
``gracemaker`` must be installed in the *remote* conda env this trainer
targets (see the ``grace`` extra for the pieces needed to test this locally
-- it cannot coexist with the ``ace`` extra in one environment, see their
comments in ``pyproject.toml``).
Included verbatim by ``docs/source/examples.rst`` and signature-checked by
``test/test_examples.py``.
"""
from pathlib import Path
from remote_handler.core import ClusterConfig
from remote_handler.core.file_handler import RemoteFileSystem
from remote_handler.workflows.trainers import GraceModelTrainer
# See grace_config.yaml (next to this script) for a minimal config.
CONFIG_FILE = Path(__file__).parent / "grace_config.yaml"
if __name__ == "__main__":
config = ClusterConfig.from_name("datalab")
remote_fs = RemoteFileSystem(remote_alias="datalab")
trainer = GraceModelTrainer(
remote_fs=remote_fs,
cluster_config=config,
config_file=CONFIG_FILE,
num_models=3,
validation_fraction=0.1,
)
trainer.update(Path("grace_run/0/training"), ["dft_labelled.extxyz"])
model_paths = trainer.get_trained_model()
Example 8: Structural analysis of a trajectory
Compute the RDF and the Steinhardt order parameters for every frame of two MD trajectories as one sharded array job, and read the results back. See Trajectory Processing for how the pipeline works and how to add your own processors. Like Examples 1–2, this is statically validated only:
"""Example 8 -- Structural analysis of a trajectory on a remote cluster.
Shard a set of trajectories, compute the radial distribution function and the
Steinhardt order parameters q4/q6 for every configuration as an array job on a
remote cluster, and collect the annotated configurations back -- one job, the
trajectory uploaded once, both analyses run back to back on each shard.
The remote conda env needs remote_handler with the ``steinhardt`` extra
(``jax``); RDF needs only ASE.
Included verbatim by ``docs/source/examples.rst`` and signature-checked by
``test/test_examples.py``.
"""
import numpy as np
from ase.io import read
from remote_handler.core import ClusterConfig
from remote_handler.core.file_handler import RemoteFileSystem
from remote_handler.processing import (
RDFProcessor,
RemoteTrajectoryProcessor,
SteinhardtProcessor,
)
if __name__ == "__main__":
config = ClusterConfig.from_name("lugus")
remote_fs = RemoteFileSystem(remote_alias="lugus")
handler = RemoteTrajectoryProcessor(
traj_files=["md_300K.extxyz", "md_600K.extxyz"],
cluster_config=config,
remote_fs=remote_fs,
n_processors=1,
shard_size=200, # configurations per array task
savepath="/scratch/me/analysis",
num_parallel=10, # array tasks running at once
# Steps run in this order on every shard.
processors=[
RDFProcessor(cutoff=6.0, nbins=300),
SteinhardtProcessor(r_cut=3.0, l_values=(4, 6)),
],
tag="ana",
)
# Stage the shards, submit the array, wait, then collect and write the
# results next to the inputs as ana_md_300K.extxyz / ana_md_600K.extxyz.
handler.run()
# Per-frame results are in atoms.info, per-atom ones in atoms.arrays.
for at in read("ana_md_300K.extxyz", index=":3"):
r = np.asarray(at.info["r_rdf"])
g = np.asarray(at.info["rdf_total"])
print(
f"g(r) peak at {r[g.argmax()]:.2f} A,",
f"<q6> = {at.info['q6_mean']:.3f},",
f"per-atom q6: {at.arrays['q6'].shape}",
)