Params

aimmd.Params is the central configuration object for a run. See Parameters for a narrative guide and the full field reference.

class aimmd.Params(*args, **kwargs)[source]

Bases: ParamsFields, ParamsMagic, ParamsHelpers, ParamsProperties, ParamsMethods, ParamsPaths, ParamsIO

Central configuration object for AIMMD runs.

A Params instance is the single source of truth for a run’s configuration: paths, engine settings, analysis pipeline, neural-network committor model, sampling controls, and scheduler metadata.

In the AIMMD architecture, Params is consumed by both:

  • Launcher, which uses it to build execution plans and write run directory layouts, and

  • Worker, which uses it to execute tasks such as shoot, free, and train.

Typical responsibilities

  • define end states and state processing conventions,

  • define the analysis pipeline (states/descriptors/values),

  • provide engine integration hooks (initialize_simulation/run_simulation),

  • hold the committor model (e.g., torch network) and training routine,

  • persist and reload run state (paths, bins/densities, network snapshots),

  • carry scheduler hints (e.g., slurm_header).

Usage >>> import aimmd >>> >>> # minimal initialization without a parameters file >>> params = aimmd.Params(states_function=states_function, … initial_paths=initial_paths) >>> >>> # initialization from a parameters file “params.py” >>> params = aimmd.Params(“params.py”) >>> params = aimmd.Params.load(“params.py”) # equivalent >>> >>> # override some parameters from file >>> params = aimmd.Params(“params.py”, initial_paths=initial_paths, nbins=5)

Notes

The concrete API (attributes and helper methods) is defined across the Params mixins in aimmd.params. See the documented Params submodules for attribute-level semantics.

Initialize a Params instance.

This initializer supports two usage patterns:

  1. Load from file (preferred for reproducibility):

    • If args[0] is a valid path to an existing file, it is treated as

a params file and loaded via Params.load(…).

  1. No file provided:

    • If no valid file is provided, defaults are loaded from ‘params.py’

(if present), otherwise initialization proceeds using defaults and provided keyword arguments.

Parameters:

*args – If args[0] is a path-like string and exists, it is used as the

params filename and removed from args before passing on. Remaining positional args are interpreted by Params.load as positional overrides in dataclass field order. :param **kwargs: Field overrides applied with higher priority than file values.

Special behavior:

  • If filename is in kwargs, it is treated as a params file

(handled upstream in ParamsIO.load).

Returns:

The initialized object (assigned in-place).

Return type:

aimmd.params.Params

Notes

This function populates self.__dict__ directly from a loaded instance’s __dict__ so the dataclass fields appear initialized in the correct order (and so that post-init checks can run coherently).

always_select_inside_the_bins: bool = False
at_least_one_transition_in_pool: bool = False
atom_types: List = None
bias_function: Callable = None
bias_reactive_threshold: float = 0.5
bias_reactive_threshold_of(system_id=None)

Reactive-bias threshold for a given system (see bias_reactive_threshold); a scalar is broadcast to all systems.

bias_source: str = 'reader'
chain_type: str = 'rfps'
check_engine(topology='', deffnm='.check_engine', timeout=10)

Run a minimal engine self-test in params.parent.

Parameters:

topology – Topology/structure file used to obtain a starting frame.

If empty, attempts to use:

  • self._universe first,

  • then the first frame of the first initial path.

Parameters:
  • deffnm (str, optional) – Output basename (no extension).

  • timeout (float, optional) – Walltime (seconds) used for initialization and execution.

Returns:

0 on success, 1 on failure.

Return type:

int

Notes

This method:

  • switches to params.parent,

  • removes old deffnm* files,

  • initializes and runs a short segment,

  • verifies that the expected trajectory file exists and has non-zero size.

check_if_initialized(*deffnms)

Check whether required engine files exist for each deffnm.

Parameters:

*deffnms (str) – One or more simulation basenames.

Returns:

True if all required files exist and are non-empty.

Return type:

bool

