Skip to content

Python API

Generated from the docstrings of the loupmd package. import loupmd as lm gives every name below as lm.NAME (for example lm.md is loupmd.quick.md); the headings name the module that defines each one.

Running

md

md(structure, *, model, head=None, charge=None, spin_multiplicity=None, sha256=None, trusted=False, checkpoint=None, download=False, ensemble='NVT', temperature_K=None, schedule=None, pressure_GPa=0.0, cell_mode='hydrostatic', timestep_fs=0.5, steps=None, mc=None, min_mc_temperature_K=None, dispersion=None, repeat=(1, 1, 1), output=None, seed=None, initial_velocities='keep', check='skip', integrator=None, capacity='auto', device=0, gate=None, skin='auto', mode=None, allow_reference=False, fallback=None, runner=None, engine=None, neighbours=None, calibrate=False) -> RunResult

Run MD on structure (a path or an Atoms) with model and return a RunResult.

  • model: a label, path or URL, with head, charge, spin_multiplicity, sha256 / trusted, checkpoint and download as lm.load; or an lm.load result (then without those);
  • ensemble: "NVT" (Langevin) or "NVE" (velocity Verlet from the structure's momenta, no temperature_K). integrator= chooses an lm.integrators record explicitly;
  • temperature_K or schedule (an lm.protocols schedule, or a profile's name for its schedule alone, as FastMACE); steps (optional with a schedule: the whole schedule); timestep_fs;
  • repeat: the supercell, (1, 1, 1) by default (never expanded silently);
  • output: a directory or an lm.Output; default ./<structure stem>.loupmd/, or ./loupmd-run/ for an Atoms;
  • seed: the noise seed; None draws one, recorded in metadata.json;
  • initial_velocities: what a structure at rest starts with. "keep" (default): at rest. "maxwell_boltzmann": seeded Maxwell-Boltzmann momenta at the run's starting target. A temperature in K: Maxwell-Boltzmann momenta at it. A structure that already moves keeps its momenta; the report says which;
  • check: "skip" (default), "gate" or "allow_unavailable", with gate= a GateConfig;
  • skin: the neighbour-list skin in A, or "auto" (default): chosen from how far the atoms move per step (loupmd.skin). It decides speed only;
  • capacity: "auto" (default): the whole system when it fits the GPU, else tiles of up to 65,536 atoms (PLAN.md D65; barostats on the device loop, LAMMPS_TILED_PLAN.md LT6 (a)), from 2^20 atoms with the wavefront schedule where the cell is long enough and the tiles' folded state does not fit the GPU (two-layer models whose tiles fold keep it there: faster); "whole", "tiled" or "wavefront" force one;
  • device: the GPU index.

RunResult dataclass

What lm.md returns.

  • summary: the one-screen report;
  • plan: the execution plan as recorded (metadata["plan"]);
  • gate: the gate's status and record;
  • simulation: the Simulation, which can run on, save a restart or be closed;
  • metadata: the dict written to metadata.json;
  • output: the output directory.

calc

calc(model, **options)

atoms.calc = lm.calc("omat0-medium"): the ASE calculator (loupmd.ase.calculator.calc has the arguments). ASE is imported here, at the first use.

calc

calc(model, *, head=None, checkpoint=None, sha256=None, trusted=False, download=False, charge=None, spin_multiplicity=None, device=None, skin=0.5, dispersion=None, engine_factory=None, ensure_bundle=None, probe=None, environ=None)

atoms.calc = lm.calc("omat0-medium"): an ASE calculator for model.

model is what lm.load takes (a label, a checkpoint path or a URL, with head, checkpoint, sha256 / trusted, download, charge, spin_multiplicity and device as there), or a ForceField that lm.load returned (then without those). skin is the neighbour-list skin in A. dispersion adds the D3 term (a preset name such as "d3bj" or an lm.Dispersion).

The stress is computed only when it is asked for.

load

load(model, head=None, *, checkpoint=None, sha256=None, trusted=False, download=False, charge=None, spin_multiplicity=None, device=0, precision='float32', engine_factory=None, ensure_bundle=None, probe=None, environ=None) -> ForceField

ff = lm.load("omat0-medium"): find the model's file, apply the trust rule and return its ForceField.

  • model: a label (loupmd models lists them), a checkpoint path or a URL; head for a multi-head model (there is no default head);
  • checkpoint: the file of a label, when it is not in $LOUPMD_MODELS or the cache; download=True fetches a label's file when it is missing;
  • sha256 or trusted=True: needed for a file that is not in the label table, because a checkpoint is a pickle and runs code when it is exported;
  • charge, spin_multiplicity: total charge and spin of the cell for models that take them (OMOL-0, POLAR-1);
  • device: the GPU index;
  • precision: "float32", the only one: float64 forces are cut (PLAN.md A3) and refused.

Nothing is exported and no engine is made here. engine_factory, ensure_bundle and probe replace the engine, the exporter and the checkpoint reader (tests).

ForceField

A loaded model. Made by lm.load; holds the engine once a structure was evaluated.

check_elements

check_elements(atomic_numbers)

Raise ModelElementError if the model has no embedding for one of atomic_numbers. Nothing is exported before this passed.

new_engine

new_engine(atoms, skin=0.5, capacity=None, extra_elements=())

An engine of its own for atoms with the system set: what a Simulation runs on, so that evaluating other structures with this force field does not disturb the run.

capacity (a CapacityConfig; None is the whole-system engine without a plan): with "auto" the engine plans the execution first (loup_plan_execution) and a system that does not fit the GPU whole gets a :class:~loupmd.tiled_engine.TiledEngine; "tiled" always does, and "wavefront" with the wavefront schedule forced (two-layer models, S5-T08). last_execution then holds {"mode", "receivers", "plan"} (mode "whole", "tiled" or "wavefront"). extra_elements: atomic numbers the bundle carries beyond the structure's (species events and transmute moves, S6-T01 and S6-T03).

engine_for

engine_for(atoms, skin=0.5)

The engine with atoms' system set: exports the bundle and creates the engine when the elements are not in the loaded bundle, and sets the system when the atomic numbers or the skin changed.

evaluate

evaluate(atoms, stress=False, skin=0.5)

(energy in eV, forces in eV/A, stress) of atoms; the stress (3x3, eV/A^3) is None unless stress=True.

evaluate_per_atom

evaluate_per_atom(atoms, stress=False, skin=0.5)

(energy, forces, stress, energies): as evaluate, plus each atom's energy in eV (its MACE node energy and its E0; they sum to the energy). Generic kernels and short-range models only: the library refuses the others.

Simulation

lm.Simulation(atoms, force_field, integrator=lm.integrators.Langevin(...), output=lm.Output("run/"), seed=1).

  • atoms: the starting structure with its momenta (a structure at rest starts at rest); it is not changed. Atoms under ASE's FixAtoms stay where they are and count no degrees of freedom; other constraints are refused;
  • force_field: what lm.load returned;
  • integrator: an lm.integrators record;
  • output: an lm.Output (directory and cadences), or None for no files;
  • seed: the thermostat's noise seed; None draws one (Simulation.seed, written to simulation.json);
  • skin: the neighbour-list skin in A, or "auto": chosen from how far the atoms move per step, first estimated from the temperature and the lightest atom, then corrected once from what the engine measured (loupmd.skin; Simulation.skin_record). It decides speed only;
  • check: "skip" (default), "gate" or "allow_unavailable": the accuracy gate (the 3x rule against MACE float64, loupmd.validate) on rattled copies of the structure before the first step; gate is its GateConfig. Simulation.gate holds the status and the record;
  • capacity: "auto" (default), "whole", "tiled", "wavefront" or a CapacityConfig. "auto" plans the execution before the first step and runs a system that does not fit the GPU whole in tiles of at most receivers atoms (Simulation.execution says which); from 2^20 atoms in a cell long enough for 12 layers of tiles it uses the wavefront schedule, which "wavefront" forces (two-layer models; S5-T08), unless the model's tiles fold their skip chain and that state fits on the GPU (faster; the plan then keeps it there). The tiled modes run every integrator on the device (PLAN.md O31), the barostats too (Langevin BAOAB, MTK and Berendsen NPT; LAMMPS_TILED_PLAN.md LT6 (a)). With a dispersion term the integrator runs on the host, NVE and Langevin only.

  • elements: more elements (symbols or atomic numbers) for the run's bundle than the structure has, for species events (set_species) and transmute moves that bring them in.

Nothing is exported and no engine is made before the first run; argument errors come before that.

atoms property

atoms

The structure as it is now: a copy with positions, momenta and a calculator holding the potential energy and the forces. Before the first run it is the starting structure.

recheck_dispersion

recheck_dispersion()

Repeat the setup check of long_range="auto" on the structure as it is now and install the method it chooses (PLAN.md S6-D07: on request; an event that changes the composition repeats it by itself).

relax

relax(optimizer=None, *, fmax=0.05, steps=100000000)

Relax the starting structure at fixed cell before the first step (lm.optimize.relax, with the run's dispersion term): the run then starts from the relaxed positions with the structure's velocities. Returns the RelaxResult. Refused once steps have run.

start

start()

What the first run does before its first step: the gate (if asked), the bundle, the engine and the force evaluation of the starting structure, whose row and frame are written. Does nothing when the run has started.

run

run(steps=None, *, schedule=None, mc=None) -> RunSummary

steps more MD steps; returns what the call did. Simulation.step counts all steps of the run.

schedule (an lm.protocols schedule: ramps and holds) moves the thermostat's target: every step of a ramp runs at the target of its end point, as in FastMACE. Without steps the whole schedule runs (or what remains of it); steps beyond its end are refused, never cut short. Rows and frames are also written at the end of every segment. When the schedule is finished the thermostat stays at its last target.

mc: Monte Carlo moves (an lm.mc.Swap, Transmute or Displace, or a list of them) for this call: after every move.every-th step of the run (counted by Simulation.step) the move makes move.attempts attempts at the thermostat's target temperature. The counters are in Simulation.mc_counters, metadata.json and the restart file.

update

update(*, positions=None, momenta=None, masses=None, species=None, charges=None, total_charge=None, spin_multiplicity=None, friction_per_fs=None)

Any combination of host changes between two run calls, as one transaction (plan task S6-T01): everything is checked first, then applied and the new state evaluated once; if any part fails, the run is left as it was before the call and the error is raised.

  • positions (A) and momenta (ASE units), (N, 3); momenta are taken with the new masses;
  • masses (amu, (N,)): the momenta stay (as in ASE), so the velocities change, v' = v m / m';
  • species (atomic numbers or symbols, (N,)): within the elements of the run's bundle (the starting structure's), so nothing is exported; an atom whose element changes takes the new element's standard mass unless masses is given too, and keeps its momentum;
  • total_charge, spin_multiplicity: for models that take them (OMOL-0, POLAR-1). They are export arguments (PLAN.md O7), so the model is loaded again with them and a new bundle and engine are made;
  • charges: per-atom charges are an input of no model LoupMD runs, and are refused;
  • friction_per_fs: the Langevin (or BAOAB) friction in 1/fs.

Every change but the friction sets the engine's state anew: its step count restarts (the thermo rows stay on their cadence) and a barostat's own momentum starts from zero.

set_positions

set_positions(positions)

Set every atom's position (A, (N, 3)), one event (update); the momenta stay.

set_momenta

set_momenta(momenta)

Set every atom's momentum (ASE units, (N, 3)), one event (update).

set_masses

set_masses(masses)

Set every atom's mass (amu, (N,)), one event (update); the momenta stay, as in ASE.

set_species

set_species(species)

Set every atom's element (atomic numbers or symbols, (N,)), one event (update): within the run's bundle, with no export; atoms whose element changes take its standard mass.

set_charges

set_charges(charges=None, *, total_charge=None, spin_multiplicity=None)

The cell's total charge and spin multiplicity (OMOL-0, POLAR-1), one event (update): the model is loaded again with them. Per-atom charges are refused.

set_friction

set_friction(friction_per_fs)

Set the Langevin (or BAOAB) friction in 1/fs, one event (update).

save_restart

save_restart(path=None) -> Path

Write the restart file (restart.npz in the output directory unless path is given). With output, this is a chunk boundary: rows and frames up to this step are closed and fsynced first.

close

close()

Finish writing and close the output files. The run can be resumed from its last restart.

resume classmethod

resume(directory, *, force_field=None, restart=None)

Continue the run of directory from its restart file: sim = lm.Simulation.resume("run/").

The model is loaded again as simulation.json names it (a label through the label table; a file by its path with the recorded SHA-256), or pass force_field. A restart of another model, a state that does not fit, or output chunks that do not fit the restart raise RestartMismatch before anything is changed.

Settings

Output dataclass

Output directory and cadences in MD steps (FastMACE's record and defaults). trajectory_every and restart_every may be None (no trajectory, no restart files); thermo rows are always written. directory is kept as given, as a string.

Dispersion dataclass

A dispersion correction. Every field can be set; the presets (:data:PRESETS) are records with names.

  • method: "d3".
  • damping: "bj" (Becke-Johnson), "zero", "bjm" or "zerom" (the modified dampings).
  • functional: the parameter set by functional name (None: the model's training functional).
  • parameters: raw parameters instead of a functional's set (s6, s8, a1, a2 for the BJ dampings; s6, s8, rs6, optional rs8 and alpha for zero damping, plus beta for zerom).
  • three_body with three_body_cutoff_bohr: the Axilrod-Teller-Muto term (s9 = 1) over triangles whose sides lie within that cutoff; smoothing switches each side off at it.
  • pair_cutoff_bohr, cn_cutoff_bohr: the pair sum's and the coordination numbers' cutoffs.
  • smoothing: "none" or the width in bohr of a switch that takes the pair sum to zero at its cutoff (and the three-body term at its own).
  • long_range: "auto" (the fastest method that meets the accuracy contract on the user's structure, checked at setup), or a method by name, used as given: "none", "tail", "split", "mesh".
  • mesh_spacing_A: the mesh of "split" and "mesh" (None: the method's default).
  • update_every: 1. Updating the long-range part every n steps was measured and rejected (S6-D02).
  • auto_methods: the methods "auto" may pick (None: all built ones).

integrators

lm.integrators: the integrator records a Simulation takes as integrator=.

Names and arguments are FastMACE's (fm.integrators). Units: fs, K, friction per fs. A thermostat's temperature and friction have no defaults: physics is not chosen silently. Each record maps onto an IntegratorConfig (to_config), which is what the engine runs: NVE, Langevin, CSVR, NoseHooverChain and Berendsen at constant volume (Berendsen with a pressure couples the cell too), and LangevinBAOAB and MTK at constant pressure.

fixcm keeps the centre of mass at rest, as in FastMACE: "auto" (the default) is on, and off when the structure has fixed atoms, which pin the frame already; True with fixed atoms is refused. Langevin's noise then loses its mass-weighted mean every step (FastMACE's "mass_weighted" projection); the total momentum of NVE, CSVR and the Nose-Hoover chain is removed at the start of every run call. The temperature counts three degrees of freedom fewer, and so do the thermostats that count them (CSVR, the Nose-Hoover chain).

NVE dataclass

Velocity Verlet: lm.integrators.NVE(timestep_fs=1.0). The conserved quantity is E_kin + E_pot.

Langevin dataclass

Langevin NVT: lm.integrators.Langevin(timestep_fs=0.5, temperature_K=300, friction_per_fs=0.002).

CSVR dataclass

Canonical sampling through velocity rescaling (Bussi, Donadio, Parrinello), as ASE's Bussi: lm.integrators.CSVR(timestep_fs=1.0, temperature_K=300, tau_fs=100).

tau_fs is ASE's taut. The conserved quantity is E_kin + E_pot minus the energy the thermostat has transferred. The velocities are rescaled, so the structure must move at the start (as ASE's Bussi).

NoseHooverChain dataclass

Nose-Hoover chains, as ASE's NoseHooverChainNVT: lm.integrators.NoseHooverChain(timestep_fs=1.0, temperature_K=300, tdamp_fs=100).

tdamp_fs, tchain and tloop are ASE's tdamp, tchain and tloop. The thermostat masses are made for temperature_K and stay when a schedule moves the target, as ASE's and FastMACE's. The conserved quantity is E_kin + E_pot plus the chain's energy. The degrees of freedom of the reported temperature stand where ASE counts 3 N: 3 N - 3 with the centre of mass at rest, 3 (N - fixed) with fixed atoms.

Berendsen dataclass

Berendsen thermostat, as ASE's NVTBerendsen: lm.integrators.Berendsen(timestep_fs=1.0, temperature_K=300, taut_fs=100); with pressure_GPa, taup_fs and compressibility_per_GPa also Berendsen's barostat, as ASE's NPTBerendsen (experimental): lm.integrators.Berendsen(timestep_fs=1.0, temperature_K=300, taut_fs=100, pressure_GPa=0.0, taup_fs=1000, compressibility_per_GPa=0.006).

Not canonical: for equilibration only. taut_fs and taup_fs are ASE's taut and taup, compressibility_per_GPa the material's compressibility (ASE's compressibility_au times units.GPa). Without mask the cell keeps its shape; mask=(1, 1, 0) lets the first two cell vectors follow their own stress and leaves the third alone (ASE's Inhomogeneous_NPTBerendsen). The barostat makes one force call per step: the first kick of a step uses the forces of the cell before its scaling, where ASE's classes evaluate again. Not with fixed atoms.

LangevinBAOAB dataclass

Langevin BAOAB NPT, as ASE's LangevinBAOAB with a barostat (experimental): lm.integrators.LangevinBAOAB(timestep_fs=1.0, temperature_K=300, friction_per_fs=0.002, pressure_GPa=0.0).

BAOAB Langevin dynamics for the atoms (Leimkuhler and Matthews) and a Langevin-Hoover barostat for the cell (Quigley and Probert). friction_per_fs is the thermostat's friction (ASE's T_tau is its inverse); cell_mode is "hydrostatic" (the cell keeps its shape; ASE's hydrostatic=True) or "full"; barostat_tau_fs is ASE's P_tau (None: ASE's default, 20 T_tau). The barostat's mass is ASE's heuristic. In the full-cell mode the barostat's drag on the velocities is Quigley and Probert's; ASE 3.27 adds its trace term to all nine elements. fixcm is False only, as for ASE's class.

FastMACE's record also takes external_stress_GPa, barostat_mass_factor, disable_cell_langevin, max_volume_ratio and max_cell_length_A; here the target is a pressure, the mass factor 1, the cell's thermostat on, and the run stops once the volume leaves a twentieth to twenty times its start (the values FastMACE defaults to); other values are refused by name.

MTK dataclass

Martyna-Tobias-Klein NPT with Nose-Hoover chains on the atoms and on the cell, as ASE's IsotropicMTKNPT (cell_mode="hydrostatic") and MTKNPT ("full"); experimental: lm.integrators.MTK(timestep_fs=1.0, temperature_K=300, pressure_GPa=0.0, tdamp_fs=100, pdamp_fs=1000).

tdamp_fs, pdamp_fs, tchain, pchain, tloop and ploop are ASE's tdamp, pdamp, tchain, pchain, tloop and ploop (chains of at most 8 links). Deterministic; the conserved quantity is E_pot + E_kin plus both chains' energies, the cell's kinetic energy and P V. The masses of both chains and of the cell are made for temperature_K and stay when a schedule moves the target. The degrees of freedom stand where ASE counts 3 N: 3 N - 3 with the centre of mass at rest (fixcm). FastMACE's record has a dof field beside fixcm; here the count follows fixcm alone.

resolve_fixcm

resolve_fixcm(fixcm, fixed_atoms) -> bool

A record's fixcm for a structure with (fixed_atoms) or without fixed atoms: "auto" is off with fixed atoms and on without; True with fixed atoms is refused.

to_data

to_data(record) -> dict

An integrator record as a table: {"type": "CSVR", "timestep_fs": ..., ...} (a run file's [integrator]).

from_data

from_data(data, *, timestep_fs=None, temperature_K=None)

The record of a table (to_data). timestep_fs and temperature_K fill those fields where the table leaves them out (a run file states them once, outside the table). Unknown keys are refused by name.

protocols

lm.protocols: temperature schedules (ramps and holds) and the run profiles.

Ported from FastMACE (fastmace/protocols/schedule.py and profiles.py), with the same names, arguments and rounding, so a schedule means the same run in both codes:

  • A Schedule is timestep-free: segments in ps. Schedule.resolve(timestep_fs) rounds each segment to whole steps (half up) and records the boundaries, the total and the rounded durations and rates.
  • The target is piecewise linear in the step. Step n of a segment uses the target at the step's end point, so the target changes every step on a ramp and never on a hold. Each ramp interpolates from its colder end.
  • ScheduleState is the schedule position: what a restart stores.
  • PROFILES holds the profiles slow, fast, ultrafast and anneal as data. Their relaxation and quench settings are data only here (PLAN.md Stage 4 runs them).

A profile's ensemble is NVT or NPT at a constant pressure; pressure schedules are refused.

Segment dataclass

One ramp or hold as requested: ps or (ramps only) rate_K_per_ps, never both.

duration_ps property

duration_ps: float

The requested duration (before rounding to whole steps).

phase property

phase: str

heating, cooling or hold: the thermo file's phase column.

to_data

to_data() -> dict

The segment as profile data (segment_from_data reads it back).

Schedule dataclass

A sequence of segments; + concatenates and refuses a temperature jump.

duration_ps property

duration_ps: float

The requested duration (before rounding).

resolve

resolve(timestep_fs) -> ResolvedSchedule

Whole steps at timestep_fs.

ResolvedSchedule dataclass

A schedule at a timestep: steps per segment, boundaries (0, end_1, ..., total), targets.

durations_ps property

durations_ps: tuple

The rounded durations.

rates_K_per_ps property

rates_K_per_ps: tuple

The rates after rounding (0 for holds).

target

target(step) -> float

The thermostat target for step step (its end point); step 0 is the start temperature.

phase

phase(step) -> str

heating, hold or cooling; a boundary step belongs to the segment it ends.

next_boundary

next_boundary(step) -> int

The first segment boundary after step.

targets

targets(first, last) -> list

The targets of steps first to last inclusive.

max_target

max_target(first, last) -> float

The highest target of steps first to last inclusive.

min_target

min_target(first, last) -> float

The lowest target of steps first to last inclusive.

output_steps

output_steps(interval) -> list

Step 0, every interval steps and every segment boundary.

record

record() -> dict

For provenance and the run report: requested and rounded durations and rates, boundaries.

ScheduleState

The schedule position: what a restart stores. step counts the schedule's steps done (0 to total_steps), not the simulation's step.

target_K property

target_K: float

The target of the current (last completed) step.

steps_to_run

steps_to_run(steps=None) -> int

The steps a run(steps=...) takes: all that remain for None. Raises before any step for a finished schedule or steps beyond the remainder; never truncates.

advance

advance(steps) -> None

Record steps completed steps.

to_restart

to_restart() -> dict

JSON-safe: the segments (with their rounded steps), the timestep, the position, the target.

from_restart classmethod

from_restart(data) -> ScheduleState

The inverse of to_restart; refuses a record whose steps or target do not match.

Profile dataclass

A named schedule with its output intervals, initial relaxation and quench settings.

relax_fmax 0 means no initial relaxation (eV/A). quench is None or a mapping with QUENCH_KEYS (frames per bin_K bin of the target from min_K, quenched to fmax with optimizer, at most max_steps). ensemble is "NVT" or "NPT" (lm.md's; any case). pressure_GPa is NPT's constant target: None for NVT, 0 GPa by default for NPT; a pressure schedule is refused. A run file or loupmd md --profile runs the profile in its ensemble; lm.md(structure, model, **profile.md_options()) does the same from Python.

md_options

md_options() -> dict

lm.md's schedule, ensemble and pressure arguments of this profile.

segment_from_data

segment_from_data(data) -> Segment

A segment from profile or restart data: {kind: ramp, start_K, end_K, ps | rate_K_per_ps} or {kind: hold, temperature_K, ps}. Unknown keys are refused by name.

ramp

ramp(start_K, end_K, *, ps=None, rate_K_per_ps=None) -> Schedule

A linear ramp from start_K to end_K, over ps or at rate_K_per_ps (signed).

hold

hold(temperature_K, *, ps) -> Schedule

temperature_K for ps.

profile_from_data

profile_from_data(data) -> Profile

A profile from a mapping: name, segments (Schedule.from_data) and optional sample_interval, trajectory_interval, relax_fmax, quench, ensemble, pressure_GPa. Unknown keys are refused by name.

find_profile

find_profile(name) -> Profile

A shipped profile by its name, else the profile of a .toml file.

load_profile

load_profile(path) -> Profile

A profile from a .toml file.

optimize

lm.optimize: structure relaxation with ASE 3.27's optimisers.

The records take ASE's arguments and defaults under FastMACE's names (fm.optimize); lengths are in A. relax runs one until the largest force on an atom is below fmax. Atoms under ASE's FixAtoms do not move.

Where the steps are taken: LBFGS at fixed cell runs on the GPU inside the engine (loup_minimize: the history and its products on the device, so a step costs little more than its force call). FIRE, and every relaxation with cell_filter=FrechetCell(...), takes its steps on host arrays around the engine's force call. Both give ASE's steps. With the cell filter the cell is relaxed with the positions (ASE's FrechetCellFilter, pressure in GPa); it is refused with fixed atoms and for models with long-range terms (MACE-POLAR-1), as in FastMACE.

FrechetCell dataclass

ASE 3.27's FrechetCellFilter: positions and the log of the deformation gradient relaxed together.

scalar_pressure_GPa is ASE's scalar_pressure in GPa; hydrostatic_strain, constant_volume, mask (six Voigt flags or a 3x3 of flags) and exp_cell_factor (None: the number of atoms) as ASE's.

LBFGS dataclass

ASE 3.27's LBFGS: maxstep_A (ASE maxstep), memory, damping and alpha with ASE's defaults. use_line_search is not offered.

FIRE dataclass

ASE 3.27's FIRE with ASE's arguments and defaults: dt and dtmax in ASE time units, maxstep_A (ASE maxstep), Nmin, finc, fdec, astart, fa and a. downhill_check is not in this version.

RelaxResult dataclass

What relax returns.

relax

relax(force_field, atoms, optimizer=None, *, fmax=0.05, steps=100000000, skin=0.5, dispersion=None, callback=None, _on_step=None) -> RelaxResult

Relax atoms until the largest force on an atom is below fmax (eV/A), or steps optimiser steps were taken. optimizer is an lm.optimize record (default LBFGS()); with its cell_filter the cell is relaxed too and the cell's rows count for fmax as in ASE. force_field is what lm.load returned. dispersion (a preset name or an lm.Dispersion, as lm.calc takes it) adds the D3 term to the energy, forces and stress; long_range="auto" is the plain sum here, without the setup check. atoms is not changed; callback(step, atoms positions, energy, max force) is called after every force call.

mc

Monte Carlo moves between MD steps (plan tasks S6-T02 to S6-T04): lm.mc.Swap, Transmute and Displace, as blocks between two run calls (lm.mc.swap and the others) or every few steps of a run (Simulation.run(mc=...)).

A swap exchanges the species at two sites: one atom of each species of a pair is chosen uniformly, the trial energy comes from the engine's energy-only pass (LOUP_EVAL_ENERGY_ONLY), and the Metropolis rule is applied on the host. LoupMD makes the exchange by moving the two atoms: they swap positions and velocities (FastMACE's velocities="exchange"), so every atom keeps its index, element and mass and the engine needs no new setup (PLAN.md D72). The configuration is the one a species swap gives; only the atoms' labels differ.

Swap dataclass

Swap the species of two atoms: a pair type uniformly from pairs, then one atom of each species uniformly. every MD steps, then attempts attempts (Simulation.run(mc=...)). velocities: "exchange" (the two atoms swap velocities, as FastMACE's default), the only one in LoupMD.

Transmute dataclass

Change one atom's element within the set species (semi-grand canonical): an atom of the set uniformly, then another element of the set uniformly; accepted with min(1, exp(-(dE - dmu) / kT)), where dmu is the difference of the configurational chemical potentials mu (eV, by species; absent species have 0; FastMACE's configurational_mu converts full ones). The atom takes the new element's standard mass; velocities "rescale" keeps its kinetic energy, the only treatment in LoupMD. Every attempt sets the engine's system for the trial composition (PLAN.md D72: the re-setup cost is in Counters.setup_s).

Displace dataclass

Displace one atom (uniformly chosen among those not fixed) uniformly within a sphere of radius delta_A; accepted with min(1, exp(-dE / kT)). A fixed step keeps the chain's detailed balance; FastMACE's adaptive step is not in this version.

Counters dataclass

Attempted and accepted moves of one kind; rejected_nonfinite counts trial energies that were not finite (rejected, never patched).

SwapResult dataclass

What a block of moves did (swap, transmute, displace): the counters and the potential energy after the block (eV).

species_number

species_number(species) -> int

An atomic number from a symbol or an atomic number.

kind

kind(move) -> str

"swap", "transmute" or "displace".

record

record(move) -> dict

The move as JSON: its kind and fields.

from_record

from_record(data)

The move a record describes (a move passes through unchanged).

swap_block

swap_block(engine, move: Swap, positions, velocities, numbers, cell, energy: float, kT: float, rng, attempts: int | None = None)

attempts (default move.attempts) swap attempts from the state positions, velocities of energy energy (eV); kT in eV; rng a numpy.random.Generator. Returns (positions, velocities, energy, Counters) of the chain's last state; the arrays are new. The engine's device positions are those of the last trial afterwards: the caller sets the state it keeps.

displace_block

displace_block(engine, move: Displace, positions, movable, cell, energy: float, kT: float, rng, attempts: int | None = None)

attempts (default move.attempts) displace attempts from positions of energy energy; movable the indices that may move. Returns (positions, energy, Counters); the engine's device positions are those of the last trial afterwards.

swap

swap(simulation, move: Swap, *, temperature_K=None, seed=None, attempts=None) -> SwapResult

move.attempts (or attempts) swap attempts on a Simulation between two run calls, at temperature_K (default: the thermostat's). The kept state is set on the engine once, so its step count restarts as after any event (Simulation.update).

transmute

transmute(simulation, move: Transmute, *, temperature_K=None, seed=None, attempts=None) -> SwapResult

move.attempts (or attempts) transmute attempts on a Simulation between two run calls, at temperature_K (default: the thermostat's). Elements the structure does not have yet must be in the run's bundle: lm.Simulation(..., elements=[...]).

displace

displace(simulation, move: Displace, *, temperature_K=None, seed=None, attempts=None) -> SwapResult

move.attempts (or attempts) displace attempts on a Simulation between two run calls, at temperature_K (default: the thermostat's).

Engine and runtime

loupmd._core.LoupEngine

One engine handle: a bundle on one GPU, then a system, then single points or MD.

set_evaluate_ahead

set_evaluate_ahead(on: bool = True) -> None

Queue each next evaluate call's force pass ahead of the call (loup_set_evaluate_ahead). Only for a process whose sole GPU work between evaluate calls is this engine's: with it on, other GPU work in between (another engine being set up, PyTorch, a device-wide synchronisation) can wait forever.

cutoff

cutoff() -> float

The model's cutoff radius in A.

species

species() -> list

The atomic numbers of the bundle's species.

compute_device

compute_device(positions_ptr: int, cell, forces_ptr: int = 0, ids_ptr: int = 0, pos_strides=(3, 1), f_strides=(3, 1), stream: int = 0, energy: bool = True, virial: bool = False)

One force evaluation on arrays that live on the GPU (loup_compute_device; the call of the LAMMPS Kokkos pair style).

positions_ptr / forces_ptr / ids_ptr are device addresses (e.g. tensor.data_ptr() of CUDA float64 / int32 tensors of this engine's device); the strides are (row, component) in elements. Forces are added to the caller's array. stream is a cudaStream_t as an integer (0: the default stream). Returns (energy in eV or None, virial [xx, yy, zz, xy, xz, yz] in eV or None); without energy and virial the call returns before the forces are there, and work queued on stream afterwards waits for them.

evaluate_tiled

evaluate_tiled(atomic_numbers, positions, cell, receivers: int, skin: float = 0.5, compute_stress: bool = True)

loup_evaluate_tiled: energy, forces and stress of a periodic system evaluated tile by tile (plan task S5-T03): at most receivers local atoms per tile, 0 for the cap of the memory plan. Returns (energy, forces, stress, tiles); stress is None without compute_stress (the sweeps then skip the virial). The handle then holds the last tile's domain: call set_system before other calls. A library older than the public name has the same call as loup_debug_evaluate_tiled.

has_tiled_md

has_tiled_md() -> bool

Whether the library has the tiled MD loop on the device (loup_tiled_run, PLAN.md O31).

tiled_set_state

tiled_set_state(atomic_numbers, masses_amu, positions, velocities, cell, fixed=None, receivers: int = 0, skin: float = 0.5, noise_step: int = 0, int_state=None, int_state_kind: int = -1)

loup_tiled_set_state: the tiled trajectory's system and state on the device (velocities in A per ASE time unit). int_state (64 doubles) restores an integrator's state block. With positions and velocities both None the device state stays and only its thermo step count starts anew.

tiled_run

tiled_run(n_steps: int, it: LoupIntegrator, max_rows: int = 0)

loup_tiled_run: n_steps steps on the device. Returns (stats, rows, max_step_A), rows a THERMO_DTYPE array (empty unless it.thermo_every and max_rows are set), max_step_A the longest step an atom took.

tiled_get_state

tiled_get_state()

loup_tiled_get_state: (positions, velocities, forces, energy, noise_step, int_state, int_state_kind).

has_tiled_barostats

has_tiled_barostats() -> bool

Whether the library's tiled MD runs the barostats (loup_tiled_get_cell, LAMMPS_TILED_PLAN.md LT6 (a)): older libraries keep the cell fixed in tiled mode.

tiled_get_cell

tiled_get_cell() -> np.ndarray

loup_tiled_get_cell: the tiled MD's cell (rows), as a barostat left it.

set_execution

set_execution(mode: int, receivers: int = 0, memory_fraction: float = 0.9)

loup_set_execution: the mode (LOUP_EXEC_*), a receiver cap (0: from the memory plan) and the fraction of free device memory the plan may use.

plan_execution

plan_execution(atomic_numbers, positions, cell, skin: float = 0.5) -> MemoryPlan

loup_plan_execution: whole or tiled, and the receiver cap, for this system under the handle's execution settings. A probe tile measures the workspace; the handle then holds it (call set_system before other calls).

last_execution

last_execution() -> Execution

loup_get_execution: the cap, tiles and device memory of the last tiled call.

evaluate_energy

evaluate_energy(positions, cell) -> float

The energy alone, from a pass without gradients (LOUP_EVAL_ENERGY_ONLY). The forces on the device are not those of these positions afterwards.

evaluate_per_atom

evaluate_per_atom(positions, cell, compute_stress: bool = False)

Energy, forces, stress (or None) and the per-atom energies [n] (LOUP_EVAL_PER_ATOM): each atom's MACE node energy plus its E0. The energy is their sum (an energy-only pass; it differs from evaluate's in float32 rounding), forces and stress are evaluate's. Generic kernels and short-range models only. The forces on the device are not those of these positions afterwards.

set_fixed_atoms

set_fixed_atoms(fixed=None)

Hold atoms in place (ASE's FixAtoms): fixed is a mask of length n_atoms or None to free all. Fixed atoms keep their positions, have zero velocity and get no thermostat noise; the temperatures the engine reports count 3 (N - n_fixed) degrees of freedom.

set_dispersion

set_dispersion(record=None)

Add the D3 pair term of a resolved :class:loupmd.dispersion.Dispersion to every force evaluation, MD step and energy-only call of this engine (None removes it). Needs a periodic cell. A library built before PLAN.md task S6-D04 is refused.

run

run(n_steps: int, it: LoupIntegrator) -> LoupMDStats

n_steps steps of the integrator it (see integrator).

debug_csvr_noise

debug_csvr_noise(seed: int, first_step: int, n_steps: int, ndof: int)

Testing only: the standard normal and the chi-square variate (ndof - 1 degrees of freedom) CSVR draws in each of n_steps steps from first_step on, as two arrays.

minimize

minimize(max_steps: int, fmax: float = 0.05, maxstep_A: float = 0.2, memory: int = 100, damping: float = 1.0, alpha: float = 70.0) -> LoupMinStats

Up to max_steps LBFGS steps on the device from the positions on the handle (ASE's LBFGS without line search), stopping when the largest force on a free atom is below fmax (eV/A). A call with the same settings continues the relaxation of the one before; max_steps=0 only evaluates. get_state reads the positions, forces and energy.

set_cell

set_cell(cell, scale_atoms: bool = True)

A new cell (3 x 3, rows are the cell vectors, in A) for the positions on the handle; with scale_atoms the atoms keep their fractional coordinates, as ASE's set_cell(scale_atoms=True). Velocities stay; forces are those of the old cell until the next evaluation or run.

get_cell

get_cell() -> np.ndarray

The cell of the positions on the handle: the one last given, or where a variable-cell run took it.

set_reference_volume

set_reference_volume(volume_A3: float)

The volume the cell limits of a variable-cell run refer to (set_state sets it to the volume it is given; a resumed run passes the first run's).

step_displacement

step_displacement() -> float

The largest distance in A an atom moved in one MD step lately (the displacement tracker's two windows): what the neighbour skin has to cover for the pipelined loop, which runs while four times this is below half the skin.

thermo_pending

thermo_pending() -> int

Unread rows in the device's thermo buffer.

read_thermo

read_thermo(max_rows: int | None = None) -> np.ndarray

The oldest unread thermo rows (all of them by default) as a structured array (THERMO_DTYPE); they leave the device's buffer.

plan_memory

plan_memory(n_atoms: int, edges_per_atom: float = 0.0) -> MemoryPlan

Device memory for n_atoms of the current material, scaled from the current system's buffers. edges_per_atom defaults to the current system's.

export_state

export_state() -> bytes

Positions, velocities, cell, step counter and displacement tracker as one versioned block of bytes.

import_state

import_state(blob: bytes)

Restore a block from export_state on a handle that holds the same system.

ensure_loup_bundle

ensure_loup_bundle(model_path: str, atomic_numbers: list[int], cache_dir: str | None = None, head: str | None = None, generic: bool | None = None, charge: int | None = None, spin_multiplicity: int | None = None) -> Path

The cached bundle for (model contents, species, head, charge / spin, exporter sources) in the flat cache of the source checkout (cache_dir, default ~/.cache/loupmd), exporting it on a miss.

Every model takes the generic kernels; generic is accepted and ignored (the kernels specialised to MACE-OMAT-0 medium were retired). head selects a multi-head model's head (default: omat_pbe if present, else the last head). charge and spin_multiplicity (total charge in e and 2S + 1) apply to MACE-OMOL-0 (its total charge / spin embedding) and to MACE-POLAR-1 (the totals its charge constraint holds); default 0 and 1. The export writes them into the bundle, so each setting is its own bundle. Other models refuse them.

runtime_info

runtime_info() -> RuntimeInfo

Load the library if it is not loaded yet and describe the runtime. Never raises for a missing GPU or library: both are reported in the record (loupmd doctor says how to fix them).

Errors

errors

LoupMD's exceptions and their message shape.

Every exception LoupMD raises derives from LoupError. Its message has one shape, so that no traceback needs reading: what happened; why, in a sentence or two; what to do next. This module imports nothing else of the package.

LoupError

Bases: Exception

Base class of every error LoupMD raises: LoupError(what, why=None, next_step=None).

BackendError

Bases: LoupError, RuntimeError

A call into libloupmd failed or was refused. what is the library's own message (loup_last_error); call names the C function.

InputError

Bases: LoupError, ValueError

An argument is refused before the library reads it (a wrong array shape, for example).

CheckpointTrustError

Bases: LoupError

A checkpoint would be unpickled without a matching SHA-256 or trusted=True.

CacheLocationError

Bases: LoupError

The cache root is somewhere it must not be (inside the Python installation).

UnsupportedModel

Bases: LoupError

The library has no compiled kernels for this model's architecture. signature names the missing kernels.

ModelElementError

Bases: LoupError

The structure has an element the model has no embedding for.

PlanRefused

Bases: LoupError, ValueError

The run cannot be planned as asked. reasons lists every reason at once; nothing is replaced silently.

CapacityError

Bases: LoupError

The system does not fit the GPU in the execution mode asked for.

GateFailed

Bases: _GateError

The accuracy gate on the user's structure failed (the 3x rule against MACE float64).

GateUnavailable

Bases: _GateError

The gate's reference could not be computed (the export extra is missing, or no device has the memory).

RestartMismatch

Bases: LoupError

A restart does not belong to this model, element set or atom count.

NonFiniteError

Bases: LoupError

A non-finite energy or force stopped the run; it is never patched over.

CellDivergedError

Bases: LoupError

An NPT run's cell left the range its integrator allows; step is the step whose cell was checked.