Trajectory Processing
remote_handler.processing runs per-configuration work over large
trajectories on a remote cluster, such as relaxing every structure or
computing structural descriptors for every frame. You give it trajectory
files and an ordered list of processors. It shards the configurations into
an array job, runs the processors on each shard, and writes the annotated
configurations back next to your input files.
How it works
flowchart LR
T["traj files<br/>(.extxyz)"] --> S["shard"]
S --> A0["shard 0"]
S --> A1["shard 1"]
S --> An["shard n"]
subgraph cluster["array job on the cluster (driver.py per shard)"]
A0 --> P0["step 1 → step 2 → …"]
A1 --> P1["step 1 → step 2 → …"]
An --> Pn["step 1 → step 2 → …"]
end
P0 --> C["collect + regroup"]
P1 --> C
Pn --> C
C --> R["<tag>_<traj>.extxyz<br/>next to each input"]
Two concerns are kept apart:
Data movement is done once, by
RemoteTrajectoryProcessor. It reads the trajectories, splits them into shards ofshard_sizeconfigurations, uploads each shard with a small input JSON, submits one array task per shard, and afterwards collects the results and regroups them into the layout of the original files.Computation is a list of
Processorsteps. On the cluster, the shipped driver (processing/driver.py) reads its shard once, runs the steps in the order you listed them, and writes the shard once. So a single job can relax structures and then characterize the relaxed result, and the trajectory is uploaded only once however many steps you run.
Each processor annotates the ase.Atoms objects in place. By convention,
per-frame results go in atoms.info and per-atom results in
atoms.arrays, so they survive the round trip through .extxyz.
The array job goes through the normal task machinery (see Core Concepts), so
it runs on SLURM or the scheduler-free direct executor, whichever the
ClusterConfig selects.
Note
The driver and the processors run in the cluster’s conda env, so
remote_handler must be installed there, together with the extras of
the processors you use (steinhardt for Steinhardt; neuralil-jaxrens for
the NNFF/MACE optimize backends). The host only needs the core
install.
Built-in processors
Processor |
What it does |
Results |
|---|---|---|
|
LBFGS relaxation. Backends: |
Relaxed positions; |
|
Total radial distribution function g(r), PBC-aware, via an ASE neighbour list. No extra dependencies. |
|
|
Steinhardt bond-orientational order parameters ql and
wl for each |
|
Each processor’s arguments are checked twice: by its constructor on the host,
and by its arg schema (OptimizeArgs, RdfArgs, SteinhardtArgs) in
the driver before any compute starts. A bad argument fails at job start,
not halfway through an array task.
Running an analysis
Pass the processors you want to
RemoteTrajectoryProcessor and call
run(). This example computes g(r) and q4/q6 for two MD trajectories:
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}",
)
Things to know:
Output files. Results are written next to each input file, prefixed with
tag:md_300K.extxyz→ana_md_300K.extxyz. The order of the configurations is the same as in the input.Subsets.
every/start/endslice each trajectory before sharding, e.g.every=10to analyse every tenth frame.Shard size.
shard_size=None(or-1) puts everything into one task. Otherwise there areceil(n_configs / shard_size)tasks, of which at mostnum_parallelrun at once.Environment modules.
slurm_header_adddefaults to"module load openblas". Pass your cluster’s equivalent, or""if it has no such module.Remote layout. Each shard works in
<savepath>/calcdirs/<i>/, which holds its input JSON, its configurations and the processed output.
For relaxation alone there is a shortcut,
RemoteOptimizationHandler, which
takes the optimize arguments directly. It is equivalent to
RemoteTrajectoryProcessor(processors=[OptimizeProcessor(...)], ...). To
relax and analyse in one job, list the steps together:
processors=[
OptimizeProcessor(pickle_file="ensemble.pkl", fmax=0.05),
RDFProcessor(),
SteinhardtProcessor(r_cut=3.0),
]
Failures and resuming
run() raises if any shard failed or fewer configurations came back than
went in, instead of writing partial results. To retry, construct the handler
again with the same arguments and collect_only=True. Nothing is restaged.
Then call:
handler.recompute_failed()
This resubmits only the failed shards, waits for them, and collects and writes the results of all shards.
A shard writes its output only when all its steps have finished. A shard that
was killed partway, for example by the time limit, therefore starts over when
it is rerun. If your steps are slow, use a smaller shard_size.
Writing your own processor
Processors are plugins. A processor that lives in your package works with
the stock driver, with no change to remote_handler. It consists of four
parts, which belong in one module:
an arg schema, a dataclass that subclasses
ScriptInput(fromremote_handler.scripts.input_models) and has avalidatemethod;a cluster-side run function,
run(atoms_list, args, calcpath=None) -> atoms_list;a host-side
Processorsubclass with a class-levelnameand abuild_argsmethod;a module-level
register()call that ties thenametorunand the schema.
Here is a complete processor that computes per-atom coordination numbers:
# 1. Arg schema: one source of truth for the step's arguments. The host fills
# it in build_args; the driver validates against it before any compute.
@dataclass
class CoordinationArgs(ScriptInput):
cutoff: float
def validate(self, root: Optional[Path] = None) -> None:
if not isinstance(self.cutoff, (int, float)) or self.cutoff <= 0:
raise ScriptInputError("coordination: 'cutoff' must be > 0")
# 2. Cluster-side compute: takes and returns the shard's list of Atoms.
# Annotate in place: per-frame values in atoms.info, per-atom values in
# atoms.arrays. Keep heavy imports inside run so the host stays light.
def run(atoms_list, args, calcpath=None):
for at in atoms_list:
centers = neighbor_list("i", at, args["cutoff"])
cn = np.bincount(centers, minlength=len(at))
at.arrays["coordination"] = cn
at.info["coordination_mean"] = float(cn.mean())
return atoms_list
# 3. Host-side spec. `name` must match the register() call below. Because the
# class lives in the same module as that call, registration_module defaults
# to this module, and the driver imports it on the cluster automatically.
class CoordinationProcessor(Processor):
name = "coordination"
def __init__(self, cutoff: float = 3.0):
self.cutoff = cutoff
def build_args(self, savepath: str) -> dict:
return CoordinationArgs(cutoff=self.cutoff).to_dict()
# 4. Registration runs at import time (on the cluster, when the driver imports
# this module). It must be idempotent: re-importing just re-registers.
register("coordination", run, schema=CoordinationArgs)
Use it like a built-in:
from my_project.processors.coordination import CoordinationProcessor
processors = [RDFProcessor(), CoordinationProcessor(cutoff=2.8)]
How it reaches the cluster. The cluster never receives your class, only
the step names, their arguments, and a list of modules to import. Every
Processor has a registration_module, which defaults to the module the
class is defined in. The driver imports those modules before it resolves the
steps, and importing yours runs its register(...) call. This is why the
four parts belong in one module, and why your package must be installed in the
cluster’s conda env. If it is not, the job fails at start with “Could not
import processor registration module … Is the downstream package installed in
this env?”.
Further rules:
namemust be unique within one pipeline and must match the name passed toregister. A subclass withoutnameraisesTypeErrorwhen the class is defined.build_argsmust return JSON-serializable values. It receives the remote working directory,savepath, for building the remote paths of staged files.To ship a file the step needs on the cluster (a model, a reference structure), override
shared_files()to return its local path. It is uploaded once intosavepathand shared by all shards. SeeOptimizeProcessorfor the pattern.Registering a name that already exists replaces it. This also lets you override a built-in.
register(..., schema=None)is allowed, but then the arguments are not checked before the job starts.
API reference
The full class and function reference is in the Trajectory Processing section of the API docs.