Notes

  • For GROMACS: checks <deffnm>.tpr.

  • For toy engine: checks <deffnm><trajectory_extension> or <deffnm>.part0000<trajectory_extension>.

property compute_descriptors_args

Arguments for computing descriptors on a Path/PathEnsemble.

Returns:

If descriptors_function is configured, returns:

(descriptors_function, ‘descriptors’). Otherwise returns None. :rtype: tuple or None

Examples

>>> if params.compute_descriptors_args is not None:
...     path.compute(*params.compute_descriptors_args)
property compute_states_args

Arguments for computing states on a Path/PathEnsemble.

Returns:

(states_function, ‘states’)

Return type:

tuple

Examples

>>> path.compute(*params.compute_states_args)
property compute_values_args

Arguments for computing values on a Path/PathEnsemble.

Returns:

(values_function, 'values', source) where source is

'coordinates' if descriptors are disabled and 'descriptors' if descriptors are enabled. :rtype: tuple

Examples

>>> path.compute(*params.compute_values_args)

Notes

This convention matches Path.compute(function, name, source=…) semantics used throughout AIMMD.

copy()

Shallow-copy this Params object. Only force reload of inital paths.

Returns:

A new Params instance with a copied __dict__ (shallow copy).

Return type:

aimmd.params.Params

Notes

This does not deep-copy mutable objects referenced in __dict__.

cutoff_max: float = 20.0
cutoff_min: float = 0.5
density_adjustment: Number = inf
descriptor_transform: Callable = None
descriptors_function: Callable = None
engine: str = 'gromacs'
extra_free_frames: int = 0
static fit(params, pathensemble, verbose=True, worker=None)

Default training hook used when Params.fit is not set.

AIMMD keeps the full run configuration in Params. This includes the neural-network model to be trained and all settings needed to run the simulation (system, engines, sampling, I/O).

If Params does not specify a custom training callable, AIMMD calls this function. It is a thin wrapper that forwards its arguments to fit() unchanged, so the training uses all default hyperparameters of fit() (e.g. learning rate, batch size, number of epochs, binning and augmentation settings) unless a custom training function is provided.

Parameters:
  • params (aimmd.Params) – Complete AIMMD configuration, including the network model.

  • pathensemble – The trajectories generated so far; used by fit() to assemble the

training set. :type pathensemble: PathEnsemble :param verbose: Controls training log/progress output. If True (default), fit() may print progress information; if False, it should run quietly. :type verbose: bool, optional :param worker: Worker context for this run. If provided, fit() may use it for coordinating with other workers. If None (default), fit() runs without a worker context. :type worker: aimmd.Worker or None, optional

Returns:

Exactly the return value of fit().

Return type:

tuple

Notes

This is a thin wrapper around fit(), which trains or updates the AIMMD model from the current PathEnsemble.

free_overriding_attempts: int = 100
free_overriding_recovery_rate: float = 0.05
free_overriding_states: str = ''
free_trajectories(directory, target_state=None)

Collect (unsplit) free trajectories from an AIMMD run directory.

Parameters:

directory – Base run directory containing free{target_state}/traj??????.part????

trajectory files. :type directory: str :param target_state: If None, load for all states in self.states. Otherwise interpreted via process_state(target_state, self.states). :type target_state: str, optional

Returns:

List of reconstructed free trajectories as Path objects.

NOT a PathEnsemble object. :rtype: list of aimmd.path.Path

Notes

  • Free trajectories are stored split into parts:

    traj??????.part????{ext}. This method groups by traj?????? index and assembles each into a Path(fnames, remove_overlapping_frames=True).

  • If indicted.log is present in free{state}/, it is parsed and used to exclude frames from trajectories by assigning _exclude_from or exclude_from (depending on code path).

gen_temperature: float = 300.0
gmx_eneconv: str = 'printf "c\nc\n" | /usr/bin/false -nobackup eneconv -settime'
gmx_grompp: str = '/usr/bin/false grompp -maxwarn 1'
gmx_mdp: str = 'run.mdp'
gmx_mdrun: str = '/usr/bin/false mdrun -v -maxh 4'
initialize_simulation(frame, *deffnm, timeout=20.0, verbose=True)

