pyretis.engines package

Definition of engines.

This package defines engines for PyRETIS. The engines are responsible for carrying out dynamics for a system. This can in principle both be molecular dynamics or Monte Carlo dynamics. Typically, with RETIS, this will be molecular dynamics in some form in order to propagate the equations of motion and obtain new trajectories.

Package structure

Modules

cp2k.py (pyretis.engines.cp2k)

Defines an engine for use with CP2K.

engine.py (pyretis.engines.engine)

Defines the base engine class.

external.py (pyretis.engines.external)

Defines the interface for external engines.

gromacs.py (pyretis.engines.gromacs)

Defines the canonical (streaming) engine for use with GROMACS. It runs GROMACS once per propagated segment and reads the frames on the fly.

gromacs_steps.py (pyretis.engines.gromacs_steps)

Defines the relaunch implementation of the GROMACS engine, which starts and stops the GROMACS executable once per order-parameter point. Reached as class = "gromacs_steps".

internal.py (pyretis.engines.internal)

Defines internal PyRETIS engines.

lammps.py (pyretis.engines.lammps)

Defines the canonical (streaming) engine for use with LAMMPS.

lammps_steps.py (pyretis.engines.lammps_steps)

Defines the relaunch implementation of the LAMMPS engine. Reached as class = "lammps_steps".

openmm.py (pyretis.engines.openmm)

Defines an engine for use with OpenMM.

Important methods defined here

engine_factory (engine_factory())

A method to create engines from settings.

get_engine_class (get_engine_class())

Return the engine class matching a name.

resolve_engine_class (resolve_engine_class())

Resolve the engine class from full settings.

get_default_units (get_default_units())

Return the default unit system for an engine.

The engine classes re-exported here (e.g. MDEngine, ExternalMDEngine, GromacsEngine) are documented on their respective module pages listed below. The package itself also provides the following engine-selection helpers:

pyretis.engines.engine_factory(settings)

Create an engine according to the given settings.

This function is included as a convenient way of setting up and selecting an engine. It will return the created engine.

Parameters:

settings (dict) – This defines how we set up and select the engine.

Returns:

out (object like EngineBase) – The object representing the engine to use in a simulation.

pyretis.engines.get_engine_class(name)

Return the class matching a given engine name.

pyretis.engines.resolve_engine_class(settings)

Resolve an engine class from the given settings.

pyretis.engines.get_default_units(settings)

Return the default unit system for the selected engine.

List of submodules

pyretis.engines.cp2k module

A continuous CP2K external MD integrator interface.

This module defines the canonical CP2K engine, selected by class = "cp2k". CP2K is run as a single persistent process for a whole propagation segment and its position/velocity trajectories are read on-the-fly, so the path is filled incrementally and CP2K is terminated as soon as a stopping interface is crossed. The SCF of each segment starts from CP2K’s initial guess: no wavefunction is carried from one segment to another (see cp2k_cold_start()).

The relaunch (start-and-stop / restart-chain) engine, which advances CP2K one order-parameter point at a time, is selected by class = "cp2k_steps" (pyretis.engines.cp2k_steps).

Important classes defined here

CP2KEngine (CP2KEngine)

The continuous CP2K engine.

class pyretis.engines.cp2k.CP2KEngine(cp2k: str, input_path: str, timestep: float, subcycles: int, extra_files: list[str] | None = None, exe_path: str | Path | None = None, sleep: float = 0.1)

Bases: CP2KEngineSteps

Streaming CP2K engine.

This engine shares its configuration and input convention with the relaunch engine CP2KEngineSteps (same [engine] settings, same initial.xyz / cp2k.inp / extra_files input directory) so a user can switch class = cp2k <-> class = cp2k_steps and have it just work – as for the two GROMACS and LAMMPS engines. The two engines build the CP2K run from the same input template; they differ only in how the trajectory is consumed: this engine runs CP2K as a single persistent process and reads its position/velocity trajectories on the fly, terminating CP2K early when an interface is crossed. The SCF of each segment starts from CP2K’s initial guess, whatever segments ran before it. An MD run (an md, md-nve or md-flux task) is the MD run of the relaunch engine (CP2KEngineSteps.integrate()): one CP2K run of subcycles MD steps from each stored step to the next.

Variables:
  • cp2k – The command for executing CP2K.

  • input_path – The directory holding the input files the engine reads.

  • timestep – The time step used in the CP2K MD simulation.

  • subcycles – The number of steps each CP2K run is composed of.

  • extra_files – List of extra files which may be required to run CP2K.

  • sleep – A time in seconds, for waiting for files to be ready.

__init__(cp2k: str, input_path: str, timestep: float, subcycles: int, extra_files: list[str] | None = None, exe_path: str | Path | None = None, sleep: float = 0.1)

Set up the CP2K MD engine.

Parameters:
  • cp2k (str) – The CP2K executable.

  • input_path (str) – The path to the directory containing CP2K input files.

  • timestep (float) – The time step used in the CP2K simulation.

  • subcycles (int) – The number of steps each CP2K run is composed of.

  • extra_files (list, optional) – List of extra files which may be required to run CP2K.

  • exe_path (str or Path, optional) – The run directory: a relative input_path is resolved against it. None resolves input_path against the working directory as the engine is created.

  • sleep (float) – A time in seconds, for waiting for files to be ready.

static _leg_project(name: str) → str

Return the name of the CP2K project of a leg.

The CP2K run of a leg writes its output (OUTPUT_FILES) under the name of its project, and _propagate_from() reads the frames and the energies of the leg from that output. The name of a leg comes from a counter of the PyRETIS process (ExternalMDEngine.propagate()), which starts at zero in every process, so a run started again in the directory of a stopped run runs legs of the names of the stopped run. CP2K runs in a session of its own. When a run stops on Ctrl+C or SIGTERM, the worker pool (aiorunner.close()) terminates the CP2K of each leg its workers run (process_sessions). A stop, or a SIGKILL, while the main process runs a leg (a kick other than the parallel kick) leaves its CP2K running: it then writes its output until its steps are done, and creates its output files again when they are removed. A SIGKILL of the main process leaves the workers running, and each of them goes on with its leg as usual. The project name is the name of the leg, the id of the process that runs it and a tag of 8 hexadecimal digits drawn for the leg from the random source of the operating system (secrets.token_hex()). The id alone does not tell the processes apart: the system gives the id of a process that has ended to a new process, each container with a process namespace of its own counts ids from 1, and each host that shares the directory counts its own ids. With the tag, the leg reads the output of its own CP2K run, also while a CP2K run of a stopped process with the same id still runs in the directory: two legs of the same name and id get the same tag with a chance of 1 in 2**32. The tag names files only; it draws on no random generator of the simulation and changes no result. The project names the output while CP2K runs: when the run has ended, the output of the project that is left takes the name of the leg (_rename_leg_output()).

Parameters:

name (str) – The name of the leg.

Returns:

str – The name of the CP2K project of the leg, <name>-<process id>-<tag>.

_propagate_from(name: str, path: InfPath, system: System, ens_set: dict[str, Any], msg_file: FileIO, reverse: bool = False) → tuple[bool, str]

Propagate with CP2K from the current system configuration.

Here, we assume that this method is called after the propagate() has been called in the parent. The parent is then responsible for reversing the velocities and also for setting the initial state of the system.

Note that the on-the-fly reading of data applies only to simulations of a fixed box (NVE, NVT), as no box information is read from CP2K.

The frames of the leg are written to its own trajectory, <name>.<ext> in the directory the engine runs in, and frame i of the leg is frame i of that file. The leg reads its frames and energies from the output files of the CP2K run it starts, under a project name of its own (_leg_project()), so it reads no output of a CP2K run that an earlier process started in the directory and that still runs. Before CP2K runs, a trajectory of the leg’s name that an earlier run left in the directory is removed, and so is CP2K output of the leg’s project, should a file of that name exist (_remove_leg_files()). When the CP2K run has ended, after its last step, stopped at an interface or with an error, the output of the project that is left takes the name of the leg (_rename_leg_output()), beside the trajectory of the leg; a CP2K run that still runs after an error of PyRETIS writes on under its project.

Parameters:
  • name (str) – A name to use for the trajectory we are generating.

  • path (InfPath) – This is the path we use to fill in phase-space points.

  • system (System) – The phase point to use as a starting point.

  • ens_set (dict) – Settings for the ensembles.

  • msg_file (FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.

  • reverse (bool) – If True, the system will be propagated backward in time.

Returns:

tuple – A tuple containing:

  • True if we generated an acceptable path, False, otherwise.

  • A text description of the status of the propagation. Can be used to interpret the reason for the path not being acceptable.

Raises:
static _read_configuration(filename: str | Path) → tuple[ndarray, ndarray, ndarray | None, list[str] | None]

Read a CP2K output configuration from a file.

This streaming engine returns the box as the THIRD element (xyz, vel, box, names). The relaunch CP2KEngineSteps._read_configuration() returns box first; calculate_order() and _propagate_from() rely on the box-third order, so this cannot be inherited. The methods inherited from the relaunch engine read a configuration box first, with _read_configuration_box_first().

Parameters:

filename (str or Path) – Path to the file to read.

Returns:

tuple –

A tuple containing:
  • The positions.

  • The velocities.

  • The box dimensions if we manage to read it.

  • The atom names found in the file.

_read_configuration_box_first(filename: str | Path) → tuple[ndarray | None, ndarray, ndarray, list[str] | None]

Read a configuration, with the box as its first item.

The methods this engine inherits from CP2KEngineSteps, its MD run (CP2KEngineSteps.integrate()) among them, unpack a configuration box first, as the relaunch engine reads it; this engine’s _read_configuration() returns the box third.

Parameters:

filename (str or Path) – Path to the file to read.

Returns:

tuple –

A tuple containing:
  • The box dimensions if we manage to read it.

  • The positions.

  • The velocities.

  • The atom names found in the file.

static _remove_leg_files(traj_file: str, out_files: dict[str, str]) → None

Remove the files of a leg that an earlier run left.

A leg appends its frames to its trajectory, traj_file, and names them from 0, and _propagate_from() reads the position and velocity output of the CP2K project of the leg as soon as it exists. The name of a leg comes from a counter of the PyRETIS process (ExternalMDEngine.propagate()), which starts at zero in every process, so the directory a leg runs in can hold a trajectory of the leg’s name that an earlier process left there: an initiation stopped by a signal or an EXIT file, and started again in the same directory, runs its legs under the names of the stopped one. Left in place, its frames would be named as frames of the leg. The project of the leg is a name of its own (_leg_project()), which no earlier run gave to its CP2K output, unless with a chance of 1 in 2**32; output files of the project are removed too, should they exist. The files are removed before CP2K runs, so the leg starts a trajectory of its own and CP2K starts the output files of the project. A CP2K run left running by a stopped process writes the output of its own project, which is not removed.

Parameters:
  • traj_file (str) – The trajectory of the leg.

  • out_files (dict of str) – The output files of the CP2K project of the leg, as OUTPUT_FILES names them.

Raises:

OSError – If one of the files cannot be removed: the leg would read the frames of another run.

static _rename_leg_output(exe_dir: str, project: str, name: str) → None

Give the output of the CP2K run of a leg the name of the leg.

While the CP2K run of a leg runs, it writes its output under the project of the leg, <leg>-<pid>-<tag> (_leg_project()). When it has ended, _propagate_from() removes the output it read (OUTPUT_FILES), and the files of the project that are left, <leg>-<pid>-<tag><suffix>, are renamed here to <leg><suffix>: the forces, the cell or the restart history that the template prints, for example. The files kept with the trajectory of a path ([output] keep_traj_fnames) are named <leg><suffix>, beside the trajectory of the leg, <leg>.<ext>. A file of the leg’s name that is there already, left by an earlier leg of that name, is replaced, as CP2K replaces its output files when a run of a project starts.

Parameters:
  • exe_dir (str) – The directory the CP2K run of the leg ran in.

  • project (str) – The CP2K project of the leg.

  • name (str) – The name of the leg.

Raises:

OSError – If a file cannot be renamed.

_reverse_velocities(filename: str, outfile: str) → None

Reverse velocity in a given snapshot.

This override unpacks this engine’s box-third _read_configuration() (xyz, vel, box, names); the relaunch base unpacks the box first, through _read_configuration_box_first().

Parameters:
  • filename (str) – Path to the file containing the configuration to reverse velocities in.

  • outfile (str) – Path to file for storing the configuration with reversed velocities.

calculate_order(system, xyz=None, vel=None, box=None)

Calculate the order parameter of the current system.

Overrides ExternalMDEngine.calculate_order because this engine’s _read_configuration() returns the box as the third element (xyz, vel, box, names), whereas that method reads it as box-first. A frame that records no cell is evaluated in the cell of the input template (CP2KEngineSteps.frame_cell()), as the relaunch engine evaluates it.

classmethod cp2k_template(engine_settings)

Return the name of the CP2K input the engine reads.

This engine reads cp2k.inp whatever the engine section sets.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (string) – cp2k.inp.

dump_phasepoint(phasepoint, deffnm='conf')

Dump the current configuration from a system object to a file.

This override points the phase point at frame index 0 of the dumped file via set_pos; the ExternalMDEngine method sets config = (pos_file, None).

engine_type = 'external'
modify_velocities(system: System, vel_settings: dict[str, Any], rgen) → tuple[float, float]

Modify the velocities of all particles.

Parameters:
  • system (System) – The system whose particle velocities are to be modified.

  • vel_settings (dict) – A dict containing the key 'zero_momentum' (boolean): if true we reset the linear momentum to zero after generating velocities internally. A missing key means False, the [tis] default. This engine draws the velocities of aimless shooting and leaves their energy as drawn, so a soft perturbation (a sigma_v that is not negative) and a positive rescale are refused before the draw.

Returns:

tuple – A tuple containing:

  • dek: The change in kinetic energy as a result of the velocity modification.

  • kin_new: The new kinetic energy of the system.

Raises:

Notes

The velocity components that the FIXED_ATOMS sections of the CP2K input fix are set to zero in the velocities of the shooting point and in the drawn ones, before the momentum is set to zero, so the kinetic energies are those of the velocities that CP2K propagates. With zero_momentum, the momentum of the components that move is set to zero (reset_free_momentum()). The constraints that CP2K imposes in the first time step (cp2k_constraints()) are left to CP2K.

needs_order = True
path_sampling_warnings() → list[str]

Return why a path sampling with this engine is not exact.

The schemes of the CP2K input template that a path-sampling run integrates with and warns about (cp2k_path_sampling_warnings()), for an engine that runs CP2K once for each piece of trajectory.

Returns:

list of strings – One warning per scheme, naming it, why the path sampling is not exact, and what to use instead; empty for an input without such a scheme.

set_mdrun(md_items: dict[str, Any]) → None

Set the execute directory of the move.

Overrides EngineBase.set_mdrun(); the infinite-swapping scheduler (see core.moves) calls this before each move to point the engine at the scratch directory of the move. CP2K requires exe_dir to be present, so it is read as a required key: md_items without one raises KeyError.

step(system, name)

Raise NotImplementedError: the streaming engine runs no single step.

CP2K is propagated via _propagate_from(), and a kick of this engine runs through ExternalMDEngine.propagate() (supports_step_kick = False). This override refuses the single CP2K run of CP2KEngineSteps.step().

supports_step_kick = False
pyretis.engines.cp2k.write_for_run_vel(infile: str | Path, outfile: str | Path, timestep: float, nsteps: int, subcycles: int, posfile: str, vel: ndarray, name: str = 'md_step', print_freq: int | None = None, seeds: dict[str, int | None] | None = None) → None

Create input file to perform n steps.

Note, a single step actually consists of a number of subcycles. But from PyRETIS’ point of view, this is a single step. The run starts from the positions of the xyz file posfile (cp2k_frame_update()) and from the velocities vel, and its SCF from CP2K’s initial guess (cp2k_cold_start()).

Parameters:
  • infile (str or Path) – Path to the input template to use.

  • outfile (str or Path) – Path to the input file to create.

  • timestep (float) – The time step to use for the simulation.

  • nsteps (int) – The number of PyRETIS steps to perform.

  • subcycles (int) – The number of sub-cycles to perform.

  • posfile (str) – The name of the xyz file to read positions from, in the folder of outfile.

  • vel (np.ndarray) – The velocities to set in the input.

  • name (str) – A name for the CP2K project.

  • print_freq (int, optional) – How often we should print to the trajectory file.

  • seeds (dict, optional) – The seeds of the run, as cp2k_run_seeds() returns them, written by add_cp2k_seeds(). None leaves the random numbers as the template sets them.

Raises:

pyretis.engines.cp2k_steps module

A CP2K external MD integrator interface (relaunch / restart-chain).

This module defines the relaunch CP2K engine, selected by class = "cp2k_steps". It advances CP2K one order-parameter point at a time, relaunching the executable for each step and chaining the run through previous.restart / previous.wfn files (the slower, start-and-stop implementation; the canonical continuous engine, which runs CP2K as a single persistent process and reads its trajectory on-the-fly, lives in pyretis.engines.cp2k).

Important classes defined here

CP2KEngineSteps (CP2KEngineSteps)

A class responsible for interfacing CP2K via relaunching.

pyretis.engines.cp2k_steps.COLD_START_WFN = 'doesnotexist.wfn'

The wavefunction file that the first CP2K run of a leg, of a kick step and of an md task names (WFN_RESTART_FILE_NAME), in place of a wavefunction file the template names. No file of this name is in the directory CP2K runs in (cp2k_cold_start() refuses one), so CP2K starts the SCF from its initial guess: the guess the template’s SCF_GUESS sets, and the ATOMIC guess for SCF_GUESS RESTART, for which CP2K warns that the file does not exist. No wavefunction is carried from one run to another; the relaunches of a leg or an md task continue its own trajectory from previous.wfn (write_for_continue()).

class pyretis.engines.cp2k_steps.CP2KEngineSteps(cp2k, input_path, timestep, subcycles, extra_files=None, exe_path='/home/enrico/cache/twoway-retis/wt2/docs', seed=0, conf='initial.xyz', template='cp2k.inp', velocity_generation='maxwell')

Bases: ExternalMDEngine

A class for interfacing CP2K.

This class defines the interface to CP2K.

Variables:
  • cp2k (string) – The command for executing CP2K.

  • input_path (string) – The directory where the input files are stored.

  • timestep (float) – The time step used in the CP2K MD simulation.

  • subcycles (integer) – The number of steps each CP2K run is composed of.

  • rgen (object like RandomGenerator) – The random generator that the seeds of each CP2K run are drawn on (cp2k_run_seeds()). The infinite-swapping scheduler replaces it with the random generator of each move.

  • extra_files (list) – List of extra files which may be required to run CP2K.

  • temperature (float) – The temperature (K) the CP2K input states, MOTION/MD TEMPERATURE (read_cp2k_temperatures()).

  • beta (float) – The inverse temperature 1 / (k_B T) in 1/hartree, with the k_B of the engine, kb.

  • engine_temperatures (object like EngineTemperatures) – The temperatures read from the CP2K input.

__init__(cp2k, input_path, timestep, subcycles, extra_files=None, exe_path='/home/enrico/cache/twoway-retis/wt2/docs', seed=0, conf='initial.xyz', template='cp2k.inp', velocity_generation='maxwell')

Set up the CP2K engine.

Parameters:
  • cp2k (string) – The CP2K executable.

  • input_path (string) – The path to where the input files are stored.

  • timestep (float) – The time step used in the CP2K simulation.

  • subcycles (integer) – The number of steps each CP2K run is composed of.

  • extra_files (list) – List of extra files which may be required to run CP2K.

  • exe_path (string, optional) – The path on which the engine is executed.

  • seed (integer, optional) – A seed for the random number generator.

  • conf (string, optional) – The default configuration file (default is ‘initial.xyz’).

  • template (string, optional) – The CP2K input template (default is ‘cp2k.inp’).

  • velocity_generation (string, optional) – How shooting velocities are drawn. "maxwell" (default) draws them in Python from a Maxwell-Boltzmann distribution via the injected random generator, using engine-level masses and the temperature of the CP2K input (so the draw does not require the system to carry masses). This mirrors the velocity_generation knob of the GROMACS/LAMMPS engines.

_ensure_velocity_setup()

Compute the engine-level masses on first use.

The masses are guessed from the initial-config atom types.

_extract_frame(traj_file, idx, out_file)

Extract a frame from a trajectory file.

This method is used by self.dump_config when we are dumping from a trajectory file. It is not used if we are dumping from a single config file.

Parameters:
  • traj_file (string) – The trajectory file to dump from.

  • idx (integer) – The frame number we look for.

  • out_file (string) – The file to dump to.

static _find_backup_files(dirname)

Return backup-files in the given directory.

static _input_folder(engine_settings)

Return the folder of the CP2K input of an engine section.

Parameters:

engine_settings (dict) – The settings of the engine section, with input_path.

Returns:

out (string) – input_path relative to exe_path, the current directory when the section sets no exe_path.

classmethod _input_template(engine_settings)

Return the CP2K input an engine section names.

The input is looked up as the engine looks it up when it is created: the file cp2k_template() names, in input_path relative to exe_path.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (string) – The path of the CP2K input.

classmethod _input_template_present(engine_settings)

Return whether an engine section names a CP2K input that is there.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (boolean) – True when the section sets input_path and that folder holds a file _input_template() can take (input_file_present()).

_prepare_shooting_point(input_file)

Create initial configuration for a shooting move.

This creates a new initial configuration with random velocities.

Velocity generation runs internally (modify_velocities()), so the engine does not call this method.

Parameters:

input_file (string) – The input configuration to generate velocities for.

Returns:

  • output_file (string) – The name of the file created.

  • energy (dict) – The energy terms read from the CP2K energy file.

_propagate_from(name, path, system, ens_set, msg_file, reverse=False)

Propagate with CP2K from the current system configuration.

Here, we assume that this method is called after the propagate() has been called in the parent. The parent is then responsible for reversing the velocities and also for setting the initial state of the system.

Parameters:
  • name (string) – A name to use for the trajectory we are generating.

  • path (object like PathBase) – This is the path we use to fill in phase-space points.

  • system (object like System) – The system to act on.

  • ens_set (dict) – It contains the simulations info:

    • interfaces : list of floats These defines the interfaces for which we will check the crossing(s).

  • msg_file (object like FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.

  • reverse (boolean, optional) – If True, the system will be propagated backward in time.

Returns:

  • success (boolean) – This is True if we generated an acceptable path.

  • status (string) – A text description of the current status of the propagation.

Raises:
static _read_configuration(filename)

Read CP2K output configuration.

This method is used when we calculate the order parameter.

Parameters:

filename (string) – The file to read the configuration from.

Returns:

  • box (numpy.array) – The box dimensions if we manage to read it.

  • xyz (numpy.array) – The positions.

  • vel (numpy.array) – The velocities.

  • names (list of strings) – The atom names found in the file.

_read_configuration_box_first(filename)

Read a configuration, with the box as its first item.

The methods of this class read a configuration with this method, which gives the items in the order of _read_configuration() of this class, the box first. The streaming engine, CP2KEngine, inherits methods of this class, its MD run (integrate()) among them, and its _read_configuration returns the box third: it overrides this method to give the box first.

Parameters:

filename (string) – The file to read the configuration from.

Returns:

  • box (numpy.array) – The box dimensions if we manage to read it.

  • xyz (numpy.array) – The positions.

  • vel (numpy.array) – The velocities.

  • names (list of strings) – The atom names found in the file.

_reverse_velocities(filename, outfile)

Reverse velocity in a given snapshot.

Parameters:
  • filename (string) – The configuration to reverse velocities in.

  • outfile (string) – The output file for storing the configuration with reversed velocities.

add_input_files(dirname)

Add required input files to a given directory.

Parameters:

dirname (string) – The full path to where we want to add the files.

property beta

Return the inverse temperature 1 / (k_B T) in 1/hartree.

classmethod cp2k_template(engine_settings)

Return the name of the CP2K input the engine reads.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (string) – The template of the section, cp2k.inp when it sets none.

default_units = 'cp2k'
frame_cell()

Return the cell for a stored frame that records none.

CP2K’s .xyz frames carry no cell; the cell is the one its input template defines.

Returns:

out (numpy.array or None) – The box read_cp2k_box() reads from the CP2K input template.

classmethod get_default_units(settings=None)

Return the default unit system for the CP2K engine.

Parameters:

settings (dict, optional) – Full simulation settings or engine settings. This argument is ignored for the CP2K engine.

Returns:

out (string) – The default unit system for the CP2K engine.

classmethod input_path_sampling_problem(engine_settings)

Return why a path-sampling run cannot use a section’s CP2K input.

The input is looked up as read_input_temperatures() looks it up, and is read as path_sampling_problem() reads it (cp2k_path_sampling_problem()).

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (string or None) – The reason, or None when a path-sampling run can integrate with the input. None for a section without an input to read (_input_template_present()): the run reports the missing input where it reads the temperature of the section (read_input_temperatures()) or creates the engine.

Raises:

ValueError – As cp2k_path_sampling_problem() raises it.

integrate(system, order_function, steps, thermo='full')

Propagate several integration steps.

This method will perform several integration steps using CP2K. It will also calculate the order parameter(s) and energy terms if requested. The first CP2K run starts its SCF from CP2K’s initial guess (cp2k_cold_start()), also when an earlier md task left its files in the directory; the relaunches continue from the wavefunction of the previous one.

Parameters:
  • system (object like System) – The system object gives the initial state for the integration.

  • order_function (object like OrderParameter or None) – An order function can be specified if we want to calculate the order parameter along with the simulation.

  • steps (integer) – The number of steps we are going to perform. Note that we do not integrate on the first step (e.g. step 0) but we do obtain the other properties. This is to output the starting configuration.

  • thermo (string, optional) – Select the thermodynamic properties we are to calculate.

Yields:

results (dict) – The results from a MD step. This contains the state of the system and order parameter(s) and energies (if calculated).

Raises:

FileExistsError – As cp2k_cold_start() raises it, before CP2K runs.

modify_velocities(system, vel_settings=None, rgen=None)

Modify the velocities of the current state.

This method will modify the velocities of a time slice.

Parameters:
  • system (object like System) – System is used here since we need access to the particle list.

  • vel_settings (dict, optional) – It contains info about the velocity settings:

    • sigma_v : numpy.array Negative values select aimless shooting. Zero or positive values set the standard deviation, one for each particle, for soft velocity perturbations.

    • zero_momentum : boolean If True, we reset the linear momentum to zero after generating. A missing key means False.

    • rescale : float In some NVE simulations, we may wish to re-scale the energy to a fixed value. If rescale is a float > 0, we will re-scale the energy (after modification of the velocities) to match the given float. The re-scale needs the potential energy of system.

  • rgen (object like RandomGenerator) – This is the random generator that will be used.

Returns:

  • dek (float) – The change in the kinetic energy.

  • kin_new (float) – The new kinetic energy.

Raises:

Notes

The velocity components that the FIXED_ATOMS sections of the CP2K input fix are set to zero in the velocities of the shooting point and in the drawn ones, before the momentum is set to zero and before the re-scale, so the kinetic energies are those of the velocities that CP2K propagates. With zero_momentum, the momentum of the components that move is set to zero (reset_free_momentum()).

path_sampling_problem()

Return why a path-sampling run cannot use this engine.

The ensemble and the thermostats of the CP2K input template (cp2k_path_sampling_problem()): a path-sampling run refuses a deterministic thermostat or barostat that carries variables from one time step to the next, one without time reversibility, an ensemble whose cell changes in time, and thermostat noise that PyRETIS cannot seed.

Returns:

out (string or None) – The reason, naming the keyword and what to use instead, or None when a path-sampling run can use the engine.

path_sampling_warnings()

Return why a path sampling with this engine is not exact.

The schemes of the CP2K input template that a path-sampling run integrates with and warns about (cp2k_path_sampling_warnings()), for an engine that runs CP2K once for each subcycles steps of a piece of trajectory.

Returns:

out (list of strings) – One warning per scheme, naming it, why the path sampling is not exact, and what to use instead; empty for an input without such a scheme.

classmethod read_input_temperatures(engine_settings)

Read the temperature of the CP2K input of an engine section.

The input is looked up as the engine looks it up when it is created: the file cp2k_template() names, in input_path relative to exe_path.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (object like EngineTemperatures) – The temperature read_cp2k_temperatures() reads.

run_cp2k(input_file, proj_name)

Run the CP2K executable.

Returns:

out (dict) – The files created by the run.

step(system, name)

Perform a single step with CP2K.

Each call is a CP2K run of its own, which starts from the positions and velocities of system with seeds drawn on the random generator of the engine, as the first run of a leg does: the state of a thermostat (the variables of a Nose-Hoover chain, the random number streams) starts anew at each call. The kick of an initiation (ExternalMDEngine.kick_across_middle()) draws all the velocities before each call.

Parameters:
  • system (object like System) – The system we are integrating.

  • name (string) – To name the output files from the CP2K step.

Returns:

out (string) – The name of the output configuration, obtained after completing the step.

Raises:
temperature_keys = 'MOTION/MD TEMPERATURE of the CP2K input'
temperature_source = 'input'
unmarked_section_temperature = True
unmarked_system_temperature = True
pyretis.engines.cp2k_steps.CP2K_ANNEALING_KEYWORDS = ('ANNEALING', 'ANNEALING_CELL')

The keywords of MOTION%MD that scale the velocities of the particles (ANNEALING) or of the cell (ANNEALING_CELL) by their value at every time step. The value 1, the default, scales nothing.

pyretis.engines.cp2k_steps.CP2K_BAROSTAT_ENSEMBLES = ('NPT_I', 'NPT_IA', 'NPT_F', 'NPE_I', 'NPE_F')

The values of MOTION%MD%ENSEMBLE with a barostat, whose cell CP2K moves.

pyretis.engines.cp2k_steps.CP2K_BAROSTAT_REASON = 'a barostat, whose box momentum CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store'

The reason a path-sampling run refuses an ensemble with a barostat.

pyretis.engines.cp2k_steps.CP2K_BAROSTAT_THERMOSTAT = 'MOTION->MD->BAROSTAT->THERMOSTAT'

The thermostat section of the barostat, whose CSVR stream PyRETIS seeds.

pyretis.engines.cp2k_steps.CP2K_CELL = 'FORCE_EVAL->SUBSYS->CELL'

The cell section of a CP2K input, whose PERIODIC keyword (XYZ, the CP2K default, when it is absent) gives the directions in which the cell is periodic.

pyretis.engines.cp2k_steps.CP2K_COORD = 'FORCE_EVAL->SUBSYS->COORD'

The section of a CP2K input that gives the names and the positions of the atoms.

pyretis.engines.cp2k_steps.CP2K_COORD_FILE_KEYWORDS = (('FORCE_EVAL->SUBSYS->TOPOLOGY', 'COORD_FILE_NAME'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'COORD_FILE'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'COORD_FILE_FORMAT'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'COORDINATE'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'NUMBER_OF_ATOMS'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'NATOMS'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'NATOM'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'USE_G96_VELOCITY'))

The keywords of FORCE_EVAL%SUBSYS%TOPOLOGY that read the system from a coordinate file, with the aliases of the CP2K input schema, in the form of the remove_keywords argument of update_cp2k_input: the name and the format of the file, the number of atoms of a file in the CP2K format and the velocities of a G96 file.

pyretis.engines.cp2k_steps.CP2K_COORD_FORMAT_KEYWORDS = ('COORD_FILE_FORMAT', 'COORDINATE')

The names of the COORD_FILE_FORMAT keyword of FORCE_EVAL%SUBSYS%TOPOLOGY in the CP2K input schema.

pyretis.engines.cp2k_steps.CP2K_COORD_KEYWORDS = ('UNIT', 'SCALED')

The keywords of the COORD section of a CP2K input, which set how its lines give the positions.

pyretis.engines.cp2k_steps.CP2K_CSVR_STREAM = 'Wiener process for Thermostat # 1'

The name of the CSVR stream in the record that PyRETIS writes.

pyretis.engines.cp2k_steps.CP2K_FIXED_COMPONENTS = {'X': (0,), 'XY': (0, 1), 'XYZ': (0, 1, 2), 'XZ': (0, 2), 'Y': (1,), 'YZ': (1, 2), 'Z': (2,)}

The Cartesian components that each value of COMPONENTS_TO_FIX of a FIXED_ATOMS section fixes.

pyretis.engines.cp2k_steps.CP2K_GLOBAL_KEYWORDS = {'PRINT_LEVEL': ('PRINT_LEVEL', 'IOLEVEL'), 'PROJECT': ('PROJECT_NAME', 'PROJECT'), 'RUN_TYPE': ('RUN_TYPE',)}

The keywords of GLOBAL that PyRETIS sets in every CP2K input it writes, each with the names that the CP2K input schema gives it (PROJECT is an alias of PROJECT_NAME and IOLEVEL of PRINT_LEVEL). The project names the files that PyRETIS reads after a run.

pyretis.engines.cp2k_steps.CP2K_GLOBAL_REFUSED = {'OUTPUT_FILE_NAME': (('OUTPUT_FILE_NAME',), 'it names the output file of CP2K, and PyRETIS keeps the output of each run it starts'), 'PROGRAM_NAME': (('PROGRAM_NAME', 'PROGRAM'), 'PyRETIS runs the CP2K program only'), 'WALLTIME': (('WALLTIME', 'WALLTI'), 'it ends a run before the steps PyRETIS asks for')}

The keywords of GLOBAL that PyRETIS refuses in a template, each with the names that the CP2K input schema gives it, and the reason. PROGRAM_NAME is refused for a value other than CP2K.

pyretis.engines.cp2k_steps.CP2K_MD_TASKS = 'The md, md-nve and md-flux tasks accept it.'

What the md tasks do with an ensemble, a thermostat or a keyword that a path-sampling run refuses, in an input whose temperature the temperature reader reads (read_cp2k_temperatures()), for the messages.

pyretis.engines.cp2k_steps.CP2K_MOMENTUM_RESET_KEYWORDS = ('COMVEL_TOL', 'ANGVEL_TOL')

The keywords of MOTION%MD that set the velocity of the center of mass (COMVEL_TOL) or the angular momentum (ANGVEL_TOL) to zero when it exceeds their value. CP2K 2025.2 applies them at every time step whenever the input sets them, the value 0 included: COMVEL_TOL in every ensemble, ANGVEL_TOL with a cell of PERIODIC NONE. They change the velocities at the first step of a run from a frame with momentum (also in NVE), and at every step in which the forces or the thermostat change the momentum (LANGEVIN, AD_LANGEVIN, FIXED_ATOMS, in CP2K 2025.2).

pyretis.engines.cp2k_steps.CP2K_PATH_SAMPLING_ADVICE = 'Use ENSEMBLE NVE, ENSEMBLE LANGEVIN, or ENSEMBLE NVT with a THERMOSTAT of TYPE CSVR and REGION GLOBAL.'

The thermostats and ensembles a path-sampling run integrates with.

pyretis.engines.cp2k_steps.CP2K_PIECE_START = 'Each piece of trajectory that a path-sampling run generates starts CP2K from a stored frame, its positions and velocities: the variables that a thermostat or a barostat carries from one time step to the next start anew with each piece. A path-sampling run refuses the deterministic schemes with such variables or without time reversibility, and the ensembles whose cell changes in time.'

What a path-sampling run does with the state of a thermostat or a barostat, and the schemes it refuses.

pyretis.engines.cp2k_steps.CP2K_POSITION_FORMATS = ('OFF', 'XYZ')

The values of COORD_FILE_FORMAT that give CP2K the names and the positions of the atoms only: XYZ reads an xyz file, and OFF, the default, reads the COORD section.

pyretis.engines.cp2k_steps.CP2K_PROJECTED_CONSTRAINTS = ('COLLECTIVE', 'G3X3', 'G4X6', 'HBONDS', 'VIRTUAL_SITE')

The sections of MOTION->CONSTRAINT whose constraints CP2K imposes on the velocities in the first time step of a run.

pyretis.engines.cp2k_steps.CP2K_REAL = re.compile('[+-]?(\\d+\\.?\\d*|\\.\\d+)([eEdD][+-]?\\d+)?')

A real number of a CP2K input, in Fortran notation.

pyretis.engines.cp2k_steps.CP2K_REFUSED_ENSEMBLES = {'HYDROSTATICSHOCK': 'a shock scheme, whose cell velocity CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'MSST': 'a shock scheme, whose cell velocity CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'MSST_DAMPED': 'a shock scheme, whose cell velocity CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store, and a friction without time reversibility', 'NPE_F': 'a barostat, whose box momentum CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'NPE_I': 'a barostat, whose box momentum CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'NPT_F': 'a barostat, whose box momentum CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'NPT_I': 'a barostat, whose box momentum CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'NPT_IA': 'a barostat, whose box momentum CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'NVT_ADIABATIC': 'Nose-Hoover chains on the fast and the slow degrees of freedom, whose variables CP2K carries from one time step to the next', 'REFTRAJ': 'which reads the frames of a reference trajectory and integrates no dynamics'}

The values of MOTION%MD%ENSEMBLE that a path-sampling run refuses, with the reason.

pyretis.engines.cp2k_steps.CP2K_RESCALING_ENSEMBLES = {'ANNEALING_CELL': ('NPT_I', 'NPT_IA', 'NPT_F', 'NPE_I', 'NPE_F'), 'MOTION->MD->ADIABATIC_DYNAMICS': ('NVT_ADIABATIC',), 'MOTION->MD->BAROSTAT': ('NPT_I', 'NPT_IA', 'NPT_F', 'NPE_I', 'NPE_F')}

The sections of CP2K_TEMP_TOL_KEYWORDS and the keywords of CP2K_ANNEALING_KEYWORDS that CP2K applies in some ensembles only, with these ensembles. In the other ensembles they take no effect. CP2K applies the others in every ensemble, and the TEMP_TOL of MOTION%MD%SHELL to the shells of a shell model.

pyretis.engines.cp2k_steps.CP2K_SEEDED_THERMOSTAT = 'MOTION->MD->THERMOSTAT'

The thermostat section of the particles, whose CSVR stream PyRETIS seeds.

pyretis.engines.cp2k_steps.CP2K_SEED_MAX = 2147483646

The largest seed that PyRETIS writes into a CP2K input. CP2K sets the six integers of the state of a random number stream from a single seed, and these integers stay below 4294944443.

pyretis.engines.cp2k_steps.CP2K_SHELL_MODEL = 'FORCE_EVAL->MM->FORCEFIELD->SHELL'

The section of a CP2K input that gives atoms a shell (a shell model).

pyretis.engines.cp2k_steps.CP2K_SHELL_THERMOSTAT = 'MOTION->MD->SHELL->THERMOSTAT'

The thermostat section of the shells of a shell model.

pyretis.engines.cp2k_steps.CP2K_SHOCK_REASON = 'a shock scheme, whose cell velocity CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store'

The reason a path-sampling run refuses a shock ensemble.

pyretis.engines.cp2k_steps.CP2K_TEMP_TOL_KEYWORDS = (('MOTION->MD', ('TEMP_TOL', 'TEMP_TO', 'TEMPERATURE_TOLERANCE')), ('MOTION->MD->THERMAL_REGION->DEFINE_REGION', ('TEMP_TOL',)), ('MOTION->MD->SHELL', ('TEMP_TOL',)), ('MOTION->MD->BAROSTAT', ('TEMP_TOL',)), ('MOTION->MD->ADIABATIC_DYNAMICS', ('TEMP_TOL_FAST', 'TEMP_TOL_SLOW')))

The keywords of a CP2K input that rescale velocities to a target temperature when the temperature deviates from it by more than their value, with the names that the CP2K input schema gives them. The value 0, the default, rescales nothing.

pyretis.engines.cp2k_steps.CP2K_THERMAL_REGION = 'MOTION->MD->THERMAL_REGION'

The section of a CP2K input whose logical keyword FORCE_RESCALING makes CP2K rescale, at the start of each of its runs, the velocities of the atoms of every DEFINE_REGION to the TEMPERATURE of the region (CP2K 2025.2: with the velocities of the input and with those of an EXT_RESTART file).

pyretis.engines.cp2k_steps.CP2K_THERMOSTATTED_BAROSTAT_ENSEMBLES = ('NPT_F', 'NPT_I', 'NPT_IA')

The values of MOTION%MD%ENSEMBLE whose barostat CP2K couples to the thermostat of CP2K_BAROSTAT_THERMOSTAT.

pyretis.engines.cp2k_steps.CP2K_THERMOSTAT_SECTIONS = ('MOTION->MD->THERMOSTAT', 'MOTION->MD->SHELL->THERMOSTAT')

those of the particles and of the shells.

Type:

The thermostat sections of a CP2K input with a REGION

pyretis.engines.cp2k_steps.CP2K_TOPOLOGY = 'FORCE_EVAL->SUBSYS->TOPOLOGY'

The section of a CP2K input that describes the topology.

pyretis.engines.cp2k_steps.CP2K_WFN_RESTART_KEYWORDS = (('FORCE_EVAL->DFT', 'RESTART_FILE_NAME'), ('FORCE_EVAL->DFT', 'WFN_RESTART_FILE_NAME'))

The keywords of FORCE_EVAL%DFT that name the wavefunction file of the SCF guess (RESTART_FILE_NAME is an alias of WFN_RESTART_FILE_NAME), in the form of the remove_keywords argument of update_cp2k_input.

pyretis.engines.cp2k_steps._cp2k_cell_periodic(nodes)

Return whether the cell of a CP2K input is periodic.

Parameters:

nodes (list of objects like SectionNode) – The root sections of the CP2K input.

Returns:

out (boolean) – False when a section CP2K_CELL sets PERIODIC NONE; True otherwise (XYZ, the CP2K default, or a cell periodic in some directions).

pyretis.engines.cp2k_steps._cp2k_md_tasks(template)

Return what the md tasks do with a CP2K input path sampling refuses.

The md, md-nve and md-flux tasks read the temperature of the CP2K input with read_cp2k_temperatures() and take the one temperature it holds, which decides the sentence (md_tasks_sentence()).

Parameters:

template (string) – The CP2K input file.

Returns:

out (string) – A sentence that says that every task refuses the input, with the reason, for an input the reader refuses or that holds no temperature; else CP2K_MD_TASKS.

pyretis.engines.cp2k_steps._refused_ensemble(nodes, template)

Return why a path-sampling run refuses the ensemble of a CP2K input.

Parameters:
  • nodes (list of objects like SectionNode) – The root sections of the CP2K input.

  • template (string) – The CP2K input file, for the message.

Returns:

out (string or None) – The ensemble or the thermostat and why the run refuses it, or None for an ensemble the run integrates with.

pyretis.engines.cp2k_steps._refused_force_rescaling(nodes, template)

Return why a path-sampling run refuses the region rescaling of CP2K.

Parameters:
  • nodes (list of objects like SectionNode) – The root sections of the CP2K input.

  • template (string) – The CP2K input file, for the message.

Returns:

out (string or None) – Why the run refuses FORCE_RESCALING of CP2K_THERMAL_REGION given without a value or with a value that CP2K reads as true (cp2k_logical()), or None for an input that does not set it on.

pyretis.engines.cp2k_steps._refused_momentum_reset(nodes, template)

Return why a path-sampling run refuses a momentum reset of CP2K.

Parameters:
  • nodes (list of objects like SectionNode) – The root sections of the CP2K input.

  • template (string) – The CP2K input file, for the message.

Returns:

out (string or None) – Why the run refuses a keyword of CP2K_MOMENTUM_RESET_KEYWORDS that CP2K applies: COMVEL_TOL with any value, ANGVEL_TOL with any value and a cell of PERIODIC NONE; None for an input without them.

pyretis.engines.cp2k_steps._refused_rescaling(nodes, template)

Return why a path-sampling run refuses a velocity rescaling of CP2K.

Parameters:
  • nodes (list of objects like SectionNode) – The root sections of the CP2K input.

  • template (string) – The CP2K input file, for the message.

Returns:

out (string or None) – The keyword and why the run refuses it, or None for an input whose velocities CP2K does not rescale. A keyword counts in the ensembles in which CP2K applies it (CP2K_RESCALING_ENSEMBLES), and the TEMP_TOL of MOTION%MD%SHELL with a shell model.

Raises:

ValueError – As cp2k_real() raises it.

pyretis.engines.cp2k_steps._refused_shell_thermostat(nodes, template)

Return why a path-sampling run refuses the shell thermostat of CP2K.

Parameters:
  • nodes (list of objects like SectionNode) – The root sections of the CP2K input.

  • template (string) – The CP2K input file, for the message.

Returns:

out (string or None) – Why the run refuses a Nose-Hoover thermostat of the shells of a shell model, or None.

pyretis.engines.cp2k_steps._rescaling_applies(key, ensemble)

Return whether CP2K applies a velocity rescaling in an ensemble.

Parameters:
Returns:

out (boolean) – True when CP2K applies the rescaling in the ensemble.

pyretis.engines.cp2k_steps.add_cp2k_seeds(to_update, remove, seeds)

Add the seeds of a run to the changes that make its CP2K input.

GLOBAL%SEED seeds the random numbers of CP2K itself, among them the initial state of a Nose-Hoover thermostat; FORCE_EVAL%SUBSYS% SEED seeds the streams of the particles, which the Langevin ensemble and the AD_LANGEVIN thermostat draw from. An RNG_INIT section of FORCE_EVAL%SUBSYS holds the states of these streams and takes precedence over the seed, so it is removed. A CSVR thermostat of the particles or of the barostat draws from the stream of the RNG_INIT record that replaces the one of its section; the sections of the record are added to an input that lacks them. The SEED keyword of FORCE_EVAL%SUBSYS is set and the other lines and the other subsections of that section are kept; SEED is set in the GLOBAL keywords of to_update, where it replaces the SEED of the template.

Parameters:
  • to_update (dict) – The updates of the input, as update_cp2k_input() takes them, with a GLOBAL entry whose data is a dict of keywords and values (cp2k_global_update()). The entries are added in place.

  • remove (list of strings) – The sections that the input removes, added to in place.

  • seeds (dict) – The seeds, as cp2k_run_seeds() returns them. Only global is required; a missing or None subsys, csvr or barostat leaves the corresponding settings as they are.

pyretis.engines.cp2k_steps.cp2k_barostat_thermostat_type(nodes)

Return the type of the thermostat of the barostat of a CP2K run.

CP2K couples the barostat of the ensembles of CP2K_THERMOSTATTED_BAROSTAT_ENSEMBLES to the thermostat of CP2K_BAROSTAT_THERMOSTAT, whose TYPE defaults to SAME_AS_PARTICLE: the type of the thermostat of the particles, CP2K_SEEDED_THERMOSTAT, whose TYPE defaults to NOSE. The ensemble defaults to NVE. Without a MOTION%MD%BAROSTAT section CP2K stops on such an ensemble, and PyRETIS gives it no thermostat of the barostat, so that the seeds never add the section and a pressure and time constant of CP2K that the template does not set.

A path-sampling run refuses these ensembles before it starts (cp2k_path_sampling_problem()), and the md tasks run CP2K with the seeds of the input (CP2KEngineSteps.integrate()): the seed of a CSVR thermostat of the barostat reaches the CP2K runs that a program starts through the engine itself, with propagate or step.

Parameters:

nodes (list of objects like SectionNode) – The root sections of the CP2K input.

Returns:

out (string or None) – The type of the thermostat of the barostat, in upper case, or None for an ensemble without one and for an input without a MOTION%MD%BAROSTAT section.

pyretis.engines.cp2k_steps.cp2k_cold_start(infile, outfile)

Return the update that starts the SCF of a CP2K run anew.

The first CP2K run of a leg, of a kick step and of an md task starts the SCF from CP2K’s initial guess, whatever ran before it: the input names COLD_START_WFN as its wavefunction file (WFN_RESTART_FILE_NAME of FORCE_EVAL%DFT), and the caller removes the wavefunction keywords of the template (CP2K_WFN_RESTART_KEYWORDS). Without that keyword, a template with SCF_GUESS RESTART would read <project>-RESTART.wfn of the directory, which an earlier run of the same project may have left there.

Parameters:
  • infile (string) – The input template.

  • outfile (string) – The input file to create, in the directory CP2K runs in.

Returns:

out (dict) – The FORCE_EVAL->DFT node of the update argument of update_cp2k_input(), applied only to a template with a FORCE_EVAL%DFT section.

Raises:

FileExistsError – For a template with a FORCE_EVAL%DFT section, if the directory of outfile holds a file named COLD_START_WFN: CP2K would start the SCF from it.

pyretis.engines.cp2k_steps.cp2k_constraints(template, natoms)

Return the velocity components that the constraints of CP2K remove.

CP2K sets the velocity components that a FIXED_ATOMS section of MOTION->CONSTRAINT fixes to zero before the first time step of a run, and imposes the constraints of the sections of CP2K_PROJECTED_CONSTRAINTS on the velocities in the first time step. A section with a RESTRAINT subsection is a restraint and removes no velocity component.

Parameters:
  • template (string) – The CP2K input file.

  • natoms (integer) – The number of atoms of the system.

Returns:

  • fixed (numpy.array of booleans or None) – For each atom (row) and Cartesian component (column), True if a FIXED_ATOMS section fixes the component; None when no component is fixed.

  • projected (list of strings) – The titles, in alphabetical order, of the sections of CP2K_PROJECTED_CONSTRAINTS that the input holds without a RESTRAINT subsection.

Raises:
pyretis.engines.cp2k_steps.cp2k_continue_topology(template)

Return the changes of the topology of a continuation.

A continuation (write_for_continue()) takes the positions and the velocities from its EXT_RESTART file. For a coordinate file of a format of CP2K_POSITION_FORMATS, which gives the names and the positions of the atoms only, the keywords of CP2K_COORD_FILE_KEYWORDS, which read it, are removed. A coordinate file of another format gives more, among it the elements and the charges of a PDB file, and is kept: CP2K reads the names and the positions of the COORD section of the EXT_RESTART file in place of those of the file, and only USE_G96_VELOCITY is removed. The CENTER_COORDINATES section, which moves the positions of a run before its first step, is removed, as the positions of a continuation are those of the run it continues. The other keywords and the subsections of FORCE_EVAL%SUBSYS%TOPOLOGY are kept, among them the connectivity (CONN_FILE_NAME, CONN_FILE_FORMAT and the GENERATE and MOL_SET sections) and the exclusions, so the continuation evaluates the force field of the run it continues. A topology section left without a keyword and without a subsection is removed, which gives the defaults of the section.

Parameters:

template (string) – The CP2K input file.

Returns:

  • remove (list of strings) – The sections that the continuation removes, in the form of the remove argument of update_cp2k_input().

  • remove_keywords (list of tuples of strings) – The lines of the topology that the continuation removes, in the form of the remove_keywords argument of update_cp2k_input().

Raises:

NotImplementedError – If the template has more than one FORCE_EVAL%SUBSYS%TOPOLOGY section, whose topologies a continuation cannot tell apart.

pyretis.engines.cp2k_steps.cp2k_coord_columns(section)

Return the words after the position of the atoms of a section.

Parameters:

section (object like SectionNode) – A FORCE_EVAL%SUBSYS%COORD section.

Returns:

out (list of lists of strings) – For each line of the section that gives an atom, the words after its fourth: the name of its molecule and of its residue. The lines of CP2K_COORD_KEYWORDS give no atom.

pyretis.engines.cp2k_steps.cp2k_coordinate_data(template)

Describe what the coordinates of a template give beyond positions.

CP2K builds the atoms of a run from the coordinate file of FORCE_EVAL%SUBSYS%TOPOLOGY and from the COORD section. A file of a format other than those of CP2K_POSITION_FORMATS is read by a reader of its own and gives more than the names and the positions of the atoms, such as the elements, the residue and molecule names, and the charges that CHARGE_EXTENDED, CHARGE_OCCUP and CHARGE_BETA read from a PDB file. A line of the COORD section with more than four words gives the molecule and the residue of its atom.

Parameters:

template (string) – The CP2K input file.

Returns:

out (list of strings) – A description of each part of the coordinates of the template that gives more than the names and the positions of the atoms; empty when there is none.

pyretis.engines.cp2k_steps.cp2k_coordinate_format(section)

Return the format of the coordinate file of a topology section.

Parameters:

section (object like SectionNode) – A FORCE_EVAL%SUBSYS%TOPOLOGY section.

Returns:

out (string) – The value, in upper case, of the last line of the section that sets COORD_FILE_FORMAT under one of its names (CP2K_COORD_FORMAT_KEYWORDS); OFF, the default of CP2K, when no line sets it.

pyretis.engines.cp2k_steps.cp2k_draw_constraints(template, natoms, vel_settings)

Return the fixed velocity components for a draw, or refuse it.

Parameters:
  • template (string) – The CP2K input file.

  • natoms (integer) – The number of atoms of the system.

  • vel_settings (dict) – The velocity settings handed to modify_velocities.

Returns:

out (numpy.array of booleans or None) – The fixed components, as cp2k_constraints() returns them.

Raises:
pyretis.engines.cp2k_steps.cp2k_frame_coord(template, frame)

Return the lines of a COORD section that give a frame.

Parameters:
  • template (string) – The CP2K input file the input is made from.

  • frame (string) – The xyz file of the frame.

Returns:

out (list of strings) – For each atom of the frame, its name, its position and the words after the fourth of the line of the template’s COORD section for the atom (cp2k_coord_columns()).

Raises:

ValueError – If the COORD section of the template gives a number of atoms other than that of the frame, or the frame holds no configuration or a configuration of no atoms.

pyretis.engines.cp2k_steps.cp2k_frame_update(template, outfile, posfile)

Return the changes of an input that starts a run from a frame.

The frame is the xyz file posfile in the folder of the input outfile, where CP2K runs. For a template whose coordinates give the names and the positions of the atoms only (cp2k_coordinate_data() finds nothing more), the frame is the coordinate file of FORCE_EVAL%SUBSYS%TOPOLOGY, in the XYZ format: the lines of the template that set a keyword of CP2K_COORD_FILE_KEYWORDS, under any of its names, are removed, COORD_FILE_NAME and COORD_FILE_FORMAT are set, and the COORD section is removed. For another template, the topology keeps its coordinate file, and the COORD section is replaced by a line for each atom of the frame: its name, its position, and the words after the fourth of the line of the template’s COORD section for the atom. CP2K reads the names and the positions of the COORD section in place of those of the coordinate file, and the rest of the coordinate file as the template gives it. USE_G96_VELOCITY is removed, so the velocities of the run are those of the input.

Parameters:
  • template (string) – The CP2K input file the input is made from.

  • outfile (string) – The input that is made.

  • posfile (string) – The name of the frame in the folder of outfile.

Returns:

  • update (dict) – The changes of FORCE_EVAL%SUBSYS, in the form of entries of the update argument of update_cp2k_input().

  • remove (list of strings) – The sections that the input removes, in the form of the remove argument of update_cp2k_input().

  • remove_keywords (list of tuples of strings) – The lines that the input removes, in the form of the remove_keywords argument of update_cp2k_input().

Raises:
  • NotImplementedError – If a template whose coordinates give more than the names and the positions of the atoms has more than one FORCE_EVAL%SUBSYS%TOPOLOGY or FORCE_EVAL%SUBSYS%COORD section.

  • ValueError – If the COORD section of such a template gives a number of atoms other than that of the frame, and as refuse_cp2k_replicated_topology() and refuse_unread_cp2k_cell() raise it.

pyretis.engines.cp2k_steps.cp2k_global_update(template, name)

Return the changes of the GLOBAL section of a CP2K input.

PyRETIS sets the keywords of CP2K_GLOBAL_KEYWORDS: the project name, RUN_TYPE MD and PRINT_LEVEL LOW. The lines of the template that set them, under any of their names, are removed, and the other keywords and the subsections of GLOBAL are kept as the template sets them.

Parameters:
  • template (string) – The CP2K input file the input is made from.

  • name (string) – The name of the CP2K project.

Returns:

  • update (dict) – The update of GLOBAL, in the form of an entry of the update argument of update_cp2k_input(), whose data is a dict of keywords and values.

  • remove_keywords (list of tuples of strings) – The lines of GLOBAL that set the keywords of PyRETIS, in the form of the remove_keywords argument of update_cp2k_input().

Raises:

ValueError – If the GLOBAL section of the template sets a keyword of CP2K_GLOBAL_REFUSED.

pyretis.engines.cp2k_steps.cp2k_has_dft(template)

Tell whether a CP2K input has a FORCE_EVAL%DFT section.

CP2K writes a wavefunction file (<project>-RESTART.wfn) for a force evaluation with a DFT section, and the relaunches of a leg start the SCF from it.

Parameters:

template (string) – The CP2K input file.

Returns:

out (boolean) – True if the input has a FORCE_EVAL%DFT section.

pyretis.engines.cp2k_steps.cp2k_keyword(section, keyword)

Return the value that a section of a CP2K input gives a keyword.

Parameters:
  • section (object like SectionNode) – The section to read.

  • keyword (string) – The keyword, in upper case.

Returns:

out (string or None) – The words after the keyword on the last line of the section that sets it, without a comment that starts with # or !; an empty string for a keyword given without a value, and None when no line sets the keyword.

pyretis.engines.cp2k_steps.cp2k_keyword_values(section, names)

Return every line of a CP2K section that sets a keyword.

Parameters:
  • section (object like SectionNode) – The section to read.

  • names (tuple of strings) – The names of the keyword, in upper case.

Returns:

out (list of tuples of strings) – For each line that sets the keyword, in the order of the lines, the name the line gives it and the words after the name, without a comment that starts with # or !.

pyretis.engines.cp2k_steps.cp2k_logical(value)

Return the truth of a logical keyword of a CP2K input.

Parameters:

value (string or None) – The value cp2k_keyword() returns for the keyword.

Returns:

out (boolean) – False for a keyword that is absent; True for a keyword given without a value, or with one of the values that CP2K reads as true.

pyretis.engines.cp2k_steps.cp2k_md_ensemble(nodes)

Return the ensemble of the MD of a CP2K input.

Parameters:

nodes (list of objects like SectionNode) – The root sections of the CP2K input.

Returns:

out (string) – The value of MOTION%MD%ENSEMBLE, in upper case, on the last line that sets it, and NVE, CP2K’s default, when no line sets it.

pyretis.engines.cp2k_steps.cp2k_noise_problem(nodes, template)

Return why PyRETIS cannot seed the thermostat noise of a CP2K input.

CP2K seeds the streams of CSVR and GLE thermostats with a fixed seed that no input keyword sets, and reads a different state from the RNG_INIT section of the thermostat type, with one record for each thermostat. PyRETIS writes that record for the CSVR thermostat of CP2K_SEEDED_THERMOSTAT with REGION GLOBAL, the one thermostat of the particles, and for a CSVR thermostat of the barostat (cp2k_barostat_thermostat_type()), one thermostat. A CSVR thermostat with another region, a CSVR thermostat of MOTION%MD%SHELL and a GLE thermostat would draw the same noise in each run.

Parameters:
  • nodes (list of objects like SectionNode) – The root sections of the CP2K input.

  • template (string) – The CP2K input file, for the message.

Returns:

out (string or None) – The reason, naming the thermostat and what to use instead, or None when PyRETIS seeds the noise of every thermostat.

pyretis.engines.cp2k_steps.cp2k_path_sampling_problem(template)

Return why a path-sampling run cannot integrate with a CP2K input.

A path-sampling run refuses a deterministic thermostat or barostat that carries variables from one time step to the next, and one without time reversibility: the ensembles of CP2K_REFUSED_ENSEMBLES, ENSEMBLE NVT with a thermostat of TYPE NOSE (CP2K’s default TYPE) and without a THERMOSTAT section, on which CP2K stops, a velocity rescaling of CP2K_TEMP_TOL_KEYWORDS (a value other than 0) or of CP2K_ANNEALING_KEYWORDS (a value other than 1) in an ensemble in which CP2K applies it, FORCE_RESCALING of CP2K_THERMAL_REGION on, a keyword of CP2K_MOMENTUM_RESET_KEYWORDS that CP2K applies, and a thermostat of TYPE NOSE of the shells of a shell model. It refuses thermostat noise that PyRETIS cannot seed (cp2k_noise_problem()). The input is read as the engines read it (read_cp2k_template()). The refusal of a scheme ends with what the md tasks do with the input, as its temperature reader decides (_cp2k_md_tasks()).

Parameters:

template (string) – The CP2K input file.

Returns:

out (string or None) – The reason, naming the keyword and what to use instead, or None when a path-sampling run can integrate with the input.

Raises:
pyretis.engines.cp2k_steps.cp2k_path_sampling_warnings(template, relaunch)

Return the schemes of a CP2K input that make path sampling inexact.

A path-sampling run integrates with these schemes and warns about each: a thermostat of TYPE AD_LANGEVIN in ENSEMBLE NVT, whose friction restarts with each piece of trajectory; and the schemes that change the start of each piece: a MOTION%MD%CASCADE section that is on, which CP2K applies at the start of each of its runs, also of a run that continues from a restart file, and a shell model (CP2K_SHELL_MODEL), whose shells a frame does not store. The velocities of each piece are given in the input, and CP2K applies no MOTION%MD%VELOCITY_SOFTENING to given velocities.

Parameters:
  • template (string) – The CP2K input file.

  • relaunch (boolean) – True for the relaunch engine, which runs CP2K once for each subcycles steps of a piece; False for the streaming engine, which runs CP2K once for each piece.

Returns:

out (list of strings) – One warning per scheme, naming it, why the path sampling is not exact, and what to use instead.

Raises:

ValueError – As cp2k_real() and read_cp2k_template() raise it.

pyretis.engines.cp2k_steps.cp2k_real(value, template, keyword)

Return the number of a real keyword of a CP2K input.

Parameters:
  • value (string) – The words after the keyword: an optional unit tag, as [K], and the number, in Fortran notation.

  • template (string) – The CP2K input file, for the message.

  • keyword (string) – The keyword with its section, as MOTION%MD%TEMP_TOL, for the message.

Returns:

out (float) – The number, in the unit of the tag.

Raises:

ValueError – If the words are not one number after the unit tag.

pyretis.engines.cp2k_steps.cp2k_rng_record(name, seed)

Return a CP2K record of a Gaussian random number stream.

A record of an RNG_INIT section gives the state of a stream: its name (40 characters), its distribution (1, Gaussian), whether it draws antithetic numbers, whether it draws in extended precision, whether its buffer is filled, the buffer, and the six integers of each of its current state and of the starts of the stream and of its substream. This record sets the eighteen integers to seed, as CP2K sets the six integers of a stream from a single value of a SEED keyword, for a stream in extended precision with an empty buffer, the streams of the CSVR thermostat.

Parameters:
  • name (string) – The name of the stream, at most 40 characters.

  • seed (integer) – The seed, in [1, CP2K_SEED_MAX].

Returns:

out (string) – The record.

pyretis.engines.cp2k_steps.cp2k_run_seeds(template, rgen)

Draw the seeds of a CP2K run that starts from a phase point.

Parameters:
  • template (string) – The CP2K input file the run is made from.

  • rgen (object like RandomGenerator or numpy.random.Generator) – The random generator of the engine.

Returns:

out (dict) – The seed of GLOBAL%SEED (global), of FORCE_EVAL%SUBSYS%SEED (subsys), of the random generator that draws the GLOBAL%SEED of each relaunch of the relaunch engine (relaunch), of the stream of a CSVR thermostat of the particles (csvr; None without one) and of the stream of a CSVR thermostat of the barostat (barostat; None without one), drawn in this order on rgen. The streaming engine draws the same seeds and does not use relaunch, so both engines draw the same seeds for each leg.

Raises:

NotImplementedError – As refuse_unseeded_cp2k_noise() raises it.

pyretis.engines.cp2k_steps.cp2k_sections(nodes, target)

Return the sections of a CP2K input at a path of section titles.

Parameters:
  • nodes (list of objects like SectionNode) – The root sections, as read_cp2k_template() returns them.

  • target (string) – The path of the sections, on the form root->section->subsection.

Returns:

out (list of objects like SectionNode) – Every section at target, also when several sections share the path.

pyretis.engines.cp2k_steps.cp2k_thermostat_type(nodes, target)

Return the type of a thermostat section of a CP2K input.

Parameters:
  • nodes (list of objects like SectionNode) – The root sections of the CP2K input.

  • target (string) – The path of the thermostat section, as CP2K_SEEDED_THERMOSTAT.

Returns:

out (string or None) – The value of TYPE, in upper case, on the last line that sets it, and NOSE, CP2K’s default, for a section that does not set it; None for an input without the section.

pyretis.engines.cp2k_steps.draw_cp2k_seed(rgen)

Draw a seed for a CP2K random number stream.

Parameters:

rgen (object like RandomGenerator or numpy.random.Generator) – The random generator of the engine.

Returns:

out (integer) – A seed in [1, CP2K_SEED_MAX].

pyretis.engines.cp2k_steps.finish_cp2k_draw(vel, mass, fixed, zero_momentum)

Remove from drawn velocities what a CP2K run would not keep.

The velocity components that fixed marks are set to zero, as CP2K sets them before it propagates. With zero_momentum, the linear momentum is then set to zero: of all the atoms without fixed components, and of the components that move (reset_free_momentum()) with them.

Parameters:
  • vel (numpy.array) – The drawn velocities, one row per atom.

  • mass (numpy.array) – The masses, one row per atom.

  • fixed (numpy.array of booleans or None) – The fixed components, as cp2k_constraints() returns them.

  • zero_momentum (boolean) – If True, the linear momentum is set to zero.

Returns:

out (numpy.array) – The velocities.

pyretis.engines.cp2k_steps.guess_particle_mass(particle_no, particle_type)

Guess a particle mass from its type and convert to CP2K units.

Parameters:
  • particle_no (integer) – The particle number. Only used for the logger message.

  • particle_type (string) – The particle type as a string; an element of the periodic table.

Returns:

out (float) – The guessed particle mass in the engine’s internal units.

pyretis.engines.cp2k_steps.has_cp2k_restraint(section)

Return True if a constraint section of a CP2K input is a restraint.

A constraint section of MOTION->CONSTRAINT with a RESTRAINT subsection adds a restraint potential, and CP2K leaves the velocities as they are.

Parameters:

section (object like SectionNode) – The constraint section.

Returns:

out (boolean) – True if the section has a RESTRAINT subsection.

pyretis.engines.cp2k_steps.read_cp2k_atom_list(section, natoms, template)

Return the atoms that the LIST keywords of a section select.

Parameters:
  • section (object like SectionNode) – A FIXED_ATOMS section.

  • natoms (integer) – The number of atoms of the system.

  • template (string) – The CP2K input, as the error messages name it.

Returns:

out (list of integers) – The indices of the atoms, counted from zero, of every LIST line of the section. An entry a..b selects the atoms a to b, counted from one as CP2K counts them.

Raises:

ValueError – If an entry is neither an atom index nor a range of them, or selects an atom outside 1 to natoms.

pyretis.engines.cp2k_steps.read_cp2k_fixed_atoms(section, natoms, template)

Return the velocity components that a FIXED_ATOMS section fixes.

Parameters:
  • section (object like SectionNode) – A FIXED_ATOMS section of MOTION->CONSTRAINT.

  • natoms (integer) – The number of atoms of the system.

  • template (string) – The CP2K input, as the error messages name it.

Returns:

  • atoms (list of integers) – The indices of the fixed atoms, counted from zero (read_cp2k_atom_list()).

  • dims (tuple of integers) – The fixed Cartesian components of these atoms (CP2K_FIXED_COMPONENTS).

Raises:
  • NotImplementedError – If the section selects atoms with MOLNAME, MM_SUBSYS or QM_SUBSYS, excludes the QM or the MM atoms, or fixes components that CP2K_FIXED_COMPONENTS does not name: PyRETIS reads the fixed atoms from LIST only.

  • ValueError – As read_cp2k_atom_list() raises it.

pyretis.engines.cp2k_steps.read_cp2k_frame(filename)

Read the names and the positions of the atoms of an xyz frame.

Parameters:

filename (string) – The xyz file.

Returns:

  • names (list of strings) – The names of the atoms.

  • xyz (numpy.array) – The positions of the atoms.

Raises:

ValueError – If the file holds no frame, or its first frame has no atoms.

pyretis.engines.cp2k_steps.refuse_cp2k_global_keywords(template)

Refuse a template whose GLOBAL section PyRETIS cannot run.

Parameters:

template (string) – The CP2K input file.

Raises:

ValueError – If a GLOBAL section of the template sets a keyword of CP2K_GLOBAL_REFUSED, under any of its names, or a PROGRAM_NAME other than CP2K.

pyretis.engines.cp2k_steps.refuse_cp2k_replicated_topology(template)

Refuse a template whose topology replicates its coordinates.

A MULTIPLE_UNIT_CELL keyword of FORCE_EVAL%SUBSYS%TOPOLOGY other than 1 1 1 makes CP2K replicate the atoms it reads. The frames that PyRETIS gives CP2K, the configuration of its input and the frames of CP2K’s trajectories, hold every atom of the system, so CP2K would replicate them again. MULTIPLE_UNIT_CELL of FORCE_EVAL%SUBSYS%CELL, which sets the cell only, is accepted (read_box_data()).

Parameters:

template (string) – The CP2K input file.

Raises:

ValueError – If a FORCE_EVAL%SUBSYS%TOPOLOGY section of the template sets MULTIPLE_UNIT_CELL to a value other than 1 1 1.

pyretis.engines.cp2k_steps.refuse_projected_cp2k_constraints(vel_settings, projected, template)

Stop before a draw whose kinetic energy CP2K constraints change.

CP2K imposes the constraints of the sections of CP2K_PROJECTED_CONSTRAINTS on the velocities in the first time step of a run and removes the kinetic energy of the velocity components along them. A re-scale to rescale_energy and the Metropolis acceptance of a soft velocity perturbation use the kinetic energy of all the components, so both are refused with such constraints.

Parameters:
  • vel_settings (dict) – The velocity settings handed to modify_velocities.

  • projected (list of strings) – The constraint sections, as cp2k_constraints() returns them.

  • template (string) – The CP2K input, as the message names it.

Raises:

NotImplementedError – If projected is not empty and the settings request a re-scale or a soft velocity perturbation.

pyretis.engines.cp2k_steps.refuse_unseeded_cp2k_noise(template)

Stop before a CP2K run with thermostat noise that PyRETIS cannot seed.

Parameters:

template (string) – The CP2K input file.

Returns:

out (dict of booleans) – csvr: True if the thermostat of the particles is a CSVR thermostat that PyRETIS seeds; barostat: True if the thermostat of the barostat is a CSVR thermostat that PyRETIS seeds.

Raises:

NotImplementedError – For a thermostat whose noise PyRETIS cannot seed (cp2k_noise_problem()).

pyretis.engines.cp2k_steps.reset_free_momentum(vel, mass, fixed)

Set the linear momentum of the components that move to zero.

For each Cartesian component, the centre-of-mass velocity of the atoms whose component is not fixed is subtracted from them, so the total momentum is zero and the fixed components stay zero.

Parameters:
  • vel (numpy.array) – The velocities, one row per atom.

  • mass (numpy.array) – The masses, one row per atom.

  • fixed (numpy.array of booleans) – The fixed components, as cp2k_constraints() returns them.

Returns:

out (numpy.array) – The velocities with zero linear momentum.

pyretis.engines.cp2k_steps.write_for_continue(infile, outfile, timestep, subcycles, name='md_continue', seed=None)

Create input file for a single step.

Note, the single step actually consists of a number of subcycles. But from PyRETIS’ point of view, this is a single step. Here, we make use of restart files named previous.restart and previous.wfn to continue a run. The EXT_RESTART section restarts from previous.restart all that CP2K restarts by default, among it the positions, the velocities, the state of the particle thermostat (the variables of a Nose-Hoover chain, the random number stream of a CSVR thermostat) and the random number streams of the particles, so the relaunched steps of a leg continue one MD run. The COORD section of the template is removed, as the positions come from previous.restart, and so are the keywords of the topology that read a coordinate file that gives the names and the positions of the atoms only; the other settings of the topology, among them the connectivity, are kept (cp2k_continue_topology()). For a template with a FORCE_EVAL%DFT section, a RESTART_FILE_NAME or WFN_RESTART_FILE_NAME keyword of that section is replaced by WFN_RESTART_FILE_NAME previous.wfn, so the SCF_GUESS RESTART of a relaunch reads the wavefunction of the previous one.

Parameters:
  • infile (string) – The input template to use.

  • outfile (string) – The file to create.

  • timestep (float) – The time-step to use for the simulation.

  • subcycles (integer) – The number of sub-cycles to perform.

  • name (string, optional) – A name for the CP2K project.

  • seed (integer, optional) – The seed of GLOBAL%SEED, which seeds the random numbers that CP2K draws outside the states it restarts. None leaves GLOBAL%SEED as the template sets it.

Raises:
pyretis.engines.cp2k_steps.write_for_genvel(infile, outfile, posfile, seed, name='genvel')

Create input file for velocity generation.

Velocity generation runs internally, so only CP2KEngineSteps._prepare_shooting_point(), which the engine does not call, writes this input.

Parameters:
  • infile (string) – The input template to use.

  • outfile (string) – The file to create.

  • posfile (string) – The (base)name for the input file to read positions from.

  • seed (integer) – A seed for generating velocities.

  • name (string, optional) – A name for the CP2K project.

pyretis.engines.cp2k_steps.write_for_integrate(infile, outfile, timestep, subcycles, posfile, name='md_step', print_freq=None)

Create input file for a single step for the integrate method.

Here, we do minimal changes and just set the time step and subcycles and the starting configuration, the positions of the xyz file posfile (cp2k_frame_update()). The SCF starts from CP2K’s initial guess (cp2k_cold_start()).

Parameters:
  • infile (string) – The input template to use.

  • outfile (string) – The file to create.

  • timestep (float) – The time-step to use for the simulation.

  • subcycles (integer) – The number of sub-cycles to perform.

  • posfile (string) – The name of the xyz file to read positions from, in the folder of outfile.

  • name (string, optional) – A name for the CP2K project.

  • print_freq (integer, optional) – How often we should print to the trajectory file.

Raises:
pyretis.engines.cp2k_steps.write_for_step_vel(infile, outfile, timestep, subcycles, posfile, vel, name='md_step', print_freq=None, seeds=None)

Create input file for a single step.

Note, the single step actually consists of a number of subcycles. But from PyRETIS’ point of view, this is a single step. The run starts from the positions of the xyz file posfile (cp2k_frame_update()) and from the velocities vel, and its SCF from CP2K’s initial guess (cp2k_cold_start()).

Parameters:
  • infile (string) – The input template to use.

  • outfile (string) – The file to create.

  • timestep (float) – The time-step to use for the simulation.

  • subcycles (integer) – The number of sub-cycles to perform.

  • posfile (string) – The name of the xyz file to read positions from, in the folder of outfile.

  • vel (numpy.array) – The velocities to set in the input.

  • name (string, optional) – A name for the CP2K project.

  • print_freq (integer, optional) – How often we should print to the trajectory file.

  • seeds (dict, optional) – The seeds of the run, as cp2k_run_seeds() returns them, written by add_cp2k_seeds(). None leaves the random numbers as the template sets them.

Raises:
pyretis.engines.cp2k_steps.zero_fixed_components(vel, fixed)

Return velocities with the fixed components set to zero.

Parameters:
  • vel (numpy.array) – The velocities, one row per atom.

  • fixed (numpy.array of booleans or None) – The fixed components, as cp2k_constraints() returns them.

Returns:

out (numpy.array) – vel itself when fixed is None; otherwise a copy with the fixed components set to zero.

pyretis.engines.engine module

Definition of PyRETIS engines.

This module defines the base class for the engines.

Important classes defined here

EngineBase (EngineBase)

The base class for engines.

Important methods defined here

refuse_path_sampling_engine (refuse_path_sampling_engine())

Refuse an engine whose integrator a path-sampling run cannot use.

refuse_path_sampling_input (refuse_path_sampling_input())

Refuse an engine input a path-sampling run cannot use (its integrator, then its thermostat or barostat), before the engine is built.

path_sampling_warnings_of (path_sampling_warnings_of())

Return why a path-sampling run with an engine is not exact.

log_path_sampling_warnings (log_path_sampling_warnings())

Log the warnings of the engine of a section.

md_tasks_sentence (md_tasks_sentence())

Return what the md tasks do with an input path sampling refuses.

pyretis.engines.engine.BROWNIAN_DYNAMICS_ADVICE = 'For Brownian dynamics in path sampling, use the internal engine: set class = "Langevin" with high_friction = true in the engine section ([engine] for [engine], [engine1] for [engine1]). '

The advice of a refusal of Brownian dynamics in a path-sampling run. Path sampling of Brownian dynamics runs with the internal Langevin engine with high_friction = true, whose path sampling the method validation covers, in the engine section of the refused engine (ENGINE_SECTION_TEXT).

pyretis.engines.engine.BROWNIAN_DYNAMICS_TASK_ADVICE = 'For Brownian dynamics, use the internal engine: set class = "Langevin" with high_friction = true in the engine section ([engine] for [engine], [engine1] for [engine1]). '

an engine input whose Brownian dynamics states no temperature PyRETIS reads (the brownian fixes of LAMMPS) is refused in the md, md-nve and md-flux tasks and in path sampling, and every task runs the internal Langevin engine with high_friction = true, in the engine section of the refused engine (ENGINE_SECTION_TEXT).

Type:

The advice of a refusal of Brownian dynamics in every task

pyretis.engines.engine.CONTINUATION_REFUSAL = ' This input continues an earlier run: a continuation adds cycles to those that run sampled, so the run is not continued with what this message refuses (an integrator, a thermostat, a barostat, a change of the velocities or a force the integrator never applies). Start a new run from its paths ([initial-path] method = "load") with the dynamics the advice above names.'

Said after the refusal of an engine input a path-sampling run cannot use (its integrator, its thermostat, its barostat, a change of the velocities or a force its integrator never applies), when the input continues an earlier run (refuse_path_sampling_input()): a continuation adds cycles to the cycles of that run, so the advice of the refusal is for a new run, which starts from the paths of the earlier one.

pyretis.engines.engine.ENGINE_SECTION_TEXT = 'the engine section ([engine] for [engine], [engine1] for [engine1])'

The engine section, in the advice of a refusal of an engine whose section is not known. The refusal of the engine of a section names that section in its place (_section_refusal()).

class pyretis.engines.engine.EngineBase(description)

Bases: object

Abstract base class for engines.

The engines perform molecular dynamics (or Monte Carlo) and they are assumed to act on a system. Typically they will integrate Newtons equation of motion in time for that system.

Variables:
  • description (string) – Short string description of the engine. Used for printing information about the integrator.

  • exe_dir (string) – A directory where the engine is going to be executed.

  • engine_type (string or None) – Describe the type of engine as an “internal” or “external” engine. If this is undefined, this variable is set to None.

  • needs_order (boolean) – Determines if the engine needs an internal order parameter or not. If not, it is assumed that the order parameter is calculated by the engine.

  • supports_step_kick (boolean) – Whether ExternalMDEngine.kick_across_middle() may drive its single-step advance through this engine’s step(). Engines whose step raises NotImplementedError (CP2K and LAMMPS streaming, ASE, TurtleMD) set this to False so kick_across_middle uses the engine-agnostic propagate() -based fallback instead. Only consulted by ExternalMDEngine.kick_across_middle(); the internal- engine and OpenMM kick_across_middle overrides define their own search and ignore this flag.

  • temperature_source (string) – Where the engine takes the temperature it runs at: SYSTEM_TEMPERATURE for [system] temperature, and INPUT_TEMPERATURE for the temperature the input of the engine states, which the engine reads when it is created (pyretis.engines.run_temperature).

  • default_temperature (float or None) – The [system] temperature an engine that takes it runs at when the input sets none, or None when the input must set it. None here: only the internal integrators (pyretis.engines.internal.MDEngine and its subclasses) have a default, 1. Any other engine that runs at [system] temperature (TurtleMD, ASE, an engine of a module on this class) has none, and a run whose input sets none is refused (pyretis.engines.run_temperature); the default of a temperature argument of its constructor is not taken either.

  • system_temperature_unit (string or None) – For an engine that takes [system] temperature and has no default, the unit it takes the temperature in, as messages name it; None for an engine that takes it in the unit of [system] units.

  • temperature_keys (string) – For an engine that reads its temperature from its input, the settings of that input that hold it, as messages name them.

  • temperature_input_keys (tuple of strings) – For an engine that reads its temperature from its input, the settings of its engine section the read needs (GROMACS: input_path); the run refuses a section without one before it reads the temperature, naming the section and the setting (pyretis.engines.run_temperature.resolve_run_temperature()).

  • temperature_module_key (string or None) – For an engine whose input is a Python module that its engine section names (OpenMM: openmm_module), the setting of the section that names the module; None for an engine whose input is a file. Only a run imports such a module to read the temperature of the engine: the analysis does not (pyretis.engines.run_temperature.compare_analysed_engine_inputs()).

  • unmarked_section_temperature (boolean) – For an engine that reads its temperature from its input: True when the temperature of its engine section, in a run file without the temperature_rule mark of pyretis.core.provenance, is a temperature the engine used: the temperature it ran, drew its velocities and accepted at, or of these the ones that unmarked_unrecorded_use() does not name (pyretis.engines.run_temperature.earlier_engine_temperatures()).

  • unmarked_system_temperature (boolean) – For an engine that reads its temperature from its input: True when [system] temperature, in a run file without the temperature_rule mark, is the temperature the engine of [engine] ran at.

  • records_input_timestep (boolean) – For an engine that reads its temperature from its input: True when a run reads the time step of the engine from that input too, in the same read (read_input_temperatures_and_timestep of the class, which returns the temperatures and the time step in ps), before any engine is built, and records it as the timestep of the engine section (pyretis.engines.run_temperature.resolve_run_temperature()). True for OpenMM, whose time step is the step size of the integrator of its simulation.

__eq__(other)

Check if two engines are equal.

__getstate__()

Return the engine state for pickling, minus transient fields.

The order function is injected on the engine per use; it is not durable engine state and must not travel in restart pickles – it is restored separately from the ensemble settings and may itself be unpicklable (e.g. an order parameter whose class was imported from a standalone file). It falls back to the class-level order_function default after unpickling and is re-injected before the engine is next used.

__init__(description)

Just add the description.

__ne__(other)

Check if two engines are not equal.

__str__()

Return the string description of the integrator.

static add_to_path(path, phase_point, left, right)

Add a phase point and perform some checks.

This method is intended to be used by the propagate methods.

Parameters:
  • path (object like PathBase) – The path to add to.

  • phase_point (object like System) – The phase point to add to the path.

  • left (float) – The left interface.

  • right (float) – The right interface.

abstractmethod calculate_order(system, xyz=None, vel=None, box=None)

Obtain the order parameter.

The order function is injected on the engine as self.order_function; system is the state to evaluate.

classmethod can_use_order_function(order_function)

Fail if the engine can’t be used with an empty order parameter.

abstractmethod clean_up()

Perform clean up after using the engine.

default_temperature = None
default_units = None
abstractmethod dump_phasepoint(phasepoint, deffnm=None)

Dump phase point to a file.

engine_type = None
property exe_dir

Return the directory we are currently using.

frame_cell()

Return the cell for a stored frame that records none.

An .xyz frame need not record the simulation cell: the trajectories CP2K writes carry no box, and a box line can read # Box: 0.0000 0.0000 0.0000. A frame read back by format (pyretis.tools.recalculate_order.recalculate_order()) that records no cell is evaluated in the cell this method returns, the one the engine itself evaluates such a frame in.

Returns:

out (numpy.array or None) – The box lengths of the cell, or None for an engine that gives such a frame no cell.

classmethod get_default_units(settings=None)

Return the default unit system for this engine.

Parameters:

settings (dict, optional) – Full simulation settings or engine settings. Engines may override this method and use the settings to resolve their default units dynamically.

Returns:

out (string or None) – The default unit system for the engine, or None if the engine does not define one.

classmethod input_path_sampling_problem(engine_settings)

Return why a path-sampling run cannot use an engine input.

The input an engine section names is read as the engine of the class reads it when it is created, without building the engine and without reading a temperature, and gives the reason of path_sampling_problem(). The run set-up checks every engine section with it before it reads a temperature (refuse_path_sampling_input()), so the refusal of an integrator comes before a message about the temperature of the input.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (string or None) – The reason, or None when a path-sampling run can use the input; None for every input of a class whose path_sampling_problem() accepts every engine.

abstractmethod integration_step(system)

Perform one time step of the integration.

abstractmethod kick_across_middle(system, ens_set, middle, tis_settings, rgen)

Force a phase point across the middle interface.

rgen is the velocity-generation random generator, injected explicitly (kept distinct from any integration self.rgen). Every kick is an aimless draw that follows the [tis] zero_momentum setting in tis_settings (make_kick_velocity_settings()).

load_restart_info(info=None)

Load restart information.

Parameters:

info (dict) – The dictionary with the restart information, should be similar to the dict produced by restart_info().

abstractmethod modify_velocities(system, vel_settings, rgen)

Modify the velocities of the current state.

Parameters:
  • system (object like System) – The state whose velocities we modify.

  • vel_settings (dict) – It contains all the info for the velocity:

    • sigma_v : numpy.array, optional Negative values select aimless shooting. Zero or positive values set the standard deviation, one for each particle, for soft velocity perturbations.

    • zero_momentum : boolean, optional If True, we reset the linear momentum to zero after generating. A missing key means False, the [tis] default; is_zero_momentum_setting() reads it.

    • rescale : float, optional In some NVE simulations, we may wish to re-scale the energy to a fixed value. If rescale is a float > 0, we will re-scale the energy (after modification of the velocities) to match the given float.

  • rgen (object like RandomGenerator) – The random generator for drawing the new velocities, injected explicitly per call. It is deliberately kept distinct from any integration random generator an engine may own as self.rgen (e.g. Langevin/random-walk dynamics), so modifying velocities never perturbs the dynamics stream.

Returns:

  • dek (float) – The change in the kinetic energy.

  • kin_new (float) – The new kinetic energy.

needs_order = True
order_function = None

The order function is injected on the engine per use (by the simulation caller); this class-level default documents the attribute and gives a sane value before it is set. It is transient state – excluded from restart info – not durable engine config.

path_sampling_problem()

Return why a path-sampling run cannot use this engine.

A path-sampling run reverses the velocities of a frame and draws new velocities at a frame, and integrates on from the positions of that frame. The new path starts at the frame only when the integrator stores the velocities at the time of the positions it stores. A leap-frog integrator stores them half a time step away from the positions, so the first step of a reversed or a shot path does not continue the frame it starts from. An engine whose integrator a path-sampling run cannot use returns the reason.

Returns:

out (string or None) – The reason, naming the integrator and the integrators to use instead, or None when a path-sampling run can use the engine.

path_sampling_warnings()

Return why a path-sampling run with this engine is not exact.

Every piece of trajectory a path-sampling run generates (the backward and the forward piece of a shooting move, the extension of a path in a swap move) starts the engine from a stored frame: positions, velocities and, where the frame stores it, the box. A thermostat or a barostat that carries a memory from one time step to the next restarts that memory with each piece, a coupling applied every N time steps counts the steps from the start of each piece, a temperature ramp starts again with each piece, and some schemes change the velocities or the positions at the start of a piece. A path then does not follow one dynamics from its first frame to its last. An engine whose settings select such a scheme returns one warning per scheme; the run goes on.

Returns:

out (list of strings) – Each warning names the scheme, why the path sampling is not exact with it, and what to use instead. Empty when the engine selects no such scheme.

abstractmethod propagate(path, ens_set, system, reverse=False)

Propagate equations of motion.

records_input_timestep = False
restart_info()

General method.

Returns the info to allow an engine exact restart.

Returns:

info (dict) – Contains all the updated simulation settings and counters.

set_mdrun(md_items)

Configure the run state of a move on the engine.

The engine keeps the run state the scheduler sets here; the transient System/rgen/order function are injected per call. The infinite-swapping scheduler calls this before each move, with the run items of the move, to point the engine at the scratch directory of the move (and, for engines that launch an external command, at the launch command of the worker). The default handles the common case – set exe_dir from md_items when provided; subclasses that need more (e.g. a per-worker mdrun command) override and extend it.

Parameters:

md_items (dict) – The run items of the move. The key exe_dir (when present) sets the engine execution directory.

static snapshot_to_system(system, snapshot)

Convert a snapshot to a system object.

This uses the System property API (pos/vel/vpot/ekin), which routes to system.particles when particles are attached and otherwise stores the values directly on the snapshot-based system. It therefore works for a system with particles, as the internal integrators use, and for a snapshot-based system without particles, as the external and streaming engines may use.

supports_step_kick = True
system_temperature_unit = None
temperature_input_keys = ()
temperature_keys = ''
temperature_module_key = None
temperature_source = 'system'
property time_per_step

Return the simulation time between two recorded path points.

This is timestep * subcycles – the physical time per PyRETIS step, expressed in the engine’s own time unit – and is the factor that converts a path length (in steps) into a time when computing fluxes and rates. The time step belongs to the engine: each subclass sets self.timestep from its own authoritative source (the [engine] setting for engines PyRETIS drives directly, or the external program’s input for engines that own their own time step). subcycles defaults to 1 when an engine does not define it.

Returns:

float or None – timestep * subcycles, or None if the engine has no timestep.

unmarked_section_temperature = False
unmarked_system_temperature = False
classmethod unmarked_unrecorded_use(engine_settings)

Return what an earlier engine did at a temperature not recorded.

For an engine with unmarked_section_temperature, a run file without the temperature_rule mark records the temperature of its engine section, which the PyRETIS that wrote it gave the engine. An engine that ran, drew its velocities and accepted at that temperature returns None.

Parameters:

engine_settings (dict) – The settings of the engine section, as the run file records them.

Returns:

out (string or None) – None for an engine whose run the recorded temperature describes; else what the engine took from it, and what it did at the temperature of its own input of that run, which no run file records, as a warning states it.

pyretis.engines.engine.INPUT_TEMPERATURE = 'input'

The EngineBase.temperature_source of an engine that runs at the temperature its own input states.

pyretis.engines.engine.SYSTEM_TEMPERATURE = 'system'

The EngineBase.temperature_source of an engine that runs at [system] temperature.

pyretis.engines.engine.log_path_sampling_warnings(section, warnings)

Log the warnings of the engine of a section of a path-sampling run.

Parameters:
  • section (string) – The input section the engine is built from, as engine1.

  • warnings (list of strings) – The warnings of its engine (path_sampling_warnings_of()). Each is logged as a warning, after the section: The engine of [engine1]: <warning>.

pyretis.engines.engine.md_tasks_sentence(read_temperatures, filename, accepted)

Return what the md tasks do with an input path sampling refuses.

The md, md-nve and md-flux tasks read the temperature of an engine input with the temperature reader of the engine (pyretis.inout.engine_temperature), which raises a ValueError for an input it refuses, and take the one temperature its settings hold (EngineTemperatures.agreed()), which raises a ValueError for an input that holds no temperature or different ones: every task refuses that input. The reader and EngineTemperatures.agreed() run on the input to word the message of a path-sampling refusal; the temperature is not used.

Parameters:
  • read_temperatures (callable) – The temperature reader of the engine, as read_lammps_temperatures(), called with filename; it returns an EngineTemperatures.

  • filename (string) – The engine input the path-sampling run refuses.

  • accepted (string) – The sentence for an input the reader reads, which the md, md-nve and md-flux tasks accept.

Returns:

out (string) – For an input the reader refuses, or whose settings hold no temperature or different ones, a sentence that says that every task refuses it, followed by the reason; accepted for an input whose settings hold one temperature.

Raises:
  • UnicodeError – As the reader raises it, for a file it cannot decode.

  • Exception – Every exception of the reader other than its ValueError.

pyretis.engines.engine.path_sampling_warnings_of(engine)

Return the warnings of the engine of a path-sampling run.

Parameters:

engine (object like EngineBase) – The engine of a path-sampling run, which a path-sampling run can use (refuse_path_sampling_engine()). An engine without the method EngineBase.path_sampling_warnings() gives no warning.

Returns:

out (list of strings) – The warnings EngineBase.path_sampling_warnings() gives, each once, in its order.

pyretis.engines.engine.refuse_path_sampling_engine(engine, section=None)

Refuse an engine whose integrator a path-sampling run cannot use.

Parameters:
  • engine (object like EngineBase) – The engine of a path-sampling run. An engine without the method EngineBase.path_sampling_problem() is accepted.

  • section (string, optional) – The input section the engine is built from, as engine1. When given, the message starts with the section, [engine1], and names that section and its integrator key in its advice (_section_refusal()).

Raises:

ValueError – If the engine gives a reason why a path-sampling run cannot use it (EngineBase.path_sampling_problem()). The message is the reason, after the section when one is given.

pyretis.engines.engine.refuse_path_sampling_input(cls, engine_settings, section=None, continuation=False)

Refuse an engine input a path-sampling run cannot use.

Parameters:
  • cls (type) – The engine class of the section. A class without the method EngineBase.input_path_sampling_problem() is accepted.

  • engine_settings (dict) – The settings of the engine section.

  • section (string, optional) – The engine section, as engine1. When given, the message starts with the section, [engine1], and names that section and its integrator key in its advice (_section_refusal()).

  • continuation (boolean, optional) – True when the input continues an earlier run (a restart or a resume): the message then ends with CONTINUATION_REFUSAL.

Raises:

ValueError – If the input gives a reason why a path-sampling run cannot use it (EngineBase.input_path_sampling_problem()): the message of refuse_path_sampling_engine() for the engine built from the input, followed by CONTINUATION_REFUSAL for a continuation.

pyretis.engines.external module

Definition of external engines.

This module defines the base class for external MD engines.

Important classes defined here

ExternalMDEngine (ExternalMDEngine)

The base class for external engines which defines the interface to external programs.

class pyretis.engines.external.ExternalMDEngine(description, timestep, subcycles)

Bases: EngineBase

Base class for interfacing external MD engines.

This class defines the interface to external programs. The interface will define how we interact with the external programs, how we write input files for them and read output files from them. New engines should inherit from this class and implement the following methods:

Variables:
  • description (string) – A string with a description of the external engine. This can, for instance, be what program we are interfacing with. This is used for outputting information to the user.

  • timestep (float) – The time step used for the external engine.

  • subcycles (integer) – The number of steps the external step is composed of. That is: each external step is really composed of subcycles number of iterations.

__init__(description, timestep, subcycles)

Set up the external engine.

Here we just set up some common properties which are useful for the execution.

Parameters:
  • description (string) – A string with a description of the external engine. This can, for instance, be what program we are interfacing with. This is used for outputting information to the user.

  • timestep (float) – The time step used in the simulation.

  • subcycles (integer) – The number of sub-cycles each external integration step is composed of.

_abc_impl = <_abc._abc_data object>
_calculate_frame_order(system, config, xyz, vel, box)

Calculate the order parameter of one frame of a trajectory.

The order function sees the frame: the positions, the velocities and the box of system are those of the frame, as calculate_order() sets them, and system.config is config, the (file, index) of the frame, which is the config the phase point of the frame stores. system.config is set back to its value before the call afterwards.

Parameters:
  • system (object like System) – The state the order parameter is calculated on.

  • config (tuple) – The (file, index) of the frame, as dump_config() resolves it.

  • xyz (numpy.array) – The positions of the frame.

  • vel (numpy.array) – The velocities of the frame.

  • box (numpy.array) – The box of the frame.

Returns:

out (list of floats) – The order parameter of the frame.

Raises:

ValueError – If the positions, the velocities or the box of the frame are missing: calculate_order() would then read them from the first frame of the file of config, not from this frame.

static _cap_engine_log(path, maxsize)

Trim an engine log to its most-recent maxsize bytes.

Thin wrapper around pyretis.engines._engine_logs.cap_engine_log().

_config_signature(filename)

Return a hash identifying a configuration’s physical content.

Confirms that an interrupted propagation we are about to resume really belongs to the shot being re-attempted: the shooting point is regenerated deterministically on restart, so its positions/velocities are identical. We hash the coordinates (not the raw file bytes) so format-specific metadata such as a title line does not affect the comparison.

static _copyfile(source, dest)

Copy file from source to destination.

static _engine_output_files(log_dir)

Return the engine stdout/stderr log paths for a run directory.

Thin wrapper around pyretis.engines._engine_logs.engine_output_files().

abstractmethod _extract_frame(traj_file, idx, out_file)

Extract a frame from a trajectory file.

Parameters:
  • traj_file (string) – The trajectory file to open.

  • idx (integer) – The frame number we look for.

  • out_file (string) – The file to dump to.

static _finalize_engine_output(return_code, err_name)

Keep stdout logs and discard stderr logs from successful runs.

Thin wrapper around pyretis.engines._engine_logs.finalize_engine_output().

_frame_config_index(frame)

Map a trajectory-frame number to its configuration index.

The configuration index is what is stored in a snapshot’s config tuple and later passed to _extract_frame(). For most engines it equals the trajectory-frame number; engines that index configurations by MD time step (the LAMMPS engines, LAMMPSEngineSteps._frame_config_index(), which store frame * subcycles) override this.

Parameters:

frame (integer) – The trajectory-frame number (0-based).

Returns:

out (integer) – The configuration index for that frame.

_kick_across_middle_propagate(system, ens_set, middle, tis_settings, rgen)

Force a phase point across the middle interface via propagate().

Engine-agnostic fallback for engines with supports_step_kick = False (no usable single step(): CP2K/LAMMPS streaming, ASE, TurtleMD). Mirrors the greedy hill-climb of the step()-based kick_across_middle() above – kick velocities, advance exactly one step, keep the new point if it did not move away from middle and revert otherwise, repeat until the step straddles middle – but advances using propagate() (a Path capped at maxlen=2) instead of step(), operating on in-memory System.copy() objects. The search keeps no files of its own: each engine’s _propagate_from manages its trajectory files.

Parameters:
  • system (object like System) – The working state we repeatedly kick and integrate. The order function is injected on the engine (self.order_function).

  • ens_set (dict) – Ensemble settings. Each advance runs propagate() on a shallow copy of them whose interfaces are [-inf, middle, +inf], so ens_set is not changed and its own interfaces are not read. The crossing search compares against the middle argument, which may differ from ens_set['interfaces'][1] for the body-ensemble edge case in generate_initial_path_kick().

  • middle (float) – This is the value for the middle interface.

  • tis_settings (dict) – Settings for TIS. kick_maxtries caps the number of kick attempts (default KICK_MAXTRIES, at least 1), and zero_momentum selects the linear-momentum reset after each kick (a missing key means False). Every kick passes the vel_settings of the step()-based search to the engine’s modify_velocities: an aimless draw with the energy left unscaled (make_kick_velocity_settings()).

  • rgen (object like RandomGenerator) – The velocity-generation random generator, injected per call (distinct from any integration self.rgen).

Returns:

  • out[0] (object like System) – The phase-point just before crossing the interface.

  • out[1] (object like System) – The phase-point just after crossing the interface.

Note

The two returned points are copies, and the caller’s system object is not one of them: the first kick and step act on that object, and the search then continues on copies. Callers must use the return value (generate_initial_path_kick() does: it reassigns ensemble['system'] from the returned points).

Each search iteration launches a fresh propagate() call, which for a subprocess-based streaming engine (CP2K, LAMMPS) means a fresh external-process launch per step of the greedy search. This is a one-time bootstrap cost (kick runs once per ensemble, not once per cycle); turtlemd and ASE are pure in-process Python engines, so this primitive is cheap for them.

static _modify_input(sourcefile, outputfile, settings, delim='=', key_name=None)

Modify input file for external software.

Here we assume that the input file has a syntax consisting of keyword = setting. We will only replace settings for the keywords we find in the file that is also inside the settings dictionary. A replaced line keeps the keyword as the file spells it; the settings the file does not hold are added at its end.

Parameters:
  • sourcefile (string) – The path of the file to use for creating the output.

  • outputfile (string) – The path of the file to write.

  • settings (dict) – A dictionary with settings to write.

  • delim (string, optional) – The delimiter used for separation keywords from settings.

  • key_name (callable, optional) – Gives, for a keyword, the name the external program reads it as (for GROMACS, mdp_key_name()). A keyword of the file is the keyword of settings with the same name. Without it, the name of a keyword is the keyword itself.

Raises:

ValueError – If two keywords of settings have the same name.

static _movefile(source, dest)

Move file from source to destination.

_name_output(basename)

Create a file name for the output file.

This method is used when we dump a configuration, to add the extension of the engine’s configurations, self.ext (for GROMACS, gro or g96).

Parameters:

basename (string) – The base name to give to the file.

Returns:

out (string) – The file name with the extension, in self.exe_dir.

static _open_engine_log(path)

Open an engine stdout/stderr log for appending, resiliently.

Thin wrapper around pyretis.engines._engine_logs.open_engine_log().

_prefill_partial(system, partial_traj, name)

Rebuild the surviving frames of an interrupted path.

Returns a tuple (phase_points, cont_conf) where phase_points are the surviving frames except the last good one (rebuilt from the partial trajectory, with order parameters recomputed) and cont_conf is a configuration file holding the last good frame, from which the propagation continues. The last good frame is excluded because _propagate_from() re-adds it as the first frame of the continued segment.

The caller, propagate(), prepends the surviving frames to its path after _propagate_from(), so the engine’s own update_energies aligns with the continued frames only. The surviving frames’ energies are not recoverable from the trajectory and are therefore left unset (None).

Returns (None, None) when there are fewer than two readable frames (nothing worth resuming).

abstractmethod _propagate_from(name, path, system, ens_set, msg_file, reverse=False)

Run the actual propagation using the specific engine.

This method is called by propagate(), which handles the necessary preparations before the actual propagation (e.g. dumping of the configuration etc.).

Parameters:
  • name (string) – A name to use for the trajectory we are generating.

  • path (object like PathBase) – This is the path we use to fill in phase-space points.

  • system (object like System) – The system object gives the initial state for the integration. The order function is injected on the engine (self.order_function).

  • ens_set (dict) – Ensemble settings. It contains:

    • interfaces : list of floats These interfaces define the stopping criterion.

  • msg_file (object like FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.

  • reverse (boolean, optional) – If True, the system will be propagated backward in time.

Returns:

  • success (boolean) – This is True if we generated an acceptable path.

  • status (string) – A text description of the current status of the propagation.

abstractmethod _read_configuration(filename)

Read output configuration from external software.

Parameters:

filename (string) – The file to open and read a configuration from.

Returns:

  • out[0] (numpy.array) – The dimensions of the simulation box.

  • out[1] (numpy.array) – The positions found in the given filename.

  • out[2] (numpy.array) – The velocities found in the given filename.

static _read_input_settings(sourcefile, delim='=')

Read input settings for simulation input files.

Here we assume that the input file has a syntax consisting of keyword = setting, where = can be any string given in the input parameter delim.

Parameters:
  • sourcefile (string) – The path of the file to use for creating the output.

  • delim (string, optional) – The delimiter used for separation keywords from settings.

Returns:

settings (dict of strings) – The settings found in the file.

Note

Important: We are here assuming that there will ONLY be one keyword per line.

_read_resume_marker(reverse, init_sig)

Return a resumable partial trajectory, or None.

A marker is resumable only when it records an incomplete propagation whose initial configuration matches init_sig (same shot) and whose partial trajectory still exists on disk.

Parameters:
  • reverse (boolean) – The propagation direction we are about to (re)run.

  • init_sig (string) – Content signature of the current shot’s initial config.

Returns:

out (string or None) – The path to the partial trajectory to resume from, or None.

_recompute_partial_orders(partial_traj, reverse)

Order parameters for every readable frame, in file order.

Reads the surviving frames of an interrupted trajectory and recomputes their order parameters (the deterministic source of truth). A frame left broken by the interruption is tolerated: the underlying readers stop at the last readable frame.

_remove_files(dirname, files)

Remove files from a directory.

Parameters:
  • dirname (string) – Where we are removing.

  • files (list of strings) – A list with files to remove.

_remove_resume_marker(reverse)

Remove the resume marker once a propagation has completed.

static _removefile(filename)

Remove a given file if it exist.

_resume_marker_path(reverse)

Return the path of the per-direction resume marker file.

abstractmethod _reverse_velocities(filename, outfile)

Reverse velocities in a given snapshot.

Parameters:
  • filename (string) – Input file with velocities.

  • outfile (string) – File to write with reversed velocities.

_trajectory_filename(name)

Return the basename of the trajectory file for a propagation.

This is the file the engine writes frames to during _propagate_from(). Engines whose trajectory format differs from their configuration format (e.g. GROMACS writes a .trr while configurations are .gro/.g96) override this.

Parameters:

name (string) – The trajectory label built in propagate().

Returns:

out (string) – The trajectory file basename.

_write_resume_marker(reverse, traj_file, init_sig, complete)

Write (atomically and durably) the resume marker.

calculate_order(system, xyz=None, vel=None, box=None)

Calculate order parameter from configuration in a file.

Note, if xyz, vel and box are all given, we will NOT read positions, velocity and box information from the current configuration file. If any of them is None, all three are read from that file.

Parameters:
  • system (object like System) – This is the system that contains the particles we are investigating. The order function is injected on the engine as self.order_function.

  • xyz (numpy.array, optional) – The positions to use, in case we have already read them somewhere else.

  • vel (numpy.array, optional) – The velocities to use, in case we already have read them.

  • box (numpy.array, optional) – The current box vectors, in case we already have read them.

Returns:

out (list of floats) – The calculated order parameter(s).

clean_up()

Will remove all files from the current directory.

continue_interrupted = False

Opt-in resume of an interrupted propagation. When True, an abruptly interrupted propagation (e.g. a cluster wall-time kill) is continued on restart instead of being re-run from the shooting point: the frames that survived on disk are reused and the trajectory is propagated onward from the last good frame. The continued segment is a new, valid path (the integrator state is restarted from a configuration, so it is not bit-identical to an uninterrupted run); such paths are flagged via path.resumed. False (the default) re-runs an interrupted propagation from the shooting point.

static draw_maxwellian_velocities(vel, mass, beta, rgen, sigma_v=None)

Draw velocities from a Maxwell-Boltzmann distribution.

This is the engine-independent (Python) velocity draw used when an external engine is configured to generate shooting velocities via velocity_generation = "maxwell" instead of delegating to the engine’s own generator. The velocities are drawn from the injected random generator so the whole shooting move stays on one reproducible stream.

Parameters:
  • vel (numpy.ndarray) – The current velocities; only the shape (npart, dim) is used (the values are overwritten).

  • mass (numpy.ndarray) – The particle masses, shape (npart, 1).

  • beta (float) – The inverse temperature 1 / (k_B T) in the engine’s unit system.

  • rgen (object like RandomGenerator) – The velocity random generator, injected explicitly. With the default PCG64 generator, its normal draw is that of numpy.random.Generator.normal.

  • sigma_v (numpy.ndarray, optional) – Per-particle standard deviation. When None (or any negative entry) it is computed from beta and mass.

Returns:

  • vel (numpy.ndarray) – The newly drawn velocities, shape (npart, dim).

  • sigma_v (numpy.ndarray) – The standard deviation used for the draw.

dump_config(config, deffnm='conf')

Extract configuration frame from a system if needed.

Parameters:
  • config (tuple) – The configuration given as (filename, index).

  • deffnm (string, optional) – The base name for the file we dump to.

Returns:

out (string) – The file name we dumped to, _name_output() of deffnm. A configuration of a single frame (index None) is copied to it, unless it is that file.

Note

If the velocities should be reversed, this is handled elsewhere.

dump_frame(system, deffnm='conf')

Just dump the frame from a system object.

dump_phasepoint(phasepoint, deffnm='conf')

Just dump the frame from a system object.

engine_log_maxsize = None

Optional cap (in bytes) on the retained engine.log stdout file. The log is appended to on every external step, so over a long run it can grow without bound. When this is set to a positive integer, after each successful command the log is trimmed to its most-recent engine_log_maxsize bytes (the oldest output is dropped and a marker line is written at the top), reclaiming disk immediately. None (the default) leaves the log unbounded. Set it on the class or an instance, e.g. engine.engine_log_maxsize = 100 * 1024 * 1024 for a 100 MB cap. A failing command’s log is never trimmed.

engine_type = 'external'
execute_command(cmd, cwd=None, inputs=None)

Execute an external command for the engine.

We are here executing a command and then waiting until it finishes. The standard out and standard error are piped to files during the execution and can be inspected if the command fails. This method returns the return code of the issued command.

Parameters:
  • cmd (list of strings) – The command to execute.

  • cwd (string or None, optional) – The current working directory to set for the command.

  • inputs (bytes or None, optional) – Additional inputs to give to the command. These are not arguments but more akin to keystrokes etc. that the external command may take.

Returns:

out (int) – The return code of the issued command.

integration_step(system)

Perform a single time step of the integration.

For external engines, it does not make much sense to run single steps unless we absolutely have to. We therefore just fail here: an external engine runs an MD task through its integrate method, where it has one.

If it’s absolutely needed, there is a step() method which can be used, for instance in the initialisation.

Parameters:

system (object like System) – A system to run the integration step on.

kick_across_middle(system, ens_set, middle, tis_settings, rgen)

Force a phase point across the middle interface.

This is accomplished by repeatedly kicking the phase point so that it crosses the middle interface.

Parameters:
  • system (object like System) – The working state we repeatedly kick and integrate. The order function is injected on the engine (self.order_function).

  • ens_set (dict) – Ensemble settings, which only the propagate()-based search (_kick_across_middle_propagate()) reads; the argument belongs to the signature of EngineBase.kick_across_middle().

  • middle (float) – This is the value for the middle interface.

  • tis_settings (dict) – This dictionary contains settings for TIS. Explicitly used here:

    • zero_momentum: boolean, determines if the momentum is zeroed after each kick. A missing key means False.

    • kick_maxtries: integer, caps the number of kick attempts (default KICK_MAXTRIES, at least 1).

    Every kick is an aimless draw with the energy left unscaled (make_kick_velocity_settings()).

  • rgen (object like RandomGenerator) – The velocity-generation random generator, injected per call (distinct from any integration self.rgen).

Returns:

  • out[0] (object like System) – The phase-point just before the crossing the interface.

  • out[1] (object like System) – The phase-point just after crossing the interface.

Note

This function will update the input system state.

Note

This is the step()-based search, used when self.supports_step_kick is True. Engines that cannot drive a single step() (supports_step_kick = False: CP2K/LAMMPS streaming, ASE, TurtleMD) are dispatched to the engine-agnostic _kick_across_middle_propagate() – see there for that fallback.

propagate(path, ens_set, system, reverse=False)

Propagate the equations of motion with the external code.

This method will explicitly do the common set-up, before calling more specialised code for doing the actual propagation.

Parameters:
  • path (object like PathBase) – This is the path we use to fill in phase-space points. We are here not returning a new path - this since we want to delegate the creation of the path to the method that is running propagate.

  • ens_set (dict) – Ensemble settings. It contains:

    • interfaces : list of floats These interfaces define the stopping criterion.

    • path_ensemble : optional, for building the working-file name prefix when present.

  • system (object like System) – The system object gives the initial state for the integration. It is mutated in place (configuration file and velocity-reversal flag) during propagation; the caller owns the lifecycle and passes a fresh copy per call. The order function and random generator are injected on the engine (self.order_function / self.rgen).

  • reverse (boolean, optional) – If True, the system will be propagated backward in time.

Returns:

  • success (boolean) – This is True if we generated an acceptable path.

  • status (string) – A text description of the current status of the propagation.

abstractmethod step(system, name)

Perform a single step with the external engine.

Parameters:
  • system (object like System) – The system we are integrating.

  • name (string) – To name the output files from the external engine.

Returns:

out (string) – The name of the output configuration, obtained after completing the step.

pyretis.engines.gromacs module

A GROMACS external MD integrator interface (canonical streaming engine).

This module defines the canonical GROMACS engine, selected by class = "gromacs". It runs GROMACS as a single persistent process and reads the output TRR file on the fly, rather than starting and stopping the executable once per order-parameter point. The slower relaunch implementation is selected by class = "gromacs_steps", in pyretis.engines.gromacs_steps.

Important classes defined here

GromacsEngine (GromacsEngine)

A class responsible for interfacing GROMACS by streaming.

class pyretis.engines.gromacs.GromacsEngine(gmx, mdrun=None, input_path=None, timestep=None, subcycles=None, exe_path='/home/enrico/cache/twoway-retis/wt2/docs', maxwarn=0, gmx_format='g96', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', masses=False, conf=None)

Bases: GromacsEngineSteps

A class for interfacing GROMACS by streaming.

This class defines an interface to GROMACS. Attributes are similar to GromacsEngineSteps. In this particular interface, GROMACS is executed without starting and stopping and we rely on reading the output TRR file from GROMACS while a simulation is running.

__init__(gmx, mdrun=None, input_path=None, timestep=None, subcycles=None, exe_path='/home/enrico/cache/twoway-retis/wt2/docs', maxwarn=0, gmx_format='g96', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', masses=False, conf=None)

Set up the GROMACS engine.

Parameters:
  • gmx (string) – The GROMACS executable.

  • mdrun (string, optional) – The GROMACS mdrun executable. May be omitted when the engine is driven by the infinite-swapping scheduler, which supplies a per-worker mdrun command via set_mdrun.

  • input_path (string) – The absolute path to where the input files are stored.

  • timestep (float) – The time step used in the GROMACS MD simulation.

  • subcycles (integer) – The number of steps each GROMACS MD run is composed of.

  • exe_path (string, optional) – The absolute path at which the main PyRETIS simulation will be run.

  • maxwarn (integer, optional) – Setting for the GROMACS grompp -maxwarn option.

  • gmx_format (string, optional) – 'g96' or 'gro' – see GromacsEngineSteps.

  • write_vel (boolean, optional) – Determines if GROMACS should write velocities or not.

  • write_force (boolean, optional) – Determines if GROMACS should write forces or not.

  • domain_decomp (boolean, optional) – Whether GROMACS uses domain decomposition or not. This will not set the domain decomposition behavior, the user should know this.

  • velocity_generation (string, optional) – "engine" (default) or "maxwell" – see GromacsEngineSteps.

  • masses (list or string, optional) – Particle masses for the "maxwell" velocity draw.

  • conf (string, optional) – The starting configuration file in input_path – see GromacsEngineSteps.

static _check_frame_step(trr_file, index, frame_step, step, steps)

Check that a frame of the .trr is at the MD step of its index.

Parameters:
  • trr_file (string) – The trajectory file the frame is read from.

  • index (integer) – The index of the frame in the trajectory, 0 for the first.

  • frame_step (integer) – The MD step of the frame, as its header stores it: a 32-bit signed integer, into which GROMACS wraps (modulo 2**32) an MD step outside its range.

  • step (integer) – The MD step of the frame of this index in the run, init-step + index * subcycles.

  • steps (integer) – The number of frames of the run.

Raises:

RuntimeError – If index is steps or more, or if frame_step is not step as the header stores it.

_energy_records(edr_file, begin, end)

Return the records of a time window of an .edr file.

Parameters:
  • edr_file (string) – The GROMACS energy file to read from.

  • begin (float) – The start of the window, in ps (gmx energy -b; a negative time is given as 0).

  • end (float) – The end of the window, in ps (gmx energy -e).

Returns:

  • times (list of float) – The time of each record read, in ps, as gmx energy prints it: the first column of the data rows of the xvg.

  • energy (dict of numpy.arrays) – The energies of the records read, in the same order, as get_energies() returns them.

_get_frame_energies(edr_file, step, time, max_attempts=100)

Read one frame’s energies from a streamed .edr, tolerating lag.

The energies of a frame are those of the .edr record of its MD step. GROMACS gives the record of the MD step s the time tinit + s * dt, and gmx energy prints that time from its double precision value with six decimals, in both precisions of GROMACS. The record of the MD step is the one printed at time to within a quarter of dt; the record of another MD step is at least dt away. The time window given to gmx energy only bounds the records read: a mixed-precision build selects them comparing times in single precision, so at large times it also returns the records of neighbouring MD steps.

The .edr is written on the fly by mdrun and can briefly lag the .trr frame being processed (notably the initial frame, before mdrun has flushed any energy). In that window a tight gmx energy selection either returns no rows or fails outright. Retry (bounded) until the record of the MD step is in the file; the final attempt is left to raise so a genuine, persistent failure is still surfaced.

Parameters:
  • edr_file (string) – The GROMACS energy file to read from.

  • step (integer) – The MD step of the frame.

  • time (float) – The time of the MD step, tinit + step * dt, in ps.

  • max_attempts (integer, optional) – Maximum number of retries while the energy file catches up.

Returns:

energy (dict of numpy.arrays) – The energies of the record of the MD step, one value per term.

Raises:

RuntimeError – If the .edr holds no record at the MD step after max_attempts reads, or the records read are not one at the MD step (_record_of_step()).

_propagate_from(name, path, system, ens_set, msg_file, reverse=False)

Propagate with GROMACS from the current system configuration.

Here, we assume that this method is called after the propagate() has been called in the parent. The parent is then responsible for reversing the velocities and also for setting the initial state of the system.

Parameters:
  • name (string) – A name to use for the trajectory we are generating.

  • path (object like PathBase) – This is the path we use to fill in phase-space points.

  • system (object like System) – The system object gives the initial state for the integration. The order function is injected on the engine (self.order_function).

  • ens_set (dict) – Ensemble settings. It contains:

    • interfaces : list of floats These interfaces define the stopping criterion.

  • msg_file (object like FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.

  • reverse (boolean, optional) – If True, the system will be propagated backward in time.

Returns:

  • success (boolean) – This is True if we generated an acceptable path.

  • status (string) – A text description of the current status of the propagation.

Raises:

ValueError – Before GROMACS runs, if init-step is not a multiple of the current subcycles (_refuse_init_step()).

_record_of_step(records, step, time, edr_file)

Return the energies of the record of one MD step, if read.

Parameters:
  • records (tuple) – The times and the energies of the records read, as _energy_records() returns them.

  • step (integer) – The MD step.

  • time (float) – The time of the MD step, in ps.

  • edr_file (string) – The energy file the records are read from.

Returns:

out (dict of numpy.arrays or None) – The energies of the one record at time, to within a quarter of dt, or None if no record at or after time is read: the .edr has not reached the MD step yet.

Raises:

RuntimeError – If two or more records are at time, or if a record after time is read and none at it: the .edr passed the MD step without its record, so the energies are not written at the MD steps of the frames.

_run_start(mdp_file)

Return the first MD step of a run and its tinit.

GROMACS gives step s of a run the MD step init-step + s and the time tinit + (init-step + s) * dt, with the init-step and tinit of its mdp file (0 if the file does not set them) and dt, the timestep of the engine. The mdp file of a PyRETIS run sets nstxout and nstenergy to subcycles: GROMACS writes a frame to the .trr and a record to the .edr at each MD step that is a multiple of subcycles. The engine refuses, when it is set up, an init-step that is not a multiple of subcycles (_refuse_init_step()), so the first frame of the run is at the MD step init-step.

Parameters:

mdp_file (string) – The mdp file of the run.

Returns:

  • out[0] (integer) – init-step, the MD step of the first frame of the run.

  • out[1] (float) – tinit, in ps.

Raises:

ValueError – If the run starts at a negative time, tinit + init-step * dt < 0: the energies are read from the time 0 on (_energy_records()).

integrate(system, order_function, steps, thermo='full')

Perform several integration steps.

This method will perform several integration steps using GROMACS. It will also calculate order parameter(s) and energy terms if requested.

Parameters:
  • system (object like System) – The system object gives the initial state for the integration. At each step, its positions, velocities and box are those of the frame of the step.

  • order_function (object like OrderParameter or None) – An order function can be specified if we want to calculate the order parameter along with the simulation.

  • steps (integer) – The number of steps we are going to perform. Note that we do not integrate on the first step (e.g. step 0) but we do obtain the other properties. This is to output the starting configuration.

  • thermo (string, optional) – Select the thermodynamic properties we are to obtain.

Yields:

results (dict) – The results of step i, which are those of frame i of the trajectory GROMACS writes, at the MD step init-step + i * subcycles (frame 0 is the starting configuration): 'order', the order parameter of the frame (with an order function), calculated with system.config naming the frame, (trr file, i), and 'thermo', the energies of the .edr record of the MD step of the frame.

Raises:
  • ValueError – Before GROMACS runs, if the mdp file starts the run at a negative time (_run_start()). An init-step that is not a multiple of subcycles is refused when the engine is set up (_refuse_init_step()).

  • RuntimeError – If a frame of the .trr is not at the MD step of its index, if mdrun writes another number of frames than steps, or if the .edr does not hold one record at the MD step of a frame (_get_frame_energies()).

classmethod mdp_template(engine_settings)

Return the name of the mdp file the engine reads.

This engine reads grompp.mdp whatever the engine section sets.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (string) – grompp.mdp.

class pyretis.engines.gromacs.GromacsRunner(cmd, trr_file, edr_file, exe_dir)

Bases: object

A helper class for running GROMACS.

This class handles the reading of the TRR on the fly and it is used to decide when to end the GROMACS execution.

Variables:
  • cmd (list of strings) – The command for executing GROMACS.

  • trr_file (string) – The GROMACS TRR file we are going to read.

  • edr_file (string) – A .edr file we are going to read.

  • exe_dir (string) – Path to where we are currently running GROMACS.

  • fileh (file object) – The current open file object.

  • running (None or object like subprocess.Popen) – The process running GROMACS.

  • bytes_read (integer) – The number of bytes read so far from the TRR file.

  • ino (integer) – The current inode we are using for the file.

  • stop_read (boolean) – If this is set to True, we will stop the reading.

  • SLEEP (float) – How long we wait after an unsuccessful read before reading again.

  • data_size (integer) – The size of the data (x, v, f, box, etc.) in the TRR file.

  • header_size (integer) – The size of the header in the TRR file.

SLEEP = 0.1
__del__()

Just stop execution and close file.

__enter__()

Start running GROMACS, for a context manager.

The with statement calls __exit__() only when this method has returned, so this method stops GROMACS (stop()) when the start raises, as when mdrun ends with an error before it creates its files: the error of the start is passed on once mdrun has ended, the slot of the worker in the registry of process_sessions is empty and the files are closed.

Returns:

out (object like GromacsRunner) – This runner, with mdrun started.

__exit__(exc_type, exc_val, exc_tb)

Just stop execution and close file for a context manager.

__init__(cmd, trr_file, edr_file, exe_dir)

Set the GROMACS command and the files we need.

Parameters:
  • cmd (list of strings) – The command for executing GROMACS.

  • trr_file (string) – The GROMACS TRR file we are going to read.

  • edr_file (string) – A .edr file we are going to read.

  • exe_dir (string) – Path to where we are currently running GROMACS.

_drain_remaining_frames()

Yield every complete frame left on disk from the boundary.

Called once mdrun has terminated cleanly. Because self.bytes_read is on a frame boundary, a final frame whose data finished flushing only as mdrun exited is read here – the incremental path and this drain deliver the same frame sequence for the same on-disk bytes.

Yields:

data (dict) – The data for each remaining complete frame, with the MD step of the frame (from its header) under 'step'.

_read_one_frame()

Read one whole frame from the TRR, or None if not ready.

The frame is the atomic unit of consumption: self.bytes_read marks the start of the next not-yet-read frame and is advanced only once the whole frame (header + data) is on disk and has been read. On any partial or torn read the file handle is seeked back to that boundary (see _reseek_after_partial_read()), so the invariant fileh.tell() == self.bytes_read on a frame boundary always holds. This makes the delivered frame a pure function of the bytes on disk, independent of when the reader samples the file.

The header is re-read (reset to None) on every call so a torn/partial header (EOFError) can never reuse a stale header from a previous frame, mirroring read_remaining_trr().

Returns:

data (dict or None) – The frame data, with the MD step of the frame (from its header) under 'step', or None if a complete frame is not yet available on disk.

_reseek_after_partial_read(frame_start)

Restore fileh to a frame boundary after a partial read.

A header read may advance self.fileh past frame_start before the frame turns out to be incomplete (its data has not been flushed yet), or the file may have been rotated (a new inode). In both cases the file handle must be put back exactly on the frame boundary so the next read – the incremental retry or the clean-exit drain – starts there, never mid-frame.

Parameters:

frame_start (integer) – The byte offset of the frame boundary to seek back to. This is always self.bytes_read (which is never advanced past a complete frame).

check_poll()

Check the current status of the running subprocess.

close()

Close the file, in case that is explicitly needed.

get_gromacs_frames()

Read the GROMACS TRR file on-the-fly.

Frames are yielded in trajectory order with no gaps or duplicates: self.bytes_read is only advanced across a whole frame, so it always sits on a frame boundary. When mdrun terminates, a non-zero exit raises loudly in check_poll(); a clean exit drains every complete frame still on disk from that boundary. Both the incremental read and the drain therefore return exactly the complete frames mdrun wrote, so the same input yields the same frame sequence on every run regardless of reader/writer timing.

Yields:

data (dict) – The data for each TRR frame, with the MD step of the frame (from its header) under 'step'.

start()

Start execution of GROMACS and wait for output file creation.

stop()

Stop the current GROMACS execution.

pyretis.engines.gromacs.get_data(fileh, header)

Read data from the TRR file.

Parameters:
  • fileh (file object) – The file we are reading.

  • header (dict) – The header read from the file. Contains sizes and what to read.

Returns:

  • data (dict) – The data read from the file.

  • data_size (integer) – The size of the data read.

pyretis.engines.gromacs.read_gromacs_gro_file(filename)

Read a single configuration GROMACS GRO file.

This method will read the first configuration from the GROMACS GRO file and return the data as given by read_gromacs_lines(). It will also explicitly return the matrices with positions, velocities and box size.

Parameters:

filename (string) – The file to read.

Returns:

  • frame (dict) – This dict contains all the data read from the file.

  • xyz (numpy.array) – The positions. The array is (N, 3) where N is the number of particles.

  • vel (numpy.array) – The velocities. The array is (N, 3) where N is the number of particles.

  • box (numpy.array) – The box dimensions.

pyretis.engines.gromacs.read_gromos96_file(filename)

Read a single configuration GROMACS .g96 file.

Parameters:

filename (string) – The file to read.

Returns:

  • rawdata (dict of list of strings) – This is the raw data read from the file grouped into sections. Note that this does not include the actual positions and velocities as these are returned separately.

  • xyz (numpy.array) – The positions.

  • vel (numpy.array) – The velocities.

  • box (numpy.array) – The simulation box.

pyretis.engines.gromacs.read_remaining_trr(filename, fileh, start)

Read remaining frames from the TRR file.

Parameters:
  • filename (string) – The file we are reading from.

  • fileh (file object) – The file object we are reading from.

  • start (integer) – The current position we are at.

Yields:
  • out[0] (dict) – The header read from the file

  • out[1] (dict) – The data read from the file.

  • out[2] (integer) – The size of the data read.

pyretis.engines.gromacs.read_trr_frame(filename, index)

Return a given frame from a TRR file.

pyretis.engines.gromacs.read_xvg_file(filename)

Return data in xvg file as numpy array.

pyretis.engines.gromacs.reopen_file(filename, fileh, inode, bytes_read)

Reopen a file if the inode has changed.

Parameters:
  • filename (string) – The name of the file we are working with.

  • fileh (file object) – The current open file object.

  • inode (integer) – The current inode we are using.

  • bytes_read (integer) – The position we should start reading at.

Returns:

  • out[0] (file object or None) – The new file object.

  • out[1] (integer or None) – The new inode.

pyretis.engines.gromacs.write_gromacs_gro_file(outfile, txt, xyz, vel=None, box=None)

Write configuration in GROMACS GRO format.

Parameters:
  • outfile (string) – The name of the file to create.

  • txt (dict of lists of strings) – This dict contains the information on residue-numbers, names, etc. required to write the GRO file.

  • xyz (numpy.array) – The positions to write.

  • vel (numpy.array, optional) – The velocities to write.

  • box (numpy.array, optional) – The box matrix.

pyretis.engines.gromacs.write_gromos96_file(filename, raw, xyz, vel, box=None)

Write configuration in GROMACS .g96 format.

Parameters:
  • filename (string) – The name of the file to create.

  • raw (dict of lists of strings) – This contains the raw data read from a .g96 file.

  • xyz (numpy.array) – The positions to write.

  • vel (numpy.array) – The velocities to write.

  • box (numpy.array, optional) – The box matrix.

pyretis.engines.gromacs_steps module

A GROMACS external MD integrator interface.

This module defines a class for using GROMACS as an external engine.

Important classes defined here

GromacsEngineSteps (GromacsEngineSteps)

A class responsible for interfacing GROMACS by relaunching the executable once per order-parameter point (the slower, relaunch implementation; the canonical streaming engine lives in pyretis.engines.gromacs).

pyretis.engines.gromacs_steps.CONFIG_SUFFIXES = ('.g96', '.gro')

Configuration file suffixes. A .g96 file holds one configuration and a .gro file one or more; _extract_frame selects a frame of either by its index.

pyretis.engines.gromacs_steps.GROMACS_PCOUPL = ('no', 'berendsen', 'isotropic', 'crescale', 'parrinellorahman', 'mttk')

The values of the mdp key pcoupl grompp accepts, in the form mdp_option() gives them. grompp reads isotropic as berendsen.

pyretis.engines.gromacs_steps.GROMACS_TCOUPL = ('no', 'berendsen', 'yes', 'nosehoover', 'andersen', 'andersenmassive', 'vrescale')

The values of the mdp key tcoupl grompp accepts, in the form mdp_option() gives them. grompp reads yes as berendsen.

class pyretis.engines.gromacs_steps.GromacsEngineSteps(gmx, mdrun=None, input_path=None, timestep=None, subcycles=None, exe_path='/home/enrico/cache/twoway-retis/wt2/docs', maxwarn=0, gmx_format='g96', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', masses=False, conf=None, template='grompp.mdp', top='topol.top')

Bases: ExternalMDEngine

A class for interfacing GROMACS.

This class defines the interface to GROMACS.

The configuration format handed between steps is INTERNAL_CONFIG_FORMAT, independent of the gmx_format setting. Input is read in whichever format each file actually is.

Variables:
  • gmx (string) – The command for executing GROMACS. Note that we are assuming that we are using version 5 (or later) of GROMACS.

  • mdrun (string) – The command for executing GROMACS mdrun. In some cases, this executable can be different from gmx mdrun.

  • mdrun_c (string) – The command for executing GROMACS mdrun when continuing a simulation. This is derived from the mdrun command.

  • input_path (string) – The directory where the input files are stored. The engine only reads from it.

  • work_path (string) – A directory of this engine’s own in the run directory (exe_path), holding the files it derives from the input: the staged configuration converted to the other format, pyretis.mdp and the .tpr. It is removed with the engine.

  • subcycles (int,) – The number of simulation steps of the external engine for each PyRETIS step (e.g. interaction between the softwares frequency)

  • exe_path (string, optional) – The absolute path at which the main PyRETIS simulation will be run.

  • maxwarn (integer) – Setting for the GROMACS grompp -maxwarn option.

  • write_vel (boolean, optional) – True if we want to output the velocities.

  • write_force (boolean, optional) – True if we want to output the forces.

  • domain_decomp (boolean, optional) – Whether gromacs uses domain decomposition (DD) or not. This does not set domain decomposition. The user should know whether DD is executed or not.

  • temperature (float) – The temperature (K) the mdp file states (read_gromacs_temperatures()): gen-temp, the temperature of the velocities GROMACS draws, and the ref-t of each tc-grps group of a run coupled to a thermostat, which must all be equal.

  • beta (float) – The inverse temperature 1 / (k_B T) in mol/kJ, with the k_B of the engine, kb.

  • engine_temperatures (object like EngineTemperatures) – The temperatures read from the mdp file.

  • gen_temp_key (string) – The key the mdp file sets gen-temp with (mdp_key_as_written()), under which the velocity draw of velocity_generation = "engine" writes temperature.

  • init_step (int) – The init-step of the mdp file (0 if it sets none), the MD step each GROMACS run of the engine starts at: a multiple of subcycles (_refuse_init_step()).

INTERNAL_CONFIG_FORMAT = 'g96'

The configuration format the engine writes and reads back between steps. gro stores three decimals per coordinate, 1e-3 nm, which can move a cutoff- or threshold-based order parameter across a write/read round trip; g96 carries enough digits that the round trip is exact. Input in either format is read.

SUBCYCLE_MDP_KEYS = ('nsteps', 'nstxout', 'nstvout', 'nstfout', 'nstlog', 'nstcalcenergy', 'nstenergy')

The MDP keys subcycles is written into. Changing subcycles moves the trajectory, the energy record and the log cadence together, which is what makes a temporary change (multiresolution wire fencing) a change of more than resolution.

__init__(gmx, mdrun=None, input_path=None, timestep=None, subcycles=None, exe_path='/home/enrico/cache/twoway-retis/wt2/docs', maxwarn=0, gmx_format='g96', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', masses=False, conf=None, template='grompp.mdp', top='topol.top')

Set up the GROMACS engine.

Parameters:
  • gmx (string) – The GROMACS executable.

  • mdrun (string) – The GROMACS mdrun executable.

  • input_path (string) – The absolute path to where the input files are stored.

  • timestep (float) – The time step used in the GROMACS MD simulation.

  • subcycles (integer) – The number of steps each GROMACS MD run is composed of.

  • exe_path (string, optional) – The absolute path at which the main PyRETIS simulation will be run. The engine creates its work_path in it.

  • maxwarn (integer, optional) – Setting for the GROMACS grompp -maxwarn option.

  • gmx_format (string, optional) – 'g96' or 'gro'; another value raises ValueError. The engine reads each configuration in the format of its file and hands configurations between steps in INTERNAL_CONFIG_FORMAT; 'gro' is warned about.

  • write_vel (boolean, optional) – Determines if GROMACS should write velocities or not.

  • write_force (boolean, optional) – Determines if GROMACS should write forces or not.

  • domain_decomp (boolean, optional) – Whether domain decomposition (DD) is executed by GROMACS or not. User should know if this happens or not.

  • velocity_generation (string, optional) – How shooting-move velocities are generated. "engine" (default) delegates to GROMACS (a zero-step gen_vel run, which removes the centre-of-mass motion, so it requires zero_momentum = true); "maxwell" draws them in Python from a Maxwell-Boltzmann distribution via the injected random generator at the temperature of the mdp file (one reproducible stream, g96 format only, requires masses).

  • masses (list or string, optional) – The masses of the particles, in g/mol, for the "maxwell" draw, one per particle of the configuration: a list of numbers, or the name of a file in input_path that lists them separated by spaces, commas or line breaks (_load_masses()). Only required when velocity_generation == "maxwell".

  • conf (string, optional) – The starting configuration file in input_path (e.g. ‘conf.gro’). When it is not given, the configuration is resolved from the conf.g96 and conf.gro staged there (_find_staged_conf()).

  • template (string, optional) – The GROMACS mdp template (default is ‘grompp.mdp’).

  • top (string, optional) – The GROMACS topology file (default is ‘topol.top’).

_check_mass_count(npart, conf)

Refuse masses that are not one per particle of the configuration.

Engines without masses (velocity_generation = "engine") pass.

Parameters:
  • npart (integer) – The number of particles of the configuration the engine starts from.

  • conf (string) – The name of that configuration, for the message.

Raises:

ValueError – If self.masses does not hold one mass per particle.

_convert_configuration(source, name)

Convert a staged configuration into the work directory.

gmx editconf writes the configuration in the format the extension of name selects. It runs in work_path, which also receives its log.

Parameters:
  • source (string) – The staged configuration file.

  • name (string) – The file name of the converted configuration.

Returns:

out (string) – The path to the converted configuration.

_draw_velocities_maxwell(system, vel_settings, rgen)

Draw shooting velocities in Python (Maxwell-Boltzmann).

The g96 frame’s positions are kept; only the velocity block is redrawn from the injected random generator. system is updated in place (config + kinetic energy) and the potential energy is left unchanged (a velocity draw does not change the configuration).

Parameters:
  • system (object like System) – The state whose velocities we redraw.

  • vel_settings (dict) – Velocity-modification settings; zero_momentum requests a zero linear-momentum reset (a missing key means False).

  • rgen (object like RandomGenerator) – The velocity random generator, injected explicitly.

Returns:

float – The new kinetic energy.

_ensure_tpr()

Build the construction “.tpr” on first use (lazily).

The construction “.tpr” is consumed by the energy rerun of a relaunch propagation and by the trjconv frame-extraction branches (non-trr/non-g96 input and the domain-decomposition pass). Deferring it here lets the engine be constructed without running grompp; a “.tpr” built later holds the same inputs (its bytes differ only in a few process-dependent header bytes), so the run output does not depend on when it is built. The preprocessor is always run in work_path (where the “.tpr” lives), restoring exe_dir afterwards.

_execute_grompp(mdp_file, config, deffnm)

Execute the GROMACS preprocessor.

Parameters:
  • mdp_file (string) – The path to the mdp file.

  • config (string) – The path to the GROMACS config file to use as input.

  • deffnm (string) – A string used to name the GROMACS files.

Returns:

out_files (dict) – This dict contains files that were created by the GROMACS preprocessor.

_execute_grompp_and_mdrun(config, deffnm)

Execute GROMACS grompp and mdrun.

Here we use the input file given in the input directory.

Parameters:
  • config (string) – The path to the GROMACS config file to use as input.

  • deffnm (string) – A string used to name the GROMACS files.

Returns:

out_files (dict of strings) – The files created by this command.

_execute_mdrun(tprfile, deffnm)

Execute GROMACS mdrun.

This method is intended as the initial gmx mdrun executed. That is, we here assume that we do not continue a simulation.

Parameters:
  • tprfile (string) – The .tpr file to use for executing GROMACS.

  • deffnm (string) – To give the GROMACS simulation a name.

Returns:

out_files (dict) – This dict contains the output files created by mdrun. Note that we here hard code the file names.

_execute_mdrun_continue(tprfile, cptfile, deffnm)

Continue the execution of GROMACS.

Here, we assume that we have already executed gmx mdrun and that we are to append and continue a simulation.

Parameters:
  • tprfile (string) – The .tpr file which defines the simulation.

  • cptfile (string) – The last checkpoint file (.cpt) from the previous run.

  • deffnm (string) – To give the GROMACS simulation a name.

Returns:

out_files (dict) – The output files created/appended by GROMACS when we continue the simulation.

_extend_and_execute_mdrun(tpr_file, cpt_file, deffnm)

Extend GROMACS and execute mdrun.

Parameters:
  • tpr_file (string) – The location of the “current” .tpr file.

  • cpt_file (string) – The last checkpoint file (.cpt) from the previous run.

  • deffnm (string) – To give the GROMACS simulation a name.

Returns:

out_files (dict) – The files created by GROMACS when we extend.

_extend_gromacs(tprfile, time)

Extend a GROMACS simulation.

Parameters:
  • tprfile (string) – The file to read for extending.

  • time (float) – The time (in ps) to extend the simulation by.

Returns:

out_files (dict) – The files created by GROMACS when we extend.

_extract_frame(traj_file, idx, out_file)

Extract a frame from a GROMACS trajectory or configuration file.

A frame of a .trr, .xtc or .trj trajectory, or of a .gro or .g96 configuration file, is written to a .gro or .g96 out_file in the format the name of out_file gives. A configuration file with another destination, or a source of another format, is converted with gmx trjconv.

Parameters:
  • traj_file (string) – The GROMACS file to open.

  • idx (integer) – The frame number we look for.

  • out_file (string) – The file to dump to.

Raises:

ValueError – If a configuration file holds fewer than idx + 1 frames.

Note

This will only properly work if the frames in the input trajectory are uniformly spaced in time.

_find_staged_conf()

Return the staged configuration file name to start from.

The configuration is resolved by staged_configuration(): the one of conf.g96 and conf.gro staged in the input directory, conf.g96 when both are staged and hold the same configuration, and conf.g96 when neither is staged, leaving the missing-file diagnostic to look_for_input_files().

Returns:

out (string) – The configuration file name, relative to input_path.

Raises:

ValueError – If conf.g96 and conf.gro are both staged and hold different configurations.

static _gen_vel_seed(rgen)

Draw a reproducible GROMACS gen_seed for an aimless kick.

The engine-mode aimless velocity draw regenerates the shooting point’s velocities with a zero-step GROMACS gen_vel run. That draw is seeded by the mdp gen_seed keyword; the GROMACS default of -1 is a time-random seed, so every shooting move would kick the point with different velocities and the whole sampled path would change from run to run. Drawing the seed from the injected velocity random generator (rgen, the same generator the Python Maxwell draw consumes) pins the kick to the controlled random stream, mirroring _ld_seed(), so the generated velocities – hence the propagated path – are byte-reproducible.

Parameters:

rgen (object like RandomGenerator or None) – The velocity random generator injected into modify_velocities(). When it is None (no controlled generator is wired) we fall back to a fixed seed so the result is at least deterministic.

Returns:

seed (int) – A positive integer seed in [1, 2147483646].

_grompp_and_mdrun_run(config, deffnm, gmx_steps)

Preprocess and run a single mdrun of gmx_steps steps.

Unlike _execute_grompp_and_mdrun() (which uses nsteps = subcycles), this overrides nsteps so the whole integrate trajectory is produced by one continuous mdrun with no checkpoint-restart. The resulting .edr is therefore free of the corrupt potential energies of checkpoint continuations (see _recompute_energies_via_rerun()).

Parameters:
  • config (string) – The path to the GROMACS config file to use as input.

  • deffnm (string) – A string used to name the GROMACS files.

  • gmx_steps (integer) – The total number of integration steps for the single run.

Returns:

out_files (dict of strings) – The files created by this command.

static _input_folder(engine_settings)

Return the folder of the input files of an engine section.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (string) – input_path relative to exe_path, the folder the engine reads its input files from when it is created.

Raises:

ValueError – If the section sets no input_path.

classmethod _input_mdp(engine_settings)

Return the mdp file an engine section names.

The file is looked up as the engine looks it up when it is created: the file mdp_template() names, in input_path relative to exe_path.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (string) – The path of the mdp file.

classmethod _input_mdp_present(engine_settings)

Return whether an engine section names an mdp file that is there.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (boolean) – True when the section sets input_path and that folder holds a file _input_mdp() can take (input_file_present()).

_ld_seed()

Draw a reproducible GROMACS ld-seed from the engine rgen.

The GROMACS stochastic integrators (sd, bd) and the stochastic thermostats (tcoupl = v-rescale, andersen, andersen-massive) draw their random numbers from ld-seed; left unset GROMACS defaults it to -1 (a time-random seed), which makes each segment irreproducible. Drawing the seed from the engine’s integration random generator (self.rgen, wired by the infinite-swapping scheduler) pins it to the controlled random stream, mirroring the LAMMPS thermostat-seed injection so such GROMACS segments are byte-reproducible. When no engine rgen is present we fall back to a fixed seed so the result is at least deterministic. A run without random numbers (md or md-vv without a stochastic thermostat) does not read ld-seed.

Returns:

seed (int) – A positive integer seed in [1, 2147483646].

_load_masses(masses)

Load the particle masses of the Python Maxwell-Boltzmann draw.

The masses are numbers in g/mol, each finite and positive: a list of numbers, or the name of a file in input_path whose masses are separated by spaces, commas or line breaks. The count is checked against the configuration by _check_mass_count().

Parameters:

masses (list or string) – The list of masses, or the name of the file that lists them.

Returns:

numpy.ndarray – The masses reshaped to (npart, 1).

Raises:
  • ValueError – If no masses are given, if masses is neither a list nor a file name, if an entry is not a number (a boolean or a string in the list, a word in the file), or if a mass is not finite and positive.

  • FileNotFoundError – If the file is not in input_path.

_mdp_overrides(write_vel, write_force)

Return the MDP settings PyRETIS imposes on the user’s input.

Parameters:
  • write_vel (boolean) – Whether GROMACS should write velocities.

  • write_force (boolean) – Whether GROMACS should write forces.

Returns:

out (dict) – The keys to override, and their values. continuation = no makes an md-vv run start from the velocities of its configuration as those at its time; with yes it takes them as those half a time step before.

static _mdp_path_sampling_problem(template)

Return why a path-sampling run cannot use an mdp file.

Parameters:

template (string) – The path of the mdp template.

Returns:

out (string or None) – The reason path_sampling_problem() gives, or None for integrator = md-vv. A refusal ends with what the md tasks do with the mdp file (_gromacs_md_tasks()).

static _modify_input(sourcefile, outputfile, settings, delim='=', key_name=<function mdp_key_name>)

Write an mdp file: a template with the given keys set.

A key of the template is replaced when grompp reads it as a key of settings (mdp_key_name(): case, - and _, and the old names), and keeps its spelling; the keys the template does not hold are added at its end. The written file holds each key once, as grompp requires.

Parameters:
  • sourcefile (string) – The mdp template.

  • outputfile (string) – The mdp file to write.

  • settings (dict) – The keys to set, and their values.

  • delim (string, optional) – The delimiter of keys and values.

  • key_name (callable, optional) – Gives the name grompp reads a key as; the default is mdp_key_name().

_prepare_shooting_point(input_file, rgen=None)

Create the initial configuration for a shooting move.

This creates a new initial configuration with random velocities. Here, the random velocities are obtained by running a zero-step GROMACS simulation.

Parameters:
  • input_file (string) – The input configuration to generate velocities for.

  • rgen (object like RandomGenerator or None, optional) – The velocity random generator for drawing a reproducible GROMACS gen_seed (see _gen_vel_seed()). With the GROMACS default of gen_seed = -1 the draw is time-random and the shooting move – hence the whole sampled path – would differ on every run.

Returns:

  • output_file (string) – The name of the file created.

  • energy (dict) – The energy terms read from the GROMACS .edr file.

_propagate_from(name, path, system, ens_set, msg_file, reverse=False)

Propagate with GROMACS from the current system configuration.

Here, we assume that this method is called after the propagate() has been called in the parent. The parent is then responsible for reversing the velocities and also for setting the initial state of the system.

Parameters:
  • name (string) – A name to use for the trajectory we are generating.

  • path (object like pyretis.core.path.PathBase) – This is the path we use to fill in phase-space points.

  • system (object like System) – The system object gives the initial state for the integration. The order function is injected on the engine (self.order_function).

  • ens_set (dict) – Ensemble settings. It contains:

    • interfaces: list of floats These interfaces define the stopping criterion.

  • msg_file (object like FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.

  • reverse (boolean, optional) – If True, the system will be propagated backward in time.

Returns:

  • success (boolean) – This is True if we generated an acceptable path.

  • status (string) – A text description of the current status of the propagation.

_read_configuration(filename)

Read output from GROMACS .g96/gro files.

Parameters:

filename (string) – The file to read the configuration from.

Returns:

  • box (numpy.array) – The box dimensions.

  • xyz (numpy.array) – The positions.

  • vel (numpy.array) – The velocities.

static _read_init_step(mdp_file)

Return the init-step of an mdp file.

Parameters:

mdp_file (string) – The mdp file.

Returns:

out (integer) – The init-step the file sets, as grompp reads the key (read_mdp_settings()), or 0, the GROMACS default, if the file does not set it.

Raises:

ValueError – If the file sets an init-step that is not an integer, which grompp refuses.

_read_masses_file(masses, source)

Return the masses a file of [engine] masses lists.

Parameters:
  • masses (string) – The file name [engine] masses gives.

  • source (string) – The file, in input_path.

Returns:

list of floats – The masses, in the order of the file; spaces, commas and line breaks separate them.

Raises:
  • FileNotFoundError – If the file is not in input_path.

  • ValueError – If an entry of the file is not a number.

_recompute_energies_via_rerun(tprfile, trrfile, name)

Recompute per-frame potential energy with mdrun -rerun.

The relaunch propagation accumulates its .edr through repeated convert-tpr -extend + mdrun -cpi -append continuations. The kinetic energy and temperature written there are correct, but the potential energy of every segment after the first is corrupt. Because the .trr frames (positions) ARE correct, the potential is recovered exactly by re-evaluating the trajectory in a single mdrun -rerun against one consistent .tpr; this reproduces the streaming GromacsEngine and plain GROMACS byte-for-byte. -rerun does not integrate velocities, so the resulting .edr holds only the potential terms (no kinetic energy or temperature); the caller keeps those from the appended .edr.

Parameters:
  • tprfile (string) – A .tpr consistent with the trajectory topology.

  • trrfile (string) – The completed .trr (positions) to re-evaluate, relative to self.exe_dir.

  • name (string) – The propagation name. The rerun writes to {name}_rerun.* so it never clobbers the source trajectory.

Returns:

energy (dict of numpy.ndarray) – The energies read from the rerun .edr. The potential entry is the corrected per-frame potential energy.

_refuse_init_step(run=False)

Refuse an init-step that is not a multiple of subcycles.

GROMACS gives step s of a run the MD step init-step + s, with the init-step of the mdp file (init_step), and writes a frame to the .trr and a record to the .edr at the MD steps that are multiples of nstxout and nstenergy, which the engine sets to subcycles. With an init-step that is not a multiple of subcycles, the first frame of a run is not its start: the first phase point of a leg would not be its shooting point, which no leg would hold, and the first step of an MD run would not be its starting configuration. The engine refuses such an init-step when it is set up, and before each run whose output strides it sets from the current subcycles: multiresolution wire fencing runs its sub-paths with the subcycles of [tis] mwf_subcycle_small_by_ensemble or mwf_subcycle_small (by default [engine] subcycles // 5) in their place.

Parameters:

run (boolean, optional) – False (the default) when the engine is set up, with the subcycles of its section; True before a GROMACS run, whose subcycles (a multiple of which init-step is when the engine is set up) differ only for a sub-path of multiresolution wire fencing. The message says what to set in each case.

Raises:

ValueError – If init-step is not a multiple of subcycles.

_remove_gromacs_backup_files(dirname)

Remove files GROMACS has backed up.

These are files starting with a ‘#’

Parameters:

dirname (string) – The directory where we are to remove files.

_reverse_velocities(filename, outfile)

Reverse velocity in a given snapshot.

Parameters:
  • filename (string) – The configuration to reverse velocities in.

  • outfile (string) – The output file for storing the configuration with reversed velocities.

_seeded_input(name, extra=None)

Create a per-segment mdp with a fresh ld-seed injected.

The relaunch engine builds its pyretis.mdp once at construction, so a varying per-segment ld-seed must be written into a fresh mdp before each grompp. This copies the one-time pyretis.mdp to {name}.mdp in the run directory with the seed updated (see _ld_seed()).

The keys in SUBCYCLE_MDP_KEYS are also rewritten from the current subcycles. Multiresolution wire fencing changes subcycles on a live engine, and ext_time follows that change; the segment length and the .trr/.edr strides must follow it too, so that each extension writes one frame and one energy record. An init-step that is not a multiple of the current subcycles is refused (_refuse_init_step()).

Parameters:
  • name (string) – A name used for the per-segment mdp file.

  • extra (dict, optional) – Additional keyword: value mdp settings, applied last so they override both the ld-seed and the subcycle keys (e.g. an nsteps override for the single continuous integrate run).

Returns:

mdp_file (string) – The path to the per-segment mdp file with the seed injected.

Raises:

ValueError – If init-step is not a multiple of the current subcycles, before the mdp file is written.

_subcycle_settings(write_vel, write_force)

Return the MDP keys set from the current subcycles.

Parameters:
  • write_vel (boolean) – Whether GROMACS should write velocities. If not, nstvout is 0.

  • write_force (boolean) – Whether GROMACS should write forces. If not, nstfout is 0.

Returns:

out (dict) – Each key of SUBCYCLE_MDP_KEYS with its value.

_trajectory_filename(name)

GROMACS writes frames to a .trr regardless of self.ext.

self.ext is the configuration format (gro/g96); the trajectory the propagation appends frames to is the .trr named after the propagation name (see out_files['trr']).

_trr_frame_order(system, traj_file, index, offset)

Calculate the order parameter of a frame of a .trr file.

The positions, the velocities and the box of the system are set to those of the frame, and the velocities are reversed when system.vel_rev is True, as in pyretis.engines.external.ExternalMDEngine.calculate_order().

Parameters:
  • system (object like System) – The system the order function sees.

  • traj_file (string) – The .trr file that holds the frame.

  • index (integer) – The index of the frame in traj_file.

  • offset (integer) – The byte offset at which the frame starts in traj_file, where the frame before it ended (0 for the first frame).

Returns:

  • out[0] (list of floats) – The order parameter(s) of the frame.

  • out[1] (integer) – The byte offset at which the next frame starts.

default_units = 'gromacs'
dump_config(config, deffnm='conf')

Write a configuration to a file in the engine’s own format.

A configuration (filename, None) is a single frame. When that file is a configuration in the other GROMACS format – a system built from an input directory staged with .gro while the engine works in .g96 – it is converted through self.top, as _extract_frame() converts a single staged frame, so the file GROMACS reads matches its name. Every other configuration is handled by ExternalMDEngine.dump_config().

Parameters:
  • config (tuple) – The configuration given as (filename, index).

  • deffnm (string, optional) – The base name for the file we dump to.

Returns:

out (string) – The file name we dumped to.

property ext_time

The simulation time one trajectory extension covers, in ps.

Derived from the current subcycles: multiresolution wire fencing changes subcycles on a live engine through multires_wf._temporary_subcycles to shoot a sub-segment at a finer stride, so an extension taken during a fine segment runs for the fine segment’s time.

Note that subcycles drives more than this. It is written into seven MDP keys – nsteps, nstxout, nstvout, nstfout, nstlog, nstcalcenergy and nstenergy – so a temporary change alters the trajectory, the energy record and the log cadence together, not just the output stride.

Returns:

out (float) – timestep * subcycles.

classmethod get_default_units(settings=None)

Return the default unit system for the GROMACS engine.

Parameters:

settings (dict, optional) – Full simulation settings or engine settings. This argument is ignored for the GROMACS engine.

Returns:

out (string) – The default unit system for the GROMACS engine.

get_energies(energy_file, begin=None, end=None)

Return energies from a GROMACS run.

Parameters:
  • energy_file (string) – The file to read energies from.

  • begin (float, optional) – Select the time for the first frame to read.

  • end (float, optional) – Select the time for the last frame to read.

Returns:

energy (dict of numpy.arrays) – The energies read from the produced GROMACS xvg file.

classmethod input_path_sampling_problem(engine_settings)

Return why a path-sampling run cannot use the mdp file of a section.

The mdp file is looked up as read_input_temperatures() looks it up, and its integrator is checked as path_sampling_problem() checks it.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (string or None) – The reason, or None for integrator = md-vv. None for a section without an mdp file to read (_input_mdp_present()): the run reports the missing file where it reads the temperature of the section (read_input_temperatures()) or creates the engine.

integrate(system, order_function, steps, thermo='full')

Perform several integration steps.

This method will perform several integration steps using GROMACS. It will also calculate order parameter(s) and energy terms if requested.

Parameters:
  • system (object like System) – The system object gives the initial state for the integration. With an order function, its configuration is the final configuration of the run when the integration is done.

  • order_function (object like OrderParameter or None) – An order function can be specified if we want to calculate the order parameter along with the simulation.

  • steps (integer) – The number of steps we are going to perform. Note that we do not integrate on the first step (e.g. step 0) but we do obtain the other properties. This is to output the starting configuration.

  • thermo (string, optional) – Select the thermodynamic properties we are to calculate.

Yields:

results (dict) – The results from a MD step. This contains the state of the system and order parameter(s) and energies (if calculated).

classmethod mdp_template(engine_settings)

Return the name of the mdp file the engine reads.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (string) – The template of the section, grompp.mdp when it sets none.

modify_velocities(system, vel_settings, rgen)

Modify the velocities of the current state.

This method will modify the velocities of a time slice.

Parameters:
  • system (object like System) – This is the system that contains the particles we are investigating.

  • vel_settings (dict) – It contains:

    • sigma_v: numpy.array, optional Negative values select aimless shooting. Zero or positive values set the standard deviation, one for each particle, for soft velocity perturbations.

    • zero_momentum: boolean, optional If True, we reset the linear momentum to zero after generating. A missing key means False. In "engine" mode GROMACS gen_vel removes the centre-of-mass motion of the velocities it generates, so this mode requires True.

    • rescale: float, optional The energy to re-scale the drawn velocities to, the [tis] rescale_energy. GROMACS does not re-scale, so a positive value is refused in both modes (refuse_energy_rescale()).

  • rgen (object like RandomGenerator) – The velocity random generator. In "maxwell" mode it draws the velocities directly (the Python draw); in the default "engine" mode it seeds the GROMACS gen_vel draw via a reproducible gen_seed (see _gen_vel_seed()). Both modes therefore consume the controlled random stream, so the kick is byte-reproducible.

Returns:

  • dek (float) – The change in the kinetic energy.

  • kin_new (float) – The new kinetic energy.

Raises:

NotImplementedError – If energy re-scaling or a soft velocity change is requested, or if zero_momentum is False in "engine" mode.

path_sampling_problem()

Return why a path-sampling run cannot use this engine.

The integrator of the mdp template (integrator, GROMACS’s default md when it is not set; grompp reads the value ignoring case, - and _) must be md-vv: velocity Verlet stores the velocities at the time of the positions. md and sd are leap-frog integrators, which store them half a time step away from the positions; bd integrates without velocities (Brownian dynamics, which a path-sampling run runs with the internal Langevin engine and high_friction); md-vv-avek takes the velocities of the configuration a run starts from as those half a time step before it; the other integrators run no dynamics. With md-vv, the thermostat and the barostat must be ones a path-sampling run accepts (gromacs_coupling_problem()).

Returns:

out (string or None) – The reason, or None for integrator = md-vv with a coupling a path-sampling run accepts.

path_sampling_warnings()

Return why a path-sampling run with this engine is not exact.

The thermostat and the barostat of the mdp template, with the time step of the engine (gromacs_coupling_warnings()).

Returns:

out (list of strings) – The warnings; empty when the template selects no such scheme.

classmethod read_input_temperatures(engine_settings)

Read the temperatures of the mdp file an engine section names.

The mdp file is looked up as the engine looks it up when it is created (_input_mdp()).

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (object like EngineTemperatures) – The temperatures read_gromacs_temperatures() reads.

static rename_energies(gmx_energy)

Rename GROMACS energy terms to PyRETIS convention.

static select_energy_terms(terms)

Select energy terms to extract from GROMACS.

Parameters:

terms (string) – This string will name the terms to extract: 'full' or 'path'; any other value selects 'path'.

set_mdrun(md_items)

Configure the per-worker mdrun command and execution directory.

Extends the base (which sets exe_dir): the infinite-swapping scheduler points each worker at its own wmdrun launch command, so build self.mdrun / self.mdrun_c from it. Without a wmdrun in md_items, the command given at construction is left untouched.

Parameters:

md_items (dict) – The run items of the move. exe_dir (set by the base) and the optional wmdrun base mdrun command of the worker.

step(system, name)

Perform a single step with GROMACS.

Parameters:
  • system (object like System) – The system we are integrating.

  • name (string) – To name the output files from the GROMACS step.

Returns:

out (string) – The name of the output configuration, obtained after completing the step.

temperature_input_keys = ('input_path',)
temperature_keys = 'gen-temp, and the ref-t of each tc-grps group of a run coupled to a thermostat, in the mdp file'
temperature_source = 'input'
unmarked_section_temperature = True
pyretis.engines.gromacs_steps.MASSES_FORMS = 'the masses of the particles, [engine] masses, in g/mol, one per particle: a list of numbers, or the name of a file in input_path that lists them separated by spaces, commas or line breaks.'

The forms of [engine] masses, as the refusals name them.

pyretis.engines.gromacs_steps.MDP_OLD_NAMES = {'nstxtcout': 'nstxoutcompressed', 'unconstrainedstart': 'continuation'}

The old names of the mdp keys PyRETIS sets, which grompp reads as the key of the current name and refuses together with it, in the form mdp_key_name() gives them.

pyretis.engines.gromacs_steps.NSTCOUPLE_DEFAULT_MOST = 100

GROMACS 2025.4’s coupling interval for nsttcouple = -1 and nstpcouple = -1 when the time constant allows it, and when no time constant is positive.

pyretis.engines.gromacs_steps.NSTCOUPLE_STEPS_PER_TAU = {'crescale': 25, 'vrescale': 5}

GROMACS 2025.4’s fewest time steps per tau-t (tcoupl = v-rescale) and per tau-p (pcoupl = c-rescale) at which its grompp couples every time step when nsttcouple or nstpcouple is -1: it couples every int(tau / (steps * dt)) steps, at least 1 and at most 100, reduced to a divisor of 100, with tau the shortest positive tau-t or tau-p and dt the time step of the run. The coupling interval is above 1 when tau is at least twice steps * dt. grompp resolves -1 by the rule of its GROMACS version: another version can choose another interval.

pyretis.engines.gromacs_steps.PATH_SAMPLING_REFUSED_PCOUPL = {'berendsen': 'the Berendsen barostat, a deterministic rescaling of the box that is not time reversible and carries the pressure of the last coupling step', 'isotropic': 'the Berendsen barostat (grompp reads isotropic as berendsen), a deterministic rescaling of the box that is not time reversible and carries the pressure of the last coupling step', 'mttk': 'the MTTK barostat, whose box velocity and thermostat variables carry a memory from one time step to the next', 'parrinellorahman': 'the Parrinello-Rahman barostat, whose box velocity carries a memory from one time step to the next'}

deterministic, and with a memory between time steps or without time reversibility.

Type:

The barostats a path-sampling run refuses

pyretis.engines.gromacs_steps.PATH_SAMPLING_REFUSED_TCOUPL = {'berendsen': 'the Berendsen thermostat, a deterministic rescaling of the velocities that is not time reversible', 'nosehoover': 'the Nose-Hoover thermostat (a chain with md-vv), a deterministic thermostat whose friction variables carry a memory from one time step to the next', 'yes': 'the Berendsen thermostat (grompp reads yes as berendsen), a deterministic rescaling of the velocities that is not time reversible'}

deterministic, and with a memory between time steps or without time reversibility.

Type:

The thermostats a path-sampling run refuses

pyretis.engines.gromacs_steps.TAU_P_DEFAULT = 5.0

GROMACS 2025.4’s tau-p, in ps, which its grompp takes when an mdp file does not set it.

pyretis.engines.gromacs_steps._COUPLING_KEYS = {'crescale': ('pcoupl', 'nstpcouple'), 'vrescale': ('tcoupl', 'nsttcouple')}

The mdp key that selects each coupling of NSTCOUPLE_STEPS_PER_TAU, and the key of its interval.

pyretis.engines.gromacs_steps._GROMACS_PIECE_START = 'Every new piece of trajectory of a path-sampling run (the backward and the forward piece of a shooting move, the extension of a path) starts GROMACS afresh from a stored frame (positions, velocities and box)'

What a path-sampling run with GROMACS starts each piece of trajectory from, for the messages.

pyretis.engines.gromacs_steps._andersen_massive_warning(settings, template, tcoupl, time_step)

Return the warning of the massive Andersen thermostat.

Parameters:
  • settings (dict of string) – The mdp settings (read_mdp_settings()).

  • template (string) – The mdp file.

  • tcoupl (string) – The value of tcoupl as the template writes it.

  • time_step (float) – The time step of the run, in ps: the [engine] timestep, which every run writes as dt.

Returns:

out (string) – The warning, with the randomisation interval round(tau-t / dt) of the first group, as GROMACS takes it.

pyretis.engines.gromacs_steps._coupled_taus(settings, scheme, template)

Return the time constants of the groups a coupling acts on.

Parameters:
  • settings (dict of string) – The mdp settings (read_mdp_settings()).

  • scheme (string) – 'vrescale' or 'crescale'.

  • template (string) – The mdp file, for the message.

Returns:

out (list of float) – The time constants in ps: the tau-t of each group with tau-t 0 or above (mdrun couples no group with a negative tau-t), or the tau-p (TAU_P_DEFAULT when the template does not set it).

pyretis.engines.gromacs_steps._coupling_interval_problem(settings, template, tcoupl, pcoupl)

Return why a path-sampling run refuses a coupling interval.

grompp resolves nsttcouple = -1, and nstpcouple -1 or below, by the rule of its GROMACS version (GROMACS 2025.4: from the time constants, _resolved_interval()), and grompp of GROMACS 2025.4 keeps every other value. tcoupl = v-rescale with nsttcouple = 0 never acts, while its reference temperature is read as the temperature of the run; with nsttcouple below -1, mdrun couples with a negative interval and the velocities become not a number. pcoupl = c-rescale with nstpcouple = 0 never acts.

Parameters:
  • settings (dict of string) – The mdp settings (read_mdp_settings()).

  • template (string) – The mdp file, for the message.

  • tcoupl (string) – The value of tcoupl, as the template writes it.

  • pcoupl (string) – The value of pcoupl, as the template writes it.

Returns:

out (string or None) – The reason, naming each interval, or None.

pyretis.engines.gromacs_steps._coupling_interval_warning(settings, scheme, template, time_step)

Return the warning of the coupling interval of a scheme, or None.

An interval above 1 is warned of, and so is the default -1 (and an nstpcouple below -1, which grompp reads as -1), which leaves the interval to grompp: grompp resolves it by the rule of its GROMACS version, and the warning names the interval grompp of GROMACS 2025.4 resolves (_resolved_interval()). An interval of 1, and a coupling that acts on no group, give no warning; gromacs_coupling_problem() refuses the other values before.

Parameters:
  • settings (dict of string) – The mdp settings (read_mdp_settings()).

  • scheme (string) – The coupling, a key of NSTCOUPLE_STEPS_PER_TAU.

  • template (string) – The mdp file, for the message.

  • time_step (float) – The time step of the run, in ps: the [engine] timestep, which every run writes as dt.

Returns:

out (string or None) – The warning, or None.

pyretis.engines.gromacs_steps._gromacs_md_tasks(template)

Return what the md tasks do with an mdp file path sampling refuses.

The md, md-nve and md-flux tasks read the temperature of the mdp file with read_gromacs_temperatures() and take the one temperature its settings hold, which decides the sentence (md_tasks_sentence()).

Parameters:

template (string) – The mdp file.

Returns:

out (string) – A sentence that says that every task refuses the mdp file, with the reason, for a file the reader refuses or whose settings hold no temperature or different ones; else that the md, md-nve and md-flux tasks accept it.

pyretis.engines.gromacs_steps._interval_warning(template, coupling, key, interval)

Return the warning of a coupling set to every N > 1 time steps.

Parameters:
  • template (string) – The mdp file.

  • coupling (string) – The coupling, as tcoupl = v-rescale.

  • key (string) – 'nsttcouple' or 'nstpcouple'.

  • interval (int) – The interval the template sets, in time steps.

Returns:

out (string) – The warning.

pyretis.engines.gromacs_steps._mass_from_number(value)

Return the mass an entry of a masses list gives.

Parameters:

value (object) – One entry of the list: a real number, a numpy one included.

Returns:

float – The entry, as a float.

Raises:

ValueError – If the entry is not a real number: a boolean is not read as 1 or 0.

pyretis.engines.gromacs_steps._mass_from_word(word, source)

Return the mass a word of a masses file gives.

Parameters:
  • word (string) – One entry of the file.

  • source (string) – The file, for the message.

Returns:

float – The number the word holds.

Raises:

ValueError – If the word is not a number.

pyretis.engines.gromacs_steps._mdp_number(settings, name, template, default, kind=<class 'float'>)

Return a number of the mdp settings.

Parameters:
  • settings (dict of string) – The mdp settings (read_mdp_settings()).

  • name (string) – The key, as the message names it (nsttcouple).

  • template (string) – The mdp file, for the message.

  • default (number) – The GROMACS default, for a key the template does not set.

  • kind (type, optional) – float or int.

Returns:

out (number) – The value.

Raises:

ValueError – If the value is not a number of the kind (grompp refuses it).

pyretis.engines.gromacs_steps._mdp_numbers(settings, name, template)

Return the numbers of an mdp key that holds one per group.

Parameters:
  • settings (dict of string) – The mdp settings (read_mdp_settings()).

  • name (string) – The key, as the message names it (tau-t).

  • template (string) – The mdp file, for the message.

Returns:

out (list of float) – The values; empty when the template does not set the key.

Raises:

ValueError – If a value is not a number (grompp refuses it).

pyretis.engines.gromacs_steps._remove_directory(dirname)

Remove a directory and its content when it exists.

Parameters:

dirname (string) – The directory to remove.

pyretis.engines.gromacs_steps._resolved_interval(taus, scheme, time_step)

Return the interval grompp of GROMACS 2025.4 gives the default -1.

grompp of GROMACS 2025.4 resolves nsttcouple = -1, and nstpcouple -1 or below, from the shortest positive time constant and the time step of the run (NSTCOUPLE_STEPS_PER_TAU), and to NSTCOUPLE_DEFAULT_MOST when no time constant is positive. grompp resolves the default by the rule of its GROMACS version: another version can choose another interval.

Parameters:
  • taus (list of float) – The time constants of the groups the coupling acts on, in ps (_coupled_taus()), at least one.

  • scheme (string) – The coupling, a key of NSTCOUPLE_STEPS_PER_TAU.

  • time_step (float) – The time step of the run, in ps: the [engine] timestep, which every run writes as dt.

Returns:

  • interval (int) – The interval in time steps, 1 when GROMACS 2025.4 couples at every time step.

  • how (string) – What GROMACS 2025.4 resolves the interval from.

pyretis.engines.gromacs_steps.gromacs_coupling_problem(settings, template)

Return why a path-sampling run refuses the coupling of an mdp file.

A path-sampling run refuses tcoupl berendsen (also written yes) and nose-hoover, and pcoupl berendsen (also written isotropic), parrinello-rahman and mttk: deterministic thermostats and barostats with a memory between time steps or without time reversibility. Every new piece of trajectory starts GROMACS from a stored frame, with the memory of the coupling at its initial value. Values are compared as grompp compares them (mdp_option()); a template without the key couples with the GROMACS default no. A coupling interval at which mdrun never couples, or couples with a negative interval, is refused too (_coupling_interval_problem()). The refusal of a coupling ends with what the md tasks do with the mdp file, as its temperature reader decides (md_tasks_sentence()).

Parameters:
Returns:

out (string or None) – The reason, naming each refused coupling and what to use instead, or None.

Raises:

Exception – As read_gromacs_temperatures() raises it for a refused coupling, other than its ValueError.

pyretis.engines.gromacs_steps.gromacs_coupling_warnings(settings, template, time_step)

Return why a path-sampling run with an mdp file is not exact.

A warning is given for: pcoupl = c-rescale, a stochastic barostat that carries the pressure of the last coupling step; a tcoupl = v-rescale or pcoupl = c-rescale coupling applied every N > 1 time steps (nsttcouple, nstpcouple above 1) or at the interval grompp chooses (the default -1; the warning names the interval grompp of GROMACS 2025.4 resolves with time_step, _coupling_interval_warning()); and tcoupl = andersen-massive, which randomises every velocity at the first time step of each run and then every tau-t / dt steps. Every new piece of trajectory starts GROMACS from a stored frame at time step 0. An annealing other than no, a temperature ramp, is refused in every task by the temperature reader (read_gromacs_temperatures()).

Parameters:
  • settings (dict of string) – The mdp settings (read_mdp_settings()), with a coupling gromacs_coupling_problem() accepts.

  • template (string) – The mdp file, for the message.

  • time_step (float) – The time step of the run, in ps: the [engine] timestep, which every run writes as dt.

Returns:

out (list of strings) – The warnings, each naming the scheme, why the path sampling is not exact with it, and what to use instead.

pyretis.engines.gromacs_steps.mdp_key_name(keyword)

Return the name grompp reads an mdp key as.

grompp compares mdp keys ignoring case and the characters - and _ (Continuation, continuation and ref_t, ref-t), and reads an old name of a key as the key (MDP_OLD_NAMES: unconstrained-start is continuation).

Parameters:

keyword (string) – The key as written in an mdp file.

Returns:

out (string) – The key in lower case without - and _, its current name for an old name.

pyretis.engines.gromacs_steps.mdp_option(value)

Return an mdp option the way grompp compares it.

Parameters:

value (string) – The option as written in an mdp file.

Returns:

out (string) – value in lower case without - and _ (Nose-Hoover is nosehoover).

pyretis.engines.internal module

Definition of numerical MD integrators.

These integrators are representations of engines for performing molecular dynamics. Typically they will propagate Newtons equations of motion in time numerically.

Important classes defined here

MDEngine (MDEngine)

Base class for internal MDEngines.

RandomWalk (RandomWalk)

A Random Walk integrator.

Verlet (Verlet)

A Verlet MD integrator.

VelocityVerlet (VelocityVerlet)

A Velocity Verlet MD integrator.

Langevin (Langevin)

A Langevin MD integrator.

class pyretis.engines.internal.Langevin(timestep, gamma, rgen=None, seed=0, high_friction=False)

Bases: MDEngine

The Langevin MD integrator.

This class defines a Langevin integrator.

Variables:
  • rgen (object like RandomGenerator) – This is the class that handles the generation of random numbers.

  • gamma (float) – The friction parameter.

  • high_friction (boolean) – Determines if we are in the high friction limit and should do the over-damped version.

  • init_params (boolean) – If true, we will initiate parameters for the Langevin integrator when integration_step is invoked.

  • param_high (dict) –

    This contains the parameters for the high friction limit. Here we integrate the equations of motion according to: r(t + dt) = r(t) + dt * f(t)/m*gamma + dr. The items in the dict are:

    • sigma : float standard deviation for the positions, used when drawing dr.

    • bddt : numpy.array Equal to dt*gamma/masses, since the masses is a numpy.array this will have the same shape.

  • param_iner (dict) –

    This dict contains the parameters for the non-high friction limit where we integrate the equations of motion according to: r(t + dt) = r(t) + c1 * dt * v(t) + c2*dt*dt*a(t) + dr and v(r + dt) = c0 * v(t) + (c1-c2)*dt*a(t) + c2*dt*a(t+dt) + dv. The dict contains:

    • c0 : float Corresponds to c0 in the equation above.

    • a1 : float Corresponds to c1*dt in the equation above.

    • a2 : numpy.array Corresponds to c2*dt*dt/mass in the equation above. Here we divide by the masses in order to use the forces rather than the acceleration. Since the masses might be different for different particles, this will result in a numpy.array with shape equal to the shape of the masses.

    • b1 : numpy.array Corresponds to (c1-c2)*dt/mass in the equation above. Here we also divide by the masses, resulting in a numpy.array.

    • b2 : numpy.array Corresponds to c2*dt/mass in the equation above. Here we also divide by the masses, resulting in a numpy.array.

    • mean : numpy.array (2,) The means for the bivariate Gaussian distribution.

    • cov : numpy.array (2,2) This array contains the covariance for the bivariate Gaussian distribution. param_iner[‘mean’] and param_iner[‘cov’] are used as parameters when drawing dr and dv from the bivariate distribution.

Note

Outside the high friction limit, the dr and dv of each particle are drawn together with the multivariate_normal method of rgen, from the Cholesky factor of the covariance that the parameters hold (param_iner['cho'], computed once with the other parameters). In the high friction limit, dr is drawn with the normal method of rgen.

__init__(timestep, gamma, rgen=None, seed=0, high_friction=False)

Set up the Langevin integrator.

Actually, it is very convenient to set some variables for the different particles. However, to have a uniform initialisation for the different integrators, we postpone this. This initialisation can be done later by calling explicitly the function self._init_parameters(system) or it will be called the first time self.integration_step is invoked.

Parameters:
  • timestep (float) – The time step in internal units.

  • gamma (float) – The gamma parameter for the Langevin integrator.

  • rgen (string, optional) – This string can be used to pick a particular random generator, which is useful for testing.

  • seed (integer, optional) – A seed for the random generator.

  • high_friction (boolean, optional) – Determines if we are in the high_friction limit and should do the over-damped version.

_init_parameters(system)

Extra initialisation of the Langevin integrator.

Parameters:

system (object like System) – The system to integrate/act on. Assumed to have a particle list in system.particles.

Returns:

out (None) – Does not return anything, but updates self.param.

integration_step(system)

Langevin integration, one time step.

Parameters:

system (object like System) – The system to integrate/act on. Assumed to have a particle list in system.particles.

Returns:

out (None) – Does not return anything, but alters the state of the given system.

integration_step_inertia(system)

Langevin integration, one time step.

Parameters:

system (object like System) – The system to integrate/act on. Assumed to have a particle list in system.particles.

Returns:

out (None) – Does not return anything, but alters the state of the given system.

integration_step_overdamped(system)

Over damped Langevin integration, one time step.

Parameters:

system (object like System) – The system to integrate/act on. Assumed to have a particle list in system.particles.

Returns:

out (None) – Does not return anything, but alters the state of the given system.

load_restart_info(info)

Load restart information.

Parameters:

info (dict) – The dictionary with the restart information, should be similar to the dict produced by restart_info().

restart_info()

Return restart info.

The restart info for the engine Langevin.

Returns:

info (dict) – Contains all the updated simulation settings and counters.

class pyretis.engines.internal.MDEngine(timestep, description, dynamics=None)

Bases: EngineBase

Base class for internal MD integrators.

This class defines an internal MD integrator. This class of integrators work with the positions and velocities of the system object directly. Further, we make use of the system object in order to update forces etc.

Variables:
  • timestep (float) – Time step for the integration.

  • description (string) – Description of the MD integrator.

  • dynamics (str) – A short string to represent the type of dynamics produced by the integrator (NVE, NVT, stochastic, …).

  • section (string) – The input section the engine is built from: engine, or the section pyretis.engines.factory.create_inf_engine() builds it from (engine0, engine1, …). setup_streaming() reads the engine’s subcycles there.

  • subcycles (integer) – The number of integration steps between two stored frames of a path: a streamed path, and a path propagate() and kick_across_middle() generate in memory.

__call__(system)

To allow calling MDEngine(system).

Here, we are just calling self.integration_step(system).

Parameters:

system (object like System) – The system we are integrating.

Returns:

out (None) – Does not return anything, but will update the particles.

__init__(timestep, description, dynamics=None)

Set up the integrator.

Parameters:
  • timestep (float) – The time step for the integrator in internal units.

  • description (string) – A short description of the integrator.

  • dynamics (string or None, optional) – Description of the kind of dynamics the integrator does.

_calculate_order_streaming(system)

Order parameter for a file-backed snapshot System.

static _draw_maxwellian(system, rgen, sigma_v=None)

Draw Maxwellian velocities for system using rgen.

Replicates RandomGenerator.draw_maxwellian_velocities() exactly (same sigma_v from beta/imass and the same normal draw) but accepts the raw numpy.random.Generator the infinite-swap scheduler injects as the velocity-generation random generator (pens['rgen-eng']), which does not carry the pyretis draw_maxwellian_velocities method.

_dump_config_streaming(config, deffnm)

Extract a single frame from a trajectory into its own file.

_ensure_dynamics_rgen()

Wrap a raw numpy dynamics rgen in the pyretis generator API.

Stochastic integrators (Langevin / random walk) draw their dynamics noise from self.rgen using the pyretis generator surface (notably multivariate_normal(..., cho=...)). The infinite-swap scheduler, however, injects a raw numpy.random.Generator onto engine.rgen per move, and the kick initiation, sequential or parallel, per ensemble (initiate_path_ensemble_kick()). To keep the dynamics draws working – and deterministic – wrap that raw generator in PCG64Generator, which exposes the pyretis surface while drawing from the very same (deterministic) underlying stream. propagate() and kick_across_middle() call it before they integrate, in memory as in the streaming loop. Engines without self.rgen (Verlet / velocity-Verlet) and already-wrapped generators are left untouched.

_evaluate_potential_and_force(system)

Evaluate potential/force using the engine’s forcefield.

On first call, lazily acquires the forcefield from the system if not yet set via set_forcefield().

_fresh_stream_system(pos, vel)

Return a working in-memory System seeded with pos/vel.

Copies the streaming template (so the box, masses, particle names and force field are all in place) and writes the given positions and velocities into it. The template’s own state is never mutated.

static _get_force(system)

Return the force array of a system.

_integrate_frame(system, reverse)

Integrate an in-memory system from one stored frame to the next.

A frame of a path is subcycles integration steps after the frame before it, in the in-memory loop as in a streamed path (_propagate_streaming()).

Parameters:
  • system (object like System) – The system, changed in place.

  • reverse (boolean) – If True, the system is integrated backward in time: its velocities are reversed around each step.

_is_streaming(system)

Return True when system is a file-backed snapshot.

The in-memory loop always hands the engine a System with particles attached; the coordinator hands it a snapshot without particles whose config points at a trajectory file. Streaming additionally requires the engine to have a template (set by setup_streaming()).

_materialize_system(system)

Read the frame system.config points at into a System.

Returns the working in-memory System plus the raw 3-column pos / vel / box arrays read from disk (kept so the produced frames are written back at full xyz width).

_modify_velocities_streaming(system, vel_settings, rgen)

Draw shooting velocities for a file-backed snapshot System.

Mirrors TurtleMDEngine.modify_velocities(): read the current frame, draw new velocities (or perturb them) with the injected random generator, write a genvel.xyz file and point the system at it. The kinetic-energy change is returned.

_propagate_streaming(path, ens_set, system, reverse)

Propagate a file-backed snapshot System (coordinator loop).

Counterpart of TurtleMDEngine._propagate_from() for the internal integrators: materialise the starting frame, run the in-memory integrator forward (or backward) one recorded frame at a time, write each frame to an xyz trajectory, and build snapshot System objects pointing at it. self.steps counts the integration steps, for the scheduler’s subcycle accounting.

calculate_order(system, xyz=None, vel=None, box=None)

Return the order parameter.

This method is just to help to calculate the order parameter in cases where only the engine can do it.

Parameters:
  • system (object like System) – This is the system that contains the particles we are investigating. The order function is injected on the engine (self.order_function).

  • xyz (numpy.array, optional) – The positions to use. Typically for internal engines, this is not needed. It is included here as it can be used for testing and also to be compatible with the generic function defined by the parent.

  • vel (numpy.array, optional) – The velocities to use.

  • box (numpy.array, optional) – The current box vectors.

Returns:

out (list of floats) – The calculated order parameter(s).

clean_up()

Clean up after using the engine.

For the in-memory loop there is nothing to clean (no files are produced and no streaming template is attached), so this is a no-op. Only when the engine runs in the streaming (file-backed) loop (a template was attached by setup_streaming()) and the scheduler has handed it a private exe_dir do we remove the working files there so a re-used engine starts from a clean directory.

default_temperature = 1.0
default_units = 'lj'
dump_phasepoint(phasepoint, deffnm=None)

Dump a phase point to a file.

In the in-memory loop the phase points carry their own particles and there is nothing to dump, so this is a no-op (EngineBase.dump_phasepoint() declares the method for every engine). In the streaming (file-backed) loop the phase point is a snapshot whose config points into a trajectory file; we extract that single frame to its own file and re-point the phase point at it, exactly as the external base does.

engine_type = 'internal'
classmethod get_default_units(settings=None)

Return the default unit system for internal engines.

Parameters:

settings (dict, optional) – Full simulation settings or engine settings. This argument is ignored for internal engines.

Returns:

out (string) – The default unit system for internal engines.

integrate(system, order_function, steps, thermo='full')

Perform several integration steps.

This method will perform several integration steps, but it will also calculate order parameter(s) if requested and energy terms.

Parameters:
  • system (object like System) – The system we are integrating.

  • order_function (object like OrderParameter or None) – An order function can be specified if we want to calculate the order parameter along with the simulation.

  • steps (integer) – The number of steps we are going to perform. Note that we do not integrate on the first step (e.g. step 0) but we do obtain the other properties. This is to output the starting configuration.

  • thermo (string, optional) – Select the thermodynamic properties we are to calculate.

Yields:

results (dict) – The result of a MD step. This contains the state of the system and also the order parameter(s) (if calculated) and the thermodynamic quantities (if calculated).

integration_step(_)

Perform a single time step of the integration.

Parameters:

- (place holder)

Returns:

out (None) – Does not return anything, in derived classes it will typically update the given System.

invert_dt()

Invert the time step for the integration.

Returns:

out (boolean) – True if the time step is positive, False otherwise.

kick_across_middle(system, ens_set, middle, tis_settings, rgen)

Force a phase point across the middle interface.

This is accomplished by repeatedly kicking the phase point so that it crosses the middle interface.

Parameters:
  • system (object like System) – The working state we repeatedly kick and integrate. The order function is injected on the engine (self.order_function).

  • ens_set (dict) – Ensemble settings, unused here; the argument belongs to the signature of EngineBase.kick_across_middle().

  • middle (float) – This is the value for the middle interface.

  • tis_settings (dict) – This dictionary contains settings for TIS. Explicitly used here:

    • zero_momentum: boolean, determines if the momentum is zeroed after each kick. A missing key means False.

    • rescale_energy: float or False, the total energy each kick is re-scaled to; False, or a value that is not positive, leaves the kicked velocities unscaled.

    Every kick is an aimless draw (make_kick_velocity_settings()).

  • rgen (object like RandomGenerator) – The velocity-generation random generator, injected per call (distinct from the integration self.rgen).

Returns:

  • out[0] (object like System) – The phase-point just before the interface.

  • out[1] (object like System) – The phase-point just after the interface.

Note

This function will update the system state.

modify_velocities(system, vel_settings, rgen)

Modify the velocities of the current state.

This method will modify the velocities of a time slice. And it is part of the integrator since it, conceptually, fits here: we are acting on the system and modifying it.

Parameters:
  • system (object like System) – This is the system that contains the particles we are investigating.

  • vel_settings (dict) – It contains all the info for the velocity:

    • sigma_v : numpy.array, optional Negative values select aimless shooting. Zero or positive values set the standard deviation, one for each particle, for soft velocity perturbations.

    • zero_momentum : boolean, optional If True, we reset the linear momentum to zero after generating. A missing key means False.

    • rescale : float, optional In some NVE simulations, we may wish to re-scale the energy to a fixed value. If rescale is a float > 0, we will re-scale the energy (after modification of the velocities) to match the given float.

  • rgen (object like RandomGenerator) – The velocity-generation random generator, injected per call. It is kept distinct from the integration self.rgen that stochastic integrators (Langevin, random walk) own, so a shooting-move velocity kick never perturbs the dynamics random stream. A numpy.random.Generator is drawn from through a PCG64Generator over its stream.

Returns:

  • dek (float) – The change in the kinetic energy.

  • kin_new (float) – The new kinetic energy.

propagate(path, ens_set, system, reverse=False)

Generate a path by integrating until a criterion is met.

This function will generate a path by calling the function specifying the integration step repeatedly. The integration is carried out until the order parameter has passed the specified interfaces or if we have integrated for more than a specified maximum number of steps.

Parameters:
  • path (object like PathBase) – This is the path we use to fill in phase-space points. We are here not returning a new path, this since we want to delegate the creation of the path (type) to the method that is running propagate.

  • ens_set (dict) – Ensemble settings. It contains:

    • interfaces : list of floats These interfaces define the stopping criterion.

  • system (object like System) – The system object gives the initial state for the integration; it is mutated in place during propagation. The order function is injected on the engine (self.order_function).

  • reverse (boolean, optional) – If True, the system will be propagated backward in time.

Returns:

  • success (boolean) – This is True if we generated an acceptable path.

  • status (string) – A text description of the current status of the propagation.

select_thermo_function(thermo='full')

Select function for calculating thermodynamic properties.

Parameters:

thermo (string, or None, optional) – String which selects the kind of thermodynamic output.

Returns:

thermo_func (callable or None) – The function matching the requested thermodynamic output.

set_forcefield(forcefield)

Attach a force field for system-independent evaluation.

setup_streaming(settings)

Build the file-backed (streaming) template for this engine.

Mirrors TurtleMDEngine, which builds its own box / particles / potential in __init__: here we reuse the pyretis.setup.createsystem.create_system() and pyretis.setup.createforcefield.create_force_field() to build a fully-attached in-memory System template (particles, box, masses, force field). Each streaming propagation materialises a fresh working copy of this template, fills in the positions and velocities read from disk, runs the existing in-memory integrator, and writes the produced frames back out as an xyz trajectory.

The engine streams with the subcycles of the section it is built from, its section attribute: [engine] for the engine of [engine], and the pool section itself ([engine0], [engine1], …) for an engine of a pool.

Parameters:

settings (dict) – The full (coordinator) settings dictionary. It carries the canonical [system] / [box] / [particles] / [potential] / [forcefield] / [engine] sections that the system and force field are built from, and the engine section the engine is built from.

streaming_beta()

Return the inverse temperature of the system the engine streams.

In the file-backed (streaming) loop the engine integrates, and draws velocities for, a copy of its streaming template (setup_streaming()): the System that [system] temperature and [system] units give, whose beta is 1 / (k_B * temperature) with the Boltzmann constant of the unit system. A file-backed snapshot the engine is handed carries no temperature of its own.

Returns:

out (float or None) – The beta of the streaming template, or None for an engine without one (the in-memory loop, which takes the beta of the System it is handed).

streaming_energies(systems)

Recompute (vpot, ekin) for file-backed snapshot systems.

The potential energy is a function of the positions and the kinetic energy a function of the velocities, both stored in each system’s trajectory frame, so the energy terms are recovered exactly by re-reading the frame and evaluating this engine’s force field. This restores the per-frame energies on paths rebuilt from disk (initial paths, swaps, and the reload done by SchedulerPathStorage.output()), whose snapshot phase points carry positions and velocities but no in-memory energy. Each distinct trajectory file is read once.

Parameters:

systems (iterable of objects like System) – File-backed snapshot systems without particles: each config is a (filename, frame_index) pair.

Returns:

list of tuple of float – One (vpot, ekin) pair per input system, in input order.

streaming_orders(systems)

Recompute the order parameter for file-backed snapshot systems.

The order parameter is a function of the stored frame, so it is recovered exactly by re-reading that frame and evaluating this engine’s order_function. Used when the configured order function differs from the order data a path was loaded with – a restart that added or removed collective variables (see pyretis.core.path_load.align_order_width()).

This is the batch counterpart of evaluating each phase point on its own: each distinct trajectory file is read ONCE and its frames are held while the phase points that reference them are evaluated. Frame-at-a-time evaluation re-reads the file from the start for every frame, which is quadratic in the path length – the reason this method exists.

Parameters:

systems (iterable of objects like System) – File-backed snapshot systems without particles: each config is a (filename, frame_index) pair.

Returns:

list of lists of floats – One order-parameter list per input system, in input order.

system_with_particles(system)

Return a phase point with particles in the state of its frame.

The phase point system holds no particles and names its frame by config. The phase point returned is a copy of the streaming template (setup_streaming()), with the box, the masses, the particle names and the force field of the engine, in the state of that frame (_materialize_system()): the positions and the velocities of the frame, the velocities negated when vel_rev is True, and the potential energy and the forces evaluated. Such a phase point is held in memory: propagate(), modify_velocities() and kick_across_middle() act on it as on the system the in-process kick initiation starts from, and write no frame files for it.

Parameters:

system (object like System) – A phase point without particles that names its frame by config.

Returns:

out (object like System) – The phase point with particles.

Raises:

ValueError – If system holds particles or names no frame, if the engine has no streaming template, or if the file holds no frame at the index config names.

class pyretis.engines.internal.RandomWalk(timestep, rgen=None, seed=0)

Bases: MDEngine

A Random Walker integrator.

This class defines a Random walker integrator.

Variables:

timestep (float) – The length of the step.

__init__(timestep, rgen=None, seed=0)

Set up the Random walker integrator.

Parameters:
  • timestep (float) – The time step in internal units.

  • rgen (string, optional) – This string can be used to pick a particular random generator, which is useful for testing.

  • seed (integer, optional) – A seed for the random generator.

integration_step(system)

Random Walker integration, one time step.

Parameters:

system (object like System) – The system to integrate/act on. Assumed to have a particle list in system.particles.

Returns:

out (None) – Does not return anything, but alters the state of the given system.

load_restart_info(info)

Load restart information for the RandomWalk engine.

Parameters:

info (dict) – The dictionary with the restart information, should be similar to the dict produced by restart_info().

restart_info()

Return restart info for the RandomWalk engine.

The integration random generator (rgen) is persisted so that a restart – including a re-run of an interrupted shot – resumes the exact same stochastic stream (bit-identical dynamics).

Returns:

info (dict) – Contains all the updated simulation settings and counters.

class pyretis.engines.internal.VelocityVerlet(timestep)

Bases: MDEngine

The Velocity Verlet MD integrator.

This class defines the Velocity Verlet integrator.

Variables:

half_timestep (float) – Half of the timestep.

__init__(timestep)

Set up the Velocity Verlet integrator.

Parameters:

timestep (float) – The time step in internal units.

integration_step(system)

Velocity Verlet integration, one time step.

Parameters:

system (object like System) – The system to integrate/act on. Assumed to have a particle list in system.particles.

Returns:

out (None) – Does not return anything, but alters the state of the given system.

load_restart_info(info)

Load restart information.

Parameters:

info (dict) – The dictionary with the restart information, should be similar to the dict produced by restart_info().

restart_info()

Return some restart info.

The restart info for the engine VelocityVerlet.

Returns:

info (dict,) – Contains all the updated simulation settings and counters.

class pyretis.engines.internal.Verlet(timestep)

Bases: MDEngine

The Verlet MD integrator.

This class defines the position Verlet (Störmer-Verlet) MD integrator. The positions follow the Verlet recursion x(t + dt) = 2 x(t) - x(t - dt) + a(t) dt**2, and the velocities are the central differences of the positions, v(t) = (x(t + dt) - x(t - dt)) / (2 dt).

The state of the integrator is the phase point of the system: its positions, velocities and forces. A step takes the positions one time step back from the phase point (previous_positions()) and leaves the system in the phase point one time step later, the positions and the velocities of the same time. A step therefore starts from the phase point the system holds, whether a velocity draw, a velocity reversal or a frame of a path gave it, and a step from a phase point with negated velocities retraces the step that led to it. In exact arithmetic, the trajectory from a phase point is the one of VelocityVerlet.

Variables:
  • half_idt (float) – Half of the inverse time step: 0.5 / timestep.

  • timestepsq (float) – Squared time step: timestep**2.

__init__(timestep)

Set up the Verlet MD integrator.

Parameters:

timestep (float) – The time step in internal units.

integration_step(system)

Perform one Verlet integration step.

The step goes from the phase point of system at time t to the phase point at time t + dt. The positions follow the Verlet recursion from the positions one time step back (previous_positions()), x(t + dt) = 2 x(t) - x(t - dt) + a(t) dt**2. The forces are evaluated at x(t + dt), and the velocities are the central difference at the new time, v(t + dt) = (x(t + 2 dt) - x(t)) / (2 dt), with x(t + 2 dt) the next term of the recursion, 2 x(t + dt) - x(t) + a(t + dt) dt**2.

Parameters:

system (object like System) – The system to integrate/act on. Assumed to have a particle list in system.particles, with the forces of its positions.

Returns:

out (None) – Does not return anything, but alters the state of the given system.

load_restart_info(info)

Load restart information.

Parameters:

info (dict) – The dictionary with the restart information, should be similar to the dict produced by restart_info().

previous_positions(system)

Return the positions one time step before the phase point.

The positions are those of the second-order Taylor expansion of the trajectory through the phase point, x(t - dt) = x(t) - v(t) dt + a(t) dt**2 / 2. The central difference of the Verlet step from them, (x(t + dt) - x(t - dt)) / (2 dt), is the velocity v(t) of the phase point.

Parameters:

system (object like System) – The phase point: its positions, velocities and forces.

Returns:

out (numpy.array) – The positions x(t - dt).

restart_info()

Return restart info.

The restart info for the engine Verlet.

Returns:

info (dict,) – Contains all the updated simulation settings and counters.

pyretis.engines.lammps module

A streaming LAMMPS external MD engine.

This module defines the canonical LAMMPS engine, selected by class = "lammps". LAMMPS is run as a single persistent process and its dump trajectory is read on-the-fly, so the path is filled incrementally and LAMMPS is terminated as soon as a stopping interface is crossed. The input of the LAMMPS run of a propagation is built as for the relaunch engine (LAMMPSEngineSteps._prepare_lammps_run()): PyRETIS appends its commands to a copy of lammps.in (create_lammps_md_input()). They are, in this order:

  • the start configuration, and the commands that reverse its velocities for a propagation that reverses them;

  • the thermo output, with thermo_modify flush yes;

  • the trajectory dump;

  • with order_mode = "lammps", the order-parameter output of order.in and the fix halt commands that stop the run at the outer interfaces;

  • the run of the number of steps, path.maxlen * subcycles;

  • the undump of the trajectory dump.

When the engine has a random generator, the command line defines the LAMMPS variable pyretis_seed, a seed drawn from it for each run. Each fix and pair style of lammps.in that draws random numbers takes it as its seed: the engine refuses another seed before LAMMPS runs (refuse_lammps_fixed_seeds()). Frame k of the dump of a run is named by the time step k * subcycles, and the engine refuses a dump whose frames it read have other time steps (check_lammps_dump_steps()).

The relaunch engine, which reads the trajectory once the LAMMPS run has ended, is class = "lammps_steps" (pyretis.engines.lammps_steps).

Important classes defined here

LAMMPSEngine (LAMMPSEngine)

The streaming LAMMPS engine.

class pyretis.engines.lammps.LAMMPSEngine(lmp, input_path, subcycles, extra_files=None, order_mode='pyretis', timestep=None, velocity_generation='engine', atom_style=None, sleep=0.1)

Bases: LAMMPSEngineSteps

Streaming LAMMPS engine.

This engine shares its configuration and input convention with the relaunch engine LAMMPSEngineSteps (same [engine] settings, same lammps.in / system.data / order.in / extra_files input directory), as the two GROMACS engines do. With order_mode = "pyretis", the two engines build the identical LAMMPS input of a propagation (via the inherited LAMMPSEngineSteps._prepare_lammps_run()) and differ in how the trajectory is consumed: this engine runs LAMMPS as a single persistent process and reads the trajectory on the fly, terminating LAMMPS early when an interface is crossed. This engine takes order_mode = "pyretis" only, its default (the relaunch engine defaults to "lammps"), and draws the velocities in PyRETIS in both velocity_generation modes (modify_velocities()).

The order parameter of a frame is evaluated on the unwrapped positions of its atoms from the lower bounds of its box, in a box of the box lengths of the frame (_frame_for_order()), as the relaunch engine evaluates it (LAMMPSEngineSteps._calculate_pyretis_order()), so the two engines give the same order parameter for a configuration, also one of an atom that has crossed a periodic boundary.

TO DO:

  • Add possibility to use LAMMPS internally to modify the velocities such that all constraints (e.g. between bonds) are fulfilled (external_orderparameter : boolean).

  • The velocity draw supports LAMMPS real units only, and refuses others (modify_velocities()).

  • Fix “exe_path” and “exe_dir”, use one but not both…

  • Fix mpi in cp2k?

  • For small systems the engine is so fast that whole trajectory finishes before we managed to check for a crossing, leading to large files.

  • Make LAMMPS remove and replace commands in input instead of making variables. Much easier to run md with the same input file

  • external_orderparameter. If this is set to true, we read in the orderparameter from and external file. May be useful when the orderparameter is calculated internally in LAMMPS for expensive calculations such as in nucleation, or any other fancy stuff.

__init__(lmp, input_path, subcycles, extra_files=None, order_mode='pyretis', timestep=None, velocity_generation='engine', atom_style=None, sleep=0.1)

Set up the streaming LAMMPS engine.

The signature matches LAMMPSEngineSteps, so the same [engine] settings and input directory drive either engine. sleep is the only streaming-specific extra, and order_mode takes "pyretis" only, its default here (the relaunch engine defaults to "lammps").

Parameters:
  • lmp (string) – The LAMMPS executable.

  • input_path (string) – Directory with the LAMMPS input files (lammps.in, system.data, optionally order.in and extra_files).

  • subcycles (integer) – The number of LAMMPS steps between stored snapshots.

  • extra_files (list of strings, optional) – Additional files required to run LAMMPS.

  • order_mode (string, optional) – Where the order parameter is evaluated. The streaming engine reads dumped frames and evaluates the PyRETIS order function in Python, and stops a run on its values: "pyretis", the default and the one mode it accepts.

  • timestep (float, optional) – Cross-check only; the time step is read from lammps.in.

  • velocity_generation (string, optional) – "engine" (the default) or "maxwell". In both modes this engine draws the velocities in PyRETIS, from a Maxwell-Boltzmann distribution at the temperature of lammps.in on the injected random generator, and resets the linear momentum as [tis] zero_momentum selects (modify_velocities()), so the two modes draw the same velocities.

  • atom_style (string, optional) – The LAMMPS atom style of the Atoms rows of a data file, from which the engine reads the masses at set-up and the positions of a configuration held in a data file. Of this setting, the Atoms # style annotation of the data file and the atom_style command of lammps.in, the ones that are given must name styles of one row layout (bond, angle and molecular share one, and a style with an accelerator suffix, as full/kk, has the layout of the style), and a ValueError is raised otherwise. The rows are read in the style of the first of the three that is given, and in atomic when none is. An atom_style command of lammps.in set by a LAMMPS variable is not a source, and without another source a ValueError is raised (resolve_lammps_atom_style()). The data file is read by read_lammps_data_file(): at set-up without its box (get_atom_masses()), and for the velocity draw and the order parameter of a configuration held in a data file with its box, which refuses a triclinic box.

  • sleep (float, optional) – Seconds to wait between polls while reading the trajectory on the fly. Default 0.1.

Raises:
  • NotImplementedError – If lammps.in has a mass command: the engine takes the masses of the atoms from the Masses section of system.data (refuse_lammps_mass_command()). Also as get_atom_masses() raises it for system.data.

  • ValueError – If order_mode is not "pyretis": with "lammps", LAMMPS would stop a run on v_op_1 of order.in while the engine samples on the PyRETIS order parameter. Also as LAMMPSEngineSteps raises it, and as get_atom_masses() raises it for system.data.

_extract_frame(traj_file: str, idx: int, out_file: str) → None

Extract a frame from a trajectory to a new file.

idx is the time step of the frame in the dump, the configuration index of a frame of a LAMMPS dump (LAMMPSEngineSteps._frame_config_index()); None names the frame of time step 0. The selected frame is rewritten as a canonical, timestep-zero dump with explicit image flags.

_frame_for_order(pos: ndarray, bounds: ndarray, images: ndarray | None = None) → tuple[ndarray, ndarray]

Return the positions and the box of a frame for its order.

The positions are the unwrapped positions of the atoms from the lower bounds of the box, along the axes of the system (lammps_order_positions()), and the box has the box lengths hi - lo of x, y and z, as the relaunch engine evaluates the order parameter of a frame (LAMMPSEngineSteps._calculate_pyretis_order()).

Parameters:
  • pos (np.ndarray) – The positions of the atoms, shape (N, 3): the unwrapped positions, or, with images, the positions of the frame.

  • bounds (np.ndarray) – The box bounds of the frame, a row lo hi for each of x, y and z, with the tilt factors in a third column for a dump of a triclinic box.

  • images (np.ndarray, optional) – The image flags of the atoms, shape (N, 3).

Returns:

tuple –

A tuple containing:
  • The positions for the order parameter, shape (N, 3).

  • The box lengths of x, y and z.

Raises:

NotImplementedError – If the frame has a triclinic box with a tilt factor other than 0 (refuse_tilted_lammps_box()).

_locate_data_file(data_file)

Return the path of the LAMMPS data file of a configuration.

A configuration names its data file by a path, absolute or relative to the working directory, or by a bare file name, as the initial configuration can name the system.data of input_path before it is staged in exe_dir. A path or a name that is a file is that file; a path with a directory is resolved against the working directory only, as the propagation resolves it (LAMMPSEngineSteps._prepare_lammps_run()). A bare name that is not a file is the file of that name in exe_dir, and, when exe_dir has none and the name is that of the system.data of the engine input, that system.data.

Parameters:

data_file (string) – The data file that the configuration names.

Returns:

out (string) – The path of the data file.

Raises:

FileNotFoundError – If data_file is none of these files; the message names data_file.

_read_configuration(filename: str) → tuple[ndarray, ndarray, ndarray | None, list[str] | None]

Read a configuration (a single frame trajectory).

Parameters:

filename (string) – The dump whose first frame is read.

Returns:

tuple –

A tuple containing:
  • The unwrapped positions of the atoms from the lower bounds of the box (_frame_for_order()).

  • The velocities of the atoms.

  • The box lengths of x, y and z.

  • None, for the atom names.

_read_data_configuration(data_file: str) → tuple[ndarray, ndarray, ndarray]

Read the configuration held in a LAMMPS data file.

The data file is the one _locate_data_file() finds. Its positions, image flags and box bounds are read by LAMMPSEngineSteps._read_lammps_data_frame(), and the positions are unwrapped with the box of its header, from the lower bounds of the box (_frame_for_order()), as those of the frame of a dump are. The velocities are those of its Velocities section (read_lammps_data_velocities()); a data file without one has zero velocities, the velocities LAMMPS read_data gives its atoms, as the GROMACS and CP2K engines read a configuration without velocities.

Parameters:

data_file (string) – The data file that the configuration names.

Returns:

tuple –

A tuple containing:
  • The unwrapped positions from the lower bounds of the box, shape (N, 3).

  • The velocities, shape (N, 3).

  • The box lengths of x, y and z.

Raises:
_recompute_partial_orders(partial_traj, reverse)

Order parameters per frame of a partial .lammpstrj dump.

The dump frames are read directly, each with the unwrapped positions of its atoms from the lower bounds of its box and its box lengths (_frame_for_order()), as the propagation reads them. Only complete frames are read: a final frame left half-written by an interruption (an incomplete block) is skipped, keeping the surviving frames – the same “use the last good frame” recovery used for the other engines. The order function sees each frame named by system.config, the dump and the time step of the frame (_calculate_frame_order()), the config the rebuilt phase point of the frame stores.

_reverse_velocities(filename: str, outfile: str) → None

Reverse the velocities of a configuration.

_velocity_draw_data_file(system)

Return the LAMMPS data file that a velocity draw reads.

The draw reads the data file of the configuration of system where it is (_locate_data_file()), and writes no file before the data file is read.

Parameters:

system (object like System) – The state whose velocities are drawn, at a data file.

Returns:

out (string) – The data file.

Raises:

FileNotFoundError – If _locate_data_file() does not find the data file.

calculate_order(system, xyz=None, vel=None, box=None)

Calculate the order parameter of the current system.

This engine’s _read_configuration returns the box as its THIRD element (pos, vel, box, names), unlike ExternalMDEngine.calculate_order, which expects the box first. We therefore unpack the box third here.

The configuration is read when xyz, vel or box is not given. A frame of a dump has the unwrapped positions of the atoms from the lower bounds of its box and the box lengths of the frame (_read_configuration()). A configuration held in a LAMMPS data file (_locate_data_file()) has the unwrapped positions of the atoms of the file, from their positions and image flags, from the lower bounds of the box of its header, the box lengths of x, y and z of its header and the velocities of its Velocities section (_read_data_configuration()).

Parameters:
  • system (object like System) – The state whose order parameter is calculated; its positions, velocities (negated when vel_rev is True) and box are set to those of the configuration.

  • xyz (numpy.array, optional) – The positions to use.

  • vel (numpy.array, optional) – The velocities to use.

  • box (numpy.array, optional) – The box lengths to use.

Returns:

out (list of floats) – The order parameter of the configuration.

Raises:
default_units = None
dump_config(config, deffnm='conf')

Extract a configuration frame, honouring the data-file case.

The shared convention stores the initial configuration as a LAMMPS data file (system.data), which is a single configuration and cannot be sliced frame-wise like a trajectory dump. In that case the data file (_locate_data_file()) is copied unchanged to <deffnm>.data in exe_dir; otherwise we defer to the generic trajectory-frame extraction.

Parameters:
  • config (tuple) – The configuration as (filename, index).

  • deffnm (string, optional) – The base name for the dumped file.

Returns:

out (string) – The file name we dumped to.

Raises:
dump_phasepoint(phasepoint, deffnm='conf')

Dump the current configuration from a system object to a file.

engine_draw_reads_set_temp = False
engine_type = 'external'
classmethod get_default_units(settings=None)

Return the default unit system for the LAMMPS engine.

The unit system is read from the units command in the LAMMPS input file. This mirrors how the engine time step is recovered at settings-parse time (pyretis.core.engine_time._engine_timestep_from_input()), which also inspects lammps.in, so unit and time-step auto-detection stay consistent.

Parameters:

settings (dict, optional) – Full simulation settings or engine settings.

Returns:

out (string) – The default unit system for the LAMMPS engine.

Raises:

ValueError – If the LAMMPS input file can not be read, or if no units command is found in that file.

modify_velocities(system: System, vel_settings: dict[str, Any], rgen) → tuple[float, float]

Modify the velocities of all particles.

The velocities are drawn in PyRETIS, from a Maxwell-Boltzmann distribution at the temperature of lammps.in, in both velocity_generation modes. A configuration held in a LAMMPS data file, as the system.data a run starts from, is drawn by LAMMPSEngineSteps._draw_velocities_maxwell(), which reads its positions, image flags and masses from that file (read_lammps_data_file()) where it is (_velocity_draw_data_file()), and writes genvel.lammpstrj in exe_dir once the file is read. Any other configuration is a frame of a LAMMPS dump: its positions and image flags come from the frame, and the masses from the data file of the engine input. The frame that this draw writes (write_lammpstrj()) keeps the image flags of the frame, and its velocities along the axes the system does not have (dimension below 3) are 0.

Parameters:
  • system (System) – The system whose particle velocities are to be modified.

  • vel_settings (dict) – A dict containing the key 'zero_momentum' (boolean): if true we reset the linear momentum to zero after generating velocities internally. A missing key means False, the [tis] default. This engine draws the velocities of aimless shooting and leaves their energy as drawn, so a soft perturbation (a sigma_v that is not negative) and a positive rescale are refused before the draw.

  • rgen (object like RandomGenerator) – The velocity random generator the Maxwell-Boltzmann draw is made from, in both velocity_generation modes.

Returns:

tuple – A tuple containing:

  • dek: The change in kinetic energy as a result of the velocity modification.

  • kin_new: The new kinetic energy of the system.

Raises:
  • NotImplementedError – If vel_settings select a soft perturbation (refuse_soft_perturbation()) or an energy re-scale (refuse_energy_rescale()), or if LAMMPS runs lammps.in in units other than real, those of its last units command after its last clear command, also in a file it includes (refuse_lammps_draw_units()). Also, for a configuration held in a data file, as read_lammps_data_file() raises it for the file: for a triclinic box, or Atoms rows of an atom style that is not supported.

  • ValueError – If the LAMMPS script runs in other units than real through a file it includes, so the engine has no beta. Also, for a configuration held in a data file, for each refusal of the file that the Raises section of read_lammps_data_file() lists.

  • FileNotFoundError – For a configuration that names a data file that _locate_data_file() does not find.

Notes

This method does not take care of constraints. The errors of the Raises section come before any random number is drawn or any file is written, and, first of all, a configuration held in a LAMMPS restart file is refused with a ValueError (LAMMPSEngineSteps.refuse_restart_configuration()).

needs_order = True
propagate(path, ens_set, system, reverse=False)

Propagate by streaming a single persistent LAMMPS run.

The relaunch base (LAMMPSEngineSteps) overrides propagate with a driver that makes one LAMMPS run of up to path.maxlen * subcycles steps and reads its trajectory when the run has ended. The streaming engine uses the generic external-engine driver, which dispatches to pyretis.engines.lammps.LAMMPSEngine._propagate_from() – a single persistent LAMMPS process whose trajectory is read on the fly and stopped early on an interface crossing.

Parameters:
  • path (object like PathBase) – The path to fill with phase points.

  • ens_set (dict) – The ensemble settings (interfaces, etc.).

  • system (object like System) – The system to propagate.

  • reverse (boolean, optional) – If True, propagate the path in reverse.

Returns:

  • success (boolean) – True if the propagation produced an acceptable path.

  • status (string) – A textual status of the propagation.

restart_configuration_what = 'The streaming LAMMPS engine (class "lammps")'
set_mdrun(md_items: dict[str, Any]) → None

Set the executional directory for workers.

step(system, name)

Perform a single step with the engine.

LAMMPS is propagated via _propagate_from; a single step() is not supported, and this override refuses the single LAMMPS run of LAMMPSEngineSteps.step().

supports_step_kick = False
pyretis.engines.lammps.get_atom_masses(lammps_data: str | Path, atom_style, input_style: str | None = None) → ndarray

Read the mass of each atom of a LAMMPS data file.

The file is read by read_lammps_data_file(), the reader of the velocity draw and of the order parameter of a configuration held in a data file (LAMMPSEngineSteps._read_lammps_data_frame()), without its box (read_box=False), so the masses of a data file of a triclinic box are read too. Each atom has the mass of the Masses row that starts with its atom type.

Parameters:
  • lammps_data (str or Path) – Path to the LAMMPS data file to read.

  • atom_style – The [engine] atom_style, or None when it is not set. Supports full, molecular, bond, angle, charge and atomic, each also with an accelerator suffix, as full/kk.

  • input_style (str, optional) – The style of the atom_style command of lammps.in (lammps_input_atom_style()).

Returns:

np.ndarray – The mass of each atom, in the order of the atom IDs, the order in which read_lammpstrj() gives the atoms of a dump frame, shape (N, 1).

Raises:

ValueError, NotImplementedError – As read_lammps_data_file() raises them without the box, for Atoms rows of an atom style that is not supported among others.

pyretis.engines.lammps.read_energies(filename: str) → dict[str, ndarray]

Read energies from a LAMMPS log file.

This method is used to read the thermodynamic output from a simulation (e.g., potential and kinetic energies).

Parameters:

filename (str) – The path to the LAMMPS log file to read.

Returns:

dict – A dictionary containing the data we found in the file.

pyretis.engines.lammps.read_lammps_input(filename)

Read a LAMMPS input file.

This will read in a LAMMPS input file and can be used to read the value of particular settings, for instance the time step. The commands are read as LAMMPS reads them (pyretis.inout.engine_temperature.lammps_script_commands()): the lines that & or an odd number of triple quotes join are one command, and the comment of a command starts at the first # outside quotes. A line inside a command, such as a line of a triple-quoted print text, is not a command of its own.

Parameters:

filename (string) – The path to the LAMMPS input file.

Returns:

out (list of tuples) – The settings found in the LAMMPS input file. The tuples are on the form (keyword, setting), the first word of a command and its other words joined by single spaces.

Raises:

ValueError – If a line of the file holds bytes that are not UTF-8, or a command, without its comment, a character that is not ASCII (pyretis.inout.engine_temperature.lammps_script_commands()).

pyretis.engines.lammps.read_lammpstrj(infile: str, frame: int, n_atoms: int, images: bool = False) → tuple[ndarray, ...]

Read a single frame from a LAMMPS trajectory.

Parameters:
  • infile (str) – The path to the file to read.

  • frame (int) – The index of the frame to read from infile.

  • n_atoms (int) – The number of atoms to read.

  • images (bool, optional) – If True, the image flags ix iy iz of the atoms are returned too, with 0 for an axis whose column the dump does not have.

Returns:

tuple –

A tuple containing:
  • The id type for the particles.

  • The positions.

  • The velocities.

  • The simulation box.

  • With images, the image flags (one row of three integers per atom).

Notes

  • The atoms are sorted according to their index, so that

    (index-based) order calculations are correct.

  • Both engine dumps with a type column and Maxwell-generated dumps without one are accepted; columns are located from the atom header.

  • The positions of a dump of the scaled columns xs ys zs are those the box of the frame gives them (lammps_scaled_positions()), and a dump of unwrapped positions (xu or xsu and so on) gives the wrapped positions and image flags whose unwrapped positions they are, with or without wrapped positions beside them (_lammpstrj_axis_positions()).

pyretis.engines.lammps.write_lammpstrj(outfile: str, id_type: ndarray, pos: ndarray, vel: ndarray, box: ndarray | None, append: bool = False, triclinic: bool = False, images: ndarray | None = None) → None

Write a LAMMPS trajectory frame in .lammpstrj format.

This method writes the LAMMPS dump fields: id type x y z vx vy vz ix iy iz.

Parameters:
  • outfile (str) – Path to the file to write.

  • id_type (np.ndarray)

  • pos (np.ndarray) – The positions to write.

  • vel (np.ndarray) – The velocities to write.

  • box (np.ndarray, optional) – The simulation box to write (if available).

  • append (bool) – If True, the outfile will be appended to, otherwise, outfile will be overwritten.

  • triclinic (bool) – If true, write in triclinic box format.

  • images (np.ndarray, optional) – The image flags ix iy iz of each atom, one row per atom in the order of pos. Without them every flag is written as 0.

pyretis.engines.lammps_steps module

This module defines the class for interfacing LAMMPS.

Important classes defined here

LAMMPSEngineSteps (LAMMPSEngineSteps)

The class responsible for interfacing with LAMMPS by launching the executable once per propagation and reading its trajectory when the LAMMPS run has ended (the slower, relaunch implementation; the canonical streaming engine lives in pyretis.engines.lammps).

class pyretis.engines.lammps_steps.LAMMPSEngineSteps(lmp, input_path, subcycles, extra_files=None, order_mode='lammps', timestep=None, velocity_generation='engine', atom_style=None)

Bases: ExternalMDEngine

A class for interfacing LAMMPS.

Variables:
  • lmp (string) – The command for executing LAMMPS

  • input_path (string) – The directory where the input files are stored.

  • input_files (dict of strings) – The names of the input files.

  • temperature (float) – The temperature lammps.in states (read_lammps_temperatures()), in kelvin, or reduced in units lj.

  • beta (float or None) – The inverse temperature 1 / (k_B T) in mol/kcal, with the k_B of LAMMPS real units, kb, for a script in units real; None in the other unit systems, in which PyRETIS draws no LAMMPS velocities (refuse_lammps_draw_units()).

  • engine_temperatures (object like EngineTemperatures) – The temperatures read from lammps.in.

__init__(lmp, input_path, subcycles, extra_files=None, order_mode='lammps', timestep=None, velocity_generation='engine', atom_style=None)

Set up the LAMMPS engine.

Parameters:
  • lmp (string) – The LAMMPS executable.

  • input_path (string) – The absolute path to where the input files are stored.

  • subcycles (integer) – The frequency of output of data by LAMMPS.

  • extra_files (list of strings, optional) – Additional files needed to run the LAMMPS simulation.

  • order_mode (string, optional) – Select where order parameters are evaluated. "lammps", the default, prints the variables of order.in for each frame and stops a run on v_op_1; each variable must read the positions and the box only (refuse_velocity_dependent_lammps_orders()). "pyretis" reads dumped LAMMPS frames and evaluates the PyRETIS order parameter and collective variables in Python.

  • timestep (float, optional) – The LAMMPS time step is read from the LAMMPS input file; this optional [engine] value is only used as a cross-check and must equal the value in the input file (otherwise an error is raised). For a lammps.in that reads a restart file, the time step is the one LAMMPS runs with: the one of the last timestep command after the last read_restart, else the one of the restart file (read_lammps_restarts()).

  • velocity_generation (string, optional) – How shooting-move velocities are generated. "engine" (default) delegates to LAMMPS (velocity create, with the mom keyword set from [tis] zero_momentum); "maxwell" draws them in Python from a Maxwell-Boltzmann distribution at the temperature of lammps.in via the injected random generator (one reproducible stream). The "maxwell" draw uses the constants of LAMMPS real units and refuses a lammps.in without units real (refuse_lammps_draw_units()). It takes the masses from the Masses section of a data file (_velocity_draw_data_file()): for a frame of a dump, the data file that LAMMPS write_data writes for the frame, whose Masses section holds the masses of the mass commands of lammps.in; for a configuration held in a data file, that file, and the draw of such a configuration refuses a lammps.in with a mass command (refuse_lammps_mass_command()).

  • atom_style (string, optional) – The LAMMPS atom style of the Atoms rows of a data file, from which the "maxwell" draw reads the positions, image flags and masses of a configuration held in a data file. Of this setting, the Atoms # style annotation of the data file, which a data file written by LAMMPS carries, and the atom_style command of lammps.in, the ones that are given must name styles of one row layout (bond, angle and molecular share one, and a style with an accelerator suffix, as full/kk, has the layout of the style), and the draw raises a ValueError otherwise. The rows are read in the style of the first of the three that is given, and in atomic when none is. An atom_style command of lammps.in set by a LAMMPS variable is not a source, and without another source the draw raises a ValueError (resolve_lammps_atom_style()).

Raises:

ValueError – If order_mode is not a mode of ORDER_MODES, if velocity_generation is neither "engine" nor "maxwell", as read_lammps_temperatures() and refuse_draw_without_set_temp() raise it for the temperature of lammps.in, if timestep differs from the time step of lammps.in, and, with order_mode = "lammps", if a variable of order.in reads the velocities or a word that PyRETIS cannot tell to be independent of them (refuse_velocity_dependent_lammps_orders()).

_calculate_pyretis_order(system, traj, reverse=False)

Calculate PyRETIS order parameters from a LAMMPS trajectory.

The order parameter of each frame is evaluated on the unwrapped positions of its atoms from the lower bounds of its box, in a box of its box lengths (lammps_order_positions()), with system.config naming the frame: the dump and the time step of the frame (_frame_config_index()), the config a phase point of the frame stores.

Parameters:
  • system (object like System) – The template of the system the order parameter is evaluated on; it is not changed.

  • traj (string) – The LAMMPS dump to read (read_lammps_dump()).

  • reverse (boolean, optional) – If True, the velocities of the frames are negated.

Returns:

out (numpy.ndarray) – The order parameter of each frame.

Raises:
  • ValueError – If the engine has no order parameter.

  • NotImplementedError – If a frame has a triclinic box with a tilt factor other than 0 (refuse_tilted_lammps_box()).

_draw_velocities_maxwell(system, vel_settings, rgen)

Draw shooting velocities in Python (Maxwell-Boltzmann).

Mirrors the engine path’s contract – sets system.config to a dump frame the next propagation reads via read_dump and updates system.ekin – but draws the velocities from the injected random generator instead of LAMMPS’s velocity create. The positions, image flags, masses and box bounds of x, y and z are those of the data file of _velocity_draw_data_file() (_read_lammps_data_frame()), and the draw writes genvel.lammpstrj in exe_dir once the file is read.

Parameters:
  • system (object like System) – The state whose velocities we redraw.

  • vel_settings (dict) – zero_momentum requests a zero linear-momentum reset; a missing key means False.

  • rgen (object like RandomGenerator) – The velocity random generator, injected explicitly.

Returns:

float – The new kinetic energy (in (g/mol)(Angstrom/fs)^2; transient – the propagation overwrites it with LAMMPS energies).

_evaluate_drawn_order(system)

Set the order parameter of the frame of a velocity draw.

The frame of system.config is the dump that _draw_velocities_maxwell() writes, of one frame. With order_mode = "pyretis" its order parameter is evaluated on that frame (_calculate_pyretis_order()), and an engine without an order parameter, as a script can make one, sets system.order to None. With order_mode = "lammps" LAMMPS evaluates it, in a run of zero time steps from the frame, genvel_order, on a copy of system, so that the configuration and the energies of system stay those of the draw.

Parameters:

system (object like System) – The state of the draw; its order is set.

_extract_frame(traj_file, idx, out_file)

Extract one LAMMPS trajectory frame as a data file.

Parameters:
  • traj_file (string) – The LAMMPS dump to extract the frame from.

  • idx (integer or None) – The time step of the frame in the dump, its configuration index (_frame_config_index()); None names the frame of time step 0.

  • out_file (string) – The data file to write.

_frame_config_index(frame)

Return the configuration index of a frame of a LAMMPS dump.

A frame of a LAMMPS dump is named by its time step, the number below its ITEM: TIMESTEP line (pyretis.tools.recalculate_order.lammpstrj_timesteps()). A run of the engine starts at time step 0 and dumps a frame every subcycles steps, so frame frame of its dump has the time step frame * subcycles; the engines check the time steps of the frames of each run (check_lammps_dump_steps()).

Parameters:

frame (integer) – The frame number in the dump, from 0.

Returns:

out (integer) – The time step of the frame.

static _input_script(engine_settings)

Return the input path and the LAMMPS script of an engine section.

The script is looked up as the engine looks it up when it is created: lammps.in in input_path.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

  • out[0] (string) – The absolute input_path.

  • out[1] (string) – The path of the script.

static _input_script_present(engine_settings)

Return whether an engine section names a script that is there.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (boolean) – True when the section sets input_path and that folder holds a file _input_script() can take (input_file_present()).

_lammps_run_seed(steps, seeded)

Return the value of pyretis_seed for a LAMMPS run.

A run that integrates time steps takes a seed drawn on the random generator of the engine, self.rgen, one draw per run in [1, 899999999]: the generator of the move in a path-sampling run, of the path ensemble in a kick initiation, and of the task in an MD task (draws_run_seeds). A run of zero steps integrates none and draws nothing: it takes PYRETIS_SEED_WITHOUT_STEPS. A run of steps on an engine without a random generator, which a script can start through the Python API, takes PYRETIS_SEED_WITHOUT_STEPS as well when lammps.in draws no random numbers, and is refused when it does.

Parameters:
  • steps (integer) – The number of time steps of the run.

  • seeded (list of strings) – The fixes and pair styles of lammps.in and of the files it reads that draw random numbers (refuse_lammps_fixed_seeds()).

Returns:

out (integer) – The value of pyretis_seed for the run.

Raises:

ValueError – If the run integrates time steps, the engine has no random generator, and seeded is not empty.

_make_order_fix(ordername)

Create a LAMMPS fix for the order parameter.

Note that we here make LAMMPS also output for step zero.

_prepare_lammps_run(system, settings, name)

Write the LAMMPS input script and return the run command.

This is the input-preparation half of run_lammps(). The streaming engine (pyretis.engines.lammps.LAMMPSEngine) builds its LAMMPS input with it too: with order_mode = "pyretis", the one order mode the streaming engine takes, the two engines ask LAMMPS to do the same in a propagation and differ in how the trajectory is consumed. With order_mode = "lammps" the input also carries the fix that prints the order parameter of order.in (_make_order_fix()).

A configuration held in a data file is copied to the file of the name of the system.data of the input in exe_dir, which lammps.in reads. A bare file name names the file of that name in exe_dir, where the input files are staged; a path with a directory, absolute or relative to the working directory, names that file, as it does for ExternalMDEngine.dump_config() and for the streaming engine (pyretis.engines.lammps.LAMMPSEngine._locate_data_file()).

Parameters:
  • system (object like System) – Defines the initial configuration to start from.

  • settings (dict) – LAMMPS input settings; mutated in place with the trajectory, order, subcycle, timestep, dimension and order-fix entries.

  • name (string) – Base name for the LAMMPS input script and output files.

Returns:

cmd (list of strings) – The command (with arguments) to launch LAMMPS.

Raises:

ValueError – If a fix or a pair style of lammps.in or of a file it reads draws random numbers with a seed other than the seed of the run, ${pyretis_seed} (refuse_lammps_fixed_seeds()), as add_input_files() raises it for a restart file of lammps.in, and, before any file is staged, for a configuration held in a LAMMPS restart file (refuse_restart_configuration()).

_propagate_from(name, path, system, ens_set, msg_file, reverse=False)

Propagate with LAMMPS from the current system configuration.

Parameters:
  • name (string) – A name to use for the trajectory we are generating.

  • path (object like PathBase) – This is the path we use to fill in phase-space points.

  • system (object like System) – The system object gives the initial state. The order function is injected on the engine (self.order_function).

  • ens_set (dict) – Ensemble settings. It contains:

    • interfaces: list of floats These interfaces define the stopping criterion.

  • msg_file (object like FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.

  • reverse (boolean, optional) – If True, the system will be propagated backward in time.

Returns:

  • success (boolean) – This is True if we generated an acceptable path.

  • status (string) – A text description of the current status of the propagation.

classmethod _read_lammps_data_frame(data_file, atom_style=None, input_style=None)

Parse a LAMMPS data file for a velocity draw or order parameter.

The file is read by read_lammps_data_file(), with its box, the reader of the masses of the streaming engine (pyretis.engines.lammps.get_atom_masses()), which reads it without the box. The order parameter of a data file is that of the streaming engine (pyretis.engines.lammps.LAMMPSEngine.calculate_order()).

Parameters:
  • data_file (string) – The LAMMPS data file to read.

  • atom_style (string, optional) – Engine-configured atom style.

  • input_style (string, optional) – The style of the atom_style command of lammps.in (lammps_input_atom_style()).

Returns:

  • ids (list of int) – The atom ids, sorted ascending.

  • positions (numpy.ndarray) – The per-atom positions, shape (N, 3).

  • images (numpy.ndarray) – The per-atom image flags, shape (N, 3).

  • masses (numpy.ndarray) – The per-atom masses, shape (N, 1).

  • box (list of tuple) – The (lo, hi) box bounds of x, y and z, from the header of the file.

Raises:

ValueError, NotImplementedError – As read_lammps_data_file() raises them, for a data file of a triclinic box among others.

_refuse_disagreeing_orders(system, order, settings)

Refuse a frame whose two order parameters differ.

With order_mode = "lammps" LAMMPS evaluates the order parameter of the frames it propagates, one column per variable of order.in (lammps_order_columns()), and stops a run when v_op_1 crosses an interface. A run with an [orderparameter] evaluates it and its collective variables in PyRETIS for the frames it reads back, as the frames of a load: on the unwrapped positions of the atoms from the lower bounds of the box and on the velocities of the path (_calculate_pyretis_order()). Both are evaluated on each frame of the run, and the run stops at the first frame whose two order parameters have another number of columns or a column whose values differ by more than LAMMPS_ORDER_AGREEMENT_TOLERANCE: its paths would hold, and its runs stop on, values of another order parameter than the one of the frames it reads. Without an order parameter on the engine, LAMMPS gives the only value.

Parameters:
  • system (object like System) – The template of the system the order parameter is evaluated on.

  • order (numpy.ndarray) – The order parameters LAMMPS gives the frames of the run, one row per frame, v_op_1 first.

  • settings (dict) – The settings of the run: the dump traj and reverse_order_velocities.

Raises:

ValueError – If the two order parameters have another number of columns, or if a column of a frame differs.

_reverse_velocities(filename, outfile)

Reverse the velocities for a given configuration.

static _trim_to_common_length(order, energy)

Trim LAMMPS run data to the common sampled-frame length.

_velocity_draw_data_file(system)

Return the LAMMPS data file that a velocity draw reads.

The configuration of system is written to a data file in exe_dir (dump_frame()), by LAMMPS for a frame of a dump, and by a copy for a whole data file, before the draw reads it. A data file that the reader refuses is left in exe_dir.

Parameters:

system (object like System) – The state whose velocities are drawn.

Returns:

out (string) – The data file.

_warn_skipped_rescale(name, system, rescale)

Log the warning of a velocity re-scale LAMMPS skipped.

The warnings are those of pyretis.core.particlefunctions.rescale_velocities() for the same two cases.

Parameters:
  • name (string) – The base name of the LAMMPS run that created the velocities.

  • system (object like System) – The state of that run; its vpot is the pe LAMMPS compared with rescale.

  • rescale (float) – The target energy of the re-scale.

static _write_velocity_dump(dump_file, ids, pos, vel, images, box)

Write a LAMMPS dump frame (positions, velocities, image flags).

The columns id x y z vx vy vz ix iy iz match what the read_dump command of the engine’s run input (READ_DUMP) reads back.

add_input_files(dirname)

Add required input files to a given directory.

Every LAMMPS run of the engines runs in the directory, after this method. The restart files that the read_restart commands of lammps.in read, and the files of its include and jump commands, are then checked where LAMMPS opens them (refuse_lammps_restart_files(), refuse_unstaged_lammps_files()).

Parameters:

dirname (string) – The path to the directory where we want to add the files.

Raises:

ValueError – As refuse_lammps_restart_files() and refuse_unstaged_lammps_files() raise it.

calculate_order(system, xyz=None, vel=None, box=None)

Return the order parameter of the configuration of a system.

The engine evaluates the order parameter of each configuration it makes: of the last frame of each run of LAMMPS that collects it (run_lammps()), a step() and the run of velocity_generation = "engine" among them, and of the frame of each velocity_generation = "maxwell" draw (_evaluate_drawn_order()). This method returns that value, system.order.

Parameters:
  • system (object like System) – The state whose order parameter we return.

  • xyz (numpy.array, optional) – Unused; present to match the base signature.

  • vel (numpy.array, optional) – Unused; present to match the base signature.

  • box (numpy.array, optional) – Unused; present to match the base signature.

Returns:

out (list of floats) – The last seen order parameter for the system.

default_units = None
draws_run_seeds = True
dump_config(config, deffnm='conf')

Extract a configuration frame, as the external engines do.

The configuration is refused first when it is held in a LAMMPS restart file (refuse_restart_configuration()).

Parameters:
  • config (tuple) – The configuration as (filename, index).

  • deffnm (string, optional) – The base name for the dumped file.

Returns:

out (string) – The file name we dumped to (ExternalMDEngine.dump_config()).

Raises:

ValueError – As refuse_restart_configuration() raises it.

dump_phasepoint(phasepoint, deffnm='conf')

Dump a phase point to a new file.

Note

We do not reverse the velocities here.

engine_draw_reads_set_temp = True
classmethod get_default_units(settings=None)

Return the default unit system for the LAMMPS engine.

This is read from the units command in the LAMMPS input template. If the template can not be inspected, or if it does not define units, an exception is raised.

Parameters:

settings (dict, optional) – Full simulation settings or engine settings.

Returns:

out (string) – The default unit system for the LAMMPS engine.

Raises:

ValueError – If the LAMMPS input template can not be read, or if no units command is found in that file.

classmethod input_path_sampling_problem(engine_settings)

Return why a path-sampling run cannot use the script of a section.

The script is looked up as read_input_temperatures() looks it up, and its fixes, with those of the files it reads in input_path, are read as path_sampling_problem() reads them (lammps_path_sampling_problem()). The files the engine stages are files of input_path, so LAMMPS reads the same files.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (string or None) – The reason, or None when every fix stores the velocities at the time of the positions. None for a section without a script to read (_input_script_present()): the run reports the missing script where it reads the units or the temperature of the section (get_default_units(), read_input_temperatures()) or creates the engine.

Raises:

NotImplementedError – As lammps_named_commands() raises it.

integrate(system, order_function, steps, thermo='full')

Propagate several integration steps with LAMMPS.

Parameters:
  • system (object like System) – The system to integrate.

  • order_function (object like OrderParameter or None) – An order function can be specified if we want to calculate the order parameter along with the simulation.

  • steps (integer) – The number of integration steps to perform. The LAMMPS run length is max(steps - 1, 0) subcycles so that the first frame is the initial configuration.

  • thermo (string, optional) – Truthy values include a 'thermo' key in each returned step dict with the energy terms read from the LAMMPS log.

Returns:

out (list of dict) – A list of step dicts each containing the integrated 'system' (and 'order' / 'thermo' when requested).

modify_velocities(system, vel_settings, rgen)

Modify velocities.

Parameters:
  • system (object like System) – The state whose velocities we modify.

  • vel_settings (dict) – It contains all the info for the velocity modification. For LAMMPS only aimless settings are supported. In "engine" mode a positive rescale is written into the LAMMPS input, which re-scales the created velocities so that the energy pe + ke LAMMPS evaluates equals it (per atom under thermo_modify norm yes, the LAMMPS default for lj units). For a pe above that energy, or a ke that is zero, LAMMPS keeps the created velocities and the warning of pyretis.core.particlefunctions.rescale_velocities() is logged (_warn_skipped_rescale()). The "maxwell" draw leaves the energy as drawn, so it refuses a positive rescale (refuse_energy_rescale()). zero_momentum requests a zero linear momentum after the draw (a missing key means False): in "engine" mode it sets the mom keyword of the LAMMPS velocity create command to yes or no, and the keyword is always written because the LAMMPS default is mom yes. In "engine" mode, with a fix of lammps.in, or of a file it reads, that constrains the velocities (lammps_constraint_fixes(), which reads an included file as LAMMPS reads it from exe_dir, where the input files are staged), the velocities that the setup of a run constrains are re-scaled to SET_TEMP, with the constrained degrees of freedom counted, before the re-scale to rescale (_add_generate_vel()).

  • rgen (object like RandomGenerator) – The velocity random generator, injected explicitly per call. In the default velocity_generation = "engine" mode it draws the LAMMPS velocity create seed; in "maxwell" mode it draws the velocities directly.

Returns:

  • dek (float) – The change in the kinetic energy.

  • kin_new (float) – The new kinetic energy.

Raises:
  • NotImplementedError – If, in "maxwell" mode, rescale is positive, LAMMPS runs lammps.in in units other than real, those of its last units command after its last clear command, also in a file it includes (refuse_lammps_draw_units()), or the configuration is held in a data file, a .data file, and lammps.in has a mass command (refuse_lammps_mass_command()). Also, in "maxwell" mode, as read_lammps_data_file() raises it for the data file of the draw: for a triclinic box, or Atoms rows of an atom style that is not supported. The data file that LAMMPS write_data writes for a frame of a dump in a triclinic box has the xy xz yz line of the box, so every draw in a triclinic box raises it. In "engine" mode, before the draw, for a constraint fix that the draw refuses (refuse_lammps_constraint_fixes()), as fix shake, and for a fix command that names its style, or an include or jump command that names its file, by a LAMMPS variable (lammps_fix_commands()).

  • ValueError – If sigma_v selects a soft velocity perturbation. Also, in "maxwell" mode, for each refusal of the data file of the draw that the Raises section of read_lammps_data_file() lists. The data file is written in exe_dir before it is read (_velocity_draw_data_file()). In both modes, before anything else, if the configuration of system is held in a LAMMPS restart file (refuse_restart_configuration()).

needs_order = False
path_sampling_problem()

Return why a path-sampling run cannot use this engine.

The fixes of lammps.in and of the files it reads, staged with the input files of the engine, are read as lammps_path_sampling_problem() reads them. A fix of Brownian dynamics (brownian, brownian/sphere, brownian/asphere, brownian/poly) integrates without inertia, and a Gronbech-Jensen-Farago Langevin fix with vhalf (fix langevin with gjf vhalf, fix gjf without vel vfull) stores the velocities half a time step away from the positions. A thermostat or barostat fix of the Nose-Hoover equations (fix nvt, npt, nph and their variants, the rigid nvt, npt and nph styles, bocs, tgnvt/drude, tgnpt/drude, nphug, pimd/nvt) or of a shock wave (msst, qbmsst) carries variables of its own from one time step to the next, which a frame does not store; fix temp/berendsen, temp/rescale, press/berendsen, heat and ehex rescale, nve/limit, viscosity and thermal/conductivity change the velocities, and fix deform/pressure with a pressure control moves the box, deterministically and without time reversibility.

Returns:

out (string or None) – The reason, or None when a path-sampling run can use every fix.

Raises:

NotImplementedError – As lammps_named_commands() raises it.

path_sampling_warnings()

Return why path sampling with this engine is not exact.

The fixes and pair styles of lammps.in and of the files it reads, staged with the input files of the engine, are read as lammps_path_sampling_warnings() reads them. A warning names fix gle, gld, press/langevin, ttm and its variants, and fix langevin with gjf vfull, whose memory between time steps restarts with each piece of trajectory, fix viscous, viscous/sphere, viscous/nonlinear, damping/cundall, deform and deform/pressure, which change the dynamics of a piece by the direction of time or by its first time step, pair style dpd/fdt/energy, whose internal energies a frame does not store, and a thermostat whose target temperature can change during a run.

Returns:

out (list of strings) – The warnings, each naming the command, why path sampling with it is not exact and what to use instead.

Raises:

NotImplementedError – As lammps_named_commands() raises it.

propagate(path, ens_set, system, reverse=False)

Propagate the equations of motion with the external code.

This is a LAMMPS-specific override: unlike the generic ExternalMDEngine.propagate(), LAMMPS reverses the velocities through its own input file rather than via _reverse_velocities(), so the common set-up is handled here directly.

Parameters:
  • path (object like PathBase) – This is the path we use to fill in phase-space points. We are here not returning a new path - this since we want to delegate the creation of the path to the method that is running propagate.

  • ens_set (dict) – Ensemble settings. It contains:

    • interfaces: list of floats These interfaces define the stopping criterion.

  • system (object like System) – The system object gives the initial state for the integration. The initial state is stored and the system is reset to the initial state when the integration is done. The order function is injected on the engine (self.order_function).

  • reverse (boolean, optional) – If True, the system will be propagated backward in time.

Returns:

  • success (boolean) – This is True if we generated an acceptable path.

  • status (string) – A text description of the current status of the propagation.

Raises:

ValueError – Before any file is written, if the configuration of system is held in a LAMMPS restart file (refuse_restart_configuration()), and as run_lammps() raises it.

read_energies(name)

Read energies obtained in a LAMMPS run.

Here, we assume that the energies can be found in a log file in the current execute directory.

classmethod read_input_temperatures(engine_settings)

Read the temperatures of the LAMMPS script of an engine section.

The script is looked up as the engine looks it up when it is created: lammps.in in input_path. The script of an engine that draws its velocities with LAMMPS must define SET_TEMP (refuse_draw_without_set_temp()).

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (object like EngineTemperatures) – The temperatures read_lammps_temperatures() reads.

Raises:

ValueError – As read_lammps_temperatures() and refuse_draw_without_set_temp() raise it.

read_order_parameters(ordername)

Read order parameters as calculated by LAMMPS.

We assume here that these can be found in the current execute directory in a file named ordername, and further that they contain the step number in the first column, followed by the order parameters in following columns.

refuse_draw_without_beta(engine)

Refuse a velocity draw of an engine without a beta.

The engine draws with the k_B of LAMMPS real units, and has a beta when the script runs in units real (engine_temperatures). refuse_lammps_draw_units() refuses a draw in other units first, from the units LAMMPS runs the script in (read_lammps_units()); this check stops a draw where the reader of the temperature finds other units.

Parameters:

engine (string) – The engine that draws, as the message names it at its start.

Raises:

ValueError – If the engine has no beta.

classmethod refuse_draw_without_set_temp(temperatures, velocity_generation)

Refuse a LAMMPS draw of the velocities without SET_TEMP.

With velocity_generation = "engine" the relaunch engine asks LAMMPS to create the velocities at the variable SET_TEMP of lammps.in (GENERATE_VEL), so the script must define it; a thermostat fix or a velocity command states the temperature of the run, but not the one LAMMPS draws at. An engine that draws the velocities in PyRETIS (a class with engine_draw_reads_set_temp False, and velocity_generation = "maxwell") reads no SET_TEMP.

Parameters:
  • temperatures (object like EngineTemperatures) – The temperatures read from lammps.in.

  • velocity_generation (string) – The velocity_generation of the engine.

Raises:

ValueError – If the engine draws the velocities with LAMMPS and lammps.in does not define SET_TEMP. The message names the variable.

refuse_restart_configuration(config)

Refuse to start from a configuration held in a restart file.

Each method of the engine that reads a configuration, or runs LAMMPS from it, calls this method first (refuse_lammps_restart_configuration()), so that no file is read or written and LAMMPS does not run: the propagation (propagate(), and every LAMMPS run, through _prepare_lammps_run()), the velocity draw (modify_velocities()) and dump_config().

Parameters:

config (tuple) – The file and the index of the configuration.

Raises:

ValueError – If the configuration is held in a LAMMPS restart file, from the working directory or from exe_dir.

restart_configuration_what = 'The relaunch LAMMPS engine (class "lammps_steps")'
run_lammps(system, settings, name)

Execute LAMMPS.

This method will handle input files, run LAMMPS and return some data after the run.

Parameters:
  • system (object like System) – The system defines the initial state we are using. When order_mode is "pyretis" it is also the template for the per-frame order-parameter evaluation; the configured order function is injected on the engine (self.order_function).

  • settings (dict) – This dict contains settings for creating the LAMMPS input file.

  • name (string) – This string is used as a base name for some of the LAMMPS input scripts and output files.

Returns:

  • out[0] (numpy.array) – The order parameters obtained during the run.

  • out[1] (dict of numpy.arrays) – The energies, each dictionary key corresponds to a specific energy term.

  • out[2] (string) – The name of the trajectory created by LAMMPS in this run.

Raises:

ValueError – As _prepare_lammps_run() raises it, and if a frame k of the dump of the run has a time step other than k * subcycles (check_lammps_dump_steps()).

step(system, name)

Perform a single step with LAMMPS.

The step is a run of subcycles time steps, and the order parameter of its last frame becomes system.order (run_lammps()), in both order modes.

Parameters:
  • system (object like System) – The system we are integrating.

  • name (string) – To name the output files from the LAMMPS step.

Returns:

out (string) – The name of the output configuration, obtained after completing the step.

temperature_keys = 'variable SET_TEMP, the thermostat fixes and the velocity commands of lammps.in'
temperature_source = 'input'
unmarked_section_temperature = True
classmethod unmarked_unrecorded_use(engine_settings)

Return what an earlier LAMMPS engine did at its lammps.in.

The PyRETIS of a run file without the temperature_rule mark gave a LAMMPS engine the temperature of its engine section, and the engine computed the beta of its acceptance at it. It drew its velocities in PyRETIS at it too, except the relaunch engine (engine_draw_reads_set_temp) with velocity_generation = "engine", which asked LAMMPS to draw them at the SET_TEMP of lammps.in (GENERATE_VEL). The dynamics ran at the thermostat fixes of lammps.in. No run file records the lammps.in of that run.

Parameters:

engine_settings (dict) – The settings of the engine section, as the run file records them.

Returns:

out (string) – What the engine took from the recorded temperature, and what it did at the lammps.in of that run, as a warning states it.

pyretis.engines.lammps_steps.LAMMPS_ORDER_AGREEMENT_TOLERANCE = 1e-06

The largest difference between an order-parameter column that LAMMPS gives a frame (a variable of order.in) and the value of the column of the [orderparameter] and the collective variables of the frame, with order_mode = "lammps": the two are one order parameter at the precision of the dump.

pyretis.engines.lammps_steps._add_generate_vel(settings)

Add generation of velocities to the LAMMPS input.

Parameters:

settings (dict) – The LAMMPS input settings. Its generate_vel entry, when present, holds the seed of the draw, the rescale energy, zero_momentum, which selects the mom keyword of the velocity create command, and constrained, True when a fix of a style of LAMMPS_PROJECTING_FIXES constrains the velocities (a missing key means False). velocity create scales the velocities it creates to SET_TEMP, and a run of 0 steps follows it. With constrained, the setup of that run constrains the velocities, and GENERATE_VEL_SCALE re-scales them to SET_TEMP, with the degrees of freedom that the fixes constrain counted, as the LAMMPS documentation of the velocity command gives for rigid bodies and constraints; the constraints are linear in the velocities, so the re-scaled velocities satisfy them. A positive rescale then re-scales the velocities so that the energy pe + ke LAMMPS evaluates equals it (RESCALE_ENERGY), when pe is not above it and ke is positive; otherwise LAMMPS keeps the velocities and prints RESCALE_SKIPPED_PE or RESCALE_SKIPPED_KE (RESCALE_CONDITION). With constrained, a run of 0 steps before this re-scale evaluates pe and ke for the velocities of GENERATE_VEL_SCALE.

Returns:

lines (list of strings) – The LAMMPS commands that create the velocities; empty when settings requests no velocity generation.

pyretis.engines.lammps_steps._add_order_fix(settings)

Add the fix for printing the order parameter for LAMMPS.

pyretis.engines.lammps_steps._add_stopping_condition(settings)

Add the interface stopping condition to the LAMMPS input.

pyretis.engines.lammps_steps._add_traj_dump(settings)

Add the dump commands for storing the LAMMPS trajectory.

pyretis.engines.lammps_steps._check_lammps_data_keyword_line(tokens, index, lines, data_file, previous)

Refuse a line that LAMMPS read_data stops at as a keyword line.

LAMMPS reads the first line below the header, and the first line below the rows of a section, that is neither blank nor a comment, as the keyword line of a section, unless it is the last line of the file (_read_lammps_data_sections()).

Parameters:
  • tokens (list of strings) – The words of the line, without its comment.

  • index (integer) – The index of the line in lines.

  • lines (list of strings) – The lines of the data file.

  • data_file (string) – The data file, as the error messages name it.

  • previous (tuple or None) – The keyword, the number of rows and the line number, from 1, of the first row of the section whose rows the line follows; None for the line below the header.

Raises:

ValueError – If the line is not the keyword line of a Masses or Atoms section, and follows the rows of a section and starts with a number, as a row beyond the number of rows of the header does, or has a keyword of a header line (_lammps_data_header_keyword()); the message names the line.

pyretis.engines.lammps_steps._counted(number, noun)

Return a number and a noun, in the plural for a number other than 1.

Parameters:
  • number (integer) – The number.

  • noun (string) – The noun in the singular, as row or atom type.

Returns:

out (string) – number and noun, with an s appended to noun for a number other than 1, as 1 row and 3 rows.

pyretis.engines.lammps_steps._is_one_lammps_word(value)

Return True if a value of a LAMMPS variable is one plain word.

Parameters:

value (string) – A word of a variable command after its style.

Returns:

out (boolean) – True if value is not empty and holds no white space (LAMMPS_WHITESPACE) and no $.

pyretis.engines.lammps_steps._is_other_lammps_data_header(tokens)

Return whether a line is a header line that PyRETIS does not read.

These are the lines N bonds, N bond types, N extra bond per atom and the like (LAMMPS_DATA_OTHER_COUNTS and LAMMPS_DATA_EXTRA_PER_ATOM), with the number N in digits, which LAMMPS read_data reads by their keywords after the number, as it reads N atoms, and ignores the words after the keywords.

Parameters:

tokens (list of strings) – The words of the line, without its comment.

Returns:

out (boolean) – True if tokens is one of these lines.

pyretis.engines.lammps_steps._iter_lammps_dump_lines(lines, dimension, source='<lines>')

Parse LAMMPS custom dump frames from an iterator of text lines.

The frames are yielded one at a time: read_lammps_dump() reads them all, and write_lammps_dump_frame() stops at the frame it writes. The parser is strict: a frame truncated mid-way raises, so a caller must hand it complete frames only.

The positions of a dump of scaled positions (xs, xsu and so on) are those its box gives them (lammps_scaled_positions()). The unwrapped position of an atom is its wrapped position plus the edge vectors of the box times its image flags: x + ix * L with the box length L of the axis in an orthogonal box, and x + ix * a + iy * b + iz * c in a triclinic box (lammps_box_vectors()), whose image flags are read from the dump.

Parameters:
  • lines (iterator of strings) – The dump lines to parse.

  • dimension (integer) – Number of spatial dimensions to extract.

  • source (string, optional) – Name used in error messages (the originating file).

Yields:

frame (dict) – A frame containing its timestep, box, atom IDs, wrapped/unwrapped positions, image flags and velocities.

pyretis.engines.lammps_steps._lammps_command_words(command)

Return the words of a LAMMPS command, as LAMMPS reads them.

The comment of the command is left out (_strip_lammps_comment()), the characters of LAMMPS_UTF8_SUBSTITUTIONS are replaced, and the words are split as LAMMPS splits them (_split_lammps_words()). LAMMPS variables are not evaluated: a word with a $ names one.

Parameters:

command (string) – A command, as _lammps_input_commands() returns it.

Returns:

out (list of strings) – The words of the command; the first is the name of the command.

pyretis.engines.lammps_steps._lammps_commands_of_name(variables, name)

Return the variable commands that define one variable.

Parameters:
  • variables (list of tuples) – The variable commands, each the file that holds it and the words of the command after variable.

  • name (string) – The name of the variable.

Returns:

out (list of tuples) – The commands whose first word is name.

pyretis.engines.lammps_steps._lammps_compute_argument_dependence(name, style, word, definitions, seen)

Return why an argument of a compute is not a position function.

Parameters:
  • name (string) – The ID of the compute.

  • style (string) – The style of the compute, without its accelerator suffix.

  • word (string) – The argument, without an index in brackets.

  • definitions (dict) – The commands of the input (lammps_order_definitions()).

  • seen (set of tuples) – The variables and computes read so far; changed in place.

Returns:

out (tuple of strings or None) – The compute and why the argument is not a function of the positions; None when it is one.

pyretis.engines.lammps_steps._lammps_compute_dependence(name, definitions, seen)

Return why a LAMMPS compute is not a function of the positions.

A compute is a function of the positions when each command that defines it has a style of LAMMPS_POSITION_COMPUTE_STYLES, without its accelerator suffix, a group that is not dynamic, and arguments that are: the attributes of property/atom are of LAMMPS_POSITION_ATOM_PROPERTIES, the arguments of reduce are of LAMMPS_REDUCE_WORDS, positions and integers (and the region first for reduce/region), and for each style a reference to a variable, a compute or a fix (v_, c_, f_) is read by _lammps_word_dependence() and a velocity is refused.

Parameters:
  • name (string) – The ID of the compute.

  • definitions (dict) – The commands of the input (lammps_order_definitions()).

  • seen (set of tuples) – The variables and computes read so far; changed in place.

Returns:

out (tuple of strings or None) – The word that the compute reads and why it is not a function of the positions; None when it is one.

pyretis.engines.lammps_steps._lammps_data_header_keyword(tokens)

Return the first keyword of a header line that a line has.

The words are compared in lower case, so XLO is the keyword xlo, which LAMMPS read_data reads in lower case only.

Parameters:

tokens (list of strings) – The words of the line, without its comment.

Returns:

out (string or None) – The keyword, in lower case, of the first word of tokens that is atoms or a keyword of the box (LAMMPS_DATA_BOX_WORDS), or of the words atom types; None when tokens has none of them.

pyretis.engines.lammps_steps._lammps_data_integer(text, row, column)

Return a column of a data-file row that holds an integer.

Parameters:
  • text (string) – The column.

  • row (string) – The row, as the error message names it.

  • column (string) – What the column holds, as the error message names it.

Returns:

out (integer) – The integer that text writes.

Raises:

ValueError – If text does not write an integer, as 1.0 or -0.82.

pyretis.engines.lammps_steps._lammps_data_number(text, row, column)

Return a column of a data-file row that holds a number.

Parameters:
  • text (string) – The column.

  • row (string) – The row, as the error message names it.

  • column (string) – What the column holds, as the error message names it.

Returns:

out (float) – The number that text writes.

Raises:

ValueError – If text does not write a number (LAMMPS_DATA_NUMBER).

pyretis.engines.lammps_steps._lammps_data_reads(section, count, first, data_file)

Return how LAMMPS read_data reads a section, for a message.

Parameters:
  • section (string) – The keyword of the section, a key of LAMMPS_DATA_VELOCITY_SECTIONS.

  • count (integer) – The number of rows of the section, from the header.

  • first (integer) – The line number, from 1, of the first row.

  • data_file (string) – The data file, as the message names it.

Returns:

out (string) – The clause of a message, without a full stop.

pyretis.engines.lammps_steps._lammps_data_section_rows(lines, index, count, data_file)

Return the rows of a section of a data file that PyRETIS reads.

The section is a Masses, Atoms or Velocities section (LAMMPS_DATA_VELOCITY_SECTIONS). LAMMPS read_data skips the line below the keyword line of a section, whatever it holds, and reads the count lines from the second line below the keyword line as the rows of the section, one for each atom type or atom of the header. The words of a row are those of _lammps_data_words().

Parameters:
  • lines (list of strings) – The lines of the data file.

  • index (integer) – The index in lines of the keyword line of the section.

  • count (integer) – The number of rows of the section, from the header.

  • data_file (string) – The data file, as the error messages name it.

Returns:

out (list of tuples) – The line and the words of each row.

Raises:

ValueError – If the file ends before the last row, or a row is a blank line or a comment, which LAMMPS stops at; the message names the line.

pyretis.engines.lammps_steps._lammps_data_words(line)

Return the words of a row of a LAMMPS data file, without a comment.

LAMMPS read_data reads a row of the Masses and Atoms sections up to its first word that starts with #, so a # inside a word, as in 1.0#H, is part of that word.

Parameters:

line (string) – The line of the row.

Returns:

out (list of strings) – The words of line before its first word that starts with #.

pyretis.engines.lammps_steps._lammps_deform_pressure_problem(source, words, template)

Return why a path-sampling run cannot use a fix deform/pressure.

The parameters and keywords of the command are read as LAMMPS reads them, from the word after N on (LAMMPS_DEFORM_PRESSURE_PARAMETERS, LAMMPS_DEFORM_PRESSURE_KEYWORDS); LAMMPS applies the last value of a keyword that the command repeats. A style of LAMMPS_DEFORM_PRESSURE_FEEDBACK, and the style volume with vol/balance/p yes, move the box by the deviation of the pressure from a target, deterministically and without time reversibility, as fix press/berendsen does.

Parameters:
  • source (string) – The file that holds the command.

  • words (list of strings) – The words of the command after fix, of the style LAMMPS_DEFORM_PRESSURE.

  • template (string) – The path of lammps.in, for the sentence on the md tasks (_lammps_md_tasks()).

Returns:

out (string or None) – The reason, for a pressure control and for a word at the place of a parameter, a style or a keyword that is not one or that holds a LAMMPS variable; None for a fix that changes the box as fix deform does.

pyretis.engines.lammps_steps._lammps_fix_variable_problem(source, words, checked, one_word)

Return why the words of a LAMMPS fix command cannot be read.

Parameters:
  • source (string) – The file that holds the command.

  • words (list of strings) – The words of the command after fix.

  • checked (integer) – The number of the words of words, from the first, whose variables must give one word.

  • one_word (set of strings) – The variables that give one word (lammps_one_word_variables()).

Returns:

out (string or None) – The reason, for the first word that reads by substitution a variable not in one_word; None when there is none.

pyretis.engines.lammps_steps._lammps_fix_warnings(source, words, style, variables)

Return the path-sampling warnings of one LAMMPS fix command.

Parameters:
  • source (string) – The file that holds the command.

  • words (list of strings) – The words of the command after fix.

  • style (string) – The style of the fix without its accelerator suffix.

  • variables (list of tuples) – The variable commands of lammps.in and of the files it reads (lammps_named_commands()).

Returns:

out (list of strings) – The warnings: for a fix of LAMMPS_MEMORY_FIXES, of LAMMPS_MOMENTUM_FIXES with an N other than 1 (_lammps_momentum_warning()), of LAMMPS_START_CHANGING_FIXES, and for fix langevin and fix langevin/eff with gjf vfull.

pyretis.engines.lammps_steps._lammps_formula_dependence(formula, definitions, seen)

Return what makes a LAMMPS formula other than a position function.

A formula is a function of the positions of the atoms and of the box of a frame when each word it reads is one: a number, an operator, a word of LAMMPS_FORMULA_BOX_KEYWORDS, LAMMPS_FORMULA_CONSTANTS, LAMMPS_FORMULA_MATH_FUNCTIONS or LAMMPS_FORMULA_POSITION_ATOMS, a group or region function of LAMMPS_FORMULA_POSITION_GROUP_FUNCTIONS of a group that is not dynamic, or a variable or a compute that is one (_lammps_word_dependence()).

Parameters:
  • formula (string) – The formula, or a value of a variable of another style.

  • definitions (dict) – The commands of the input (lammps_order_definitions()).

  • seen (set of tuples) – The variables and computes read so far; changed in place.

Returns:

out (tuple of strings or None) – The word that the formula reads and why it is not a function of the positions; None when the formula is one.

pyretis.engines.lammps_steps._lammps_gjf_choice(words, style)

Return the value of the keyword that chooses the GJF velocities.

The keywords are read as _lammps_gjf_problem() reads them.

Parameters:
  • words (list of strings) – The words of the command after fix.

  • style (string) – The style of the fix without its accelerator suffix, a key of LAMMPS_GJF_FIXES.

Returns:

out (string or None) – The last value of the keyword, or the value LAMMPS takes when the command does not give it; None when a word at the place of a keyword is not a keyword of the style or holds a LAMMPS variable.

pyretis.engines.lammps_steps._lammps_gjf_problem(source, words, style, template)

Return why a path-sampling run cannot use a GJF Langevin fix.

The keywords of the command are read as LAMMPS reads them, from the word LAMMPS_GJF_FIRST_KEYWORD after fix on, each with the number of values LAMMPS_GJF_FIXES gives; the last value of the keyword that chooses the velocities is the one LAMMPS applies.

Parameters:
  • source (string) – The file that holds the command.

  • words (list of strings) – The words of the command after fix.

  • style (string) – The style of the fix without its accelerator suffix, a key of LAMMPS_GJF_FIXES.

  • template (string) – The path of lammps.in, for the sentence on the md tasks (_lammps_md_tasks()).

Returns:

out (string or None) – The reason, for a fix that stores the velocities half a time step away from the positions, for a keyword or the value of the keyword that chooses the velocities given by a LAMMPS variable, and for a word at the place of a keyword that is not one of LAMMPS_GJF_FIXES; None for a fix that stores the velocities at the time of the positions.

pyretis.engines.lammps_steps._lammps_if_commands(arguments)

Return the commands of every branch of a LAMMPS if command.

Parameters:

arguments (list of strings) – The words of the if command after if: the condition, then and its commands, and for each elif its condition and commands, and for else its commands.

Returns:

out (list of strings) – The commands of all branches, in their order.

pyretis.engines.lammps_steps._lammps_immediate_end(command, index)

Return the index past the immediate variable that starts at index.

As LAMMPS reads an immediate variable, $( starts it and the parenthesis that closes its ( ends it, with the parentheses in between counted. An immediate variable that is not closed runs to the end of the command; LAMMPS stops at such a command.

Parameters:
  • command (string) – A command of a LAMMPS input.

  • index (integer) – The index of the $ of $( in command.

Returns:

out (integer) – The index of the character after the closing parenthesis, or the length of command.

pyretis.engines.lammps_steps._lammps_input_commands(text)

Return the commands of a LAMMPS input text, one string each.

The lines are joined as LAMMPS joins them: a line whose last printable character is & continues on the next line, without the & and the line break, and a command whose lines so far hold an odd number of triple quotes, three double quotes in a row, continues on the next line, after a line break.

Parameters:

text (string) – The text of a LAMMPS input file.

Returns:

out (list of strings) – The commands, each line without its white space at the end (LAMMPS_WHITESPACE).

pyretis.engines.lammps_steps._lammps_keyword_seeds(words, keyword, offset, first)

Return the seeds that a keyword of a LAMMPS command gives.

Parameters:
  • words (list of strings) – The words of the command after its name.

  • keyword (tuple of strings) – The words of the keyword.

  • offset (integer) – The position of the seed after the first word of the keyword.

  • first (integer) – The position of the first word of words that may be a keyword.

Returns:

out (list) – For each place of the keyword in words, the word at the position of its seed, or None when the command ends before it.

pyretis.engines.lammps_steps._lammps_md_tasks(template)

Return what the md tasks do with a LAMMPS input path sampling refuses.

The md, md-nve and md-flux tasks read the temperature of lammps.in with read_lammps_temperatures() and take the one temperature its settings hold, which decides the sentence (md_tasks_sentence()).

Parameters:

template (string) – The path of lammps.in.

Returns:

out (string) – A sentence that says that every task refuses the input, with the reason, for an input the reader refuses or whose settings hold no temperature or different ones; else that the md, md-nve and md-flux tasks accept it.

pyretis.engines.lammps_steps._lammps_momentum_warning(words, style, variables)

Return the warning of a fix of LAMMPS_MOMENTUM_FIXES.

Parameters:
  • words (list of strings) – The words of the command after fix.

  • style (string) – The style of the fix without its accelerator suffix.

  • variables (list of tuples) – The variable commands of lammps.in and of the files it reads (lammps_named_commands()).

Returns:

out (string or None) – The warning; None when its N, the word at LAMMPS_MOMENTUM_INTERVAL, is 1 as _lammps_number() reads it: the fix then acts at the end of every time step.

pyretis.engines.lammps_steps._lammps_number(word, variables)

Return the number that a word of a LAMMPS command gives.

Parameters:
  • word (string) – The word: a number (LAMMPS_NUMBER), or ${name} or $x of a variable that every variable command of its name defines with a style of LAMMPS_VALUE_VARIABLE_STYLES and one number.

  • variables (list of tuples) – The variable commands of lammps.in and of the files it reads (lammps_named_commands()).

Returns:

out (float or None) – The number; None for another word, or for a variable that is defined with two numbers that differ or in another way.

pyretis.engines.lammps_steps._lammps_pimd_ensemble(words)

Return the ensemble of a fix of LAMMPS_PIMD_LANGEVIN_FIXES.

Parameters:

words (list of strings) – The words of the command after fix.

Returns:

out (string) – The value of the last keyword LAMMPS_PIMD_ENSEMBLE_KEYWORD among the keywords after the style, or LAMMPS_PIMD_DEFAULT_ENSEMBLE when the command does not give it.

pyretis.engines.lammps_steps._lammps_pimd_memory(style, ensemble)

Return what a fix of LAMMPS_PIMD_LANGEVIN_FIXES carries.

Parameters:
  • style (string) – The style of the fix without its accelerator suffix.

  • ensemble (string) – Its ensemble (_lammps_pimd_ensemble()).

Returns:

out (string) – What the fix integrates with this ensemble, and what carries from one time step to the next that a frame does not store.

pyretis.engines.lammps_steps._lammps_restart_configuration_reason(config, run_dir=None, named=None)

Tell why a configuration is held in a LAMMPS restart file.

A configuration is held in a LAMMPS restart file when its file is named .restart and it is the one configuration of the file (index 0 or None), or when its file starts with the magic string of a LAMMPS restart file (is_lammps_restart_file()), whatever its name and index. The file is looked for where PyRETIS reads it, from the working directory, and, for a relative name, where LAMMPS reads it, in run_dir.

Parameters:
  • config (tuple) – The file and the index of the configuration.

  • run_dir (string, optional) – The directory that LAMMPS runs in.

  • named (string, optional) – The file as the message names it, in place of the file of config (a staged copy stands for the file it is a copy of).

Returns:

out (string or None) – Why the configuration is held in a restart file, for a message; None when it is not.

pyretis.engines.lammps_steps._lammps_rigid_body_keyword(words)

Return the keyword with which rigid bodies keep their velocities.

The setup of a run of a fix rigid style sets the velocities of its bodies from the velocities of their atoms, unless the command has the keyword infile (LAMMPS_RIGID_INFILE), with which the bodies take their velocities from the file, or its last keyword reinit (LAMMPS_RIGID_REINIT), the one LAMMPS applies, has a value other than one of LAMMPS_TRUE_WORDS, with which the bodies take their velocities from their atoms at the setup of the first run only. A value that holds a LAMMPS variable is not one of LAMMPS_TRUE_WORDS.

Parameters:

words (list of strings) – The words of the fix command after fix.

Returns:

out (string or None) – infile and its value, or else the last reinit and its value, as the command has them; None when the command has no infile and no reinit, or a last reinit with a value of LAMMPS_TRUE_WORDS.

pyretis.engines.lammps_steps._lammps_row_layout(style)

Return the row layout of an atom style, or its base style.

pyretis.engines.lammps_steps._lammps_substituted_variables(word)

Return the LAMMPS variables that a word reads by substitution.

LAMMPS replaces ${name} and $x (a name of one character) by the value of the variable before it splits a command into words. An immediate variable $(...) is replaced by one number.

Parameters:

word (string) – A word of a LAMMPS command, as _lammps_command_words() returns it.

Returns:

out (list of strings) – The names of the variables of ${name} and $x, in the order the word reads them.

pyretis.engines.lammps_steps._lammps_thermostat_problem(source, words, style, template)

Return why a path-sampling run cannot use a thermostat or barostat.

Every piece of trajectory that a path-sampling run generates is a LAMMPS run of its own from a stored frame. A fix of the Nose-Hoover equations (LAMMPS_NOSE_HOOVER_ROOTS, LAMMPS_NOSE_HOOVER_FIXES) or of a shock wave (LAMMPS_SHOCK_FIXES) carries variables of its own from one time step to the next, which the frame does not store and which LAMMPS starts anew for each piece, and so does a fix of LAMMPS_PIMD_LANGEVIN_FIXES with an ensemble without its thermostat (nve, nph: _lammps_pimd_memory()). A fix of LAMMPS_RESCALING_FIXES rescales the velocities, or the box, deterministically and is not time reversible, and a fix of LAMMPS_IRREVERSIBLE_FIXES changes the velocities deterministically and is not time reversible.

Parameters:
  • source (string) – The file that holds the command.

  • words (list of strings) – The words of the command after fix.

  • style (string) – The style of the fix without its accelerator suffix.

  • template (string) – The path of lammps.in, for the sentence on the md tasks (_lammps_md_tasks()).

Returns:

out (string or None) – The reason, naming the fix and the fixes to use instead; None for a fix of none of these styles.

pyretis.engines.lammps_steps._lammps_variable_dependence(name, definitions, seen)

Return why a LAMMPS variable is not a function of the positions.

Each command that defines the variable is read: the formula of an equal, vector or atom variable and the values of an index, string, world or universe variable by _lammps_formula_dependence(), and the variable of a format variable. A loop or uloop variable is a number; a variable of another style is not read as a position function.

Parameters:
  • name (string) – The name of the variable.

  • definitions (dict) – The commands of the input (lammps_order_definitions()).

  • seen (set of tuples) – The variables and computes read so far; changed in place.

Returns:

out (tuple of strings or None) – The word that the variable reads and why it is not a function of the positions; None when it is one.

pyretis.engines.lammps_steps._lammps_word_dependence(word, follows, definitions, seen)

Return why a word of a LAMMPS formula is not a position function.

Parameters:
  • word (string) – A name that the formula reads.

  • follows (string) – The character after the word and its white space: ( for a function, [ for an atom value or an element.

  • definitions (dict) – The commands of the input (lammps_order_definitions()).

  • seen (set of tuples) – The variables and computes read so far; changed in place.

Returns:

out (tuple of strings or None) – The word and why it is not a function of the positions; None when it is one.

pyretis.engines.lammps_steps._locate_lammps_file(name, run_dir, staged)

Return the file that LAMMPS reads for a file name of a command.

LAMMPS reads a file that a command names by a relative path from the directory it runs in, run_dir. A file of run_dir that is not there is the copy that the engine stages there before the run, of the file of its name in staged.

Parameters:
  • name (string) – The file name of the command.

  • run_dir (string) – The directory that LAMMPS runs in.

  • staged (dict of strings) – The files that the engine stages in run_dir, as the name of the copy -> the path of the file.

Returns:

out (string or None) – The path of the file that LAMMPS reads; None when there is none, as LAMMPS then stops at the command.

pyretis.engines.lammps_steps._parse_dump_box(bounds)

Return orthogonal box lengths from LAMMPS dump bounds.

pyretis.engines.lammps_steps._parse_lammps_dump_lines(lines, dimension, source='<lines>')

Return all the frames of a LAMMPS dump iterator.

pyretis.engines.lammps_steps._read_lammps_commands(source, files, commands)

Add the commands of a LAMMPS input file and of the files it reads.

The file is read as UTF-8 text, and a byte that is not UTF-8 is read as the replacement character, which no LAMMPS command name or style holds.

Parameters:
  • source (string) – The path of the file.

  • files (dict) – The directory LAMMPS runs in, the staged files and the files read so far, as _scan_lammps_command() describes.

  • commands (dict of lists) – The commands read so far; changed in place, as _scan_lammps_command() describes.

pyretis.engines.lammps_steps._read_lammps_data(data_file, styles, read_box, read_velocities)

Read the header and the sections of a LAMMPS data file.

The file is read as read_lammps_data_file() describes, and, with read_velocities, its Velocities section too (_read_lammps_data_sections()).

Parameters:
  • data_file (string) – The LAMMPS data file.

  • styles (tuple of strings) – The [engine] atom_style and the style of the atom_style command of lammps.in, each None when not given.

  • read_box (boolean) – True to read the box of the header, as read_lammps_data_file() reads it.

  • read_velocities (boolean) – True to read the Velocities section.

Returns:

  • type_masses (list of tuples) – The atom type and the mass of each row of the Masses section.

  • atoms (dict) – The atom type, the positions and the image flags of each atom, by atom ID.

  • velocities (dict or None) – The velocity of each atom, by atom ID; None without read_velocities and for a file without a Velocities section.

  • box (list of tuple or None) – The (lo, hi) box bounds of x, y and z; None when read_box is False.

Raises:

ValueError, NotImplementedError – As read_lammps_data_file() and _read_lammps_data_sections() raise them.

pyretis.engines.lammps_steps._read_lammps_data_atoms(style, rows, data_file)

Read the rows of the Atoms section of a LAMMPS data file.

Parameters:
Returns:

out (dict) – The atom type, the positions and the image flags of each atom, by atom ID.

Raises:
pyretis.engines.lammps_steps._read_lammps_data_bounds(tokens, line, axis, box)

Read a box-bounds line of the header of a LAMMPS data file.

Parameters:
  • tokens (list of strings) – The words of the line, without its comment: the lo and hi bounds and the keywords of the axis (LAMMPS_DATA_BOUNDS).

  • line (string) – The line, as the error messages name it.

  • axis (integer) – The axis of the bounds, 0 for x, 1 for y and 2 for z.

  • box (dict or None) – The (lo, hi) bounds of the header by axis, which the line adds to; None for a read without the box.

Raises:

ValueError – If a bound is not a number, or the hi bound is not above the lo bound, which LAMMPS read_data stops at. If box is not None and gives the bounds of axis, from an earlier line.

pyretis.engines.lammps_steps._read_lammps_data_header(tokens, line, counts, box)

Read a line of the header of a LAMMPS data file.

The line is read as LAMMPS read_data reads it, by the keywords at fixed positions of the line, and the words after them are ignored:

  • N atoms and N atom types, with the number N in digits (LAMMPS_DATA_COUNTS);

  • lo hi xlo xhi, lo hi ylo yhi and lo hi zlo zhi, the bounds of an axis (LAMMPS_DATA_BOUNDS);

  • three numbers and xy xz yz, avec, bvec, cvec or abc origin, a line of a triclinic box (LAMMPS_DATA_TRICLINIC).

The other header lines of LAMMPS, as N bonds with trailing words or none (_is_other_lammps_data_header()), and a line without the keywords of these lines are not read.

Parameters:
  • tokens (list of strings) – The words of the line, without its comment.

  • line (string) – The line, as the error messages name it.

  • counts (dict) – The numbers of the header, by the keys atoms and atom types, which the line adds to.

  • box (dict or None) – The (lo, hi) bounds of the header by axis, 0 for x, 1 for y and 2 for z (LAMMPS_DATA_BOUNDS), which a bounds line adds to. None for a read without the box: a line of the box is then read for its form only.

Raises:
  • NotImplementedError – If box is not None and the line is a line of a triclinic box.

  • ValueError – If the line has a keyword of these lines and is none of them, nor another header line of LAMMPS (_lammps_data_header_keyword()), or gives a number of atoms or atom types that is not written in digits, which LAMMPS stops at with “Unknown identifier in data file”; if a bound, or a number of a line of a triclinic box, is not a number; if a hi bound is not above its lo bound, which LAMMPS stops at. If box is not None and the line gives the bounds of an axis that an earlier line of the header gives.

pyretis.engines.lammps_steps._read_lammps_data_masses(rows, n_types, data_file)

Read the rows of the Masses section of a LAMMPS data file.

Parameters:
  • rows (list of tuples) – The line and the words of each row of the section (_lammps_data_section_rows()).

  • n_types (integer) – The number of atom types that the header of the file gives.

  • data_file (string) – The data file, as the error messages name it.

Returns:

out (list of tuples) – The atom type and the mass of each row.

Raises:

ValueError – If a row does not hold an integer atom type and a number, or holds an atom type outside 1 to n_types or a mass that is not positive, which LAMMPS read_data stops at.

pyretis.engines.lammps_steps._read_lammps_data_sections(lines, index, counts, data_file, styles, *, read_velocities=False)

Read the Masses and Atoms sections of a LAMMPS data file.

The lines from index, the first line below the header, are read as LAMMPS read_data reads them: the first line that is neither blank nor a comment is a keyword line (_check_lammps_data_keyword_line()), the rows of a Masses or Atoms section follow it (_lammps_data_section_rows()), and so does the keyword line of the next section. The keyword line of another section and the line below it are skipped, and so are the lines below them up to the next Masses or Atoms keyword line. LAMMPS reads a keyword line together with the line below it, and at a keyword line that is the last line of the file it ends the read without the section, so such a line is not read. With read_velocities, a Velocities section is read as the Masses and Atoms sections are (_read_lammps_data_velocity_rows()), below the Atoms section, as LAMMPS read_data requires.

Parameters:
  • lines (list of strings) – The lines of the data file.

  • index (integer) – The index in lines of the first line below the header.

  • counts (dict) – The numbers of the header, by the keys atoms and atom types.

  • data_file (string) – The data file, as the error messages name it.

  • styles (tuple of strings) – The [engine] atom_style and the style of the atom_style command of lammps.in, each None when not given (resolve_lammps_atom_style()).

  • read_velocities (boolean, optional) – True to read the Velocities section too. False (the default) to skip it as another section.

Returns:

  • type_masses (list of tuples) – The atom type and the mass of each row of the last Masses section, empty for a file without one.

  • atoms (dict or None) – The atom type, the positions and the image flags of each atom, by atom ID (_read_lammps_data_atoms()); None for a file without an Atoms section.

  • velocities (dict or None) – The velocity of each atom, by atom ID (_read_lammps_data_velocity_rows()); None without read_velocities, and for a file without a Velocities section.

Raises:

ValueError, NotImplementedError – As read_lammps_data_file() raises them for the lines below the header. With read_velocities, a ValueError also for a Velocities section above the Atoms section, which LAMMPS read_data stops at, for a second Velocities section, and as _lammps_data_section_rows() and _read_lammps_data_velocity_rows() raise it for the rows of the section.

pyretis.engines.lammps_steps._read_lammps_data_velocity_rows(rows, atoms, data_file)

Read the rows of the Velocities section of a LAMMPS data file.

Each row is atom-ID vx vy vz, the row of the atom styles whose Atoms rows PyRETIS reads (LAMMPS_DATA_ATOM_COLS), with the velocity of the atom of that ID of the Atoms section.

Parameters:
  • rows (list of tuples) – The line and the words of each row of the section (_lammps_data_section_rows()).

  • atoms (dict) – The atoms of the Atoms section, by atom ID (_read_lammps_data_atoms()).

  • data_file (string) – The data file, as the error messages name it.

Returns:

out (dict) – The velocity of each atom, [vx, vy, vz], by atom ID.

Raises:

ValueError – If a row has another number of columns than 4, an atom ID that is not an integer, a velocity that is not a number, the atom ID of no atom of the Atoms section, which LAMMPS read_data stops at, or the atom ID of an earlier row.

pyretis.engines.lammps_steps._read_lammps_data_velocity_section(rows, atoms, velocities, index, data_file)

Read a Velocities section below the Atoms section.

Parameters:
  • rows (list of tuples) – The line and the words of each row of the section (_lammps_data_section_rows()).

  • atoms (dict or None) – The atoms of the Atoms section read so far, by atom ID; None when no Atoms section is above the Velocities section.

  • velocities (dict or None) – The velocities of a Velocities section read so far; None when no Velocities section is above this one.

  • index (integer) – The index of the keyword line of the section in the lines of the file.

  • data_file (string) – The data file, as the error messages name it.

Returns:

out (dict) – The velocity of each atom, by atom ID (_read_lammps_data_velocity_rows()).

Raises:

ValueError – If no Atoms section is above the section, which LAMMPS read_data stops at, or a Velocities section is, and as _read_lammps_data_velocity_rows() raises it.

pyretis.engines.lammps_steps._refuse_lammps_variable(word, command, source, what)

Refuse a word of a LAMMPS command that holds a LAMMPS variable.

Parameters:
  • word (string) – The word of the command.

  • command (string) – The command, as the message names it.

  • source (string) – The file that holds the command.

  • what (string) – What the word names, as the message names it.

Raises:

NotImplementedError – If word holds a $, the reference to a LAMMPS variable.

pyretis.engines.lammps_steps._scan_lammps_command(words, source, files, commands)

Add the commands of one LAMMPS command to commands.

A command whose name is a key of commands is added to its list. The commands of a file that an include command, or a jump command to a file other than SELF, names are read at that command (_read_lammps_commands()), and the commands of every branch of an if command are read, as commands that LAMMPS may run. An unfix command removes no command from commands.

Parameters:
  • words (list of strings) – The words of the command (_lammps_command_words()).

  • source (string) – The file that holds the command.

  • files (dict) – The run_dir and staged of _locate_lammps_file(), and in read the set of the paths of the files read so far; a file is read once.

  • commands (dict of lists) – The name of a command -> the commands of the name read so far, each the file that holds it and the words of the command after its name; changed in place.

Raises:

NotImplementedError – If a fix command names its style by a LAMMPS variable, or holds fewer than three words after fix and a LAMMPS variable, whose value may hold the style, if a pair_style command names its style by a LAMMPS variable, or if an include or jump command names its file by a LAMMPS variable.

pyretis.engines.lammps_steps._split_lammps_words(command)

Return the words of a LAMMPS command without its comment.

A word is separated from the next by white space (LAMMPS_WHITESPACE), and a word in single, double or triple quotes is the text between the quotes. A quote that is not closed makes the rest of the command one word; LAMMPS stops at such a command. An immediate variable $(...) outside quotes belongs to the word it starts in, white space included: LAMMPS replaces it by its value before it splits the command into words (_lammps_immediate_end()).

Parameters:

command (string) – A command from _strip_lammps_comment().

Returns:

out (list of strings) – The words of the command.

pyretis.engines.lammps_steps._strip_lammps_comment(command)

Return a LAMMPS command without its comment.

The comment starts at the first # that is not between single, double or triple quotes. A quote that is not closed leaves the rest of the command as it is; LAMMPS stops at such a command.

Parameters:

command (string) – A command from _lammps_input_commands().

Returns:

out (string) – The command up to its comment.

pyretis.engines.lammps_steps.add_to_lammps_input(infile, outfile, to_add)

Add PyRETIS specific settings to an input file for LAMMPS.

This method will append settings needed by PyRETIS to an input file for LAMMPS.

Parameters:
  • infile (string) – Path to a file which contains the LAMMPS settings.

  • outfile (string) – Path to the file we should create.

  • to_add (list of strings) – The settings to add for PyRETIS.

pyretis.engines.lammps_steps.check_lammps_atom_row(style, count, row)

Refuse an Atoms row that fits no row layout of an atom style.

A row of a supported style (LAMMPS_ATOM_STYLE_LAYOUT) ends with the three positions, or with the positions and the three image flags, so it has one of two column counts.

Parameters:
  • style (string) – The atom style of the rows, whose base style (lammps_base_atom_style()) is a key of LAMMPS_ATOM_STYLE_LAYOUT.

  • count (integer) – The number of columns of the row.

  • row (string) – The row, as the error message names it.

Raises:

ValueError – If count is neither of the two column counts of style.

pyretis.engines.lammps_steps.check_lammps_dump_steps(filename, subcycles, nframes=None)

Check that frame k of a LAMMPS dump has the step k * subcycles.

The engines name frame k of the dump of a LAMMPS run by the time step k * subcycles (LAMMPSEngineSteps._frame_config_index()), the time step at which a run that starts at time step 0 and dumps every subcycles steps writes it.

Parameters:
  • filename (string) – Path to the LAMMPS dump of a run.

  • subcycles (integer) – The number of steps between two frames of the dump.

  • nframes (integer, optional) – The number of frames to check from the start of the dump; all frames when None. With 0, the dump is not read.

Raises:

ValueError – If a frame of those checked has another time step, or the dump has fewer than nframes frames.

pyretis.engines.lammps_steps.create_lammps_md_input(system, infile, outfile, settings)

Create MD input file for LAMMPS.

We will here write to a new file, by appending text to the given template.

Parameters:
  • system (object like System) – The system contains the current particle state, and this determines the initial configuration and if we are to modify velocities in some way (e.g. reversing them before running or drawing new ones).

  • infile (string) – Path to a file which contains the LAMMPS settings.

  • settings (dict) – The settings we are going to use for creating the LAMMPS file.

Returns:

out (list of strings) – The LAMMPS commands written to the output file.

pyretis.engines.lammps_steps.is_pyretis_seed_word(word)

Return True if a word of a LAMMPS command gives the seed of the run.

The engines define the LAMMPS variable pyretis_seed (PYRETIS_SEED_VARIABLE) for each LAMMPS run, a seed drawn on their random generator. A word gives that seed when it is the variable, ${pyretis_seed}, or an immediate expression that reads it, as $(v_pyretis_seed+1).

Parameters:

word (string) – A word of a LAMMPS command, as _lammps_command_words() returns it.

Returns:

out (boolean) – True if word gives the seed of the run.

pyretis.engines.lammps_steps.lammps_atom_columns(style)

Return the atom-type and first position column of a style’s rows.

Parameters:

style (string) – A LAMMPS atom style, in lower case, with or without an accelerator suffix (lammps_base_atom_style()).

Returns:

out (tuple of integers) – The 0-based atom-type column and first position column of the Atoms rows of style: those of the row layout of its base style (LAMMPS_ATOM_STYLE_LAYOUT) in LAMMPS_DATA_ATOM_COLS.

Raises:

NotImplementedError – If the base style of style is not a key of LAMMPS_ATOM_STYLE_LAYOUT; the message names style.

pyretis.engines.lammps_steps.lammps_atom_masses(atom_types, type_masses, data_file)

Return the mass of each atom from the Masses rows of a data file.

Each row of the Masses section of a LAMMPS data file starts with the atom type whose mass it gives, and the rows can come in any order of the types. An atom has the mass of the row of its type.

Parameters:
  • atom_types (sequence of numbers) – The atom type of each atom, from its Atoms row.

  • type_masses (sequence of pairs of numbers) – The atom type and the mass of each row of the Masses section.

  • data_file (string) – The data file, as the error messages name it.

Returns:

out (numpy.ndarray) – The mass of each atom, in the order of atom_types, shape (N, 1).

Raises:

ValueError – If the Masses section gives an atom type twice, or does not give the atom type of an atom.

pyretis.engines.lammps_steps.lammps_base_atom_style(style)

Return a LAMMPS atom style without its accelerator suffix.

LAMMPS names the variant of an atom style of an accelerator package by the style and a suffix after a /, as full/kk or full/kk/device of the KOKKOS package, and read_data reads the Atoms rows of the variant in the columns of the style.

Parameters:

style (string) – A LAMMPS atom style, in lower case.

Returns:

out (string) – The text of style before its first /.

pyretis.engines.lammps_steps.lammps_base_fix_style(style)

Return a LAMMPS fix or pair style without its accelerator suffix.

LAMMPS names the variant of a style in an accelerator package by the style and a suffix after a / (LAMMPS_ACCELERATOR_SUFFIXES), as rigid/nve/omp of the OPENMP package, and the variant computes what the style computes.

Parameters:

style (string) – A LAMMPS fix or pair style.

Returns:

out (string) – style without its accelerator suffix.

pyretis.engines.lammps_steps.lammps_box_vectors(bounds)

Return the origin and the edge vectors of the box of a dump frame.

A dump of an orthogonal box has a row lo hi for each of x, y and z. A dump of a triclinic box has the rows xlo_bound xhi_bound xy, ylo_bound yhi_bound xz and zlo_bound zhi_bound yz: the bounds of the orthogonal box that holds the tilted box, and the tilt factors. As the LAMMPS dump command defines these bounds, the origin of the box is (xlo, ylo, zlo) and its edge vectors are a = (xhi - xlo, 0, 0), b = (xy, yhi - ylo, 0) and c = (xz, yz, zhi - zlo), with xlo = xlo_bound - min(0, xy, xz, xy + xz), xhi = xhi_bound - max(0, xy, xz, xy + xz), ylo = ylo_bound - min(0, yz) and yhi = yhi_bound - max(0, yz). The unwrapped position of an atom of the image flags ix iy iz is its position plus ix * a + iy * b + iz * c. A box without tilt factors has the tilt factors 0.

Parameters:

bounds (array_like) – The box bounds of the frame, a row for each of x, y and z.

Returns:

  • origin (numpy.ndarray) – The origin (xlo, ylo, zlo) of the box.

  • vectors (numpy.ndarray) – The edge vectors a, b and c of the box, one per row.

pyretis.engines.lammps_steps.lammps_constraint_fixes(template, run_dir, staged=None)

Return the fixes of a LAMMPS input that constrain the velocities.

A constraint fix is a fix command of lammps.in or of a file it reads (lammps_fix_commands()) whose style, without its accelerator suffix (lammps_base_fix_style()), is a style of LAMMPS_PROJECTING_FIXES or of LAMMPS_REFUSED_CONSTRAINT_FIXES.

Parameters:
  • template (string) – The path of lammps.in.

  • run_dir (string) – The directory that LAMMPS runs in.

  • staged (dict of strings, optional) – The files that the engine stages in run_dir before the run, as lammps_fix_commands() takes them.

Returns:

out (list of tuples) – For each constraint fix, the file that holds it, the words of the command after fix and the style without its accelerator suffix.

Raises:

NotImplementedError – As lammps_fix_commands() raises it.

pyretis.engines.lammps_steps.lammps_derived_image_flags(unwrapped, wrapped, length, label, atom_ids, source)

Return the image flags that wrapped and unwrapped positions give.

The image flag of an atom along x of a dump with the columns x and xu and without ix is the integer nearest to (xu - x) / (xhi - xlo); so along y and z. Wrapped and unwrapped columns printed with few significant digits can miss an exact box multiple by a few units of their last place, far below the half box length at which the nearest integer changes, so x + ix * L is accepted within 1e-5 * max(1, L) of xu.

Parameters:
  • unwrapped (float or numpy.ndarray) – The unwrapped positions of the atoms along the axis.

  • wrapped (float or numpy.ndarray) – The wrapped positions of the atoms along the axis.

  • length (float) – The box length of the axis, xhi - xlo along x.

  • label (string) – The axis, x, y or z.

  • atom_ids (integer or numpy.ndarray) – The LAMMPS ids of the atoms, as the message of a refusal names them.

  • source (string) – The dump, as the message of a refusal names it.

Returns:

out (numpy.ndarray) – The image flags of the atoms along the axis, integers in the shape of unwrapped.

Raises:

ValueError – If xu - x of an atom is not an integer box length.

pyretis.engines.lammps_steps.lammps_fix_commands(template, run_dir, staged=None)

Return the fix commands of lammps.in and of the files it reads.

The commands are read as lammps_named_commands() reads them.

Parameters:
  • template (string) – The path of lammps.in.

  • run_dir (string) – The directory that LAMMPS runs in.

  • staged (dict of strings, optional) – The files that the engine stages in run_dir before the run, as the name of the copy -> the path of the file.

Returns:

out (list of tuples) – For each fix command, the file that holds it and the words of the command after fix: the fix ID, the group, the style and the arguments of the style.

Raises:

NotImplementedError – As lammps_named_commands() raises it.

pyretis.engines.lammps_steps.lammps_fix_seeds(words)

Return the seeds of a LAMMPS fix command.

The seeds of a fix style, without its accelerator suffix (lammps_base_fix_style()), are the words at the positions of LAMMPS_FIX_SEED_ARGUMENTS and after the keywords of LAMMPS_FIX_SEED_KEYWORDS and LAMMPS_FIX_DEFAULT_SEED_KEYWORDS. A LAMMPS variable in a word is read as one word.

Parameters:

words (list of strings) – The words of the command after fix: the fix ID, the group, the style and the arguments of the style.

Returns:

out (list) – The word of each seed, or None for a seed that the command does not give: a position after its last word, or a keyword of LAMMPS_FIX_DEFAULT_SEED_KEYWORDS that it does not have, with which LAMMPS seeds the fix with a seed of its own. Empty for a style that draws no random numbers.

pyretis.engines.lammps_steps.lammps_input_atom_style(settings)

Return the style that the atom_style command of an input sets.

Parameters:

settings (dict) – The commands of a LAMMPS input file, as keyword -> arguments, from read_lammps_input().

Returns:

out (string or None) – The first argument of the atom_style command, in lower case, or as written when it holds a $, the reference to a LAMMPS variable; None when the input has no atom_style command with an argument.

pyretis.engines.lammps_steps.lammps_named_commands(template, run_dir, staged=None, names=('fix',))

Return the commands of some names of lammps.in and its files.

The commands are read as LAMMPS reads them (_lammps_command_words()), from template and, at the command that names it, from each file that an include command, or a jump command to a file other than SELF, names, and from the branches of the if commands (_scan_lammps_command()). A file named by a relative path is the one that LAMMPS reads from the directory it runs in (_locate_lammps_file()). A file that is not there is not read, as LAMMPS stops at its command, and a file is read once. Every command of the names that is read is returned: those of the branches of an if command, which LAMMPS may not run, of the commands that a jump command skips, and a fix that an unfix command deletes.

Parameters:
  • template (string) – The path of lammps.in.

  • run_dir (string) – The directory that LAMMPS runs in.

  • staged (dict of strings, optional) – The files that the engine stages in run_dir before the run, as the name of the copy -> the path of the file.

  • names (tuple of strings, optional) – The names of the commands to return.

Returns:

out (dict of lists) – For each name of names, the commands of the name, each the file that holds it and the words of the command after its name.

Raises:

NotImplementedError – As _scan_lammps_command() raises it: for a fix or a pair_style command that names its style, or an include or jump command that names its file, by a LAMMPS variable, a word with a $.

pyretis.engines.lammps_steps.lammps_one_word_variables(variables)

Return the LAMMPS variables whose substitution gives one word.

A variable gives one word when every variable command that defines it has a style of LAMMPS_NUMBER_VARIABLE_STYLES, or a style of LAMMPS_WORD_VARIABLE_STYLES and words after the style that are each one plain word (_is_one_lammps_word()). The engines define pyretis_seed (PYRETIS_SEED_VARIABLE) as a number on the command line of each LAMMPS run, a definition of style index.

Parameters:

variables (list of tuples) – The variable commands of lammps.in and of the files it reads, each the file that holds it and the words of the command after variable (lammps_named_commands()).

Returns:

out (set of strings) – The names of the variables that give one word.

pyretis.engines.lammps_steps.lammps_order_columns(order_file)

Return the variables that LAMMPS prints as order-parameter columns.

With order_mode = "lammps" LAMMPS prints, for each frame, the value of every variable that a variable command of order.in names, in the order of the commands: column k of the order parameter of the frame is the k-th variable.

Parameters:

order_file (string) – The path of order.in.

Returns:

out (list of strings) – The names of the variables, one per column.

pyretis.engines.lammps_steps.lammps_order_definitions(template, order_file, run_dir, staged=None)

Return the variables, computes and groups an order parameter reads.

The variable, compute and group commands are read from lammps.in and the files it reads, as lammps_named_commands() reads them, and from order.in when lammps.in does not read it.

Parameters:
  • template (string) – The path of lammps.in.

  • order_file (string) – The path of order.in.

  • run_dir (string) – The directory that LAMMPS runs in.

  • staged (dict of strings, optional) – The files that the engine stages in run_dir before the run, as the name of the copy -> the path of the file.

Returns:

out (dict) – variable: the name of a variable -> the words after the name of each command that defines it (the style first); compute: the ID of a compute -> the words after the ID of each command that defines it (the group, then the style); dynamic: the IDs of the dynamic groups.

pyretis.engines.lammps_steps.lammps_order_positions(pos, bounds, dimension, images=None)

Return the positions of a LAMMPS frame for its order parameter.

The order parameter of a frame, of both LAMMPS engines and of a frame read back from a dump, is evaluated on the configuration of LAMMPS translated by the lower bounds of its box: the unwrapped positions of the atoms from the lower bounds, in a box of the box lengths xhi - xlo, yhi - ylo and zhi - zlo whose lower bounds are 0. Along x the position is x + ix * (xhi - xlo) - xlo, the xu of LAMMPS minus xlo, and so on along y and z, for the axes of the system; a position along an axis that the system does not have (dimension below 3) is kept. A frame of a triclinic box is evaluated when its tilt factors are 0, in the orthogonal box of its bounds, and refused otherwise (refuse_tilted_lammps_box()).

Parameters:
  • pos (numpy.ndarray) – The positions of the atoms, one row per atom: the unwrapped positions, or, with images, the positions of the frame.

  • bounds (array_like) – The box bounds of the frame, a row lo hi for each of x, y and z, with the tilt factors in a third column for a dump of a triclinic box.

  • dimension (integer) – The number of axes of the system.

  • images (numpy.ndarray, optional) – The image flags of the atoms, in the shape of pos. Without them the positions are taken as unwrapped.

Returns:

out (numpy.ndarray) – The positions from the lower bounds, in the shape of pos.

Raises:

NotImplementedError – If the frame has a triclinic box with a tilt factor other than 0 (refuse_tilted_lammps_box()).

pyretis.engines.lammps_steps.lammps_pair_seeds(words)

Return the seeds of a LAMMPS pair_style command.

Each word of the command that is a pair style of LAMMPS_PAIR_SEED_ARGUMENTS, without its accelerator suffix (lammps_base_fix_style()), is a style of the command, the first word or a sub-style of a hybrid style, and its seed is the word at the position that the table gives after it. A LAMMPS variable in a word is read as one word.

Parameters:

words (list of strings) – The words of the command after pair_style.

Returns:

out (list) – The word of each seed, or None for a seed that the command does not give, a position after its last word. Empty for a command without a style of the table.

pyretis.engines.lammps_steps.lammps_path_argument(path)

Return a file path as one argument of a LAMMPS command.

LAMMPS splits a line of its input into arguments at white space, reads the text from a # on as a comment and the text from a $ as a variable, except between quotes: a text in double or in single quotes is one argument, read without its quotes. A path with none of these characters is returned as it is. Any other path is put in double quotes, or in single quotes if it holds a double quote.

Parameters:

path (string) – The path of a file that a dump, read_dump or write_data command reads or writes.

Returns:

out (string) – The path, as LAMMPS reads it as one argument.

Raises:

ValueError – If the path holds a line break, which ends the line of the command; three double quotes in a row, which LAMMPS reads as the start of a text over several lines, also between single quotes; a *, which LAMMPS replaces by a time step in the file name of these commands, or a %, which it replaces by the rank of a processor in the file name of a dump, where read_dump then expects one file per processor; or both a double and a single quote.

pyretis.engines.lammps_steps.lammps_path_sampling_problem(template, run_dir, staged=None)

Return why a path-sampling run cannot use the fixes of a LAMMPS input.

The fix and variable commands are read from lammps.in and the files it reads, as lammps_named_commands() reads them: every fix command that LAMMPS may run counts, also one that an unfix command deletes or a later fix of its ID replaces. A fix of a style of LAMMPS_BROWNIAN_FIXES integrates Brownian dynamics, without inertia. A fix of a style of LAMMPS_GJF_FIXES stores the velocities half a time step away from the positions with the value vhalf of its keyword (_lammps_gjf_problem()). LAMMPS substitutes the variables of a command before it reads its words, so the fix ID and the group of every fix, and every word of a fix of LAMMPS_GJF_FIXES, must read only variables that give one word (lammps_one_word_variables()). When every fix passes these checks, a thermostat or barostat fix that carries variables of its own from one time step to the next, or that changes the velocities deterministically without time reversibility, is refused (_lammps_thermostat_problem()), and so is a fix deform/pressure that controls the pressure (_lammps_deform_pressure_problem()): the reason of an integrator comes first. The other fixes, as fix nve and the thermostat fixes fix langevin without gjf vhalf, fix temp/csvr and fix temp/csld, with run_style verlet or respa, store the velocities at the time of the positions; lammps_path_sampling_warnings() names those of them that path sampling runs with a warning. The refusal of a fix of Brownian dynamics, of a GJF Langevin fix with vhalf, of a thermostat or barostat fix and of a fix deform/pressure ends with what the md tasks do with lammps.in, as its temperature reader decides (_lammps_md_tasks()).

Parameters:
  • template (string) – The path of lammps.in.

  • run_dir (string) – The directory that LAMMPS runs in.

  • staged (dict of strings, optional) – The files that the engine stages in run_dir before the run, as lammps_named_commands() takes them.

Returns:

out (string or None) – The reason, for the first fix command that a path-sampling run cannot use or cannot read, by the checks of the integrator first; None when there is none.

Raises:
pyretis.engines.lammps_steps.lammps_path_sampling_warnings(template, run_dir, staged=None)

Return why path sampling with a LAMMPS input is not exact.

The fix and variable commands are read from lammps.in and the files it reads, as lammps_named_commands() reads them. Every piece of trajectory that a path-sampling run generates is a LAMMPS run of its own from a stored frame. A warning names a fix that carries a memory from one time step to the next which restarts with each piece (LAMMPS_MEMORY_FIXES, fix langevin with gjf vfull), and a fix that changes the dynamics of a piece by the direction of time or by its first time step (LAMMPS_START_CHANGING_FIXES, and LAMMPS_MOMENTUM_FIXES that act every N > 1 time steps). The other fixes with such a memory or such a change, the pair styles with one and a thermostat whose target temperature changes during a run set the temperature in a way the temperature reader refuses in every task (read_lammps_temperatures()).

Parameters:
  • template (string) – The path of lammps.in.

  • run_dir (string) – The directory that LAMMPS runs in.

  • staged (dict of strings, optional) – The files that the engine stages in run_dir before the run, as lammps_named_commands() takes them.

Returns:

out (list of strings) – The warnings, each once, in the order of the commands.

Raises:

NotImplementedError – As lammps_named_commands() raises it.

pyretis.engines.lammps_steps.lammps_scaled_positions(columns, values, bounds, source=None)

Return the positions that the scaled columns of a dump row give.

A LAMMPS dump gives the position of an atom along x as x (wrapped into the box), xu (unwrapped), xs (wrapped and scaled) or xsu (unwrapped and scaled), and so on along y and z. A scaled position is in units of the edge vectors of the box (lammps_box_vectors()): the atom of the scaled position (xs, ys, zs) is at origin + xs * a + ys * b + zs * c, as the LAMMPS dump command defines it, and the atom of (xsu, ysu, zsu) is at the unwrapped position of that sum. In an orthogonal box, and in a triclinic box whose tilt factors are 0, this is x = xlo + xs * (xhi - xlo) along x, and so on, for each scaled column of the row. In a box with a tilt factor other than 0 each position mixes the scaled positions of the axes, and the row gives its positions when it has the three scaled columns of the set.

Parameters:
  • columns (dict) – The index of each column of the row, by its name in the ITEM: ATOMS header of the dump.

  • values (sequence) – The values of the row, numbers or the words of the dump.

  • bounds (array_like) – The box bounds of the frame, a row for each of x, y and z, with the tilt factors in a third column for a dump of a triclinic box.

  • source (string, optional) – The dump of the row, as the message of a refusal names it.

Returns:

out (dict) – The position of each axis that a scaled column gives, by the name of its column (x, y, z, xu, yu or zu), for a name that columns does not have; empty when the row has no scaled column.

Raises:

ValueError – If the box has a tilt factor other than 0 and the row has some, but not all three, scaled columns of a set.

pyretis.engines.lammps_steps.lammps_word_variables(word)

Return the names of the LAMMPS variables that a word reads.

A word reads a variable as $x (a name of one character), ${name}, or v_name in an immediate variable $(...).

Parameters:

word (string) – A word of a LAMMPS command, as _lammps_command_words() returns it.

Returns:

out (list of strings) – The names of the variables, in the order the word reads them.

pyretis.engines.lammps_steps.read_lammps_data_file(data_file, atom_style=None, input_style=None, read_box=True)

Read the box, the atoms and their masses from a LAMMPS data file.

This is the one reader of the Atoms rows of a data file, for the masses of the streaming engine at set-up, for the velocity draw of a configuration held in a data file, of both LAMMPS engines, and for the order parameter of such a configuration, of the streaming engine (pyretis.engines.lammps.LAMMPSEngine.calculate_order()), whose velocities read_lammps_data_velocities() reads. The file is read in the layout that LAMMPS read_data reads:

  • The first line is the title.

  • The header is the lines below the title up to the first line that does not start with a number, blank lines and comments aside. Each line is read by the keywords at fixed positions of the line, and the words after them are ignored, in any order of the lines (_read_lammps_data_header()): the number of atoms (N atoms), the number of atom types (N atom types) and the box bounds, a line lo hi xlo xhi for x, lo hi ylo yhi for y and lo hi zlo zhi for z. An axis whose line the header leaves out has the bounds -0.5 0.5, the default of LAMMPS read_data (LAMMPS_DATA_DEFAULT_BOUNDS), as the z axis of a 2D system often has. The other lines of the header, as N bonds, are not read.

  • A section is a keyword line and its rows. The rows of the Masses and Atoms sections are the lines from the second line below the keyword line, whatever the line below the keyword line holds, one for each atom type, the atom type and its mass, and one for each atom of the header (_lammps_data_section_rows()). The first line below the header, and the first line below the rows of a section, that is neither blank nor a comment, is the keyword line of the next section, with no blank line needed above it. A keyword line that is the last line of the file is not read: LAMMPS reads a keyword line together with the line below it, and ends the read there. The keyword line of another section, as Velocities, the line below it and the lines below them are skipped up to the next Masses or Atoms keyword line (_read_lammps_data_sections()).

  • In the header and in a keyword line, the text from a # is a comment; in a row, the words from its first word that starts with # (_lammps_data_words()). The comment of the Atoms keyword line is the # style annotation of the atom style.

The Atoms rows are read in the atom style that resolve_lammps_atom_style() gives for the Atoms keyword line, atom_style and input_style, in the columns of its row layout (lammps_atom_columns()). Each row has a column count of the style (check_lammps_atom_row()), the column count of the first row, as LAMMPS read_data requires, a positive integer atom ID, an integer atom type, numbers for the positions and, when it ends with them, integer image flags. Each atom has the mass that the Masses section gives its atom type (lammps_atom_masses()).

Parameters:
  • data_file (string) – The LAMMPS data file.

  • atom_style (string, optional) – The [engine] atom_style.

  • input_style (string, optional) – The style of the atom_style command of lammps.in (lammps_input_atom_style()).

  • read_box (boolean, optional) – True (the default) to read the box of the header. False to read the atoms and masses only, as the set-up of the streaming engine does: the lines of the box are then read for their form only, and a data file of a triclinic box is read as any other.

Returns:

  • ids (list of int) – The atom IDs, in ascending order. The other outputs give the atoms in this order, the order in which read_lammps_dump() and pyretis.engines.lammps.read_lammpstrj() give the atoms of a dump frame.

  • positions (numpy.ndarray) – The positions of the atoms, shape (N, 3).

  • images (numpy.ndarray) – The image flags of the atoms, zero for a row without them, shape (N, 3).

  • masses (numpy.ndarray) – The masses of the atoms, shape (N, 1).

  • box (list of tuple or None) – The (lo, hi) box bounds of x, y and z, in this order; None when read_box is False.

Raises:
  • NotImplementedError – If read_box is True and the header gives a triclinic box, with an xy xz yz line or an avec, bvec, cvec or abc origin line of a general triclinic box: the box is read from the lo and hi bounds only, as an orthogonal box. Also if the atom style of the Atoms rows is not supported (lammps_atom_columns()).

  • ValueError – If the header of the Atoms section has an empty # annotation, or the sources of the atom style disagree, or the style of lammps.in is a LAMMPS variable and no other source gives one (resolve_lammps_atom_style()). With a message that names the file, and the line or the row for a line or a row, for each of these, which LAMMPS read_data stops at unless said otherwise: * a header line that has a keyword of the lines of the header in another form, and is no other header line of LAMMPS (_read_lammps_data_header()), as 0 40 zlo zhj, a number of atoms or atom types that is not written in digits, a bound, or a number of a line of a triclinic box, that is not a number, or a hi bound that is not above its lo bound; if read_box is True, two lines of the header for the bounds of one axis, of which LAMMPS takes the last; * a Masses or Atoms section without a number of atom types or atoms in the header, or with a blank line or a comment among its rows, or with fewer rows than the header gives before the end of the file (_lammps_data_section_rows()); * a line below the rows of a section, the first that is neither blank nor a comment, that starts with a number, as a row beyond the number of the header does; LAMMPS stops at it with “Unknown identifier in data file”, and leaves it out when it is the last line of the file. Also that line, or the line below the header, when it has a keyword of the lines of the header (_check_lammps_data_keyword_line()); * a file with no Atoms section with rows, or with two; * an Atoms row that fits no row layout of the style (check_lammps_atom_row()), has another number of columns than the first row, has an atom ID, atom type or image flag that is not an integer, an atom ID that is not positive or a position that is not a number, or repeats the atom ID of an earlier row; * a Masses row that is not an integer atom type and a number, or has an atom type outside 1 to the number of atom types of the header, or a mass that is not positive; a Masses section that gives an atom type twice, or not the atom type of an atom (lammps_atom_masses()).

pyretis.engines.lammps_steps.read_lammps_data_velocities(data_file, atom_style=None, input_style=None)

Read the velocities of the atoms from a LAMMPS data file.

The file is read as read_lammps_data_file() reads it, without its box, and its Velocities section too: the section of the keyword line Velocities, below the Atoms section, with one row atom-ID vx vy vz for each atom of the header, as LAMMPS read_data reads it (_read_lammps_data_sections()). The velocities are in the velocity units of the units of LAMMPS, as the velocities of a dump frame are.

Parameters:
  • data_file (string) – The LAMMPS data file.

  • atom_style (string, optional) – The [engine] atom_style.

  • input_style (string, optional) – The style of the atom_style command of lammps.in (lammps_input_atom_style()).

Returns:

out (numpy.ndarray or None) – The velocities of the atoms, shape (N, 3), in the order of the atom IDs of read_lammps_data_file(); None for a file without a Velocities section.

Raises:

ValueError, NotImplementedError – As read_lammps_data_file() raises them without the box. A ValueError also for a Velocities section above the Atoms section, which LAMMPS read_data stops at, for a second Velocities section, for a Velocities section with fewer rows than the atoms of the header before the end of the file, or with a blank line or a comment among its rows (_lammps_data_section_rows()), and for a row of another number of columns than 4, an atom ID that is not an integer, of no atom or of an earlier row, or a velocity that is not a number (_read_lammps_data_velocity_rows()).

pyretis.engines.lammps_steps.read_lammps_dump(filename, dimension)

Read custom LAMMPS dump frames written by the PyRETIS engine.

The parser expects the custom dump produced by TRAJ_DUMP, i.e. one atom table per frame with an id column, position columns, velocity columns, and optional image flags. Atoms are returned sorted by LAMMPS id.

Parameters:
  • filename (string) – Path to a LAMMPS dump trajectory.

  • dimension (integer) – Number of spatial dimensions to extract.

Returns:

frames (list of dict) – Each frame contains its timestep, box, atom IDs, wrapped/unwrapped positions, image flags and velocities.

pyretis.engines.lammps_steps.read_lammps_dump_steps(filename, nframes=None)

Return the time steps of the frames of a LAMMPS dump.

The time step of a frame is the number on the line after its ITEM: TIMESTEP line.

Parameters:
  • filename (string) – Path to a LAMMPS dump trajectory.

  • nframes (integer, optional) – The number of frames to read from the start of the dump; all frames when None.

Returns:

out (list of integers) – The time step of each frame read, in the order of the frames.

pyretis.engines.lammps_steps.read_lammps_input(filename)

Read a LAMMPS input file.

This will read in a LAMMPS input file and can be used to read the value of particular settings, for instance the time step. The commands are read as LAMMPS reads them (pyretis.inout.engine_temperature.lammps_script_commands()): the lines that & or an odd number of triple quotes join are one command, and the comment of a command starts at the first # outside quotes. A line inside a command, such as a line of a triple-quoted print text, is not a command of its own.

Parameters:

filename (string) – The path to the LAMMPS input file.

Returns:

out (list of tuples) – The settings found in the LAMMPS input file. The tuples are on the form (keyword, setting), the first word of a command and its other words joined by single spaces.

Raises:

ValueError – If a line of the file holds bytes that are not UTF-8, or a command, without its comment, a character that is not ASCII (pyretis.inout.engine_temperature.lammps_script_commands()).

pyretis.engines.lammps_steps.read_lammps_log(filename)

Read some info from a LAMMPS log file.

In particular, this method is used to read the thermodynamic output from a simulation (e.g. potential and kinetic energies).

Parameters:

filename (string) – The path to the LAMMPS log file.

Returns:

out (dict) – A dict containing the data we found in the file.

pyretis.engines.lammps_steps.read_lammps_rescale_skip(filename)

Read which velocity re-scale LAMMPS skipped from its log file.

LAMMPS echoes each command of its input to the log, so the line of RESCALE_CONDITION holds the two skip lines inside quotes; the output of its print command is the whole line.

Parameters:

filename (string) – The path to the LAMMPS log file of a velocity generation.

Returns:

out (string or None) – RESCALE_SKIPPED_PE or RESCALE_SKIPPED_KE when a line of the log is that line, and None when no line is either.

pyretis.engines.lammps_steps.refuse_lammps_constraint_fixes(fixes, engine)

Refuse the constraint fixes that a velocity create draw cannot use.

The draw creates the velocities with velocity create and, for the fixes of the styles of LAMMPS_PROJECTING_FIXES, re-scales them to SET_TEMP after the setup of a run has constrained them (_add_generate_vel()). It refuses a fix of a style of LAMMPS_REFUSED_CONSTRAINT_FIXES, and a fix rigid style whose bodies keep their velocities over the setup of a run (_lammps_rigid_body_keyword()).

Parameters:
  • fixes (list of tuples) – The constraint fixes of the input, from lammps_constraint_fixes().

  • engine (string) – The engine that draws, as the message names it at its start.

Raises:

NotImplementedError – For the first fix of fixes that the draw refuses.

pyretis.engines.lammps_steps.refuse_lammps_draw_units(template, engine)

Refuse a velocity draw in LAMMPS units other than real.

PyRETIS draws LAMMPS velocities with the constants of LAMMPS real units: k_B in kcal/(mol K), and velocities in Å/fs. The units are those LAMMPS runs lammps.in with (read_lammps_units()): the last units command after the last clear command, of lammps.in or of a file it includes; LAMMPS runs a script without one in lj units.

Parameters:
  • template (string) – The path of lammps.in.

  • engine (string) – The engine that draws, as the message names it at its start.

Raises:

NotImplementedError – If LAMMPS runs lammps.in in units other than real.

pyretis.engines.lammps_steps.refuse_lammps_fixed_seeds(template, run_dir, staged=None)

Refuse a LAMMPS input that seeds its random numbers the same each run.

The engines run lammps.in for every LAMMPS run, and a fix or a pair style that draws random numbers (LAMMPS_FIX_SEED_ARGUMENTS, LAMMPS_FIX_SEED_KEYWORDS, LAMMPS_FIX_DEFAULT_SEED_KEYWORDS, LAMMPS_PAIR_SEED_ARGUMENTS) draws the same numbers in every run when its seed is the same. Each seed of the fix and pair_style commands of lammps.in and of the files it reads (lammps_named_commands()) must be the seed of the run (is_pyretis_seed_word()).

Parameters:
  • template (string) – The path of lammps.in.

  • run_dir (string) – The directory that LAMMPS runs in.

  • staged (dict of strings, optional) – The files that the engine stages in run_dir before the run, as lammps_named_commands() takes them.

Returns:

out (list of strings) – The commands of the fixes and pair styles that draw random numbers, each as <file>: <command>; empty when there is none.

Raises:
  • ValueError – For the first seed that is not the seed of the run: a number, a LAMMPS variable other than pyretis_seed, or a seed that the command does not give.

  • NotImplementedError – As lammps_named_commands() raises it.

pyretis.engines.lammps_steps.refuse_lammps_mass_command(template, engine)

Refuse a mass command of lammps.in.

A mass command, which LAMMPS runs after read_data, sets the mass of atom types in LAMMPS in place of the Masses rows of the data file. PyRETIS takes the masses from the Masses section (read_lammps_data_file()) and does not read mass commands. The commands are those of lammps.in itself; PyRETIS does not read a file that lammps.in includes.

Parameters:
  • template (string) – The path of lammps.in.

  • engine (string) – The engine that takes the masses from the data file, as the message names it at its start.

Raises:

NotImplementedError – If template has a mass command; the message names each.

pyretis.engines.lammps_steps.refuse_lammps_restart_configuration(config, what, run_dir=None, named=None)

Refuse a configuration held in a LAMMPS restart file.

PyRETIS cannot start a LAMMPS run from a restart file. The input of the run would read it with read_restart after lammps.in, and LAMMPS defines no fix before the simulation box, which the restart file defines; so no fix would integrate the motion of the atoms, and the frames of the run would all hold the configuration of the file.

Parameters:
  • config (tuple) – The file and the index of the configuration.

  • what (string) – What starts from the configuration, as the message names it at its start.

  • run_dir (string, optional) – The directory that LAMMPS runs in, where a relative file name is also looked for (_lammps_restart_configuration_reason()).

  • named (string, optional) – The file as the message names it, in place of the file of config: the file of a load folder whose staged copy the load reads.

Raises:

ValueError – If the configuration is held in a restart file.

pyretis.engines.lammps_steps.refuse_lammps_restart_files(restarts, run_dir, staged=None)

Refuse a restart file of lammps.in that contradicts the script.

LAMMPS opens the file that a read_restart command of lammps.in (or of a file it includes) names in the directory it runs in, where the engine stages its input files (_locate_lammps_file()). The reader of lammps.in checks the restart file in the input directory (read_lammps_restarts()); this check, made before each LAMMPS run, checks the file that LAMMPS opens: its unit system, and its time step (refuse_lammps_restart_file()).

Parameters:
  • restarts (object like LammpsRestarts) – The units command, the restart files and the time step of lammps.in.

  • run_dir (string) – The directory that LAMMPS runs in.

  • staged (dict of strings, optional) – The files that the engine stages in run_dir before the run, as the name of the copy -> the path of the file.

Raises:

ValueError – If a restart file is not where LAMMPS opens it, or read_lammps_restart_header() or refuse_lammps_restart_file() refuses it.

pyretis.engines.lammps_steps.refuse_lammps_restart_phasepoints(phasepoints, what)

Refuse phase points whose configuration is a LAMMPS restart file.

Parameters:
  • phasepoints (iterable of objects like System) – The phase points, each with its config.

  • what (string) – What holds the phase points, as the message names it at its start.

Raises:

ValueError – As refuse_lammps_restart_configuration() raises it for the first phase point held in a restart file.

pyretis.engines.lammps_steps.refuse_tilted_lammps_box(bounds, source=None)

Refuse the order parameter of a frame of a tilted LAMMPS box.

PyRETIS evaluates the order parameter of a frame of a LAMMPS dump in an orthogonal box, of the box lengths hi - lo of the frame (lammps_order_positions()). The box of a dump with tilt factors (lammps_box_vectors()) is that orthogonal box when its tilt factors are all 0, and a frame of a box with a tilt factor other than 0 is refused.

Parameters:
  • bounds (array_like) – The box bounds of the frame, a row for each of x, y and z, with the tilt factors xy, xz and yz in a third column.

  • source (string, optional) – The dump of the frame, as the message names it.

Raises:

NotImplementedError – If a tilt factor of the frame is not 0.

pyretis.engines.lammps_steps.refuse_unstaged_lammps_files(script_files, script_dir, run_dir)

Refuse an include or a jump file that LAMMPS reads elsewhere.

PyRETIS reads the file of each include command, and of each jump command to another file, of lammps.in in the directory of lammps.in (pyretis.inout.engine_temperature.lammps_script_files()), for the temperature and the time step of the script. LAMMPS opens the file in the directory it runs in, where the engines stage the input files by their names (LAMMPSEngineSteps.add_input_files()): the configuration, order.in and the files of extra_files. Each such file must be there and hold the text PyRETIS reads.

Parameters:
  • script_files (list of tuples) – The files of the include and jump commands, as pyretis.inout.engine_temperature.lammps_script_files() gives them.

  • script_dir (string) – The directory of lammps.in, where PyRETIS reads them.

  • run_dir (string) – The directory that LAMMPS runs in, with the staged files.

Raises:

ValueError – If LAMMPS would not find such a file in run_dir, or would find a file there whose text is not the one PyRETIS reads.

pyretis.engines.lammps_steps.refuse_velocity_dependent_lammps_orders(template, order_file, run_dir, staged=None)

Refuse an order.in column that is not a function of positions.

With order_mode = "lammps" LAMMPS evaluates the variables of order.in (lammps_order_columns()) on the velocities of the LAMMPS run. The frames of a backward leg hold the velocities of the run, which are those of the path reversed (vel_rev), and PyRETIS evaluates the order parameter of such a frame on the velocities of the path. A variable is a column of the order parameter of every frame, of both legs, when it reads the positions of the atoms and the box only (_lammps_variable_dependence()).

Parameters:
  • template (string) – The path of lammps.in.

  • order_file (string) – The path of order.in.

  • run_dir (string) – The directory that LAMMPS runs in.

  • staged (dict of strings, optional) – The files that the engine stages in run_dir before the run, as the name of the copy -> the path of the file.

Raises:

ValueError – If a variable of order.in reads the velocities, or a word that PyRETIS cannot tell to be independent of them.

pyretis.engines.lammps_steps.rename_lammps_energy_keys(energy)

Rename LAMMPS thermo column labels to PyRETIS conventions.

pyretis.engines.lammps_steps.resolve_lammps_atom_style(header, configured=None, input_style=None)

Resolve and validate the atom style used by a data Atoms block.

LAMMPS reads the rows of a data file with the atom_style of its input, and with atomic when the input sets none. The style is the first given of the engine setting configured, the # style annotation of the Atoms header and the atom_style command of lammps.in (input_style), and atomic when none of the three is given. Any two of the three that are given must name styles of the same row layout (LAMMPS_ATOM_STYLE_LAYOUT): bond, angle and molecular share one. The layout of a style is that of its base style, the style without an accelerator suffix (lammps_base_atom_style()), so full/kk agrees with full, and a style without a row layout agrees with the styles of its base style only, as sphere with sphere/kk.

A style of lammps.in that holds a $ is set by a LAMMPS variable, which PyRETIS does not evaluate, and it is not a source: the rows are read in the style of the setting or of the annotation, and without either of them the style is refused.

Parameters:
  • header (string) – The Atoms header line of the data file.

  • configured (string, optional) – The [engine] atom_style.

  • input_style (string, optional) – The style of the atom_style command of lammps.in (lammps_input_atom_style()).

Returns:

out (string) – The atom style of the rows, in lower case, as its source gives it, with its accelerator suffix.

Raises:

ValueError – If the header has an empty # annotation; if two of the given sources name styles of different row layouts, and the message names both as their sources give them; or if the style of lammps.in holds a $ and neither configured nor an annotation is given.

pyretis.engines.lammps_steps.system_to_lammps(system, reverse_velocities, dimension)

Convert a LAMMPS system into LAMMPS commands for loading it.

This method will convert a system created by LAMMPS into LAMMPS commands, so that LAMMPS can read the given snapshot and use it.

Parameters:
  • system (object like System) – The system we are converting.

  • reverse_velocities (boolean) – True if the velocities in the system are to be reversed.

  • dimension (integer) – The number of dimensions used in the LAMMPS simulation.

Returns:

out (list of strings) – The commands needed by LAMMPS to read the configuration.

Raises:

ValueError – If the configuration is held in a LAMMPS restart file (refuse_lammps_restart_configuration()): no input reads one.

pyretis.engines.lammps_steps.write_lammps_dump_frame(infile, step, outfile, dimension)

Write one referenced dump step in PyRETIS’s canonical dump format.

Wrapped and unwrapped input coordinates are reconciled by _iter_lammps_dump_lines(); when image flags are absent they are derived from xu/yu/zu. The frames are parsed one at a time up to the selected step, which alone is kept, so a large file-backed initial path is not duplicated or retained in memory.

pyretis.engines.openmm module

Definition of the OpenMM engine.

This module defines the class for the OpenMM MD engine.

Important classes defined here

OpenMMEngine (OpenMMEngine)

The class for running the OpenMM engine.

class pyretis.engines.openmm.OpenMMEngine(openmm_simulation, subcycles=1, openmm_module=None, timestep=None)

Bases: EngineBase

A class for interfacing with OpenMM.

This class defines the interface to OpenMM.

Variables:
  • simulation (OpenMM.simulation) – OpenMM simulation object.

  • subcycles (int) – Number of OpenMM steps per PyRETIS step.

  • temperature (float or None) – The temperature (K) of the integrator and of the forces with a temperature (a thermostat or a barostat) of the simulation (openmm_temperatures()), or None for a simulation without an integrator.

  • beta (float or None) – The inverse temperature 1 / (k_B T) in mol/kJ, with the k_B of the openmm unit system, or None without a temperature.

  • engine_temperatures (object like EngineTemperatures) – The temperatures read from the simulation, or None for a simulation without an integrator.

  • simulation_source (string) – The module the simulation comes from, or 'the OpenMM simulation' for a simulation given as an object; it names the simulation in the messages about its temperature.

Notes

Each leg of MD, a call of propagate() or a crossing search of kick_across_middle(), starts in _start_leg(): the random numbers of the integration are drawn from seeds of rgen, the random generator of the move, the context parameters and the integrator parameters are those the context held when the engine was built, and the context starts at step count 0. The paths of a move are then a function of its start frame, of its random stream, of the platform and of its settings, whichever worker runs the move and whichever legs that worker ran before.

__init__(openmm_simulation, subcycles=1, openmm_module=None, timestep=None)

Set up the OpenMM Engine.

Parameters:
  • openmm_simulation (OpenMM.simulation, or string) – The OpenMM simulation object or the variable name if module is not None.

  • subcycles (int) – Number of OpenMM integration steps per PyRETIS step.

  • openmm_module (string, optional) – If defined and simulation is a string, try loading simulation from module.

  • timestep (float, optional) – The OpenMM time step is the step size of the integrator (simulation_step_size()); this optional value of the engine section, in ps, is a cross-check and must equal it. A run records the step size there.

Raises:
  • RuntimeError – If OpenMM is not installed, or openmm_simulation is a string that is not loaded from a module.

  • ValueError – If the simulation steps with a variable step (refuse_variable_step_integrator()); if the integrators its CompoundIntegrator holds have different step sizes (simulation_step_size()); if timestep differs from the step size of the integrator; if the simulation steps with a CustomIntegrator that holds a variable named kT from which PyRETIS reads no temperature (another letter case, or per degree of freedom), or a CustomIntegrator that draws random numbers and has no global variable kT, alone or in a CompoundIntegrator (openmm_temperatures()); if a getTemperature() returns no temperature Quantity; if the simulation states no temperature: neither its integrator, nor an integrator its CompoundIntegrator holds, nor a force of its System (a thermostat or a barostat) carries one (openmm_temperatures()); if a temperature it states is not positive; or if it states different temperatures (EngineTemperatures.agreed()).

_constrain_velocities(system)

Remove the velocity components along the constraints.

The integrator removes these components when it propagates, so the kinetic energy that a re-scale sets is the kinetic energy of the run only for constrained velocities. The projection keeps the linear momentum, and scaling constrained velocities by one factor keeps them constrained. A System without constraints, or a simulation that holds no OpenMM System, is left as it is.

Parameters:

system (object like System) – The state whose velocities are constrained, in place, with the constraint tolerance of the integrator.

_draw_leg_seeds()

Draw the random number seeds of a leg of MD from rgen.

The parts of the simulation that draw random numbers (random_number_owners()) take seeds drawn from rgen, in SEED_RANGE: one seed for the integrators and the AndersenThermostat forces, drawn first, and then one seed for each other force with a seed, in the order of the forces of the System. Nothing is drawn for a simulation without such parts, or for an engine without rgen.

Returns:

out (list of tuple) – One (part, seed) pair for each part that draws random numbers; empty when nothing is drawn.

static _input_simulation(engine_settings)

Import the simulation an engine section names.

The simulation is imported as the engine imports it when it is created: openmm_simulation from the module openmm_module.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

  • out[0] (object like openmm.app.Simulation) – The simulation.

  • out[1] (string) – The module.

Raises:

ValueError – If the section names no openmm_module.

_leg_file()

Return the name of a new trajectory file for the frames of a leg.

The file is <exe_dir>/<n>_openmm.xyz in the main process of a run and <exe_dir>/w<k>_<n>_openmm.xyz in the scheduler worker of index k (worker_index()), with n from counter(), which gives a new number at each call of a process: no two legs of a run, in one process or in two, name the same file.

Returns:

out (string) – The name of the file.

_materialize_if_filebacked(system)

Populate pos / vel from system.config when needed.

A coordinator load_dir phasepoint arrives file-backed: its positions live in an XYZ frame referenced by system.config and the in-memory system.pos is None. OpenMM integrates in memory (integration_step pushes system.pos into the OpenMM context), so read the referenced frame into the system before propagating – mirroring the streaming internal engine’s pyretis.engines.internal.MDEngine._materialize_system(). A system that already carries positions (system.pos set) is left untouched.

The system gets the box a read-back by format gives the frame (xyz_frame_box()): the box of its box line, or, for a frame whose box line is absent or all zero, the cell of frame_cell(). The order parameter is evaluated, and the OpenMM context propagates the frame, in that box. A box line with a length of inf or 0 gives an unbounded dimension, which stops the run where the box would reach the OpenMM context (periodic_box_vectors()).

Parameters:

system (object like System) – The phase point to materialise in place.

_set_context_state(system)

Synchronize the OpenMM context with a PyRETIS system.

The positions, the velocities and, when the system has a box, its box vectors (periodic_box_vectors()) are set in the context.

Parameters:

system (object like System) – The state to set, in nm and nm/ps.

Returns:

out (object like openmm.Context) – The context of the simulation.

Raises:

ValueError – If the box of the system is not a periodic cell with finite components and positive lengths; the context is then left as it was.

_set_frame_state(system, snapshot)

Set the state of a stored frame on a phase point.

The phase point gets the positions and the velocities of the frame, the velocities negated when its vel_rev is True, the masses and the temperature of the OpenMM simulation (_template_system()), and the box a read-back by format gives the frame (xyz_frame_box()): the box of its box line, or, for a box line that is absent or all zero, the cell of frame_cell().

Parameters:
  • system (object like System) – The phase point to set, in place.

  • snapshot (dict) – The frame, as read_xyz_file() reads it.

_start_leg()

Start a leg of MD from a defined state of the context.

The seeds come from rgen (_draw_leg_seeds()), the random generator of the move, which the scheduler sets for each move (run_md()), and the kick initiation, sequential or parallel, for each ensemble (initiate_path_ensemble_kick()). OpenMM reads the seeds of an integrator and of a force when it builds a context, so with seeds drawn the context is rebuilt (Context.reinitialize(preserveState=False)), and the random number generators start from the new seeds. Without rgen no seed is drawn, and the integrator goes on with its random numbers from where they are.

The context is then given the state it held when the engine was built (Context.setState): its context parameters and its integrator parameters, which hold the state of a NoseHooverIntegrator thermostat chain and the global and per-degree-of-freedom variables of a CustomIntegrator; the MD of the leg sets the positions, the velocities and the box of the phase point it starts from. A leg is then the same leg whichever legs the engine ran before, as for an engine built anew in another worker or in a restarted run.

The step count and the time of the context are set to 0, so a force that acts at the steps whose count is a multiple of its frequency, a CMMotionRemover, acts at the same steps of every leg.

_template_system()

Return the engine’s reference pyretis System (cached).

Built from the OpenMM Simulation (particles, masses, box and the thermodynamic temperature/beta at the temperature the engine runs at, temperature, _system_from_simulation()), it supplies the engine-level state absent from a file-backed XYZ frame. Cached, as it is constant for the simulation’s lifetime.

_write_frame(filename, system, *, step=None, append=False, reverse=False)

Write the state of a system as a frame of an .xyz file.

The frame holds the positions (nm), the velocities (nm/ps) and, on its box line, the box parameters of system.box (nm, FRAME_BOX_FMT), the format _materialize_if_filebacked() reads back. The file is recorded for clean_up().

Parameters:
  • filename (string) – The file to write to.

  • system (object like System) – The state to write.

  • step (integer, optional) – The frame number written to the header.

  • append (boolean, optional) – If True, the frame is added to the end of the file; if False, the file is written anew with this frame.

  • reverse (boolean, optional) – If True, the velocities are written negated: the frame then holds them in the direction of the MD of a backward propagation, and the phase point that names it carries vel_rev = True, which negates them when it is read back.

calculate_order(system, xyz=None, vel=None, box=None)

Return the order parameter.

This method is just to help to calculate the order parameter in cases where only the engine can do it.

Parameters:
  • system (object like System) – This is the system that contains the particles we are investigating.

  • xyz (numpy.array, optional) – The positions to use. Typically for internal engines, this is not needed. It is included here as it can be used for testing and also to be compatible with the generic function defined by the parent.

  • vel (numpy.array, optional) – The velocities to use.

  • box (numpy.array, optional) – The current box vectors.

Returns:

out (list of floats) – The calculated order parameter(s).

clean_up()

Remove the frame files this engine wrote in exe_dir.

The engine writes the frames of the phase points it stores into exe_dir (_write_frame()). Storing an accepted path moves its frame files into the path archive (SchedulerPathStorage); the files of a trial that is not stored stay behind until this method removes them. The scheduler points exe_dir at the directory of the ensemble whose move the engine runs next, which no other move uses until the coordinator has stored the outcome of this one; the files the engine wrote in that directory and that are still there are removed. The files it wrote in another directory, which a move of another worker may be using, and every file the engine did not write are left in place.

default_units = 'openmm'
dump_phasepoint(phasepoint, deffnm=None)

Write the frame of a stored phase point to a file of its own.

A phase point with particles is held in memory only, and it is left as it is. A phase point without particles names its frame by config, a (file, index) pair; that frame is copied, as it is stored, into <exe_dir>/<deffnm>.xyz and config names the copy. The velocity direction vel_rev and the state the phase point holds in memory are kept.

Parameters:
  • phasepoint (object like System) – The phase point to write.

  • deffnm (string, optional) – The base name of the file; conf by default.

Raises:

ValueError – If the file config names holds no frame at its index.

engine_type = 'openmm'
file_backed_path(path, filename)

Return a copy of a path whose phase points name stored frames.

The phase points of a path the in-process initiation generates hold their state in their particles. Each one is written, in the order of the path, as a frame of the trajectory filename (_write_frame()): its positions, its velocities and its box, as the frames of the MD are stored (propagate()). The phase points of the copy hold no particles. Each names its frame by config, with vel_rev False since the frame holds the velocities of the phase point, and keeps the order parameter, the box and the energies of the phase point, which storing the copy (SchedulerPathStorage) writes into the energy.txt of the path.

Parameters:
  • path (object like Path) – The path, with phase points that hold particles.

  • filename (string) – The trajectory file to write, in the directory the path is stored in. clean_up() leaves it in place.

Returns:

out (object like Path) – The copy, with phase points without particles.

frame_cell()

Return the cell for a stored frame that records none.

A frame staged for a load may have no box line, or the box line # Box: 0.0000 0.0000 0.0000. Such a frame is evaluated in the periodic box vectors of the OpenMM simulation, as _template_system() reads them; a phase point built from the simulation (_system_from_simulation()) carries the same box into its MD. The frames the engine stores itself carry their own box (_write_frame()), the frames of the initial paths of a kick initiation included (file_backed_path()).

Returns:

out (numpy.array) – The box parameters in nm: xx, yy, zz, followed by xy, xz, yx, yz, zx, zy for a triclinic box (box_matrix_to_list()).

frame_energies(systems)

Return the potential and kinetic energies of stored frames.

Each phase point names its frame by config, a (file, index) pair of an .xyz trajectory, and the frame is read as _materialize_if_filebacked() reads it (_set_frame_state()). The potential energy is the energy of the OpenMM System at the positions and in the box of the frame (potential_energy()), and the kinetic energy the energy of the velocities of the frame with the masses of the OpenMM System (calculate_kinetic_energy()), both in kJ/mol, as propagate() records them for the frames of its MD. Each file is read once.

The state of the last frame is left in the OpenMM context. The MD sets the state of its phase point in the context before each integration step (_set_context_state()).

Parameters:

systems (iterable of objects like System) – The phase points; each names its frame by config and its velocity direction by vel_rev.

Returns:

out (list of tuple of float) – One (vpot, ekin) pair per phase point, in the order of systems.

Raises:

ValueError – If the file of a phase point is not an .xyz file or holds no frame at its index, or if the box of a frame is not a periodic cell with finite components and positive lengths (periodic_box_vectors()).

classmethod get_default_units(settings=None)

Return the default unit system for the OpenMM engine.

Parameters:

settings (dict, optional) – Full simulation settings or engine settings. This argument is ignored for the OpenMM engine.

Returns:

out (string) – The default unit system for the OpenMM engine.

classmethod input_path_sampling_problem(engine_settings)

Return why a path-sampling run cannot use a section’s simulation.

The simulation is imported as read_input_temperatures() imports it, and its integrator and its scheme are checked as path_sampling_problem() checks them (path_sampling_integrator_problem(), then path_sampling_scheme_problem()).

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (string or None) – The reason, or None when a path-sampling run can use the integrator and the scheme of the simulation. None for a section that names no openmm_module, names a module file that is not there, or gives the simulation object itself: the run refuses the first two where it reads the temperature of the section (read_input_temperatures()) or creates the engine, and path_sampling_problem() checks the engine built from the third.

integration_step(system)

Perform one integration step of n subcycles.

Parameters:

system (object like System) – The system to integrate/act on. Assumed to have a particle list in system.particles.

Returns:

out (None) – Does not return anything, but alters the state of the given system.

kick_across_middle(system, ens_set, middle, tis_settings, rgen)

Force a phase point across the middle interface.

This is accomplished by repeatedly kicking the phase point so that it crosses the middle interface.

Parameters:
  • system (object like System) – This is the system that contains the particles we are investigating.

  • ens_set (dict) – It contains the ensemble settings. This method does not use it directly, but it is part of the common interface.

  • middle (float) – This is the value for the middle interface.

  • tis_settings (dict) – This dictionary contains settings for TIS. Explicitly used here:

    • zero_momentum: boolean, determines if the momentum is zeroed after each kick. A missing key means False. A re-scaled kick on a System with a CMMotionRemover requires True (refuse_momentum_with_remover()).

    • rescale_energy: float or False, the total energy each kick is re-scaled to; False, or a value that is not positive, leaves the kicked velocities unscaled.

    Every kick is an aimless draw (make_kick_velocity_settings()).

  • rgen (object like RandomGenerator) – This is the random generator that will be used.

Returns:

  • out[0] (object like System) – The phase-point just before the interface.

  • out[1] (object like System) – The phase-point just after the interface.

Note

This function will update the system state. The search starts with _start_leg(): its integration steps draw their random numbers from seeds of self.rgen, the integration random generator of the engine, and the kicks draw their velocities from the argument rgen.

modify_velocities(system, vel_settings, rgen)

Modify the velocities of the current state.

This method will modify the velocities of a time slice. And it is part of the integrator since it, conceptually, fits here: we are acting on the system and modifying it.

Parameters:
  • system (object like System) – This is the system that contains the particles we are investigating.

  • vel_settings (dict) – It contains info about velocity settings:

    • sigma_v : numpy.array, optional Negative values select aimless shooting. Zero or positive values set the standard deviation, one for each particle, for soft velocity perturbations, in nm/ps. A soft perturbation is refused for an OpenMM System with constraints (refuse_constrained_soft_perturbation()). Without a re-scale, on a System with a CMMotionRemover its kinetic-energy change starts from the old velocities without their centre-of-mass motion, which the run does not keep.

    • zero_momentum : boolean, optional If True, we reset the linear momentum to zero after generating. A missing key means False. A re-scale or a soft perturbation on a System with a CMMotionRemover requires True (refuse_momentum_with_remover()).

    • rescale : float, optional In some NVE simulations, we may wish to re-scale the energy to a fixed value. If rescale is a float > 0, we will re-scale the energy (after modification of the velocities) to match the given float. The velocities of a System with constraints are constrained before the re-scale (_constrain_velocities()), so the total energy is the given float for the velocities the integrator propagates.

  • rgen (object like RandomGenerator) – This is the random generator that will be used.

Returns:

  • dek (float) – The change in the kinetic energy, in kJ/mol.

  • kin_new (float) – The new kinetic energy, in kJ/mol.

Raises:

NotImplementedError – If sigma_v selects a soft velocity perturbation and the OpenMM System has constraints, or if the settings request a re-scale or a soft perturbation with zero_momentum False and the System holds a CMMotionRemover.

Notes

A system without particles, a phase point of the infinite-swapping scheduler, is materialised from the frame it names (_materialize_if_filebacked()), and the state with its new velocities is written to <exe_dir>/genvel.xyz (_write_frame()), which config then names, with vel_rev = False.

path_sampling_problem()

Return why a path-sampling run cannot use this engine.

Returns:

out (string or None) – The reason (path_sampling_integrator_problem(), then path_sampling_scheme_problem()), or None when a path-sampling run can use the integrator and the forces of the simulation.

path_sampling_warnings()

Return why a path-sampling run with this engine is not exact.

Returns:

out (list of strings) – The warnings (openmm_path_sampling_warnings()); empty when the simulation selects no such scheme.

potential_energy(system)

Return the system potential energy in kJ/mol.

Parameters:

system (object like System) – The PyRETIS state whose coordinates and box are evaluated.

Returns:

float – The OpenMM potential energy in the engine’s native kJ/mol units.

propagate(path, ens_set, system, reverse=False)

Generate a path by integrating until a criterion is met.

This function will generate a path by calling the function specifying the integration step repeatedly. The integration is carried out until the order parameter has passed the specified interfaces or if we have integrated for more than a specified maximum number of steps. The given system defines the initial state and the system is reset to its initial state when this method is done.

Parameters:
  • path (object like PathBase) – This is the path we use to fill in phase-space points. We are here not returning a new path - this since we want to delegate the creation of the path (type) to the method that is running propagate.

  • ens_set (dict) – It contains the ensemble settings. Explicitly used here:

    • interfaces : list of floats These interfaces define the stopping criterion.

  • system (object like System) – The system object gives the initial state for the integration. The initial state is stored and the system is reset to the initial state when the integration is done.

  • reverse (boolean, optional) – If True, the system will be propagated backward in time.

Returns:

  • success (boolean) – This is True if we generated an acceptable path.

  • status (string) – A text description of the current status of the propagation.

Notes

Every phase point holds its positions, velocities and box in memory. A system without particles, a phase point of the infinite-swapping scheduler, is also stored on disk: the frames of the leg are written to a trajectory file of the leg in exe_dir (_leg_file(), _write_frame()), which the first frame writes anew, and each phase point names its frame by config and vel_rev, as the streaming internal engine does (MDEngine._propagate_streaming()). A path stored by the scheduler (SchedulerPathStorage) then names the frames of its MD, and a stored frame read back (_materialize_if_filebacked()) gives the positions, velocities and box of the MD at that frame, to the nine decimals of the file.

The MD starts from the velocities the system holds in memory, or, for a system without them, from the velocities of its stored frame, negated when vel_rev is True. The two agree: the velocities in memory are those of the stored frame with the sign vel_rev gives, and a time reversal of a phase point (System.reverse_velocities()) negates the velocities in memory as it toggles vel_rev.

The MD starts with _start_leg(): it draws its random numbers from seeds of rgen, the random generator of the move, a new seed for each call, it starts from the context parameters and the integrator parameters the context held when the engine was built, and it starts at step count 0.

classmethod read_input_temperatures(engine_settings)

Read the temperatures of the simulation an engine section names.

The simulation is imported as the engine imports it when it is created (_input_simulation()).

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (object like EngineTemperatures) – The temperatures openmm_temperatures() reads.

Raises:

ValueError – If the section names no openmm_module; if the simulation steps with a variable step (refuse_variable_step_integrator(), checked before the temperature, as the engine checks it when it is built); if the simulation steps with a CustomIntegrator that holds a variable named kT from which PyRETIS reads no temperature (another letter case, or per degree of freedom), or a CustomIntegrator that draws random numbers and has no global variable kT, alone or in a CompoundIntegrator (openmm_temperatures()); if a getTemperature() returns no temperature Quantity; if the simulation states no temperature: neither its integrator, nor an integrator its CompoundIntegrator holds, nor a force of its System (a thermostat or a barostat) carries one (openmm_temperatures()); or if a temperature it states is not positive.

classmethod read_input_temperatures_and_timestep(engine_settings)

Read the temperatures and the time step of a section’s simulation.

The simulation is imported once, as read_input_temperatures() imports it, and its temperatures are read as that method reads them; then its time step, the step size of its integrator in ps (simulation_step_size()), the value the engine takes when it is built.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

Raises:

ValueError – As read_input_temperatures() raises it, and as simulation_step_size() raises it for a CompoundIntegrator whose integrators have different step sizes.

records_input_timestep = True
system_with_particles(system)

Return a phase point with particles in the state of its frame.

The phase point system holds no particles and names its frame by config. The phase point returned is a copy of the system built from the OpenMM simulation (_template_system()), whose particles carry the masses and the names of the simulation, in the state of that frame (_materialize_if_filebacked()): the positions and the velocities of the frame, the velocities negated when vel_rev is True, and the box of the frame. Such a phase point is held in memory: propagate() and modify_velocities() write no frame files for it, as for the system the in-process kick initiation starts from (make_pyretis_system()).

Parameters:

system (object like System) – A phase point without particles that names its frame by config.

Returns:

out (object like System) – The phase point with particles.

Raises:

ValueError – If system holds particles or names no frame, or if its file holds no frame at its index.

temperature_keys = 'the temperature of the integrator and of each force with a temperature, a thermostat or a barostat, of the OpenMM simulation'
temperature_module_key = 'openmm_module'
temperature_source = 'input'
pyretis.engines.openmm.custom_integrator_temperature(integrator)

Return the temperature a CustomIntegrator gives, in K.

A CustomIntegrator gives its temperature by its global variable kT (CUSTOM_THERMAL_ENERGY), the thermal energy in kJ/mol (thermal_energy_temperature()).

Parameters:

integrator (object like openmm.Integrator) – An OpenMM integrator.

Returns:

out (float or None) – The temperature, or None for an integrator that is not a CustomIntegrator or has no global variable kT.

pyretis.engines.openmm.molar_gas_constant()

Return the molar gas constant of OpenMM, in kJ/(mol K).

Returns:

out (float) – MOLAR_GAS_CONSTANT_R of OpenMM, in kJ/(mol K).

pyretis.engines.openmm.path_sampling_integrator_problem(simulation)

Return why a path-sampling run cannot use an OpenMM simulation.

A path-sampling run reverses the velocities of a frame and draws new velocities at a frame, and integrates on from the positions of that frame, so the velocities of a frame must be those at the time of its positions. The integrators of OpenMM other than CustomIntegrator are refused: the leap-frog integrators (LEAP_FROG_INTEGRATORS) store the velocities half a time step away from the positions, BrownianIntegrator integrates Brownian dynamics without velocities (a path-sampling run of Brownian dynamics runs with the internal Langevin engine with high_friction), and the others are not known to store velocities at the time of the positions. A CustomIntegrator, except the leap-frog ones of LEAP_FROG_INTEGRATORS, is accepted; a CustomIntegrator a CompoundIntegrator holds is the CustomIntegrator of OpenMM, and one with the global variables and steps of an accelerated-MD integrator (accelerated_md_class()) is refused as that integrator is. The steps of an accepted one must give the velocities at the time of its positions, as velocity Verlet and BAOAB Langevin dynamics do (MTSIntegrator and MTSLangevinIntegrator of OpenMM are such integrators; MTSIntegrator has no kT, so a simulation with it takes its temperature from a force of the System with a temperature, a thermostat or a barostat, and one without such a force is refused, openmm_temperatures()).

Parameters:

simulation (object like openmm.app.Simulation) – The OpenMM simulation.

Returns:

out (string or None) – The reason, naming the integrator (or each integrator of a CompoundIntegrator) and the integrators to use instead, or None when a path-sampling run can use the simulation.

pyretis.engines.openmm.path_sampling_scheme_problem(simulation)

Return why a path-sampling run refuses the scheme of a simulation.

The integrators of the simulation are ones a path-sampling run can use (path_sampling_integrator_problem()). A deterministic CustomIntegrator with a memory between time steps (deterministic_memory_problem()) is refused, and so is a force that acts only in an addUpdateContextState() step beside a CustomIntegrator without one (context_state_force_problem()). A CustomIntegrator that draws random numbers and holds no global variable CUSTOM_THERMAL_ENERGY gives no reason here: the run refuses it, first, where it reads the temperature of the simulation (pyretis.inout.engine_temperature.openmm_temperatures()).

Parameters:

simulation (object like openmm.app.Simulation) – The OpenMM simulation.

Returns:

out (string or None) – The reason, or None when a path-sampling run can use the scheme of the simulation.

pyretis.engines.openmm.simulation_step_size(simulation, source='the OpenMM simulation')

Return the time step of an OpenMM simulation, in ps.

The time step of the OpenMM engine is the step size of the integrator of its simulation. A simulation that steps with a variable step is refused first (refuse_variable_step_integrator()). Every integrator a CompoundIntegrator holds counts, the current one or not, those of a CompoundIntegrator it holds included: their step sizes must agree within the tolerance of pyretis.core.engine_time.timesteps_agree(), and the time step is then the step size of the compound integrator, the one of the integrator it steps with.

The engine takes its time step from this function when it is built (OpenMMEngine), and a run reads it before any engine is built (OpenMMEngine.read_input_temperatures_and_timestep()) and records it as the timestep of the engine section.

Parameters:
  • simulation (object like openmm.app.Simulation) – The OpenMM simulation, with its integrator.

  • source (string, optional) – The module the simulation comes from, as the message names it.

Returns:

out (float) – The step size of the integrator, in ps.

Raises:
  • RuntimeError – If OpenMM is not installed.

  • ValueError – If the simulation steps with a variable step (refuse_variable_step_integrator()), or if the integrators its CompoundIntegrator holds have different step sizes; the message names each integrator, its step size in ps and the integrator the compound steps with.

pyretis.engines.openmm.thermal_energy_temperature(thermal_energy)

Return the temperature, in K, of a thermal energy in kJ/mol.

The temperature is the thermal energy divided by the molar gas constant of OpenMM (MOLAR_GAS_CONSTANT_R, molar_gas_constant()). A thermal energy computed as the gas constant times a temperature T divides back to T within a few units in the last place of a double, the differences pyretis.inout.engine_temperature.same_temperature() accepts between two temperatures.

Parameters:

thermal_energy (float) – The thermal energy, in kJ/mol.

Returns:

out (float) – The temperature, in K.

pyretis.engines.ams module

A AMS external MD integrator interface.

This module defines a class for using AMS as an external engine.

Important classes defined here

AMSEngine (AMSEngine)

A class responsible for interfacing AMS.

class pyretis.engines.ams.AMSEngine(input_path, timestep, subcycles)

Bases: ExternalMDEngine

A class for interfacing AMS.

This class defines the interface to AMS.

Variables:
  • input_path (string) – The directory where the input files are stored.

  • input_files (dict of strings) – The names of the input files: the key 'input' names the AMS input, ams.inp.

__init__(input_path, timestep, subcycles)

Set up the AMS engine.

Parameters:
  • input_path (string) – The absolute path to where the input files are stored.

  • timestep (float) – The time step used in the AMS MD simulation.

  • subcycles (integer) – The number of steps each AMS MD run is composed of.

_copyfile(source, dest)

Copy a file from source to destination and updates the state.

This method first calls the superclass’s _copyfile method to perform the actual file copy. If the destination file is already in the states, it deletes the existing state. Finally, it copies the state from the source to the destination.

Parameters:
  • source (str) – The path to the source file.

  • dest (str) – The path to the destination file.

_deletestate(filename)

Delete the state associated with the given filename.

This method distinguishes between trajectory and snapshot files based on the presence of the substring “traj” in the filename. For trajectory files, it deletes multiple states indexed by appending an underscore and an index to the filename. For snapshot files, it deletes the state directly.

Parameters:

filename (str) – The name of the file whose state is to be deleted.

Raises:

KeyError – If the filename is not found in the states dictionary.

_extract_frame(traj_file, idx, out_file)

Extract a frame from a trajectory file.

Parameters:
  • traj_file (string) – The AMS file to open.

  • idx (integer) – The frame number we look for.

  • out_file (string) – The file to dump to.

Note

This will only properly work if the frames in the input trajectory are uniformly spaced in time.

_extract_frame_from_disk(traj_file, idx, out_file)

Extract a frame from a trajectory file from disk.

Parameters:
  • traj_file (string) – The AMS file to open.

  • idx (integer) – The frame number we look for.

  • out_file (string) – The file to dump to.

Note

This will only properly work if the frames in the input trajectory are uniformly spaced in time.

_movefile(source, dest)

Move a file from source to destination and update internal states.

This method moves a file from the specified source path to the destination path using the superclass’s _movefile method. Additionally, it updates the internal states if the source path is present in the states.

Parameters:
  • source (str) – The path of the file to be moved.

  • dest (str) – The destination path where the file should be moved.

_propagate_from(name: str, path: InfPath, system: System, ens_set: dict, msg_file: FileIO, reverse: bool = False) → tuple[bool, str]

Propagate with AMS from the current system configuration.

Here, we assume that this method is called after the propagate() has been called in the parent. The parent is then responsible for reversing the velocities and also for setting the initial state of the system.

Parameters:
  • name (string) – A name to use for the trajectory we are generating.

  • path (object like pyretis.core.path.PathBase) – This is the path we use to fill in phase-space points.

  • system (object like System) – The system object gives the initial state for the integration. The order function is injected on the engine (self.order_function).

  • ens_set (dict) – Ensemble settings. It contains:

    • interfaces : list of floats These interfaces define the stopping criterion.

  • msg_file (object like FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.

  • reverse (boolean, optional) – If True, the system will be propagated backward in time.

Returns:

  • success (boolean) – This is True if we generated an acceptable path.

  • status (string) – A text description of the current status of the propagation.

_read_configuration(filename, idx=-1)

Read output from AMS snapshot/trajectory.

Parameters:
  • filename (string) – The file to read the configuration from.

  • idx (integer) – Optional, frame index in trajectory

Returns:

  • xyz (numpy.array) – The positions.

  • vel (numpy.array) – The velocities.

  • box (list of floats) – The box dimensions; inf for each of the three lengths when the state has no lattice vectors.

  • names (None) – No atom names are read.

_removefile(filename, disk_only=False)

Remove a file from the system and optionally from the internal state.

This method removes a file by calling the superclass’s _removefile method. It can also remove the file from the internal state if it represents a molecular dynamics (MD) state.

Parameters:
  • filename (str) – The name of the file to be removed.

  • disk_only (bool, optional) – If True, only remove the file from the disk and not from the internal state. Defaults to False.

Returns:

None

_reverse_velocities(filename, outfile)

Reverse velocity in a given snapshot.

Parameters:
  • filename (string) – The configuration to reverse velocities in.

  • outfile (string) – The output file for storing the configuration with reversed velocities.

calculate_order(system, xyz=None, vel=None, box=None)

Calculate the order parameter from a configuration.

The AMS _read_configuration returns (xyz, vel, box, names) with the box as the THIRD element, so this override unpacks the configuration accordingly (ExternalMDEngine.calculate_order() reads the box first).

Parameters:
  • system (object like System) – The system that contains the particles we are investigating.

  • xyz (numpy.array, optional) – The positions to use, in case we have already read them.

  • vel (numpy.array, optional) – The velocities to use, in case we have already read them.

  • box (numpy.array, optional) – The current box vectors, in case we have already read them.

Returns:

out (list of floats) – The calculated order parameter(s).

dump_phasepoint(phasepoint, deffnm='conf')

Dump the configuration of a phase point to a file.

This override points the phase point at frame index 0 of the dumped file, (pos_file, 0); the ExternalMDEngine base stores (pos_file, None).

Parameters:
  • phasepoint (object like System) – The phase point whose configuration we dump to file.

  • deffnm (string, optional) – The default file name for the dumped configuration.

engine_type = 'internal'
modify_velocities(system: System, vel_settings: dict[str, Any], rgen) → tuple[float, float]

Draw new velocities for the current state with AMS.

AMS draws the velocities (GenerateVelocities) for the state system points at, and PyRETIS uses them as drawn. The draws with RandomVelocitiesMethod = Gromacs, for which the SCM manual states the removal of the net linear momentum, and with Exact, the default (AMS2023.1 or later), have zero net linear momentum; for Boltzmann this is not checked.

Parameters:
  • system (object like System) – The state whose velocities are drawn anew; it is pointed at the new AMS state.

  • vel_settings (dict) – The velocity settings: the dictionary of make_velocity_settings() or make_kick_velocity_settings(). It contains:

    • sigma_v: float or numpy.array, optional Negative values select aimless shooting, the draw AMS makes; zero or positive values select soft velocity perturbations. A missing key means aimless (is_aimless_velocity_setting()).

    • zero_momentum: boolean, optional Selects the reset of the linear momentum after the draw. The AMS draws with Gromacs and Exact have zero net linear momentum (see above), so the AMS engine requires True; a missing key means False, the [tis] default, which is refused.

    • rescale: float, optional The energy to re-scale the drawn velocities to, the [tis] rescale_energy. AMS does not re-scale, so a positive value is refused (refuse_energy_rescale()).

  • rgen (object like RandomGenerator) – The velocity random generator of the modify_velocities signature; AMS draws from its own generator.

Returns:

  • dek (float) – The change in the kinetic energy.

  • kin_new (float) – The new kinetic energy.

Raises:

NotImplementedError – If zero_momentum is False, if rescale is positive, or if sigma_v selects soft velocity perturbations.

needs_order = False
classmethod read_input_temperatures(engine_settings)

Read the temperatures of the AMS input of an engine section.

The input is the one the engine reads when it is created: ams.inp in input_path.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (object like EngineTemperatures) – The temperatures read_ams_temperatures() reads.

set_mdrun(md_items)

Set up the molecular dynamics run with the given parameters.

Parameters:

md_items (dict) – A dictionary with the keys used here: exe_dir (str), the directory where the executable is located, and ens (dict), the ensemble information carrying ens_name (str), the ensemble name.

Notes

Sets the executable directory and ensemble name, logs the executable directory, deletes the states left from earlier cycles, and updates the list of old states to the current states.

step(system, name, set_trajfile=True, set_step_to_zero=False)

Perform a single step with AMS.

Parameters:
  • system (object like System) – The system we are integrating.

  • name (string) – To name the output files from the AMS step.

  • set_trajfile (logical) – Optional, True if new output file should be opened

  • set_step_to_zero (logical) – Optional, True if new MD step should start from number zero

Returns:

out (string) – The name of the output configuration, obtained after completing the step.

temperature_keys = 'MolecularDynamics%InitialVelocities%Temperature and the Temperature of each Thermostat of ams.inp'
temperature_source = 'input'

pyretis.engines.ase module

An ASE integrator interface.

class pyretis.engines.ase.ASEEngine(timestep: float, temperature: float, subcycles: int, input_path: str, integrator: str, calculator_settings: dict, langevin_friction: float = -1.0, langevin_fixcm: float = -1.0, exe_path: str | Path = PosixPath('/home/enrico/cache/twoway-retis/wt2/docs'))

Bases: ExternalMDEngine

An ASE engine class.

The random numbers of the engine come from the random generators of PyRETIS (ase_random_generator()): each leg of MD with the Langevin integrator draws its noise from a generator seeded from self.rgen, the random generator of the move, and each velocity draw (modify_velocities()) from a generator seeded from the rgen it is given. The velocity Verlet integrator draws no random numbers and takes nothing from self.rgen.

The calculator, and every calculator it holds, that has a directory computes in that directory below the engine’s exe_dir, set again each time exe_dir is set (place_calculators()): the files of a file-based calculator are those of the move that runs, in the directory the move holds.

__init__(timestep: float, temperature: float, subcycles: int, input_path: str, integrator: str, calculator_settings: dict, langevin_friction: float = -1.0, langevin_fixcm: float = -1.0, exe_path: str | Path = PosixPath('/home/enrico/cache/twoway-retis/wt2/docs'))

Initialize the ase engine.

temperature: the temperature (K) of the Langevin integrator and of

the velocity draws, [system] temperature, which the engine factory gives the constructor (pyretis.engines.run_temperature.engine_constructor_settings()).

langevin_fixcm: removes center of mass motion. Should not be used for

low dimensional systems like double well.

_make_integrator(atoms)

Return the ASE integrator of one leg of MD.

The Langevin integrator draws its noise from a generator seeded with one number of self.rgen, the random generator of the move, which the scheduler sets for each move (run_md()), and the kick initiation, sequential or parallel, for each ensemble (initiate_path_ensemble_kick()). The velocity Verlet integrator takes no generator.

Parameters:

atoms (object like ase.Atoms) – The atoms the integrator moves.

Returns:

out (object like ase.md.md.MolecularDynamics) – The integrator of the leg.

_recompute_partial_orders(partial_traj, reverse)

Order parameters per frame of a partial ASE .traj dump.

The frames are read with ASE’s Trajectory, which exposes only complete frames, so a final frame left half-written by an interruption is excluded and the surviving frames are kept (“use the last good frame” recovery, as for the other engines).

property beta

Return the inverse temperature of the runs, in 1/eV.

The engine runs at [system] temperature, in kelvin, and beta = 1 / (k_B * temperature) with the k_B of ASE in eV/K, the unit of the potential energies the calculator reports.

calculate_order(system, xyz=None, vel=None, box=None)

Calculate the order parameter.

The engine’s _read_configuration returns the box as the third element (positions, velocities, box, names), so this override reads them in that order; ExternalMDEngine.calculate_order() reads the box first.

default_temperature = None
default_units = 'ase'
dump_phasepoint(phasepoint, deffnm='conf')

Dump a phase point to a file and point it at frame 0 there.

engine_type = 'internal'
property exe_dir

Return the directory the engine runs in.

modify_velocities(system: System, vel_settings: dict, rgen) → tuple[float, float]

Modify the velocities.

The Langevin fixcm option (set at construction) and the zero_momentum setting here are independent mechanisms acting at different times: fixcm removes the centre-of-mass motion every integrator step, whereas zero_momentum zeroes the COM momentum once, after the velocities are drawn. Each is set by the user on its own.

Parameters:
  • system (object like System) – The system whose particle velocities are to be modified.

  • vel_settings (dict) – A dict; zero_momentum (bool) resets the linear momentum to zero after the velocities are drawn. A missing key means False, the [tis] default. The engine draws the velocities of aimless shooting and leaves their energy as drawn, so a soft perturbation (a sigma_v that is not negative) and a positive rescale are refused before the draw.

  • rgen (object like RandomGenerator) – The random generator of the velocity draw. ASE draws the velocities from a generator seeded with one number of it (ase_random_generator()).

Returns:

  • dek (float) – The change in kinetic energy from the velocity modification.

  • kin_new (float) – The kinetic energy of the velocities written out, after the momentum reset when one is requested.

Raises:
needs_order = False
place_calculators()

Point the calculators’ directories into exe_dir.

Each calculator of ase_calculator_directories() gets its directory joined to self.exe_dir: exe_dir itself for a calculator with the directory ".". A move runs in a directory no other move uses while it runs, so a file-based calculator of one worker never reads the input or the output of another worker’s calculation.

step(system, name)

Raise NotImplementedError: the ASE engine runs no single step.

A kick of this engine runs through ExternalMDEngine.propagate() (supports_step_kick = False); step exists only so the class can be instantiated as a concrete subclass of the abstract ExternalMDEngine base.

supports_step_kick = False
system_temperature_unit = 'kelvin'
pyretis.engines.ase.SEED_RANGE = (1, 2147483646)

The range, both ends included, of the seeds the engine draws for the numpy random generators that ASE draws from: the positive values of a signed 32-bit integer below 2**31 - 1.

pyretis.engines.ase._ase_box_cell(atoms)

Return the ASE cell as a PyRETIS box-cell list, keeping angles.

ASE stores the cell as a 3x3 lattice-vector matrix; PyRETIS’ box helpers take the flattened xx, yy, zz, xy, xz, ... form. pyretis.core.box.box_matrix_to_list() collapses an orthorhombic cell to its three lengths (the diagonal of the matrix) and keeps the off-diagonal terms for a triclinic cell, so every box vector reaches the caller.

Parameters:

atoms (object like ase.Atoms) – The ASE atoms object whose cell is converted.

Returns:

list of float – The cell in PyRETIS’ flattened ordering (3 items for an orthorhombic cell, otherwise the full set).

pyretis.engines.ase._searched_for_calculators(item)

Return True if the attributes of item may hold calculators.

Parameters:

item (object) – An object a calculator holds.

Returns:

bool – True for an object with attributes other than an ase.Atoms, a numpy array, a module, a class or a function.

pyretis.engines.ase.ase_calculator_directories(calc)

Return the calculators that have a directory, with that directory.

A calculator that writes files (an ASE FileIOCalculator, as the calculators of DFT programs) writes them in its directory. The engine places this directory in the directory of each move (ASEEngine.place_calculators()), so the directory a calculator is given must be relative and stay below the directory it is placed in.

Parameters:

calc (object like ase.calculators.calculator.BaseCalculator) – The calculator of the engine.

Returns:

list of tuple – (calculator, directory) for calc and each calculator it holds (ase_calculators()) that has a directory.

Raises:

ValueError – If a directory is absolute or leaves the directory it is placed in: the calculations of all moves would share its files.

pyretis.engines.ase.ase_calculators(calc)

Return an ASE calculator and every ASE calculator it holds.

A calculator can combine others (a sum, a mixing or a QM/MM calculator of ASE, or a class of a user module), directly or through an object of its own, as the mixer of an ASE sum calculator. They are found among the attributes of the calculator and of the objects it holds, alone or in a list, tuple, set or dict, at any depth; an ase.Atoms, a numpy array, a module and a class are not searched.

Parameters:

calc (object like ase.calculators.calculator.BaseCalculator) – The calculator of the engine.

Returns:

list of object – calc first, then the ASE calculators it holds, each once.

pyretis.engines.ase.ase_random_generator(rgen, what)

Return a numpy random generator seeded from rgen.

ASE draws the random numbers of its Langevin integrator and of ase.md.velocitydistribution.MaxwellBoltzmannDistribution() from the generator passed as rng. The engine passes a numpy.random.default_rng() (PCG64) generator whose seed is one integer drawn from rgen in SEED_RANGE, so each leg and each velocity draw takes one number of rgen.

Parameters:
  • rgen (object like RandomGenerator or numpy.random.Generator) – The random generator the seed is drawn from.

  • what (string) – The part that draws the random numbers, for the error message.

Returns:

out (object like numpy.random.Generator) – The generator ASE draws from.

Raises:

ValueError – If rgen is None.

pyretis.engines.ase.set_ase_box(system, box)

Set the box of a System from the cell of an ASE frame.

A cell with three positive lengths is a periodic cell. It becomes a Box (RectangularBox or TriclinicBox), whose length, low and pbc_dist_coordinate the periodic order parameters use. Any other cell, as the all-zero cell of a gas-phase ASE system, is stored as the list itself: such a system has no periodic cell, and its order parameters are the non-periodic ones.

Parameters:
  • system (object like System) – The system whose box is set.

  • box (list of float) – The cell of the frame, as _ase_box_cell() returns it.

pyretis.engines.factory module

Engine factory for keyed scheduler engine creation.

This module supplements pyretis.engines with the keyed-creation helpers used by the path-sampling scheduler. Unlike pyretis.engines.engine_factory() and pyretis.setup.common.create_engine(), which expect the engine settings to sit at the top-level "engine" key, create_inf_engine takes an explicit eng_key so multiple named engines (engine, engine2, etc.) can coexist in one config.

Both creation routes resolve the same canonical engine classes:

  • from pyretis.setup.common import create_engine – canonical single-engine creation, resolved through the untouched pyretis.engines.ENGINE_MAP.

  • from pyretis.engines.factory import create_inf_engine – keyed scheduler creation, resolved through build_engine_map(). ENGINE_MAP is never mutated.

pyretis.engines.factory.assign_engines(engine_occ: dict[str, list], eng_names, pin) → dict[Any, int]

Assign free engine instances to worker pin.

Releases any engines currently held by pin, then claims one free instance of each engine type in eng_names for that worker. Returns {name: index} mapping each requested engine name to the index inside engine_occ[name] that pin holds when the function returns.

Raises:

ValueError – If no free engine is available for one of the requested names (this should never happen with a correctly sized pool).

pyretis.engines.factory.build_engine_map() → dict[str, dict[str, Any]]

Return a copy of ENGINE_MAP with the optional-dependency engines.

The ase, ams and turtlemd engines are registered on the copy when their modules import, as pyretis.engines registers them in ENGINE_MAP itself; missing optional dependencies (e.g. scm.plams for AMS, turtlemd) just lead to that entry being skipped.

pyretis.engines.factory.check_engine(settings: dict[str, Any], eng_key: str = 'engine') → bool

Light-touch validation of an engine settings block.

Ensures the section exists and that file-format-bearing engines specify their format (resolving cp2k’s and gmx’s via the shared resolve_engine_format(), neither of which can fail).

pyretis.engines.factory.constructor_settings(engine_settings: dict[str, Any], cls: type) → dict[str, Any]

Return the settings of an engine section its constructor is offered.

An internal integrator reads the STREAMING_SETTINGS from its section itself, so its constructor is offered the other settings of the section; the constructor of every other engine is offered the whole section. The check of the settings a constructor does not take (pyretis.core.common.initiate_instance()) then warns about the keys no part of the engine reads.

Parameters:
  • engine_settings (dict) – The settings of the engine section.

  • cls (type) – The engine class of the section, from the engine map or from the module the section names.

Returns:

dict – The settings the constructor is offered: engine_settings itself for an engine that is not an internal integrator, and a copy without the STREAMING_SETTINGS for an internal integrator.

pyretis.engines.factory.create_engines(config: dict[str, Any]) → tuple[dict[Any, Any], dict[Any, list]]

Build the engine pool for a multi-worker parallel run.

For each unique engine name referenced in config["simulation"]["ensemble_engines"], instantiate min(occurrences, n_workers) copies and pair them with a per-instance occupancy slot initialised to -1 (free).

Returns (engines, engine_occ) where:

  • engines[name] is the list of instantiated engines.

  • engine_occ[name][i] is the worker pin currently using engines[name][i], or -1 when free.

Raises:

ValueError – As create_inf_engine() raises it. The input of every section of the pool whose class engine_section_class() resolves is checked (refuse_path_sampling_input()) before the first engine is built, so the refusal of an integrator comes before a message about the temperature of another section.

pyretis.engines.factory.create_inf_engine(settings: dict[str, Any], eng_key: str = 'engine') → Any | None

Create a keyed scheduler engine from a settings section.

Counterpart to pyretis.setup.common.create_engine() for the scheduler: takes an explicit eng_key so multiple named engines (engine, engine2, …) can coexist in one config, and resolves engine classes through build_engine_map() without mutating the canonical engine map.

Parameters:
  • settings (dict) – Full simulation settings. The engine settings live under settings[eng_key].

  • eng_key (str) – Which engine section to instantiate ("engine", "engine2", …).

Returns:

EngineBase | None – The created engine, or the result of pyretis.setup.common.create_external() if the engine class is not in the extended engine map. An internal integrator (pyretis.engines.internal.MDEngine) holds eng_key in its section attribute, the section it streams the subcycles of.

Raises:
pyretis.engines.factory.engine_section_class(settings: dict[str, Any], eng_key: str = 'engine') → type | None

Return the class an engine section builds, without building it.

The class is resolved as create_inf_engine() resolves it: a class of the engine map (build_engine_map()) gives its class; any other class is imported from the section’s module, looked up as a file and, failing that, relative to settings['simulation']['exe_path'].

Parameters:
  • settings (dict) – Full simulation settings, with the engine section at settings[eng_key].

  • eng_key (str, optional) – The engine section, "engine", "engine1", …

Returns:

type or None – The class; None when the section is missing, gives no class, or gives a class outside the engine map without a module.

Raises:

ValueError – If the module of the section cannot be found or imported, or does not define the class.

pyretis.engines.factory.engine_settings_offered(settings: dict[str, Any], eng_key: str, cls: type, engine_settings: dict[str, Any]) → dict[str, Any]

Return the settings the constructor of an engine is offered.

These are the settings constructor_settings() gives, with the temperature of the engine from the source of its class (pyretis.engines.run_temperature.engine_constructor_settings()): a temperature of the section is left out, and compared with [system] temperature for an engine that runs at it, and an engine that takes [system] temperature in its constructor is given it.

Parameters:
  • settings (dict) – The settings of the run.

  • eng_key (str) – The engine section, e.g. "engine".

  • cls (type) – The engine class of the section.

  • engine_settings (dict) – The settings of the section.

Returns:

dict – The settings the constructor is offered.

pyretis.engines.factory.import_external(settings: dict[str, Any], key: str, required_methods: list[str] | None = None) → Any

Import and instantiate a class described by settings.

The settings dict must hold "class" and "module" keys; the module is looked up relative to the current directory and, failing that, settings["simulation"]["exe_path"].

This complements pyretis.setup.common.create_external(), which requires a factory (engine map) argument.

Parameters:
  • settings (dict) – Settings describing the object to load.

  • key (str) – Label used in error messages.

  • required_methods (list of str, optional) – Method names that the imported class must expose.

pyretis.engines.factory.is_internal_integrator(klass: Any) → bool | None

Return whether the engine of a class is an internal integrator.

An internal integrator (pyretis.engines.internal.MDEngine) streams with the subcycles of the engine section it is built from (pyretis.engines.internal.MDEngine.setup_streaming()); every other engine of the map takes subcycles through its constructor.

Parameters:

klass (object) – The class of an engine section, looked up in build_engine_map() in lower case, as create_inf_engine() looks it up.

Returns:

bool or None – True for a class of the map whose engine is an internal integrator, False for another class of the map, and None for a class the map does not hold: an engine imported from a module, whose class is known once the run imports it.

pyretis.engines.process_sessions module

Track and terminate external-engine process sessions.

Streaming external engines run MPI launchers in fresh POSIX sessions. The session keeps an interrupted engine isolated from the PyRETIS process group, but it also means that cancelling a running process-pool future cannot stop the launcher. This module gives every scheduler worker one shared registry slot so the parent process can terminate active sessions during forced shutdown.

pyretis.engines.process_sessions._proc_session_members(session_id: int) → list[int] | None

Return Linux procfs members of session_id, or None elsewhere.

pyretis.engines.process_sessions._registered_sessions(slots: Any) → set[int]

Return a stable snapshot of non-empty shared registry slots.

pyretis.engines.process_sessions._session_is_alive(session_id: int) → bool

Return whether any process still belongs to session_id.

pyretis.engines.process_sessions._signal_session(session_id: int, signum: int) → None

Signal every visible member of an external-engine session.

Open MPI ranks may create process groups distinct from the launcher’s group. On Linux, enumerate the whole session through procfs so those ranks receive the signal directly. Other POSIX systems fall back to the launcher’s process group; MPI launchers normally forward that signal to their ranks.

pyretis.engines.process_sessions._terminate_sessions(sessions: set[int], term_timeout: float, kill_timeout: float) → set[int]

Terminate sessions with a bounded TERM-then-KILL sequence.

pyretis.engines.process_sessions.configure_process_session_registry(slots: Any | None, worker_id: int | None, shutdown_event: Any | None = None) → None

Configure the shared active-session slot for this worker process.

pyretis.engines.process_sessions.register_process_session(session_id: int) → None

Record the session leader PID of a running external engine.

pyretis.engines.process_sessions.terminate_registered_process_sessions(slots: Any, term_timeout: float = 5.0, kill_timeout: float = 2.0) → set[int]

Terminate and reap all active external sessions in slots.

SIGTERM is sent first so MPI can clean up its ranks. Sessions still alive after term_timeout receive SIGKILL. The return value contains any session IDs that remain visible after both phases.

pyretis.engines.process_sessions.unregister_process_session(session_id: int) → None

Clear this worker’s slot if it still identifies session_id.

pyretis.engines.run_temperature module

The temperature of a run and of each of its engines.

Every engine runs at the temperature of one place, its source (pyretis.engines.engine.EngineBase.temperature_source):

  • The internal integrators, TurtleMD, ASE and an engine of a module on pyretis.engines.engine.EngineBase run at [system] temperature. The internal integrators run at 1 when the input sets none; they are the only engines with a default. The input of any other engine that runs at [system] temperature must set it, and so must the input of an umbrellawindow run, whose Monte Carlo moves run at it: a run whose input sets none is refused before any engine runs.

  • GROMACS, LAMMPS, CP2K, OpenMM and AMS run at the temperature their own input states (pyretis.inout.engine_temperature), which the engine reads when it is created. A [system] temperature is then optional, and when the input sets it, it must equal the temperature of every such engine of the run.

The temperature of an engine section ([engine], [engine0] and the numbered sections of a pool) is optional. When the input gives it, it is compared with the temperature the engine of the section runs at, in the units of that engine (compare_engine_temperature()), and a run whose engine section gives another temperature is refused before any engine runs. The engine runs at the temperature of its source. Wherever a temperature is compared with another one, it must equal it within the relative tolerance ENGINE_TEMPERATURE_RTOL (temperatures_agree()).

Important functions defined here

temperatures_agree (temperatures_agree())

Return whether a temperature equals another within the tolerance.

compare_engine_temperature (compare_engine_temperature())

Refuse the temperature of an engine section that differs from the temperature the engine of the section runs at.

set_default_temperature (set_default_temperature())

Give [system] temperature its default when every engine of the run takes it.

refuse_path_sampling_inputs (refuse_path_sampling_inputs())

Refuse, before a temperature is read, the engine inputs whose integrator a path-sampling run cannot use.

resolve_run_temperature (resolve_run_temperature())

Set the temperature a run records from the sources of its engines, and compare the temperatures the settings state with them; set the time step of each OpenMM engine section from the integrator of its simulation.

resolve_resumed_temperature (resolve_resumed_temperature())

Resolve the temperatures of the run file a run resumes.

read_analysed_temperatures (read_analysed_temperatures())

Read the temperatures of the run file of a run the analysis reads.

compare_analysed_engine_inputs (compare_analysed_engine_inputs())

Compare the temperature the analysis reads from a file without a state with the inputs of its engines.

refuse_temperatures_not_numbers (refuse_temperatures_not_numbers())

Refuse a temperature of settings that is not a finite, positive number.

read_earlier_engine_temperatures (read_earlier_engine_temperatures())

Give [system] temperature the temperature a TurtleMD or ASE engine section of an earlier schema ran its engine at.

engine_constructor_settings (engine_constructor_settings())

Return the settings the constructor of an engine is offered.

check_engine_temperature (check_engine_temperature())

Compare the temperature an engine read from its input with the settings of the run.

pyretis.engines.run_temperature.ENGINE_TEMPERATURE_RTOL = 1e-09

The relative tolerance of every comparison of two temperatures (temperatures_agree()): the temperature of an engine section, and [system] temperature, must lie within this fraction of the temperature they are compared with.

class pyretis.engines.run_temperature.EarlierTemperatures(run: float | None = None, system_sections: dict = <factory>, inputs: dict = <factory>, no_effect: dict = <factory>, unknown: list = <factory>, recorded: float | None = None, partly_recorded: dict = <factory>)

Bases: object

The temperatures the engines of an earlier run ran at.

A run file or restart file without the temperature_rule mark of pyretis.core.provenance, and an input of the legacy-runner schema, were written for a PyRETIS that ran each engine (earlier_engine_temperatures()):

  • an internal integrator at [system] temperature, 1 when the file sets none; the temperature of its engine section took no effect on it;

  • any other engine that takes [system] temperature and whose constructor takes no temperature (an engine of a module on EngineBase) at [system] temperature; a file that sets none does not tell the temperature it ran at, since this PyRETIS gives such an engine no default;

  • an engine whose constructor takes a temperature (TurtleMD, ASE) at the temperature of its engine section;

  • an engine that reads its temperature from its input at the temperature of that input. The file records that temperature as the temperature of the engine section of an engine with EngineBase.unmarked_section_temperature, and as [system] temperature for the engine of [engine] with EngineBase.unmarked_system_temperature; the temperature of the section of any other such engine took no effect on it. An engine that used the temperature of its section for a part of its run only, and its input of that run for the rest (EngineBase.unmarked_unrecorded_use(), LAMMPS), ran at a temperature the file does not record in full.

Variables:
  • run (float or None) – The one temperature the engines that take [system] temperature ran at; None for a run without such an engine.

  • system_sections (dict of tuple) – For each engine section of an engine that takes [system] temperature and whose temperature the file records, the temperature it ran at and the setting that records it, as (value, place).

  • inputs (dict) – For each engine section of an engine that reads its temperature from its input, the temperature it ran at and the setting that records it, as (value, place); None for an engine whose temperature the file does not record.

  • no_effect (dict of float) – The temperature of each engine section on whose engine it took no effect, keyed by the section.

  • unknown (list of strings) – The engine sections whose temperature the file gives no way to know: a section whose engine class is not known, the section of an engine whose constructor takes a temperature that gives none, and the section of an engine without a default (EngineBase.default_temperature) in a file that records no [system] temperature.

  • recorded (float or None) – The [system] temperature the file records, or None.

  • partly_recorded (dict of strings) – For each engine section of inputs whose engine used the temperature the file records for a part of its run only: what the engine took from it, and what it did at the temperature of its input of that run, which the file does not record (EngineBase.unmarked_unrecorded_use()), as a warning states it.

inputs: dict
names_no_engine()

Return whether the settings name no engine section with a class.

Returns:

out (boolean) – True when no engine section of the settings names a class, so that nothing tells how an engine of the run ran.

no_effect: dict
partly_recorded: dict
recorded: float | None = None
run: float | None = None
system_sections: dict
unknown: list
unrecorded()

Return the engine sections whose temperature is not recorded.

Returns:

out (list of strings) – The engine sections of inputs whose engine ran at a temperature the file does not record, and the sections of unknown.

pyretis.engines.run_temperature.NO_DEFAULT_TEMPERATURE_TASKS = frozenset({'umbrellawindow'})

The tasks that run no engine and make their moves at [system] temperature: the input of a new run of one must set it (_default_temperature()); the continuation of a restart file runs at the temperature of the run it continues (resolve_restart_temperature()).

pyretis.engines.run_temperature.PATH_ENSEMBLE_TASKS = frozenset({'biretis', 'explore', 'make-tis-files', 'pptis', 'repptis', 'retis', 'tis'})

the path-sampling tasks and make-tis-files. Such a run refuses an engine whose integrator a path-sampling run cannot use (pyretis.engines.engine.refuse_path_sampling_engine()).

Type:

The tasks whose runs build path ensembles

pyretis.engines.run_temperature.RESTART_FILE_TASKS = frozenset({'md', 'md-flux', 'md-nve', 'umbrellawindow'})

The tasks that run in process and continue the run of the restart file that [simulation] restart names (pyretis.inout.settings.settings_from_restart()).

pyretis.engines.run_temperature.check_engine_temperature(engine, settings, section)

Compare the temperature an engine read from its input with the run.

Parameters:
  • engine (object like EngineBase) – An engine just created from an engine section.

  • settings (dict) – The settings of the run.

  • section (string) – The engine section, as the messages name it.

Raises:

ValueError – If the engine reads its temperature from its input, and it read none, or the input states a unit system other than [system]     units (check_engine_units()), or the temperature of the engine section differs from the temperature of the input (compare_engine_temperature()), or [system]     temperature differs from it by more than the tolerance (temperatures_agree()). The message of a difference ends with how the input gives the temperature (reading_advice()).

pyretis.engines.run_temperature.check_engine_units(temperatures, settings, section)

Refuse an engine input in another unit system than [system].

Parameters:
  • temperatures (object like EngineTemperatures) – The temperatures read from the input of the engine; its engine_units is the unit system the input declares (the LAMMPS units command), or None.

  • settings (dict) – The settings of the run.

  • section (string) – The engine section, as the message names it.

Raises:

ValueError – If the input declares a unit system and [system] units names another one.

pyretis.engines.run_temperature.compare_analysed_engine_inputs(settings, name)

Compare the temperature of a file without a state with engine inputs.

A file without a [current] state (an input, or the settings an in-process task of an earlier PyRETIS stored, out.toml, without the mark of pyretis.core.provenance.has_stored_temperature_rule()) is no record of the temperature its engines ran at: the analysis compares the [system] temperature it reads from the file with the input file of each engine that reads its temperature from its own input, as a run of the file compares them, the input read where the file names it (_analysed_input_conflict()). A file with a state is the record of its run, and is not compared. A difference, or an engine input that cannot be read, leaves the file without [system] temperature, with a warning that names both values or the input: the analysis refuses no file for its temperatures, and reads no temperature the run may not have run at. The analysis does not read the temperature of an engine from a Python module: a file with a module engine, or with an engine whose input is a Python module (OpenMM), and a [system] temperature is left without [system] temperature, with a warning that the temperature of that engine is read only by a run (_analysed_module_engine()); such a file without [system] temperature gives no warning. A read of the file again (pyretis.inout.checker.rereading()) logs no warning.

Parameters:
  • settings (dict) – The settings the analysis reads from a file without a state; [system] temperature of the settings and of each ensemble is removed in place for a difference.

  • name (string) – The file, as the warning names it.

Returns:

out (string or None) – What the file and the engine input state, or why the analysis does not read the temperature of an engine, as the warning states it, when the analysis reads no [system] temperature for that reason; None otherwise.

pyretis.engines.run_temperature.compare_engine_temperature(given, temperature, section, engine, place, *, run_file=None, reading='')

Refuse an engine-section temperature unlike the one the engine runs at.

The temperature of an engine section sets no temperature: the engine runs at the temperature of its source (the settings of its input, or [system] temperature). A section that gives one is compared with it, in the units of the engine, within the relative tolerance ENGINE_TEMPERATURE_RTOL.

Parameters:
  • given (object) – The temperature of the engine section, or None when the section gives none.

  • temperature (float) – The temperature the engine of the section runs at.

  • section (string) – The engine section, as the message names it, e.g. engine1.

  • engine (string) – The engine class of the section, as the message names it.

  • place (string) – Where the engine takes its temperature from, as the message names it: the settings of its input and the input (input_temperature_place()), or [system] temperature (system_temperature_place()).

  • run_file (string, optional) – The run file a resume reads the section from. The message then says how the run it records continues.

  • reading (string, optional) – Said at the end of the message of a difference: how the engine reads temperature from the setting it comes from (reading_advice()), starting with a space; empty for none.

Raises:

ValueError – If given is not a temperature, a finite, positive number (_temperature_problem()), or differs from temperature by more than ENGINE_TEMPERATURE_RTOL times temperature. The message names the two values, the section and the place, followed by reading.

pyretis.engines.run_temperature.continues_earlier_run(settings)

Return whether the settings of a path-sampling run continue a run.

Parameters:

settings (dict) – The settings of a path-sampling run: an input, the document of a run file or a state file, or their parsed settings.

Returns:

out (boolean) – True for settings with [initial-path] method = "restart", and for a document with the [current] state of an earlier run (the resume of a run file or a state file).

pyretis.engines.run_temperature.continues_restart_file(settings)

Return whether settings continue a run from its restart file.

Parameters:

settings (dict) – The settings of a run.

Returns:

out (boolean) – True for a task of RESTART_FILE_TASKS with [simulation] restart: the run continues the run its restart file records, at the temperature of that run (resolve_restart_temperature()).

pyretis.engines.run_temperature.earlier_engine_temperatures(settings, classes, name, *, reader)

Return the temperatures the engines of an earlier run ran at.

The settings are read as EarlierTemperatures describes (_collect_earlier_temperatures()). The engines that take [system] temperature run at one temperature, [system] temperature, so they must have run at one temperature, within the tolerance (temperatures_agree()).

Parameters:
  • settings (dict) – The sections of an input, of a run file or of the settings of a restart file, or a scheduler configuration.

  • classes (dict) – The engine class of each engine section of the run, keyed by the section; None for a section whose class is not known.

  • name (string) – The file the settings are read from, as the message names it.

  • reader (string) – Who reads the file: 'input' for the input of a new run, 'resume' for a run file a run resumes; it selects the advice of the refusal (_EARLIER_ADVICE).

Returns:

out (object like EarlierTemperatures) – The temperatures the engines ran at.

Raises:

ValueError – If the engines that take [system] temperature ran at different temperatures (_earlier_system_temperature()).

pyretis.engines.run_temperature.earlier_input_evidence(settings, velocity)

Return what a file without a state records that only earlier runs ran.

A file without a [current] state and without the [provenance] temperature_rule mark that this PyRETIS writes into the settings an in-process run stores (pyretis.core.provenance.has_stored_temperature_rule()) is an input, or the out.toml of a run of an earlier PyRETIS. A setting that this PyRETIS refuses in the input of a run for its temperature, and that the file shows by itself, was run by an earlier PyRETIS only: a [particles.velocity] temperature (refuse_velocity_temperature()), a TurtleMD integrator beta, the temperature of a TurtleMD or ASE section without [system] temperature, and the temperature of an engine section unlike the [system] temperature the file states, by more than the tolerance (compare_engine_temperature() and resolve_run_temperature() refuse it). The analysis reads a file that records one as the record of a run of an earlier PyRETIS (read_analysed_temperatures()).

Parameters:
  • settings (dict) – The sections of the file, before the settings parse.

  • velocity (object or None) – The [particles.velocity] temperature the file records, which was left out of the sections (pop_velocity_temperature()), or None.

Returns:

out (list of strings) – Each such setting and its value, as a warning names it; empty for a file that records none.

Raises:

ValueError – If [system] temperature, the temperature of an engine section (refuse_temperatures_not_numbers()) or velocity (_refuse_velocity_not_number()) is not a temperature, a finite, positive number: such a value is an invalid input, and no evidence.

pyretis.engines.run_temperature.engine_class(settings, section)

Return the class of the engine an engine section creates.

Parameters:
  • settings (dict) – The settings of a run.

  • section (string) – The engine section, e.g. engine.

Returns:

out (type) – The class the section names: a class of the engine map (pyretis.engines.factory.build_engine_map()), or the class of the module the section names (_module_path()).

Raises:

ValueError – If the section names a class without a module that is not a class of the engine map, or a module that cannot be imported.

pyretis.engines.run_temperature.engine_constructor_settings(settings, section, cls, section_settings)

Return the settings an engine constructor is offered.

The temperature of the engine section is no setting of the engine: it is left out of the settings offered. For an engine that takes [system] temperature it is compared with [system] temperature here (compare_engine_temperature()), and the constructor of such an engine with an argument temperature (TurtleMD, ASE) is given [system] temperature there. The temperature of an engine that reads its own from its input is compared once the engine has read it (check_engine_temperature()).

Parameters:
  • settings (dict) – The settings of the run.

  • section (string) – The engine section the engine is created from.

  • cls (type) – The engine class of the section.

  • section_settings (dict) – The settings of the section the constructor is offered.

Returns:

out (dict) – A copy of section_settings without temperature, with temperature set to [system] temperature (_system_temperature()) for a constructor that takes it.

Raises:

ValueError – As compare_engine_temperature() and _system_temperature() raise it.

pyretis.engines.run_temperature.engine_sections(settings)

Return the engine sections of settings that name an engine class.

Parameters:

settings (dict) – The settings of a run.

Returns:

out (list of strings) – engine, engine0 and the numbered sections of a pool (pyretis.inout.settings.is_pool_engine_section()), in this order, for each one that the settings hold with a class.

pyretis.engines.run_temperature.input_temperature_place(temperatures)

Return how a message names where an engine input states its temperature.

Parameters:

temperatures (object like EngineTemperatures) – The temperatures read from the input of an engine.

Returns:

out (string) – The settings of the input that hold the temperature, the input and the unit, e.g. gen-temp, ref-t[System] of grompp.mdp, in kelvin.

pyretis.engines.run_temperature.known_engine_class(settings, section)

Return the class of an engine section, or None for an unknown one.

The settings parse gives [system] temperature its default before the files of a run are staged, so the class of an engine whose module is not on disk yet is not known there. The resume lock reads the class of an engine section of a recorded configuration, which can name a module the working directory does not hold.

Parameters:
  • settings (dict) – The settings of a run.

  • section (string) – The engine section.

Returns:

out (type or None) – The class engine_class() returns, or None for a section that names no class, a class without a module that is not a class of the engine map, and a module that is not a file (_module_path()).

pyretis.engines.run_temperature.pop_velocity_temperature(document)

Remove the [particles.velocity] temperature of a file.

A [particles.velocity] table that holds nothing else is removed with it: the input of the run gave no other setting of the velocities.

Parameters:

document (dict) – The canonical sections of a run file, or the scheduler configuration of a state file; changed in place.

Returns:

out (object or None) – The value removed; None when the file records none.

pyretis.engines.run_temperature.read_analysed_temperatures(settings, state, name, velocity=None)

Read the temperatures of the run file of a run the analysis reads.

The analysis reads the temperature of a run from its run file, not from the inputs or the modules of its engines (pyretis.inout.run_record.read_settings()), and refuses no run for its temperatures. A run file with the temperature_rule mark of pyretis.core.provenance records the temperature each engine of its run ran at, and is read as it is; a [particles.velocity] temperature it records is read as for a run file without the mark, with its [system] temperature (_read_marked_velocity()). One without the mark was written by an earlier PyRETIS, as is a file without a state that records a setting only an earlier PyRETIS ran (earlier_input_evidence()), and its temperatures are read as that PyRETIS ran its engines (_read_analysed_run()): [system] temperature is the one temperature the engines that take it ran at, the temperature of a TurtleMD or ASE section among them. A run whose engines all read their temperature from their own input is read at the temperatures the run file records for them (_read_analysed_inputs()): one temperature is [system] temperature, and different ones leave it out. A run with an engine the analysis does not know keeps the [system] temperature the file records. A run whose record gives no one temperature (_analysed_conflict(): engines that take [system] temperature at different temperatures, a TurtleMD integrator beta of another temperature, an engine at its input at another temperature than those, an engine the analysis does not know with a recorded input temperature that differs from the recorded [system] temperature, a [particles.velocity] temperature that differs from the temperature of the run) is read without [system] temperature, with a warning, and an analysis that needs it stops as for a run that states none. When the run file does not record in full the temperature an engine ran at, a warning says that the [system] temperature the analysis reads is not verified for that engine. The settings of each ensemble are read in the same way. A read of the file again (pyretis.inout.checker.rereading()) logs no warning: the analysis has read the file once.

Parameters:
  • settings (dict) – The parsed settings of the run file, or the scheduler configuration of a state file, or the sections of a file without a state; changed in place.

  • state (dict or None) – The [current] state of the run file, or, for the settings an in-process task of this PyRETIS stored (out.toml), the provenance that carries their mark (pyretis.inout.run_record.read_settings()); None for a file without a state, which is read as a run file without the mark.

  • name (string) – The run file, as the messages name it.

  • velocity (object, optional) – The [particles.velocity] temperature the file records, which was left out of the settings before they were parsed (pop_velocity_temperature()); None (the default) for a file that records none.

Returns:

out (string or None) – Why the record gives no one temperature, as the warning states it (the file and what it records), when the analysis reads no [system] temperature for that reason; None otherwise.

Raises:

ValueError – If [system] temperature, the temperature of an engine section (refuse_temperatures_not_numbers()) or velocity (_refuse_velocity_not_number()) is not a temperature, a finite, positive number: the file is an invalid input, and is refused as one.

pyretis.engines.run_temperature.read_earlier_engine_temperatures(document, name)

Read the temperature of a TurtleMD or ASE section as [system].

The legacy-runner schema ran an engine that takes [system] temperature through its constructor (TurtleMD, ASE) at the temperature of its engine section, and the Langevin integrator of TurtleMD at the beta of its settings, and an internal integrator at [system] temperature (earlier_engine_temperatures()). Their one temperature is the temperature of the run here (_read_section_temperatures()).

Parameters:
  • document (dict) – The sections of an input; changed in place.

  • name (string) – The file the document is read from, as the messages name it.

Returns:

out (string or None) – What was read in another place, and the [system] temperature it replaces, as a warning states it; None when the document has no TurtleMD or ASE engine section with a temperature.

Raises:

ValueError – If these engines ran at different temperatures (earlier_engine_temperatures()), or a TurtleMD integrator beta differs from the inverse temperature the engine derives (_derived_beta()).

pyretis.engines.run_temperature.read_earlier_velocity_temperature(document, name)

Leave out the [particles.velocity] temperature of a run file.

A run file a run resumes without the temperature_rule mark of pyretis.core.provenance records the [particles.velocity] temperature of the input of its run. The velocities are drawn at [system] temperature (refuse_velocity_temperature()), the temperature of the run, which the resume reads as the temperature the engines of the earlier run ran at (_earlier_run_temperature()), so a value equal to that one, within the tolerance (temperatures_agree()), is left out. The analysis reads the value with the temperatures of the run (read_analysed_temperatures()).

Parameters:
  • document (dict) – The canonical sections of the run file, or the scheduler configuration of a state file; changed in place.

  • name (string) – The run file, as the messages name it.

Returns:

out (string or None) – The value left out, as a warning states it; None for a run file without a [particles.velocity] temperature.

Raises:

ValueError – If the run file records a [particles.velocity] temperature that is not a temperature, with the message of the analysis (_refuse_velocity_not_number()), or that differs from the temperature the engines of the run ran at, or records no temperature they ran at; and as _earlier_run_temperature() raises it.

pyretis.engines.run_temperature.reading_advice(temperatures)

Return how an engine input gives the temperature the engine runs at.

The temperature an engine runs at is the first setting of its input (EngineTemperatures.agreed()). When that setting gives the temperature through another quantity (the kT of an OpenMM CustomIntegrator, a thermal energy), a temperature unlike it can come from that quantity, and the message of the difference says how PyRETIS reads it.

Parameters:

temperatures (object like EngineTemperatures) – The temperatures the input of the engine states.

Returns:

out (string) – EngineTemperatures.advice when the first key of values is a key of EngineTemperatures.advised, else an empty string.

pyretis.engines.run_temperature.refuse_path_sampling_inputs(settings, sections=None)

Refuse the engine inputs a path-sampling run cannot use.

The input of each engine section is read as the class of the section reads it (engine_class()), without building the engine and without reading a temperature, and is refused when its integrator, or then its thermostat or barostat, is one a path-sampling run cannot use (pyretis.engines.engine.refuse_path_sampling_input()). Each route of a path-sampling run calls this function before it reads a temperature (resolve_run_temperature(), resolve_resumed_temperature(), and the default of set_default_temperature()), so the refusal of the integrator comes before a message about a temperature of the same input. An input is read once.

Parameters:
  • settings (dict) – The settings of a path-sampling run.

  • sections (list of strings, optional) – The engine sections of the run. The default is every engine section of the settings (engine_sections()) and of each of their ensembles (settings['ensemble']), the sections resolve_run_temperature() reads.

Raises:

ValueError – If the input of an engine section integrates with an integrator, a thermostat or a barostat a path-sampling run cannot use, with a message that starts with the section, [engine1]; the sections are checked in turn, each integrator first. For settings that continue an earlier run (continues_earlier_run()), the message ends with pyretis.engines.engine.CONTINUATION_REFUSAL.

pyretis.engines.run_temperature.refuse_path_sampling_task_inputs(settings)

Refuse the engine inputs a path-sampling task cannot use.

The settings parse calls this function before it refuses a temperature of the input: a [system] temperature that is not a temperature (refuse_system_temperature_not_number()), also when set_default_temperature() checks it again in the [system] units the parse has given their default, a [particles.velocity] temperature (refuse_velocity_temperature()), and a [system] temperature unlike the temperature of the CP2K input of [engine], or a CP2K input whose temperature reader refuses it (pyretis.inout.formats.cp2k.cp2k_settings()), so the refusal of an integrator, a thermostat or a barostat a path-sampling run cannot use comes first. The settings of a task of PATH_ENSEMBLE_TASKS are checked (refuse_path_sampling_inputs()); the settings of another task, and the settings the analysis reads (pyretis.inout.settings.run_file_reader() gives one of pyretis.inout.settings.ANALYSIS_READERS), are not.

Parameters:

settings (dict) – The settings of a run.

Raises:

ValueError – As refuse_path_sampling_inputs() raises it.

pyretis.engines.run_temperature.refuse_system_temperature_not_number(settings)

Refuse a [system] temperature that is not a temperature.

[system] temperature is the temperature of the run, a finite, positive number whose inverse temperature is finite. A value that is not one (a string, a boolean, a list, a table, nan, inf, zero or a negative number: _temperature_problem(); a number so small that beta overflows: _system_temperature_problem()) is refused as an invalid input, by every reader of the settings, before it is compared with any temperature or read as one: a boolean is not read as the temperature 1 or 0.

Parameters:

settings (dict) – The sections of an input or of a run file, or the scheduler configuration of a state file. [system] and the [system] of each ensemble (settings['ensemble']) are checked.

Raises:

ValueError – If [system] temperature, of the settings or of an ensemble, is given and is not a temperature (_system_temperature_problem()).

pyretis.engines.run_temperature.refuse_temperatures_not_numbers(settings)

Refuse the temperatures of settings that are not temperatures.

[system] temperature (refuse_system_temperature_not_number()) and the temperature of each engine section (_refuse_section_not_number()) are checked before a reader of an earlier run counts them as the evidence of that run, compares them or reads them as the temperature of the run.

Parameters:

settings (dict) – The sections of an input or of a run file, or the scheduler configuration of a state file.

Raises:

ValueError – If [system] temperature or the temperature of an engine section is given and is not a temperature, a finite, positive number (_temperature_problem()).

pyretis.engines.run_temperature.refuse_velocity_temperature(settings)

Refuse a temperature in [particles.velocity].

The velocities of the system are drawn at the temperature of the system, [system] temperature.

Parameters:

settings (dict) – The settings of a run.

Raises:

ValueError – If [particles.velocity] sets temperature (velocity_temperature_given()).

pyretis.engines.run_temperature.resolve_restart_temperature(settings, restart, name)

Resolve the temperature of the continuation of a restart file.

The continuation (continues_restart_file()) runs at the temperature of the run its restart file records (_restart_file_temperature()). Settings without [system] temperature, the settings of an input that sets none for an engine that takes it, are given that temperature. A [system] temperature the settings hold, the input’s or the one the input of an engine states (resolve_run_temperature()), must equal it within the tolerance (temperatures_agree()), and is then replaced by it, so that the settings the run stores record the temperature the continuation runs at. A restart file without the temperature_rule mark that does not record the temperature its engine ran at, an engine that reads its temperature from its input, gives way to the temperature of that input, with a warning that the temperature of the continuation is not verified. One that records the temperature an engine used for a part of its run only (LAMMPS) is compared on it, and the continuation is warned of as not verified, also when the two are equal. The temperature of the engine section of an engine that takes [system] temperature is compared with the temperature of the continuation (compare_engine_temperature()).

Parameters:
  • settings (dict) – The settings of the continuation; [system] temperature is set in place to the temperature of the continuation when they hold none or another value within the tolerance.

  • restart (dict) – The restart file, as pyretis.inout.restart.read_restart_file() reads it. The temperature of its system and of its settings is set to the temperature of the continuation where it holds another one (_set_restart_temperature()).

  • name (string) – The restart file, as the messages name it.

Raises:

ValueError – If [system] temperature of the settings differs from the temperature the restart file records by more than the tolerance, or neither holds a temperature, or as _restart_file_temperature() and compare_engine_temperature() raise it.

pyretis.engines.run_temperature.resolve_resumed_temperature(settings, state, name)

Resolve the temperatures of the run file a run resumes.

A [system] temperature that is not a finite, positive number is refused first, with or without the mark (refuse_system_temperature_not_number()). A run file whose [current] provenance holds pyretis.core.provenance.TEMPERATURE_RULE_KEY records the temperature each engine of its run runs at, and is refused when it records none for an engine (_refuse_unrecorded_run_file()). One without it was written by an earlier PyRETIS, and its temperatures are read as that PyRETIS ran them (_read_earlier_run_file()), with a warning for each engine whose temperature it does not record, or records in part (_warn_partly_recorded_temperatures()). The settings are then resolved as the settings of a new run (resolve_run_temperature()): the temperatures the run file records are compared with the sources of the engines, so a resume whose engine input states another temperature is refused before any engine runs.

Parameters:
  • settings (dict) – The parsed settings of the run file, or the scheduler configuration of a state file; changed in place.

  • state (dict or None) – The [current] state of the run file.

  • name (string) – The run file, as the messages name it.

Raises:

ValueError – As refuse_system_temperature_not_number(), _refuse_unrecorded_run_file(), _read_earlier_run_file() and resolve_run_temperature() raise it.

pyretis.engines.run_temperature.resolve_run_temperature(settings, run_file=None)

Set the temperatures a run records from the sources of its engines.

Each engine of the run that reads its temperature from its input (GROMACS, LAMMPS, CP2K, OpenMM, AMS) has that input read, with the reader the engine itself calls when it is created (read_input_temperatures of the engine class), and every temperature the input states must agree. Then:

  • a run whose engines all take [system] temperature is given its default when the settings hold none (_default_temperature()), as the settings parse gives it (set_default_temperature()) when the classes of the engines are known there; the continuation of a restart file (continues_restart_file()) is given the temperature of the run it continues when the restart file is read (resolve_restart_temperature());

  • a [system] temperature the input sets must equal the temperature of each engine that reads its own;

  • otherwise, when the inputs of those engines state one temperature (the lowest and the highest agree to the round-off, same_temperature()), [system] temperature is set to the temperature of the first of their engine sections, which the run record then holds;

  • otherwise each engine runs at the temperature of its own input, which its engine section records when it gives none, and [system] temperature stays unset, unless an engine of the run takes [system] temperature, which is refused.

The temperature of each engine section that gives one is compared with the temperature the engine of the section runs at (compare_engine_temperature()): the temperature of its input, or [system] temperature. An input that declares a unit system (the LAMMPS units command) must declare the one of [system] units (check_engine_units()).

The time step of an OpenMM engine is the step size of the integrator of its simulation (pyretis.engines.openmm.simulation_step_size()), which the same read of the module gives (EngineBase.records_input_timestep), so the module runs once. It is set as the timestep of each OpenMM engine section that states none, which the run record then holds, and a section that states one must equal it (_resolve_input_timestep()). The run then has the time step of each OpenMM section before any engine is built: the record holds it, a resume compares it, the sections of a pool are compared for one time per step (pyretis.core.engine_time.one_time_per_step_problem()) and the analysis reads it from the run file. OpenMM runs in nm and ps: a run with an OpenMM engine section and a [system] units whose time unit differs from the ps is refused (_refuse_input_time_unit()).

The settings of each ensemble (settings['ensemble']), which the settings parse copies from the general sections, are resolved in the same way.

Parameters:
  • settings (dict) – The parsed settings of a run. [system] temperature, the temperature of the engine sections of a run whose engines run at different temperatures, and the timestep of the OpenMM engine sections, are set in place, in the general sections and in each ensemble.

  • run_file (string, optional) – The run file a resume reads the settings from (resolve_resumed_temperature()). A refusal then says how the run it records continues.

Raises:

ValueError – If the temperature of an engine section differs from the temperature its engine runs at, an engine input states no temperature, several different ones or a unit system other than [system] units, [system] temperature differs from the temperature of an engine input, or the engine inputs state different temperatures and an engine of the run takes [system]     temperature; as pyretis.engines.openmm.simulation_step_size() raises it for the simulation of an OpenMM engine section; if the timestep of an OpenMM engine section differs from the step size of its integrator, or [system] units has a time unit other than the ps (_resolve_input_timestep()).

pyretis.engines.run_temperature.runs_at_constructor_temperature(cls)

Return whether an engine takes [system] temperature as an argument.

Parameters:

cls (type) – An engine class.

Returns:

out (boolean) – True for an engine that runs at [system] temperature and has an argument temperature in its constructor, which the engine factory gives it (TurtleMD, ASE).

pyretis.engines.run_temperature.set_default_temperature(settings)

Give [system] temperature its default.

When the input sets no [system] temperature and every engine of the run takes it, the run runs at the EngineBase.default_temperature of its engines, 1 (_default_temperature()), when they are internal integrators; an input with any other engine that takes it (TurtleMD, ASE, an engine of a module on EngineBase), which has no default, is refused, and so is the input of a new umbrellawindow run (NO_DEFAULT_TEMPERATURE_TASKS). A run with an engine that reads its temperature from its input is given the temperature of that input when the run is set up (resolve_run_temperature()), and gets no default here; nor does a run with an engine whose class is not known when the settings are read (known_engine_class()), which the run set-up gives its default, nor the continuation of a restart file (continues_restart_file()), which runs at the temperature of the run it continues; the continuation of an input with an engine without a default that sets no [system] temperature is refused as well. Other settings without an engine class, which run no engine, are given 1. The settings of a run file the analysis reads (pyretis.inout.settings.reading_run_file() with the reader 'analysis') get no default and are not refused: the run file records the temperature of its run, or the analysis reads it as an earlier PyRETIS ran its engines (read_analysed_temperatures()), and a run file that records none is analysed without one. The settings of a run file whose state carries the temperature_rule mark, which a run resumes or continues (the reader 'marked-resume'), get no default either: the run file records the temperature of its run, and the resume refuses one that records none (resolve_resumed_temperature(), and the resume lock of a continuation, pyretis.bin.pyretisrun._check_resume_compatibility()); an engine without a default and without [system] temperature is refused there as in an input. A file without a state that the analysis reads as an input (the reader 'input-analysis') is given the defaults of an input, with the classes of its engine sections read without importing a module (_recorded_engine_class()): an engine section that names a module gives no default temperature (compare_analysed_engine_inputs() says why). The default of [system] units imports such a module (pyretis.inout.settings._set_default_units_from_engine()).

Parameters:

settings (dict) – The parsed settings. [system] temperature is set in place.

Raises:

ValueError – If [system] temperature is not a temperature in [system]     units (refuse_system_temperature_not_number()), or the input sets no [system] temperature and an engine of the run takes it with no default (TurtleMD, ASE, an engine of a module on EngineBase), or the input is the one of a new umbrellawindow run, outside the analysis of a run file (_default_temperature()); first, for a task of PATH_ENSEMBLE_TASKS outside the analysis, if the input of an engine of the run integrates with an integrator a path-sampling run cannot use (refuse_path_sampling_inputs()), and for an md, md-nve or md-flux task outside the analysis, if the class of [engine] cannot run the task (pyretis.setup.md_task_refusal.refuse_md_task_input()).

pyretis.engines.run_temperature.system_resume_advice(run_file, recorded, value)

Return the advice of a resume refused on [system] temperature.

Parameters:
  • run_file (string) – The run file the resume reads.

  • recorded (float) – The [system] temperature the run file records.

  • value (float) – The temperature the input of an engine states.

Returns:

out (string) – The advice: the run file records recorded for the run it resumes, which the input of the engine must state again, within a relative ENGINE_TEMPERATURE_RTOL, to continue that run.

pyretis.engines.run_temperature.system_temperature_not_number(settings)

Return why a [system] temperature is not a temperature.

Parameters:

settings (dict) – The sections of an input or of a run file, or the scheduler configuration of a state file. [system] and the [system] of each ensemble (settings['ensemble']) are read, in this order.

Returns:

out (string or None) – The refusal of the first [system] temperature given that is not a temperature in the [system] units of its [system] (_system_temperature_problem()), as refuse_system_temperature_not_number() states it, or None when each one given is a temperature.

pyretis.engines.run_temperature.system_temperature_place(cls)

Return how a message names the temperature of an engine at [system].

Parameters:

cls (type) – An engine class that runs at [system] temperature.

Returns:

out (string) – [system] temperature, with the temperature the engine runs at when the input sets none (EngineBase.default_temperature), or with the statement that the input must set it.

pyretis.engines.run_temperature.temperatures_agree(value, reference)

Return whether a temperature equals another within the tolerance.

Parameters:
  • value (float) – The temperature compared.

  • reference (float) – The temperature it is compared with.

Returns:

out (boolean) – True when value differs from reference by no more than ENGINE_TEMPERATURE_RTOL times reference.

pyretis.engines.run_temperature.velocity_temperature_given(settings)

Return whether [particles.velocity] sets temperature.

Parameters:

settings (dict) – The settings of a run.

Returns:

out (boolean) – True when [particles.velocity] is a table with the key temperature, which refuse_velocity_temperature() refuses.

pyretis.engines.turtlemd module

A TurtleMD integrator interface.

This module defines a class for using the TurtleMD.

pyretis.engines.turtlemd.ENGINE_INTEGRATOR_PARAMETERS = ('timestep', 'beta', 'seed', 'rgen')

The parameters of a TurtleMD integrator that the engine gives it, and that its settings do not set: the time step, the inverse temperature (TurtleMDEngine._integrator_settings()), the seed of a seeded integrator and its random generator.

pyretis.engines.turtlemd.SEEDED_INTEGRATORS = (<class 'turtlemd.integrators.LangevinInertia'>,)

The TurtleMD integrators that the engine seeds. Each leg seeds its integrator with a seed drawn from the random generator of the move; the other integrators take the time step and their settings only.

class pyretis.engines.turtlemd.TurtleMDEngine(timestep: float, subcycles: int, temperature: float, boltzmann: float, integrator: dict[str, Any], potential: dict[str, Any], particles: dict[str, Any], box: dict[str, Any])

Bases: ExternalMDEngine

Interface the TurtleMD engine.

To do:
  • Add support for multiple potentials?

  • Velocity generation needs to account for the dimensionality of the system

__init__(timestep: float, subcycles: int, temperature: float, boltzmann: float, integrator: dict[str, Any], potential: dict[str, Any], particles: dict[str, Any], box: dict[str, Any])

Initialize the TurtleMD engine.

Parameters:
  • timestep (float) – The simulation timestep.

  • subcycles (int) – The number of subcycles to execute per path-sampling step.

  • temperature (float) – The temperature of the simulation, [system] temperature, which the engine factory gives the constructor (pyretis.engines.run_temperature.engine_constructor_settings()).

  • boltzmann (float) – The value of Boltzmann’s constant (kB).

  • integrator (dict) – The name of the integrator to use for TurtleMD, class, and its settings. A Langevin integrator is given the inverse temperature beta of the engine (_integrator_settings()), and its settings must not set it.

  • potential (dict) – The name of the potential to use for TurtleMD.

  • particles (dict) – The mass and name of the particles in the system.

  • box (dict) – Definition of the simulation box.

_extract_frame(traj_file: str, idx: int, out_file: str) → None

Extract a frame from a trajectory file.

This method is used by self.dump_config when we are dumping from a trajectory file. It is not used if we are dumping from a single config file.

Parameters:
  • traj_file (str) – The trajectory file to dump from.

  • idx (int) – The frame number we look for.

  • out_file (str) – The file to dump to.

static _integrator_problem(integrator)

Return why a path-sampling run cannot use a TurtleMD integrator.

Parameters:

integrator (type) – A TurtleMD integrator class, a value of INTEGRATOR_MAPS.

Returns:

out (string or None) – The reason path_sampling_problem() gives, or None.

_integrator_settings(integrator)

Return the settings the TurtleMD integrator is created with.

An integrator that takes the inverse temperature beta (the Langevin integrators) is given the beta of the engine, 1 / (boltzmann * temperature), from [engine] boltzmann and [system] temperature, so the dynamics and the velocity draws run at one temperature.

Parameters:

integrator (dict) – The integrator setting of the engine: its class and its settings.

Returns:

out (dict) – A copy of the settings (empty for an integrator given none), with beta for an integrator that takes it.

Raises:

ValueError – If the settings set beta.

_leg_integrator()

Return the TurtleMD integrator of one leg.

An integrator of SEEDED_INTEGRATORS takes a seed drawn from rgen, the random generator of the move; the other integrators take the time step and their settings.

Returns:

out (object like turtlemd.integrators.MDIntegrator) – The integrator.

Raises:

ValueError – If a seeded integrator finds no random generator.

_persist_force_evals()

Write this engine’s running force-eval total, when opted in.

Persistence is OFF by default (no stray files in normal runs or the test suite). The validation driver sets PYRETIS_FORCE_EVAL_DIR to a run directory; each propagating engine then keeps a small per-process file force_evals_<pid>.txt there holding its current cumulative count. The driver sums every such file in the run directory, so the total is correct across the worker pool and across a restart-continued run (a fresh process starts a new file).

_propagate_from(name: str, path: Path, system: System, ens_set: dict[str, Any], msg_file: FileIO, reverse: bool = False) → tuple[bool, str]

Propagate the equations of motion from the given system.

We assume the following:
  • Box does not change (constant volume simulation)

  • Box is orthogonal

static _read_configuration(filename: str) → tuple[ndarray, ndarray, ndarray | None, list[str]]

Read TurtleMD output configuration.

This method reads the specified TurtleMD output configuration and extracts the configuration which includes the positions, velocities, box dimensions and particle names. It is used when calculating the order parameter from a TurtleMD simulation.

Parameters:

filename (str) – The path to the file to read the configuration from.

Returns:

tuple –

A tuple containing:

  • xyz: An array of atomic positions.

  • vel: An array of atomic velocities.

  • box: An array of box dimensions or None if not available.

  • names: A list of atom names found in the file.

_refuse_unbound_settings(name, settings)

Refuse integrator settings the integrator does not take.

Each leg creates the integrator (_leg_integrator()) with the time step of the engine, the settings, and a seed for an integrator of SEEDED_INTEGRATORS. The settings are checked against the parameters of the integrator when the engine is created, so a setting the integrator does not take, or a parameter it needs that the settings do not give, stops the run before a file is written. An integrator that a path-sampling run cannot use is refused by its own message (path_sampling_problem()) and is not checked here.

Parameters:
  • name (string) – The class of the integrator, as the input gives it.

  • settings (dict) – The settings the integrator is created with (_integrator_settings()), beta included for an integrator that takes it.

Raises:

ValueError – If the settings give a parameter the integrator does not take, a parameter the engine gives (timestep, and seed for a seeded integrator), or leave out a parameter without a default that the engine does not give. The message names the settings and the ones the integrator takes (integrator_settings_text()).

_reverse_velocities(filename: str, outfile: str) → None

Reverse velocities in the given snapshot.

Parameters:
  • filename (str) – The path to the file containing the configuration to reverse the velocities of.

  • outfile (str) – The path to the output file for storing the configuration with reversed velocities.

static _update_phase_point_box(system, box)

Give the phase point the size of the box TurtleMD integrates in.

A phase point without a box gets one of that size. A phase point that holds the box of the settings takes the size when the box has as many dimensions as TurtleMD’s box. A non-periodic box of another dimension is left as it is: no length of it enters a distance.

Parameters:
  • system (object like System) – The phase point.

  • box (numpy.array) – The box lengths of the configuration TurtleMD read.

Raises:

ValueError – If the phase point holds a periodic box with another number of dimensions than TurtleMD’s box.

property beta

The inverse temperature 1 / (boltzmann * temperature).

calculate_order(system, xyz=None, vel=None, box=None)

Calculate the order parameter of the current system.

default_temperature = None
default_units = 'reduced'
draw_maxwellian_velocities(vel, mass, beta, rgen, sigma_v=None)

Draw velocities from a Gaussian distribution.

dump_phasepoint(phasepoint, deffnm='conf')

Dump the current configuration from a system object to a file.

engine_type = 'internal'
classmethod get_default_units(settings=None)

Return the default unit system for TurtleMD.

TurtleMD examples are dimensionless (boltzmann = 1.0, unscaled lengths/energies), and the general-purpose “reduced” unit system (pyretis.core.units.UNIT_SYSTEMS, length scale 1) matches them.

Parameters:

settings (dict, optional) – Full simulation settings or engine settings. This argument is ignored for the TurtleMD engine.

Returns:

out (string) – The default unit system for TurtleMD, "reduced".

classmethod input_path_sampling_problem(engine_settings)

Return why a path-sampling run cannot use a section’s integrator.

The integrator is the class [engine.integrator] class names in INTEGRATOR_MAPS, as the engine takes it when it is created, and is checked as path_sampling_problem() checks it.

Parameters:

engine_settings (dict) – The settings of the engine section.

Returns:

out (string or None) – The reason for the Verlet and the LangevinOverdamped integrators; None for the other integrators, and for a section that names no integrator of INTEGRATOR_MAPS, which the engine refuses when it is created.

modify_velocities(system: System, vel_settings: dict[str, Any], rgen) → tuple[float, float]

Modify the velocities of all particles.

Parameters:
  • system (object like System) – The system whose particle velocities are to be modified.

  • vel_settings (dict) – A dict; zero_momentum (bool) resets the linear momentum to zero after generating velocities internally. A missing key means False, the [tis] default. The engine draws the velocities of aimless shooting and leaves their energy as drawn, so a soft perturbation (a sigma_v that is not negative) and a positive rescale are refused before the draw.

Returns:

  • dek (float) – The change in kinetic energy from the velocity modification.

  • kin_new (float) – The new kinetic energy of the system.

Raises:

NotImplementedError – If vel_settings select a soft perturbation (refuse_soft_perturbation()) or an energy re-scale (refuse_energy_rescale()).

needs_order = False
path_sampling_problem()

Return why a path-sampling run cannot use this engine.

The TurtleMD Verlet integrator stores, with the positions of a step, the velocity of the step before (the central difference of the positions around it), and starts each leg from the positions one step back that it derives from the first velocity. LangevinOverdamped integrates Brownian dynamics, without velocities; PyRETIS runs Brownian dynamics in path sampling with the internal Langevin engine, whose high_friction integrator the method validation covers. VelocityVerlet and LangevinInertia store the velocities at the time of the positions.

Returns:

out (string or None) – The reason for the Verlet and the LangevinOverdamped integrators, or None.

step(system, name)

Perform a single step with the engine.

This engine integrates whole segments (_propagate_from()), so a single step() is not supported. The method exists only so the class can be instantiated (the ExternalMDEngine base declares it as an abstract method). supports_step_kick = False routes kick_across_middle to the propagate()-based _kick_across_middle_propagate, so this method is never called.

supports_step_kick = False
system_temperature_unit = 'the temperature unit of [engine] boltzmann'
pyretis.engines.turtlemd.VELOCITY_FREE_INTEGRATORS = (<class 'turtlemd.integrators.LangevinOverdamped'>,)

The TurtleMD integrators that integrate without velocities (Brownian dynamics).

pyretis.engines.turtlemd._ADVISED_INTEGRATOR_SETTINGS = ' "velocityverlet" takes no settings, and "langevininertia" takes the setting gamma.'

The settings of the integrators the refusal of a TurtleMD integrator advises (TurtleMDEngine._integrator_problem()).

pyretis.engines.turtlemd.integrator_settings_text(integrator)

Return the settings a TurtleMD integrator takes, as a message says.

Parameters:

integrator (type) – A TurtleMD integrator class, a value of INTEGRATOR_MAPS.

Returns:

out (string) – takes no settings, or takes the setting (the settings) and the names of its parameters other than ENGINE_INTEGRATOR_PARAMETERS.