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 does not rely on continuously starting and stopping the GROMACS executable.
- 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 wavefunction
is warm-started from a .wfn restart kept in the run directory for
speed (see WFN_STORE).
The relaunch (start-and-stop / restart-chain) engine, which advances
CP2K one order-parameter point at a time, remains available as
class = "cp2k_steps" (pyretis.engines.cp2k_steps).
Important classes defined here¶
- CP2KEngine (
CP2KEngine) The continuous CP2K engine.
- pyretis.engines.cp2k.COLD_START_WFN = 'doesnotexist.wfn'¶
The wavefunction file a segment names when the engine keeps no store (an engine created without
exe_path). The directory CP2K runs in holds no file of this name, so CP2K starts the SCF from its initial guess.
- class pyretis.engines.cp2k.CP2KEngine(cp2k: str, input_path: str, timestep: float, subcycles: int, temperature: float | None = None, extra_files: list[str] | None = None, exe_path: str | Path | None = None, sleep: float = 0.1)¶
Bases:
CP2KEngineStepsStreaming CP2K engine.
This engine shares its configuration and input convention with the relaunch engine
CP2KEngineSteps(same[engine]settings, sameinitial.xyz/cp2k.inp/extra_filesinput directory) so a user can switchclass = cp2k<->class = cp2k_stepsand 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 wavefunction is warm-started from a.wfnrestart kept in the run directory for speed.- Variables:
cp2k – The command for executing CP2K.
input_path – The directory holding the input files the engine reads.
wfn_store – The directory
WFN_STOREin the run directory (exe_path), holding the wavefunctions the MD segments start from; None for an engine created withoutexe_path, whose segments start their SCF from CP2K’s initial guess.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, temperature: float | None = None, 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.
temperature (float, optional) – The temperature of the simulation.
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_pathis resolved against it, and it holdswfn_store. None resolvesinput_pathagainst the working directory as the engine is created and gives the engine no wavefunction store.sleep (float) – A time in seconds, for waiting for files to be ready.
- _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 is currently only applicable for NVT simulations, as no box information is read from CP2K.
- 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.
- 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), so the override is kept verbatim. The relaunchCP2KEngineSteps._read_configuration()returnsboxfirst instead;calculate_order()and_propagate_from()rely on the box-third order, so this cannot be inherited.- 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.
- _reverse_velocities(filename: str, outfile: str) None¶
Reverse velocity in a given snapshot.
Kept as an override because it unpacks this engine’s box-third
_read_configuration()(xyz, vel, box, names); the relaunch base unpacks 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.
- property beta¶
The thermodynamic temperature in units of the engine.
- calculate_order(system, xyz=None, vel=None, box=None)¶
Calculate the order parameter of the current system.
Overrides the classic
ExternalMDEngine.calculate_orderbecause this engine’s_read_configuration()returns the box as the third element (xyz, vel, box, names), whereas the classic 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.
- dump_phasepoint(phasepoint, deffnm='conf')¶
Dump the current configuration from a system object to a file.
Kept from the inf base: it points the phase point at frame index
0viaset_pos(the classic external override instead setsconfig = (pos_file, None)). The inf scheduler (moves.dump_phasepointcall sites) relies on the index-0 form, so this preserves byte-identical behaviour.
- 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 (asigma_vthat is not negative) and a positiverescaleare 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:
NotImplementedError – If
vel_settingsselect a soft perturbation (refuse_soft_perturbation()) or an energy re-scale (refuse_energy_rescale()).
Notes
This method does not take care of constraints.
- needs_order = True¶
- set_mdrun(md_items: dict[str, Any]) None¶
Set the per-worker execute directory.
Overrides
EngineBase.set_mdrun(); the infinite-swapping scheduler (seecore.moves) calls this once per worker to point the engine at its private execution directory. CP2K requiresexe_dirto be present, so it is read as a required key rather than with the base.getdefault.
- step(system, name)¶
Perform a single step with the engine.
CP2K is propagated via
_propagate_from(); a bare singlestep()is not used by the infinite-swapping scheduler. The method exists only so the class can be instantiated (the classic external base declares it abstract).
- supports_step_kick = False¶
- pyretis.engines.cp2k.WFN_STORE = 'pyretis-cp2k-wfn'¶
The directory, in the run directory (the engine’s
exe_path), holding the wavefunction each MD segment starts its SCF from. After a segment the wavefunction CP2K wrote is saved there, under a key taken from the segment’s name, and the next segment with that key starts from it. Every engine of the run – the initiation, the workers and a restart – shares the directory.pyretis run, a run of a legacy-runner input, and a scheduler run of staged initial paths or beside the ensemble output of an earlier run stop before they start when the run directory holds one of an earlier run (seepyretis.simulation.setup.refuse_before_initiation(),pyretis.simulation.setup.refuse_left_wavefunction_store()andpyretis.simulation.setup.refuse_before_staged_load()).
- 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', restart_wfn: str = 'doesnotexist.wfn', print_freq: int | 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. Further, we here assume that we start from a given xyz file and we also explicitly give the velocities here.
- 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 (base)name for the input file to read positions from.
vel (np.ndarray) – The velocities to set in the input.
name (str) – A name for the CP2K project.
restart_wfn (str, optional) – The wavefunction file CP2K starts the SCF from (
WFN_RESTART_FILE_NAME). The default isCOLD_START_WFN.print_freq (int, optional) – How often we should print to the trajectory file.
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.
- class pyretis.engines.cp2k_steps.CP2KEngineSteps(cp2k, input_path, timestep, subcycles, extra_files=None, exe_path='/builds/pyretis/pyretis/docs', seed=0, conf='initial.xyz', template='cp2k.inp', velocity_generation='maxwell', temperature=None)¶
Bases:
ExternalMDEngineA 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) – An object we use to set seeds for velocity generation.extra_files (list) – List of extra files which may be required to run CP2K.
- __init__(cp2k, input_path, timestep, subcycles, extra_files=None, exe_path='/builds/pyretis/pyretis/docs', seed=0, conf='initial.xyz', template='cp2k.inp', velocity_generation='maxwell', temperature=None)¶
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 temperature (so the draw does not require the system to carry masses). This mirrors thevelocity_generationknob of the GROMACS/LAMMPS engines.temperature (float, optional) – The MD temperature for the Maxwell draw. When
Noneit is read from theMOTION->MDsection of the CP2K input template, so the same input directory drives velocity generation without an extra[engine]setting.
- _ensure_velocity_setup()¶
Compute engine-level masses + beta on first use.
The masses are guessed from the initial-config atom types and the temperature is taken from the
[engine]setting or, when that is absent, theMOTION->MDsection of the CP2K input template. Deferred from__init__so the engine can be constructed before the input files exist on disk.
- _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.
- _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, so this function is kept for future need.
- 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.
- 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.
- _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.
- default_units = 'cp2k'¶
- frame_cell()¶
Return the cell for a stored frame that records none.
CP2K’s
.xyzframes 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.
- 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.
- Parameters:
system (object like
System) – The system object gives the initial state for the integration.order_function (object like
OrderParameteror 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).
- 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:
ValueError – If
rescaleis positive and the potential energy ofsystemis not known.
- run_cp2k(input_file, proj_name)¶
Run the CP2K executable.
- Returns:
out (dict) – The files created by the run.
- 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.write_for_continue(infile, outfile, timestep, subcycles, name='md_continue')¶
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.restartandprevious.wfnto continue a run.- 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.
- pyretis.engines.cp2k_steps.write_for_genvel(infile, outfile, posfile, seed, name='genvel')¶
Create input file for velocity generation.
Velocity generation runs internally, so this function is kept for future need.
- 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.
- 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 (base)name for the input file to read positions from.
name (string, optional) – A name for the CP2K project.
print_freq (integer, optional) – How often we should print to the trajectory file.
- pyretis.engines.cp2k_steps.write_for_step_vel(infile, outfile, timestep, subcycles, posfile, vel, name='md_step', print_freq=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. Further, we here assume that we start from a given xyz file and we also explicitly give the velocities here.
- 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 (base)name for the input file to read positions from.
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.
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.
- class pyretis.engines.engine.EngineBase(description)¶
Bases:
objectAbstract 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’sstep(). Engines whosestepraisesNotImplementedError(CP2K and LAMMPS streaming, ASE, TurtleMD) set this to False sokick_across_middleuses the engine-agnosticpropagate()-based fallback instead. Only consulted byExternalMDEngine.kick_across_middle(); the internal- engine and OpenMMkick_across_middleoverrides define their own search and ignore this flag.
- __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 (the explicit/injected convention); 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_functiondefault 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 py:class:.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;systemis 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_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
.xyzframe 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
Noneif the engine does not define one.
- 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.
rgenis the velocity-generation random generator, injected explicitly (kept distinct from any integrationself.rgen). Every kick is an aimless draw that follows the[tis]zero_momentumsetting intis_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 asself.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) under the explicit/injected convention; 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.
- abstractmethod propagate(path, ens_set, system, reverse=False)¶
Propagate equations of motion.
- 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 per-worker, durable run state on the engine.
The unified (explicit/injected) convention keeps only durable, per-worker configuration on the engine; the transient
System/rgen/order function are injected per call. The infinite-swapping scheduler calls this once per worker to point the engine at its private execution directory (and, for engines that launch an external command, its worker-unique launch command). The default handles the common case – setexe_dirfrommd_itemswhen provided; subclasses that need more (e.g. a per-workermdruncommand) override and extend it.- Parameters:
md_items (dict) – Per-worker run items. 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 unified
Systemproperty API (pos/vel/vpot/ekin), which routes tosystem.particleswhen a harness-style engine has attached one and otherwise stores the values directly on the snapshot-based system. It therefore works for both particle-based engines (the internal integrators) and snapshot-based engines (the external/ streaming engines, whoseparticlesisNone). Reaching throughsystem.particlesunconditionally hitsNone.posfor the latter.
- supports_step_kick = True¶
- 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 setsself.timestepfrom 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).subcyclesdefaults to 1 when an engine does not define it.- Returns:
float or None –
timestep * subcycles, orNoneif the engine has notimestep.
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:
EngineBaseBase 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:
ExternalMDEngine.step()A method for performing a MD step with the external engine. Note that the MD step can consist of a number of subcycles.
ExternalMDEngine._read_configuration()For reading output (configurations) from the external engine. This is used for calculating the order parameter(s).
ExternalMDEngine._reverse_velocities()For reversing velocities in a snapshot. This method will typically make use of the method
ExternalMDEngine._read_configuration().
ExternalMDEngine._extract_frame()For extracting a single frame from a trajectory.
ExternalMDEngine._propagate_from()The method for propagating the equations of motion using the external engine.
ExternalMDEngine.modify_velocities()The method used for generating random velocities for shooting points. Note that this method is defined in
EngineBase.modify_velocities().
- 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
subcyclesnumber 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>¶
- static _cap_engine_log(path, maxsize)¶
Trim an engine log to its most-recent
maxsizebytes.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
configtuple and later passed to_extract_frame(). For most engines it equals the trajectory-frame number; engines that index configurations by MD time step (e.g. the streaming LAMMPS engine, which storesframe * 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 singlestep(): CP2K/LAMMPS streaming, ASE, TurtleMD). Mirrors the greedy hill-climb of the step()-basedkick_across_middle()above – kick velocities, advance exactly one step, keep the new point if it got closer tomiddleor revert otherwise, repeat until the step straddlesmiddle– but advances usingpropagate()(aPathcapped atmaxlen=2) instead ofstep(), operating on in-memorySystem.copy()objects. No file-based prev/curr bookkeeping is needed here: each engine’s own_propagate_fromalready manages its own 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; only
ens_set['interfaces']is read (by the innerpropagate()call’s own bookkeeping – the[1]middle interface it carries is irrelevant here, the crossing search instead compares against themiddleargument, which may differ fromens_set['interfaces'][1]for the body-ensemble edge case inpyretis.initiation.initiate_kick. generate_initial_path_kick()).middle (float) – This is the value for the middle interface.
tis_settings (dict) – Settings for TIS.
kick_maxtriescaps the number of kick attempts (defaultKICK_MAXTRIES, at least 1), andzero_momentumselects the linear-momentum reset after each kick (a missing key means False). Every kick passes thevel_settingsof the step()-based search to the engine’smodify_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 integrationself.rgen).
- Returns:
Note
Unlike
kick_across_middle(), this method does NOT mutate the caller’ssystemobject in place – it returns fresh copies via(previous, right_point). Callers must use the return value (generate_initial_path_kick()already does: it reassignsensemble['system']from the returned points rather than relying on in-place mutation).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 – there is no persistent-streaming optimisation across the greedy search’s many small steps here. This is a one-time bootstrap cost (kick runs once per ensemble, not once per cycle), and is strictly better than today’s “cannot kick at all” for these engines; turtlemd and ASE are pure in-process Python engines, so this primitive is cheap for them. Performance characterisation for CP2K/LAMMPS is deferred.
- static _modify_input(sourcefile, outputfile, settings, delim='=')¶
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 thesettingsdictionary.- 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.
- 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 correct extension for GROMACS (either gro or g96).
- Parameters:
basename (string) – The base name to give to the file.
- Returns:
out (string) – A file name with an extension.
- 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)wherephase_pointsare the surviving frames except the last good one (rebuilt from the partial trajectory, with order parameters recomputed) andcont_confis 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 surviving frames are deliberately not added to the caller’s path here: the caller prepends them after
_propagate_from()so the engine’s ownupdate_energiesaligns 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 after
propagate(). And we assume that the necessary preparations before the actual propagation (e.g. dumping of the configuration etc.) is handled in that method.- 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 parameterdelim.- 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.trrwhile 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,velorboxare given, we will NOT read positions, velocity and box information from the current configuration 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 asself.order_function.xyz (numpy.array, optional) – The positions to use, in case we have already read them somewhere else. We will then not attempt to read them again.
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) keeps the historical behaviour exactly, so existing runs are byte-for-byte unaffected.
- 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 PCG64 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. Itsnormaldraw matchesnumpy.random.Generator.normalunder the canonical PCG64 generator.sigma_v (numpy.ndarray, optional) – Per-particle standard deviation. When
None(or any negative entry) it is computed frombetaandmass.
- 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. If we did not in fact dump, this is because the system contains a single frame and we can use it directly. Then we return simply this file name.
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.logstdout 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-recentengine_log_maxsizebytes (the oldest output is dropped and a marker line is written at the top), reclaiming disk immediately.None(the default) keeps the historical unbounded behaviour, so existing runs are unaffected. Set it on the class or an instance, e.g.engine.engine_log_maxsize = 100 * 1024 * 1024for 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. I.e. the external engines are not intended for performing pure MD simulations.
If it’s absolutely needed, there is a
self.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 (unused here directly, kept for interface symmetry with the other explicit-convention methods).
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 integrationself.rgen).
- Returns:
Note
This function will update the input system state.
Note
This is the step()-based search, used when
self.supports_step_ kickis True. Engines that cannot drive a singlestep()(supports_step_kick = False: CP2K/LAMMPS streaming, ASE, TurtleMD) are dispatched to the engine-agnostic_kick_across_middle_propagate()instead – 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 remains available as 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='/builds/pyretis/pyretis/docs', maxwarn=0, gmx_format='g96', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', temperature=None, masses=False)¶
Bases:
GromacsEngineStepsA 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='/builds/pyretis/pyretis/docs', maxwarn=0, gmx_format='g96', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', temperature=None, masses=False)¶
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 -maxwarnoption.gmx_format (string, optional) – The format used for GROMACS configurations.
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) – Wheter GROMACS uses domain decomposition or not. This will not set the domain decomposition behavior, the user should know know this.
velocity_generation (string, optional) –
"engine"(default) or"maxwell"– seeGromacsEngineSteps.temperature (float, optional) – Temperature (K) for the
"maxwell"velocity draw.masses (list or string, optional) – Particle masses for the
"maxwell"velocity draw.
- _get_frame_energies(edr_file, begin, end, max_attempts=100)¶
Read one frame’s energies from a streamed
.edr, tolerating lag.The
.edris written on the fly by mdrun and can briefly lag the.trrframe being processed (notably the initial frame, before mdrun has flushed any energy). In that window a tightgmx energyselection either returns no rows or fails outright. Retry (bounded) until this frame’s energies are available; 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.
begin, end (float) – The time window selecting this frame.
max_attempts (integer, optional) – Maximum number of retries while the energy file catches up.
- Returns:
energy (dict of numpy.arrays) – The energies for the requested window.
- _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 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).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.
- 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.order_function (object like
OrderParameteror 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 from a MD step. This contains the state of the system and order parameter(s) and energies (if calculated).
- class pyretis.engines.gromacs.GromacsRunner(cmd, trr_file, edr_file, exe_dir)¶
Bases:
objectA 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 (string) – 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.
- __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 (string) – 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_readis on a frame boundary, a final frame whose data finished flushing only as mdrun exited is read here rather than being dropped – 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.
- _read_one_frame()¶
Read one whole frame from the TRR, or
Noneif not ready.The frame is the atomic unit of consumption:
self.bytes_readmarks 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 invariantfileh.tell() == self.bytes_readon 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, mirroringread_remaining_trr().- Returns:
data (dict or None) – The frame data, or
Noneif a complete frame is not yet available on disk.
- _reseek_after_partial_read(frame_start)¶
Restore
filehto a frame boundary after a partial read.A header read may advance
self.filehpastframe_startbefore 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_readis only advanced across a whole frame, so it always sits on a frame boundary. When mdrun terminates, a non-zero exit raises loudly incheck_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.
- 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 give 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] (string) – 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
.g96file holds one configuration and a.grofile one or more;_extract_frameselects a frame of either by its index.
- class pyretis.engines.gromacs_steps.GromacsEngineSteps(gmx, mdrun=None, input_path=None, timestep=None, subcycles=None, exe_path='/builds/pyretis/pyretis/docs', maxwarn=0, gmx_format='g96', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', temperature=None, masses=False, conf=None, template='grompp.mdp', top='topol.top')¶
Bases:
ExternalMDEngineA class for interfacing GROMACS.
This class defines the interface to GROMACS.
The configuration format handed between steps is
INTERNAL_CONFIG_FORMAT, independent of thegmx_formatsetting. 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
mdruncommand.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.mdpand 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 -maxwarnoption.gmx_format (string) – This string selects the output format for GROMACS.
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.
- INTERNAL_CONFIG_FORMAT = 'g96'¶
The configuration format the engine writes and reads back between steps.
grostores three decimals per coordinate, 1e-3 nm, which can move a cutoff- or threshold-based order parameter across a write/read round trip;g96carries 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
subcyclesis written into. It is NOT only the output stride: changingsubcyclesmoves 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='/builds/pyretis/pyretis/docs', maxwarn=0, gmx_format='g96', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', temperature=None, 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_pathin it.maxwarn (integer, optional) – Setting for the GROMACS
grompp -maxwarnoption.gmx_format (string, optional) – The format used for GROMACS configurations.
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-stepgen_velrun, which removes the centre-of-mass motion, so it requireszero_momentum = true);"maxwell"draws them in Python from a Maxwell-Boltzmann distribution via the injected random generator (one reproducible stream,g96format only, requirestemperatureandmasses).temperature (float, optional) – The temperature (K) for drawing Maxwell-Boltzmann velocities when
velocity_generation == "maxwell".masses (list or string, optional) – Particle masses for the
"maxwell"draw: a list of masses or the name of a CSV file (relative toinput_path) holding them. Only required whenvelocity_generation == "maxwell".conf (string, optional) – The default configuration file (e.g. ‘conf.gro’).
template (string, optional) – The GROMACS mdp template (default is ‘grompp.mdp’).
top (string, optional) – The GROMACS topology file (default is ‘topol.top’).
- _convert_configuration(source, name)¶
Convert a staged configuration into the work directory.
gmx editconfwrites the configuration in the format the extension ofnameselects. It runs inwork_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.
systemis 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_momentumrequests 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 invoking GROMACS, while keeping the run output identical: a “.tpr” built later holds the same inputs (its bytes differ only in a few process-dependent header bytes). The preprocessor is always run in
work_path(where the “.tpr” lives), restoringexe_dirafterwards.
- _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
gromppandmdrun.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 mdrunexecuted. 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 mdrunand 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_filein the format the name ofout_filegives. A configuration file with another destination, or a source of another format, is converted withgmx 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 + 1frames.
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.
Looks for
conf.<ext>in the input directory, preferring the engine’s own output format and falling back to the other one, so a directory holding only aconf.grostill runs under the g96 default. When neither is present the engine’s own format is returned unchanged, leaving the missing-file diagnostic tolook_for_input_files().- Returns:
out (string) – The configuration file name, relative to
input_path.
- static _gen_vel_seed(rgen)¶
Draw a reproducible GROMACS
gen_seedfor an aimless kick.The engine-mode aimless velocity draw regenerates the shooting point’s velocities with a zero-step GROMACS
gen_velrun. That draw is seeded by the mdpgen_seedkeyword; the GROMACS default of-1is 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
RandomGeneratoror None) – The velocity random generator injected intomodify_velocities(). When it isNone(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
mdrunofgmx_stepssteps.Unlike
_execute_grompp_and_mdrun()(which usesnsteps=subcycles), this overridesnstepsso the wholeintegratetrajectory is produced by one continuousmdrunwith no checkpoint-restart. The resulting.edris therefore free of the P7.13 restart-frame corruption.- 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.
- _ld_seed()¶
Draw a reproducible GROMACS
ld-seedfrom the engine rgen.The GROMACS stochastic integrators (
sd,bd) draw their thermal noise fromld-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 GROMACS sd segments are byte-reproducible. When no engine rgen is present (classic runs do not inject one) we fall back to a fixed seed so the result is at least deterministic. Deterministic integrators (md,md-vv) ignoreld-seedentirely, so this is a harmless no-op for them.- Returns:
seed (int) – A positive integer seed in
[1, 2147483646].
- _load_masses(masses)¶
Load particle masses for the Python Maxwell-Boltzmann draw.
- Parameters:
masses (list or string) – A list of particle masses, or the name of a CSV file (relative to
input_path) that holds them.- Returns:
numpy.ndarray – The masses reshaped to
(npart, 1).
- _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.
- _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
RandomGeneratoror None, optional) – The velocity random generator for drawing a reproducible GROMACSgen_seed(see_gen_vel_seed()). With the GROMACS default ofgen_seed = -1the 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 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).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.
- _recompute_energies_via_rerun(tprfile, trrfile, name)¶
Recompute per-frame potential energy with
mdrun -rerun.The relaunch propagation accumulates its
.edrthrough repeatedconvert-tpr -extend+mdrun -cpi -appendcontinuations. The kinetic energy and temperature written there are correct, but the potential energy of every segment after the first is corrupt (P7.13). Because the.trrframes (positions) ARE correct, the potential is recovered exactly by re-evaluating the trajectory in a singlemdrun -rerunagainst one consistent.tpr; this reproduces the streamingGromacsEngineand plain GROMACS byte-for-byte.-rerundoes not integrate velocities, so the resulting.edrholds only the potential terms (no kinetic energy or temperature); the caller keeps those from the appended.edr.- Parameters:
tprfile (string) – A
.tprconsistent with the trajectory topology.trrfile (string) – The completed
.trr(positions) to re-evaluate, relative toself.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. Thepotentialentry is the corrected per-frame potential energy.
- _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-seedinjected.The relaunch engine builds its
pyretis.mdponce at construction, so a varying per-segmentld-seedmust be written into a fresh mdp before eachgrompp. This copies the one-timepyretis.mdpto{name}.mdpin the run directory with the seed updated (see_ld_seed()).The keys in
SUBCYCLE_MDP_KEYSare also rewritten from the currentsubcycles. Multiresolution wire fencing changessubcycleson a live engine, andext_timefollows that change; the segment length and the.trr/.edrstrides must follow it too, so that each extension writes one frame and one energy record.- Parameters:
name (string) – A name used for the per-segment mdp file.
extra (dict, optional) – Additional
keyword: valuemdp settings, applied last so they override both theld-seedand the subcycle keys (e.g. annstepsoverride for the single continuousintegraterun).
- Returns:
mdp_file (string) – The path to the per-segment mdp file with the seed injected.
- _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,
nstvoutis 0.write_force (boolean) – Whether GROMACS should write forces. If not,
nstfoutis 0.
- Returns:
out (dict) – Each key of
SUBCYCLE_MDP_KEYSwith its value.
- _trajectory_filename(name)¶
GROMACS writes frames to a
.trrregardless ofself.ext.self.extis the configuration format (gro/g96); the trajectory the propagation appends frames to is the.trrnamed after the propagationname(seeout_files['trr']).
- 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.growhile the engine works in.g96– it is converted throughself.top, as_extract_frame()converts a single staged frame, so the file GROMACS reads matches its name. Every other configuration is handled byExternalMDEngine.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 wall time one trajectory extension covers, in ps.
DERIVED, not stored. Computing it once at construction is correct only while
subcyclesis constant, and multiresolution wire fencing changes it on a live engine throughmultires_wf._temporary_subcyclesto shoot a sub-segment at a finer stride. A stored value would then still describe the COARSE stride, so an extension taken during a fine segment would run for the coarse segment’s time – five times too long at the shippedsubcycle_small = subcycles // 5.Note that
subcyclesdrives more than this. It is written into seven MDP keys –nsteps,nstxout,nstvout,nstfout,nstlog,nstcalcenergyandnstenergy– 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 fo numpy.arrays) – The energies read from the produced GROMACS xvg file.
- 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. The initial state is stored and the system is reset to the initial state when the integration is done.order_function (object like
OrderParameteror 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).
- 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 GROMACSgen_velremoves 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 GROMACSgen_veldraw via a reproduciblegen_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_momentumis False in"engine"mode.
- 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. Currently we only allow for two types of output, but this can be customized in the future.
- 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 ownwmdrunlaunch command, so buildself.mdrun/self.mdrun_cfrom it. Safe for the classic flow too (it providesmdrunat construction and does not passwmdrun, so the existing command is left untouched).- Parameters:
md_items (dict) – Per-worker run items.
exe_dir(set by the base) and the optionalwmdrunbase mdrun command.
- 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.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:
MDEngineThe 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 integrate_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) + drandv(r + dt) = c0 * v(t) + (c1-c2)*dt*a(t) + c2*dt*a(t+dt) + dv. The dict contains:c0 : float Corresponds to
c0in the equation above.a1 : float Corresponds to
c1*dtin the equation above.a2 : numpy.array Corresponds to
c2*dt*dt/massin 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/massin the equation above. Here we also divide by the masses, resulting in a numpy.array.b2 : numpy.array Corresponds to
c2*dt/massin 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
dranddvfrom the bivariate distribution.
Note
Currently, we are using a multi-normal distribution from numpy. Consider replacing this one as it seems somewhat slow.
- __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 insystem.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 insystem.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 insystem.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 insystem.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:
EngineBaseBase 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 sectionpyretis.engines.factory.create_inf_engine()builds it from (engine0,engine1, …).setup_streaming()reads the engine’ssubcyclesthere.subcycles (integer) – The number of integration steps between two stored frames of a path: a streamed path, and a path
propagate()andkick_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
systemusingrgen.Replicates
RandomGenerator.draw_maxwellian_velocities()exactly (samesigma_vfrombeta/imassand the samenormaldraw) but accepts the rawnumpy.random.Generatorthe infinite-swap scheduler injects as the velocity-generation random generator (pens['rgen-eng']), which does not carry the pyretisdraw_maxwellian_velocitiesmethod.
- _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.rgenusing the pyretis generator surface (notablymultivariate_normal(..., cho=...)). The infinite-swap scheduler, however, injects a rawnumpy.random.Generatorontoengine.rgenper move. To keep the dynamics draws working – and deterministic – wrap that raw generator inPCG64Generator, which exposes the pyretis surface while drawing from the very same (deterministic) underlying stream. Engines withoutself.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 from either System type.
- _integrate_frame(system, reverse)¶
Integrate an in-memory system from one stored frame to the next.
A frame of a path is
subcyclesintegration 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
systemis a file-backed snapshot.The in-memory loop always hands the engine a
Systemwith particles attached; the coordinator hands it a snapshot whoseparticlesisNoneand whoseconfigpoints at a trajectory file. Streaming additionally requires the engine to have a template (set bysetup_streaming()).
- _materialize_system(system)¶
Read the frame
system.configpoints at into a System.Returns the working in-memory
Systemplus the raw 3-columnpos/vel/boxarrays 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 agenvel.xyzfile 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 snapshotSystemobjects pointing at it.self.stepsis accumulated so the scheduler’s subcycle accounting matches the external engines.
- 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 – byte-identical to the historical behaviour. 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 privateexe_dirdo we remove the working files there so a re-used engine starts from a clean directory.
- 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 (kept for compatibility with the external integrators). In the streaming (file-backed) loop the phase point is a snapshot whose
configpoints 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
OrderParameteror 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 (kept for interface symmetry with the other explicit-convention methods).
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: boolean, determines if energy is re-scaled.
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 integrationself.rgen).
- Returns:
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 integrationself.rgenthat stochastic integrators (Langevin, random walk) own, so a shooting-move velocity kick never perturbs the dynamics random 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 thepyretis.setup.createsystem.create_system()andpyretis.setup.createforcefield.create_force_field()to build a fully-attached in-memorySystemtemplate (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
subcyclesof the section it is built from, itssectionattribute:[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 the classic flow uses to build the system and force field, and the engine section the engine is built from.
- 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: eachconfigis a(filename, frame_index)pair andparticlesis None.- 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 (seepyretis.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: eachconfigis a(filename, frame_index)pair andparticlesis None.- Returns:
list of lists of floats – One order-parameter list per input system, in input order.
- class pyretis.engines.internal.RandomWalk(timestep, rgen=None, seed=0)¶
Bases:
MDEngineA 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 insystem.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:
MDEngineThe 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 insystem.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:
MDEngineThe Verlet MD integrator.
This class defines the Verlet MD integrator.
- Variables:
half_idt (float) – Half of the inverse time step: 0.5 / timestep.
timestepsq (float) – Squared time step: timestep**2.
previous_pos (numpy.array) – Stores the previous positions of the particles.
- __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.
- Parameters:
system (object like
System) – The system to integrate/act on. Assumed to have a particle list insystem.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 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 oforder.inand thefix haltcommands that stop the run at the outer interfaces;the
runof the number of steps,path.maxlen * subcycles;the
undumpof 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,
which a stochastic thermostat of lammps.in can use.
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', temperature=None, atom_style=None, sleep=0.1)¶
Bases:
LAMMPSEngineStepsStreaming LAMMPS engine.
This engine shares its configuration and input convention with the relaunch engine
LAMMPSEngineSteps(same[engine]settings, samelammps.in/system.data/order.in/extra_filesinput directory) so a user can switchclass = lammps<->class = lammps_stepsand have it just work – as for the two GROMACS engines. The two engines build the identical LAMMPS input (via the inheritedLAMMPSEngineSteps._prepare_lammps_run()); they differ only 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.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
realunits 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
Periodicity in LAMMPS has to take into account hi and lo box bounds: As of now, we subtract the lower bounds from the positions and the box vectors to create a regular box with 0 lower bounds. This is hard coded in _propagate_from() when calculating, and also in _read_configuration().
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', temperature=None, 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 (switchclass = lammps<->class = lammps_stepsand it just works).sleepis the only streaming-specific extra.- Parameters:
lmp (string) – The LAMMPS executable.
input_path (string) – Directory with the LAMMPS input files (
lammps.in,system.data, optionallyorder.inandextra_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;
"pyretis"(the default) reflects that.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 attemperatureon the injected random generator, and resets the linear momentum as[tis] zero_momentumselects (modify_velocities()), so the two modes draw the same velocities."maxwell"requirestemperaturewhen the engine is set up.temperature (float, optional) – Temperature (K) for Maxwell-Boltzmann velocity generation; every velocity draw of this engine requires it.
atom_style (string, optional) – The LAMMPS atom style of the
Atomsrows 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, theAtoms # styleannotation of the data file and theatom_stylecommand oflammps.in, the ones that are given must name styles of one row layout (bond,angleandmolecularshare one, and a style with an accelerator suffix, asfull/kk, has the layout of the style), and aValueErroris raised otherwise. The rows are read in the style of the first of the three that is given, and inatomicwhen none is. Anatom_stylecommand oflammps.inset by a LAMMPS variable is not a source, and without another source aValueErroris raised (resolve_lammps_atom_style()). The data file is read byread_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.inhas amasscommand: the engine takes the masses of the atoms from theMassessection ofsystem.data(refuse_lammps_mass_command()). Also asget_atom_masses()raises it forsystem.data.ValueError – As
LAMMPSEngineStepsraises it, and asget_atom_masses()raises it forsystem.data.
- _extract_frame(traj_file: str, idx: int, out_file: str) None¶
Extract a frame from a trajectory to a new file.
idxis a LAMMPS time step (the shared config-index convention); the selected frame is rewritten as a canonical, timestep-zero dump with explicit image flags.
- _frame_config_index(frame: int) int¶
LAMMPS indexes configurations by MD time step.
The on-the-fly dump stores one frame every
subcyclessteps and snapshots are indexed by time step (frame * subcycles), the shared convention with the relaunch engine. Frame extraction (_extract_frame) selects the frame by that timestep.
- _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.dataofinput_pathbefore it is staged inexe_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 inexe_dir, and, whenexe_dirhas none and the name is that of thesystem.dataof the engine input, thatsystem.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_fileis none of these files; the message namesdata_file.
- _read_configuration(filename: str) tuple[ndarray, ndarray, ndarray | None, list[str] | None]¶
Read a configuration (a single frame trajectory).
- _recompute_partial_orders(partial_traj, reverse)¶
Order parameters per frame of a partial
.lammpstrjdump.recalculate_orderdoes not handle the LAMMPS trajectory format, so the dump frames are read directly. 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.
- _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
systemwhere 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_configurationreturns the box as its THIRD element (pos, vel, box, names), unlike the classicExternalMDEngine.calculate_orderwhich expects the box first. We therefore keep the box-third unpacking here.A configuration held in a LAMMPS data file (
_locate_data_file()) has the positions of the file, from the lower bounds of its box, and the box lengths of x, y and z of its header (LAMMPSEngineSteps._read_lammps_data_frame()).- Raises:
FileNotFoundError – If the configuration names a data file that
_locate_data_file()does not find.NotImplementedError, ValueError – As
read_lammps_data_file()raises them for the data file of the configuration, for a triclinic box among others. AValueErroralso if the engine has no order parameter.
- 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>.datainexe_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:
FileNotFoundError – If
confignames a data file that_locate_data_file()does not find.
- dump_phasepoint(phasepoint, deffnm='conf')¶
Dump the current configuration from a system object to a file.
- 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
unitscommand 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 inspectslammps.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
unitscommand 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 engine
temperature, in bothvelocity_generationmodes. A configuration held in a LAMMPS data file, as thesystem.dataa run starts from, is drawn byLAMMPSEngineSteps._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 writesgenvel.lammpstrjinexe_dironce 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 (dimensionbelow 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 (asigma_vthat is not negative) and a positiverescaleare refused before the draw.rgen (object like
RandomGenerator) – The velocity random generator the Maxwell-Boltzmann draw is made from, in bothvelocity_generationmodes.
- 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_settingsselect a soft perturbation (refuse_soft_perturbation()) or an energy re-scale (refuse_energy_rescale()), or iflammps.initself has nounits realcommand (refuse_lammps_draw_units()); aunitscommand in a file thatlammps.inincludes is not read. Also, for a configuration held in a data file, asread_lammps_data_file()raises it for the file: for a triclinic box, orAtomsrows of an atom style that is not supported.ValueError – If the engine has no
temperature. Also, for a configuration held in a data file, for each refusal of the file that the Raises section ofread_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.
- needs_order = True¶
- propagate(path, ens_set, system, reverse=False)¶
Propagate by streaming a single persistent LAMMPS run.
The relaunch base (
LAMMPSEngineSteps) overridespropagatewith a driver that makes one LAMMPS run of up topath.maxlen * subcyclessteps and reads its trajectory when the run has ended. The streaming engine uses the generic external-engine driver, which dispatches topyretis.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:
- Returns:
success (boolean) – True if the propagation produced an acceptable path.
status (string) – A textual status of the propagation.
- 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 singlestep()is not supported. The method exists only so the class can be instantiated (the classic external base declares it as an abstract method).
- 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 theMassesrow 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. Supportsfull,molecular,bond,angle,chargeandatomic, each also with an accelerator suffix, asfull/kk.input_style (str, optional) – The style of the
atom_stylecommand oflammps.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, forAtomsrows 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.
- 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).
- 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 izof 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
typecolumn and Maxwell-generated dumps without one are accepted; columns are located from the atom header.
- 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 izof 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', temperature=None, atom_style=None)¶
Bases:
ExternalMDEngineA 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.
- __init__(lmp, input_path, subcycles, extra_files=None, order_mode='lammps', timestep=None, velocity_generation='engine', temperature=None, 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"keeps the traditionalorder.in/v_op_1mode."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).velocity_generation (string, optional) – How shooting-move velocities are generated.
"engine"(default) delegates to LAMMPS (velocity create, with themomkeyword set from[tis] zero_momentum);"maxwell"draws them in Python from a Maxwell-Boltzmann distribution via the injected random generator (one reproducible stream; requirestemperature). The"maxwell"draw uses the constants of LAMMPSrealunits and refuses alammps.inwithoutunits real(refuse_lammps_draw_units()). It takes the masses from theMassessection of a data file (_velocity_draw_data_file()): for a frame of a dump, the data file that LAMMPSwrite_datawrites for the frame, whoseMassessection holds the masses of themasscommands oflammps.in; for a configuration held in a data file, that file, and the draw of such a configuration refuses alammps.inwith amasscommand (refuse_lammps_mass_command()).temperature (float, optional) – The temperature (K) for drawing Maxwell-Boltzmann velocities when
velocity_generation == "maxwell".atom_style (string, optional) – The LAMMPS atom style of the
Atomsrows 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, theAtoms # styleannotation of the data file, which a data file written by LAMMPS carries, and theatom_stylecommand oflammps.in, the ones that are given must name styles of one row layout (bond,angleandmolecularshare one, and a style with an accelerator suffix, asfull/kk, has the layout of the style), and the draw raises aValueErrorotherwise. The rows are read in the style of the first of the three that is given, and inatomicwhen none is. Anatom_stylecommand oflammps.inset by a LAMMPS variable is not a source, and without another source the draw raises aValueError(resolve_lammps_atom_style()).
- _calculate_pyretis_order(system, traj, reverse=False)¶
Calculate PyRETIS order parameters from a LAMMPS trajectory.
- _draw_velocities_maxwell(system, vel_settings, rgen)¶
Draw shooting velocities in Python (Maxwell-Boltzmann).
Mirrors the engine path’s contract – sets
system.configto a dump frame the next propagation reads viaread_dumpand updatessystem.ekin– but draws the velocities from the injected random generator instead of LAMMPS’svelocity 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 writesgenvel.lammpstrjinexe_dironce the file is read.- Parameters:
system (object like
System) – The state whose velocities we redraw.vel_settings (dict) –
zero_momentumrequests 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).
- _extract_frame(traj_file, idx, out_file)¶
Extract one LAMMPS trajectory frame as a data file.
- _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(), factored out so the streaming engine (pyretis.engines.lammps.LAMMPSEngine) builds the identical LAMMPS input – the relaunch and streaming engines must differ only in how the trajectory is consumed, not in what LAMMPS is asked to do.A configuration held in a data file is copied to the file of the name of the
system.dataof the input inexe_dir, whichlammps.inreads. A bare file name names the file of that name inexe_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 forExternalMDEngine.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.
- _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_stylecommand oflammps.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.
- _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
systemis written to a data file inexe_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 inexe_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; itsvpotis thepeLAMMPS compared withrescale.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 izmatch what the classic engine’sread_dumpoverlay reads back.
- add_input_files(dirname)¶
Add required input files to a given directory.
- Parameters:
dirname (string) – The path to the directory where we want to add the files.
- calculate_order(system, xyz=None, vel=None, box=None)¶
Return the last seen order parameter.
- Parameters:
system (object like
System) – The state whose last seen 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¶
- dump_phasepoint(phasepoint, deffnm='conf')¶
Dump a phase point to a new file.
Note
We do not reverse the velocities here.
- classmethod get_default_units(settings=None)¶
Return the default unit system for the LAMMPS engine.
This is read from the
unitscommand in the LAMMPS input template. If the template can not be inspected, or if it does not defineunits, 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
unitscommand is found in that file.
- 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
OrderParameteror 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 positiverescaleis written into the LAMMPS input, which re-scales the created velocities so that the energype + keLAMMPS evaluates equals it (per atom underthermo_modify norm yes, the LAMMPS default forljunits). For apeabove that energy, or akethat is zero, LAMMPS keeps the created velocities and the warning ofpyretis.core.particlefunctions.rescale_velocities()is logged (_warn_skipped_rescale()). The"maxwell"draw leaves the energy as drawn, so it refuses a positiverescale(refuse_energy_rescale()).zero_momentumrequests a zero linear momentum after the draw (a missing key means False): in"engine"mode it sets themomkeyword of the LAMMPSvelocity createcommand toyesorno, and the keyword is always written because the LAMMPS default ismom yes.rgen (object like
RandomGenerator) – The velocity random generator, injected explicitly per call. In the defaultvelocity_generation = "engine"mode it draws the LAMMPSvelocity createseed; 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,rescaleis positive,lammps.initself has nounits realcommand (refuse_lammps_draw_units(); aunitscommand in a file thatlammps.inincludes is not read), or the configuration is held in a data file, a.datafile, andlammps.inhas amasscommand (refuse_lammps_mass_command()). Also, in"maxwell"mode, asread_lammps_data_file()raises it for the data file of the draw: for a triclinic box, orAtomsrows of an atom style that is not supported. The data file that LAMMPSwrite_datawrites for a frame of a dump in a triclinic box has thexy xz yzline of the box, so every draw in a triclinic box raises it.ValueError – If
sigma_vselects a soft velocity perturbation. Also, in"maxwell"mode, for each refusal of the data file of the draw that the Raises section ofread_lammps_data_file()lists. The data file is written inexe_dirbefore it is read (_velocity_draw_data_file()).
- needs_order = False¶
- 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.
- 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.
- 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.
- 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. Whenorder_modeis"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.
- 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_velentry, when present, holds theseedof the draw, therescaleenergy andzero_momentum, which selects themomkeyword of thevelocity createcommand (a missing key means False). A positiverescalere-scales the created velocities so that the energype + keLAMMPS evaluates equals it (RESCALE_ENERGY), whenpeis not above it andkeis positive; otherwise LAMMPS keeps the created velocities and printsRESCALE_SKIPPED_PEorRESCALE_SKIPPED_KE(RESCALE_CONDITION).- Returns:
lines (list of strings) – The LAMMPS commands that create the velocities; empty when
settingsrequests 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_datastops 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
MassesorAtomssection, 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
roworatom type.
- Returns:
out (string) –
numberandnoun, with ansappended tonounfor anumberother than 1, as1 rowand3 rows.
- 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 atomand the like (LAMMPS_DATA_OTHER_COUNTSandLAMMPS_DATA_EXTRA_PER_ATOM), with the numberNin digits, which LAMMPSread_datareads by their keywords after the number, as it readsN 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
tokensis 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.
Split out from
read_lammps_dump()so the streaming engine (pyretis.engines.lammps.LAMMPSRunner) can feed it only the already-completed frames of a trajectory that LAMMPS is still writing. The parser is strict: a frame truncated mid-way raises, so callers reading a growing file must hand it complete frames only.- 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_data_header_keyword(tokens)¶
Return the first keyword of a header line that a line has.
The words are compared in lower case, so
XLOis the keywordxlo, which LAMMPSread_datareads 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
tokensthat isatomsor a keyword of the box (LAMMPS_DATA_BOX_WORDS), or of the wordsatom types; None whentokenshas 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
textwrites.- Raises:
ValueError – If
textdoes not write an integer, as1.0or-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
textwrites.- Raises:
ValueError – If
textdoes not write a number (LAMMPS_DATA_NUMBER).
- pyretis.engines.lammps_steps._lammps_data_reads(section, count, first, data_file)¶
Return how LAMMPS
read_datareads a section, for a message.- Parameters:
section (string) – The keyword of the section, a key of
LAMMPS_DATA_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
MassesorAtomssection of a data file.LAMMPS
read_dataskips the line below the keyword line of a section, whatever it holds, and reads thecountlines 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
linesof 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_datareads a row of theMassesandAtomssections up to its first word that starts with#, so a#inside a word, as in1.0#H, is part of that word.- Parameters:
line (string) – The line of the row.
- Returns:
out (list of strings) – The words of
linebefore its first word that starts with#.
- pyretis.engines.lammps_steps._lammps_row_layout(style)¶
Return the row layout of an atom style, or its base style.
- 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 complete frames from a LAMMPS dump iterator.
- pyretis.engines.lammps_steps._read_lammps_data_atoms(style, rows, data_file)¶
Read the rows of the
Atomssection of a LAMMPS data file.- Parameters:
style (string) – The atom style of the rows (
resolve_lammps_atom_style()).rows (list of tuples) – The line and the words of each row of the section (
_lammps_data_section_rows()).data_file (string) – The data file, as the error messages name it.
- Returns:
out (dict) – The atom type, the positions and the image flags of each atom, by atom ID.
- Raises:
ValueError – As
read_lammps_data_file()raises it for anAtomsrow.NotImplementedError – If the atom style of the rows is not supported (
lammps_atom_columns()).
- 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_datastops at. Ifboxis not None and gives the bounds ofaxis, 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_datareads it, by the keywords at fixed positions of the line, and the words after them are ignored:N atomsandN atom types, with the numberNin digits (LAMMPS_DATA_COUNTS);lo hi xlo xhi,lo hi ylo yhiandlo hi zlo zhi, the bounds of an axis (LAMMPS_DATA_BOUNDS);three numbers and
xy xz yz,avec,bvec,cvecorabc origin, a line of a triclinic box (LAMMPS_DATA_TRICLINIC).
The other header lines of LAMMPS, as
N bondswith 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
atomsandatom 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
boxis 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. Ifboxis 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
Massessection 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_typesor a mass that is not positive, which LAMMPSread_datastops at.
- pyretis.engines.lammps_steps._read_lammps_data_sections(lines, index, counts, data_file, styles)¶
Read the
MassesandAtomssections of a LAMMPS data file.The lines from
index, the first line below the header, are read as LAMMPSread_datareads them: the first line that is neither blank nor a comment is a keyword line (_check_lammps_data_keyword_line()), the rows of aMassesorAtomssection 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 nextMassesorAtomskeyword 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.- Parameters:
lines (list of strings) – The lines of the data file.
index (integer) – The index in
linesof the first line below the header.counts (dict) – The numbers of the header, by the keys
atomsandatom types.data_file (string) – The data file, as the error messages name it.
styles (tuple of strings) – The
[engine] atom_styleand the style of theatom_stylecommand oflammps.in, each None when not given (resolve_lammps_atom_style()).
- Returns:
type_masses (list of tuples) – The atom type and the mass of each row of the last
Massessection, 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 anAtomssection.
- Raises:
ValueError, NotImplementedError – As
read_lammps_data_file()raises them for the lines below the header.
- 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
Atomsrow 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 ofLAMMPS_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
countis neither of the two column counts ofstyle.
- 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.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
Atomsrows ofstyle: those of the row layout of its base style (LAMMPS_ATOM_STYLE_LAYOUT) inLAMMPS_DATA_ATOM_COLS.- Raises:
NotImplementedError – If the base style of
styleis not a key ofLAMMPS_ATOM_STYLE_LAYOUT; the message namesstyle.
- pyretis.engines.lammps_steps.lammps_atom_masses(atom_types, type_masses, data_file)¶
Return the mass of each atom from the
Massesrows of a data file.Each row of the
Massessection 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
Atomsrow.type_masses (sequence of pairs of numbers) – The atom type and the mass of each row of the
Massessection.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
Massessection 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
/, asfull/kkorfull/kk/deviceof the KOKKOS package, andread_datareads theAtomsrows 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
stylebefore its first/.
- pyretis.engines.lammps_steps.lammps_input_atom_style(settings)¶
Return the style that the
atom_stylecommand 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_stylecommand, in lower case, or as written when it holds a$, the reference to a LAMMPS variable; None when the input has noatom_stylecommand with an argument.
- 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
Atomsrows 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()). The file is read in the layout that LAMMPSread_datareads: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 linelo hi xlo xhifor x,lo hi ylo yhifor y andlo hi zlo zhifor z. An axis whose line the header leaves out has the bounds-0.5 0.5, the default of LAMMPSread_data(LAMMPS_DATA_DEFAULT_BOUNDS), as the z axis of a 2D system often has. The other lines of the header, asN bonds, are not read.A section is a keyword line and its rows. The rows of the
MassesandAtomssections 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, asVelocities, the line below it and the lines below them are skipped up to the nextMassesorAtomskeyword 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 theAtomskeyword line is the# styleannotation of the atom style.
The
Atomsrows are read in the atom style thatresolve_lammps_atom_style()gives for theAtomskeyword line,atom_styleandinput_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 LAMMPSread_datarequires, 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 theMassessection 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_stylecommand oflammps.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()andpyretis.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 whenread_boxis False.
- Raises:
NotImplementedError – If
read_boxis True and the header gives a triclinic box, with anxy xz yzline or anavec,bvec,cvecorabc originline of a general triclinic box: the box is read from theloandhibounds only, as an orthogonal box. Also if the atom style of theAtomsrows is not supported (lammps_atom_columns()).ValueError – If the header of the
Atomssection has an empty#annotation, or the sources of the atom style disagree, or the style oflammps.inis 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 LAMMPSread_datastops 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()), as0 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; ifread_boxis True, two lines of the header for the bounds of one axis, of which LAMMPS takes the last; * aMassesorAtomssection 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 noAtomssection with rows, or with two; * anAtomsrow 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; * aMassesrow 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; aMassessection that gives an atom type twice, or not the atom type of an atom (lammps_atom_masses()).
- 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 anidcolumn, 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_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.
- 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).
- 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_CONDITIONholds the two skip lines inside quotes; the output of itsprintcommand 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_PEorRESCALE_SKIPPED_KEwhen a line of the log is that line, and None when no line is either.
- pyretis.engines.lammps_steps.refuse_lammps_draw_units(settings, template, engine)¶
Refuse a velocity draw in LAMMPS units other than
real.PyRETIS draws LAMMPS velocities with the constants of LAMMPS
realunits: k_B in kcal/(mol K), and velocities in Å/fs. The units are those of theunitscommand oflammps.initself; PyRETIS does not read a file thatlammps.inincludes. LAMMPS runs an input without aunitscommand inljunits, unless a file it includes sets the units.- Parameters:
settings (dict) – The commands of
lammps.in, as keyword -> arguments, fromread_lammps_input().template (string) – The path of
lammps.in, as the message names it.engine (string) – The engine that draws, as the message names it at its start.
- Raises:
NotImplementedError – If
settingshas aunitscommand other thanunits real, or none.
- pyretis.engines.lammps_steps.refuse_lammps_mass_command(template, engine)¶
Refuse a
masscommand oflammps.in.A
masscommand, which LAMMPS runs afterread_data, sets the mass of atom types in LAMMPS in place of theMassesrows of the data file. PyRETIS takes the masses from theMassessection (read_lammps_data_file()) and does not readmasscommands. The commands are those oflammps.initself; PyRETIS does not read a file thatlammps.inincludes.- 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
templatehas amasscommand; the message names each.
- 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
Atomsblock.LAMMPS reads the rows of a data file with the
atom_styleof its input, and withatomicwhen the input sets none. The style is the first given of the engine settingconfigured, the# styleannotation of theAtomsheader and theatom_stylecommand oflammps.in(input_style), andatomicwhen 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,angleandmolecularshare one. The layout of a style is that of its base style, the style without an accelerator suffix (lammps_base_atom_style()), sofull/kkagrees withfull, and a style without a row layout agrees with the styles of its base style only, asspherewithsphere/kk.A style of
lammps.inthat 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
Atomsheader line of the data file.configured (string, optional) – The
[engine] atom_style.input_style (string, optional) – The style of the
atom_stylecommand oflammps.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 oflammps.inholds a$and neitherconfigurednor 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.
- 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 fromxu/yu/zu. Only the selected step is read, 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:
EngineBaseA class for interfacing with OpenMM.
This class defines the interface to OpenMM.
- Variables:
simulation (OpenMM.simulation) – OpenMM simulation object.
subcyles (int) – Number of OpenMM steps per PyRETIS step.
- __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 defined by the integrator; this optional
[engine]value is only used as a cross-check (in ps) and must equal the integrator step size (otherwise an error is raised).
- _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.
- _materialize_if_filebacked(system)¶
Populate
pos/velfromsystem.configwhen needed.A coordinator
load_dirphasepoint arrives file-backed: its positions live in an XYZ frame referenced bysystem.configand the in-memorysystem.posisNone. OpenMM integrates in memory (integration_steppushessystem.posinto the OpenMM context), so read the referenced frame into the system before propagating – mirroring the streaming internal engine’spyretis.engines.internal.MDEngine._materialize_system(). A system that already carries positions (system.posset) is left untouched.- Parameters:
system (object like
System) – The phase point to materialise in place.
- _removes_center_of_mass_motion()¶
Return True when the OpenMM System removes centre-of-mass motion.
A
CMMotionRemoverforce sets the centre-of-mass velocity to zero while the integrator propagates, so the kinetic energy of the centre-of-mass motion of a shot does not stay in the run.- Returns:
bool – True if the System of the simulation holds a
CMMotionRemover; False otherwise, also for a simulation that holds no OpenMM System.
- _set_context_state(system)¶
Synchronize the OpenMM context with a PyRETIS system.
- _template_system()¶
Return the engine’s reference pyretis
System(cached).Built from the OpenMM
Simulation(particles, masses, box and the thermodynamictemperature/beta), it supplies the engine-level state absent from a file-backed XYZ frame. Cached, as it is constant for the simulation’s lifetime.
- 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()¶
Clean up after using the engine.
Currently, this is only included for compatibility with external integrators.
- default_units = 'openmm'¶
- dump_phasepoint(phasepoint, deffnm=None)¶
For compatibility with external integrators.
- engine_type = 'openmm'¶
- 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.
- 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 insystem.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.
rescale_energy: boolean, determines if energy is re-scaled.
Every kick is an aimless draw (
make_kick_velocity_settings()).rgen (object like
RandomGenerator) – This is the random generator that will be used.
- Returns:
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 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()).zero_momentum : boolean, optional If True, we reset the linear momentum to zero after generating. A missing key means False. A re-scale on a System with a
CMMotionRemoverresets it in either case (see rescale).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()), and the momentum of a System with aCMMotionRemoveris reset before it whatever zero_momentum says (_removes_center_of_mass_motion()), 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.
- 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.
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:
ExternalMDEngineA 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. We expect to find the keys
'conf','input''topology'.ext_time (float) – The time to extend simulations by. It is equal to
timestep * subcycles.
- __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 GROMACS MD simulation.
subcycles (integer) – The number of steps each GROMACS 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.ensemble (dict) – It contains:
system: object like
SystemThe 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.order_function: object like
OrderParameterThe object used for calculating the order parameter.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:
box (numpy.array) – The box dimensions.
xyz (numpy.array) – The positions.
vel (numpy.array) – The velocities.
- _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_configurationreturns(xyz, vel, box, names)with the box as the THIRD element, so this override unpacks the configuration accordingly (the classic external base assumes a different ordering).- 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 preserves byte-identity with the inf-flavour engines, which stored
(pos_file, 0)as the configuration index rather than the classic(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 statesystempoints at, and PyRETIS uses them as drawn. The draws withRandomVelocitiesMethod = Gromacs, for which the SCM manual states the removal of the net linear momentum, and withExact, the default (AMS2023.1 or later), have zero net linear momentum; forBoltzmannthis 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()ormake_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
GromacsandExacthave 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 themodify_velocitiessignature; 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_momentumis False, ifrescaleis positive, or ifsigma_vselects soft velocity perturbations.
- needs_order = False¶
- 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, andens(dict), the ensemble information carryingens_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.
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('/builds/pyretis/pyretis/docs'))¶
Bases:
ExternalMDEngineAn ASE engine class.
- __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('/builds/pyretis/pyretis/docs'))¶
Initialize the ase engine.
- langevin_fixcm: removes center of mass motion. Should not be used for
low dimensional systems like double well.
- _recompute_partial_orders(partial_traj, reverse)¶
Order parameters per frame of a partial ASE
.trajdump.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).
- calculate_order(system, xyz=None, vel=None, box=None)¶
Calculate the order parameter.
The engine’s
_read_configurationreturns the box as the third element (positions, velocities, box, names), so this override reads them in that order instead of the box-first ordering assumed by the classic external base.
- default_units = 'ase'¶
- dump_phasepoint(phasepoint, deffnm='conf')¶
Dump a phase point to a file using the inf convention.
- engine_type = 'internal'¶
- modify_velocities(system: System, vel_settings: dict, rgen) tuple[float, float]¶
Modify the velocities.
The Langevin
fixcmoption (set at construction) and thezero_momentumsetting here are independent mechanisms acting at different times:fixcmremoves the centre-of-mass motion every integrator step, whereaszero_momentumzeroes 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 (asigma_vthat is not negative) and a positiverescaleare refused before the draw.rgen (object like
RandomGenerator) – The velocity random generator of themodify_velocitiessignature; ASE draws from its own global 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:
NotImplementedError – If
vel_settingsselect a soft perturbation (refuse_soft_perturbation()) or an energy re-scale (refuse_energy_rescale()).
- needs_order = False¶
- step(system, name)¶
Perform a single MD step with the ASE engine.
This engine is never kicked;
stepexists only so the class can be instantiated as a concrete subclass of the abstractExternalMDEnginebase.
- supports_step_kick = False¶
- 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 (identical to the previousatoms.cell.diagonal()) 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.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,lowandpbc_dist_coordinatethe 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.
The public function keeps its historical name for compatibility. Both creation routes resolve the same canonical engine classes:
from pyretis.setup.common import create_engine– canonical single-engine creation, resolved through the untouchedpyretis.engines.ENGINE_MAP.from pyretis.engines.factory import create_inf_engine– keyed scheduler creation, resolved throughbuild_engine_map().ENGINE_MAPis 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 ineng_namesfor that worker. Returns{name: index}mapping each requested engine name to the index insideengine_occ[name]thatpinholds 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 ENGINE_MAP extended with the scheduler-keyed engines.
Importable engines are added to the map; missing optional dependencies (e.g.
scm.plamsfor 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_SETTINGSfrom 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_settingsitself for an engine that is not an internal integrator, and a copy without theSTREAMING_SETTINGSfor 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"], instantiatemin(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 usingengines[name][i], or-1when free.
- 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 expliciteng_keyso multiple named engines (engine,engine2, …) can coexist in one config, and resolves engine classes throughbuild_engine_map()without mutating the canonical engine map. The function name is retained for compatibility with existing callers and configuration tooling.- 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) holdseng_keyin itssectionattribute, the section it streams thesubcyclesof.
- 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 helper instantiates an external engine from the
settingsdict 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 afactory(engine map) argument and is geared toward the canonical engine creation flow.- 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 thesubcyclesof the engine section it is built from (pyretis.engines.internal.MDEngine.setup_streaming()); every other engine of the map takessubcyclesthrough its constructor.- Parameters:
klass (object) – The
classof an engine section, looked up inbuild_engine_map()in lower case, ascreate_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.turtlemd module¶
A TurtleMD integrator interface.
This module defines a class for using the TurtleMD.
- 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:
ExternalMDEngineInterface the TurtleMD engine.
- To do:
Add support for multiple potentials?
Velocity generation adds 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.
boltzmann (float) – The value of Boltzmanns constant (kB).
integrator (dict) – The name of the integrator to use for TurtleMD.
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.
- _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_DIRto a run directory; each propagating engine then keeps a small per-process fileforce_evals_<pid>.txtthere 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.
- _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.
- property beta¶
The thermodynamic temperature in units of the engine.
- calculate_order(system, xyz=None, vel=None, box=None)¶
Calculate the order parameter of the current system.
- 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) – the general-purpose “reduced” unit system (pyretis.core.units.UNIT_SYSTEMS, length scale 1) matches this, unlike the internal engines’ “lj” system (Lennard-Jones-calibrated, a specific length/energy scale that would misrepresent a generic TurtleMD potential such as a 1D double well).- Parameters:
settings (dict, optional) – Full simulation settings or engine settings. Ignored, like the other engines’
get_default_unitsoverrides.- Returns:
out (string) – The default unit system for TurtleMD,
"reduced".
- 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 (asigma_vthat is not negative) and a positiverescaleare 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_settingsselect a soft perturbation (refuse_soft_perturbation()) or an energy re-scale (refuse_energy_rescale()).
- needs_order = False¶
- step(system, name)¶
Perform a single step with the engine.
This engine is an internal integrator that is never kicked, so a single
step()is not supported. The method exists only so the class can be instantiated (the classic external base declares it as an abstract method).supports_step_kick = Falserouteskick_across_middleto thepropagate()-based_kick_across_middle_propagatefallback instead, so this is never actually called.
- supports_step_kick = False¶