Initialize engine inputs for a simulation started from a given frame.

Parameters:

frame – Starting configuration.

If a Path is provided, the last frame is used as the shooting frame, while preceding frames are written as .part0000* to preserve history in toy mode or for bookkeeping in GROMACS initialization. :type frame: MDAnalysis Timestep-like or aimmd.path.Path :param *deffnm: One or more output basenames (without extension). For each deffnm, initialization is performed separately. The method flips velocities sign each time (useful for forward/backward branches). :type *deffnm: str :param timeout: Walltime (seconds) used for the grompp call via execute_command. :type timeout: float, optional :param verbose: If True, print grompp output to stdout. :type verbose: bool, optional

Return type:

None

Raises:

TypeError – If no deffnm is provided, if toy output cannot be read back, etc.

Notes

  • Velocity generation:

    • if params.gen_temperature < 0 and velocities are present: reuse them

(with a sign flip for the first branch).

  • else randomize from params.masses if available.

  • else set zeros (with a warning).

  • For GROMACS:

    • writes a temporary .trr file to pass velocities to grompp via -t.

    • uses params.topology for both -r and -c.

classmethod load(filename='params.py', *args, **kwargs)

Load parameters from a Python params file.

This method can be called either as:

  • Params.load(filename, …) (class call), or

  • params.load(filename, …) (instance call).

Behavior

  • If filename is a path to a file:

  • switch to its folder,

  • execute it in a fresh ModuleType namespace,

  • populate known dataclass fields from module globals,

  • apply explicit overrides from args/kwargs,

  • validate all fields together with _process_and_check,

  • optionally save a canonical params file in the same folder.

  • If filename is falsy/None:

  • do not execute a file; treat the current working directory as the

params folder and only apply overrides.

Parameters:

filename – Params file path. If None, no file is executed and only overrides

are applied to defaults/current values. :type filename: str or None, optional :param *args: Positional overrides mapped to dataclass fields in declared order. (Only fields present in Params.__dataclass_fields__ are used.) :param **kwargs: Keyword overrides for dataclass fields.

Special keys:

save : bool, optional If False, do not call self.save() after successful load.

Returns:

Params instance (updated in place or freshly created).

Return type:

aimmd.params.Params

Raises:

TypeError – If the file cannot be found, invalid fields are provided, required fields are missing, or validation fails.

Notes

This function temporarily mutates:

  • current working directory,

  • sys.path,

  • sys.modules.

It attempts to restore them in finally / except blocks.

load_bins_and_densities(directory, timeout=20.0, raise_if_failure=True)

Load bin boundaries and densities from .npy files.

Parameters:
  • directory (str) – Directory containing bins{states}.npy and densities{states}.npy.

  • timeout (float, optional) – Maximum wait time (seconds) for files to appear and be readable.

  • raise_if_failure (bool, optional) – If True, raise after timeout; otherwise warn and return empty arrays.

Returns:

bins : 1D array of bin boundaries (length nbins+1 typically)

densities : 1D array of per-bin densities (length len(bins)-1) :rtype: (numpy.ndarray, numpy.ndarray)

Raises:

Exception – Any final exception after timeout if raise_if_failure is True.

Notes

This function validates:

  • bins and densities are both 1D,

  • len(densities) == len(bins) - 1.

lorentzian: float = inf
property masses

Per-atom masses inferred from the cached Universe.

Returns:

1D array of length n_atoms containing masses if self._universe

is available, otherwise None. :rtype: numpy.ndarray or None

Notes

Masses are guessed via guess_masses(self._universe.atoms). The exact units depend on the conventions used by guess_masses and the topology format.

masses_of(system_id=None)

Per-atom masses for a given system (see masses/universe_of).

max_length: int = 50000
minimize_energy(trajectory, out, em_mdp=None)

Energy-minimize each frame of a trajectory using GROMACS.

Parameters:
  • trajectory (str or aimmd.path.Path or trajectory-like) – Input trajectory containing frames to minimize. Converted to Path.

  • out (str or pathlib.Path) – Output filename for the minimized trajectory.

  • em_mdp (str, optional) – Override .mdp file used for minimization. If None, uses EM_MDP.

Return type:

None

Raises:

TypeError – If engine is not GROMACS, or if output would overwrite an input file.

Notes

Implementation strategy:

  • Load positions into memory.

  • For each frame:

    • initialize a temporary run (initialize_simulation),

    • run the minimization (run_simulation),

    • read minimized coordinates from <temp>.trr,

    • clean up temp files.

  • Finally, write the minimized trajectory to out.

multi_system: bool = False
multi_system_share_network: bool = False
name: str = 'AIMMD'
nbins: int = 10
network: _install_doc_stubs.<locals>.Module = <aimmd.network.utils.PlaceholderNetwork object>
network_batch_size: int = 4096
network_save_interval: int = 10
property parent

Parent folder associated with this Params instance.

Returns:

If self.path is a file, returns self.path.parent.

If self.path is a directory, returns self.path. :rtype: pathlib.Path

Notes

AIMMD uses parent as the base directory for engine operations and for saving/loading run artifacts.

path: Path = PosixPath('.')
pathensemble(directory, shot_chains=[])

Assemble a complete PathEnsemble from shot chains + free trajectories.

Parameters:
  • directory (str) – AIMMD run directory.

  • shot_chains (list, optional) – Previously loaded shot chains (used for incremental update).

Returns:

Full ensemble with the correct state mapping and categories.

Return type:

aimmd.pathensemble.PathEnsemble

Notes

This delegates to assemble_pathensemble, which expects:

  • list of shot chains (PathEnsembles),

  • list of free trajectories (Paths).

property pipeline

Preferred compute pipeline under the current configuration.

Returns:

Ordered tuple of compute-argument tuples, suitable for driving

repeated Path.compute(…) and PathEnsemble.compute(…) calls. If descriptors are disabled, the tuple is (compute_states_args, compute_values_args). If descriptors are enabled, it is (compute_descriptors_args, compute_states_args, compute_values_args). :rtype: tuple

Examples

>>> for args in params.pipeline:
...     path.compute(*args)

Notes

Descriptors are computed first (when enabled) so that values can be computed from cached descriptors rather than raw coordinates.

record_bias: bool = False
rescale_committor: bool = False
restart_free_simulations_with_transitions: str = ''
retry_with_state_definition_glitches: bool = False
run_simulation(deffnm, backup=False, cpt=0.1, noappend=False, **kwargs)

Run a simulation segment for the configured engine.

Parameters:
  • deffnm (str) – Basename used by the engine (GROMACS -deffnm).

  • backup (bool, optional) – If False, add -nobackup for GROMACS output control.

  • cpt (float, optional) – If non-zero, enable checkpointing (-cpi and -cpt) for GROMACS.

  • noappend (bool, optional) – If True, add -noappend for GROMACS to avoid appending to existing files.

  • **kwargs – Forwarded to execute_command (e.g., stop_condition, walltime, log_file).

Returns:

  • For GROMACS: the exit code returned by execute_command.

  • For toy engine: returns None (ToyEngine performs its own loop).

Return type:

int or None

Notes

  • For toy engine, ToyEngine(…) is called with **kwargs to allow stop-condition / walltime semantics in Python.

save(path=None, seek_existing_file=True)

Save params to a Python file and update params.path.

Parameters:

path – Destination filename. If None, uses self.path. If self.path is a

directory, defaults to <dir>/params.py. :type path: str or pathlib.Path, optional :param seek_existing_file: If True, attempt to find an existing .py file in the same folder whose trailing body matches self.__str__() output; if found, reuse it instead of writing a new file. :type seek_existing_file: bool, optional

Returns:

Relative path (from current working directory) to the params file.

Return type:

str

Raises:

TypeError – If attempting to save outside the original Params.parent folder.

Notes

The saved file contains:

  • imports for modules present in __main__,

  • the verbose parameters body produced by Params.__str__, including callable bodies/imports and per-field descriptions.

selection_pool_size: int = 10
shared_density_adjustment: bool = False
shot_chains(directory, target_state=None, k=None, old=PathEnsemble with 0 paths)

Convenience wrapper for shot_paths(…, prefix=’chain’, …).

shot_paths(directory, prefix='chain', target_state=None, k=None, old=PathEnsemble with 0 paths)

Load shot paths (shooting trajectories) from a run directory.

Parameters:
  • directory (str) – Base run directory containing {prefix}{state}{k}/path??????{ext}.

  • prefix (str, optional) – Folder prefix (e.g., ‘chain’, ‘sweep’, etc.).

  • target_state – If None, load for all states in self.states.

Otherwise interpreted via process_state(target_state, self.states). :type target_state: str, optional :param k: Shooting chain index/indices to load.

  • int/str: load exactly that chain.

  • iterable: load those chains.

  • None: scan all matching folders and load all chains found.

Parameters:

old (PathEnsemble, optional) – Previously loaded data used for incremental updates.

Returns:

For a specific (target_state, k) returns a PathEnsemble.

For a broader query returns a list indexed by k and/or state. :rtype: aimmd.pathensemble.PathEnsemble or list

Notes

  • This function tries to reuse already-loaded paths and only append new ones (except the last path which may still be changing on disk).

  • For TPS (self.chain_type == ‘tps’) it may load tps_weights.npy and assign weights to newly loaded paths, zeroing weights for non-transitions.

slurm_header: str = '#SBATCH --mail-type=FAIL'
property sorted_states

Deterministic ordering of endpoint state labels for file naming.

Returns:

Either self.states or self.states[::-1], chosen so that the

first and last characters are ordered alphabetically. :rtype: str

Notes

This provides stable artifact names such as:

  • network{sorted_states}.h5

  • bins{sorted_states}.npy

independent of whether you conceptually describe a transition as A→B or B→A.

states: str = 'ARB'
subsample_caps: dict = None
subsample_caps_of(system_id=None)

Value-pass subsampling caps for a given system (see subsample_caps); a single dict is broadcast to all systems.

terminal_bin_extension: str = ''
topology: str = 'run.gro'
toy_mdrun: Callable = None
toy_slowdown: float = 0.01
trainers_share_gpu: bool = True
trajectory_extension: str = '.xtc'
trajectory_update_batch_size: int = 1000
property universe

Cached MDAnalysis Universe derived from topology.

Returns:

Universe built when setting topology, or None if topology

could not be loaded. :rtype: MDAnalysis.Universe or None

universe_of(system_id=None)

MDAnalysis Universe for a given system.

Multi-system runs cache one Universe per system in _universes (keyed by system_id); single-system runs use the single _universe. With system_id=None this returns the single-system universe (backward compatible).

update(*args, **kwargs)

Update an existing Params object without executing a file.

Parameters:
  • *args – Same override semantics as load, but filename is forced to None.

  • **kwargs – Same override semantics as load, but filename is forced to None.

Returns:

Updated instance.

Return type:

aimmd.params.Params

update_network(path, timeout=20.0, raise_if_failure=True)

Load a network checkpoint from disk into self.network.

Parameters:

path – If path to file: path containing the checkpoint file.

If path to directory: directory containing the network{params.states}.h5 checkpoint file. :type path: str :param timeout: Maximum wait time (seconds) for the checkpoint to become readable. :type timeout: float, optional :param raise_if_failure: If True, re-raise the final exception after timeout; otherwise print a warning and return. :type raise_if_failure: bool, optional

Return type:

None

Notes

The checkpoint name depends on self.sorted_states (ensures stable naming independent of A/B ordering).

values_function: Callable = None
states_function: Callable
initial_paths: List
free_overriding_bins: List
reweight_parameters: dict
system_ids: List