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)[source]¶ 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.resolve_engine_class(settings)[source]¶ Resolve an engine class from the given settings.
-
pyretis.engines.get_default_units(settings)[source]¶ Return the default unit system for the selected engine.
List of submodules¶
- pyretis.engines.cp2k
- pyretis.engines.cp2k_steps
- pyretis.engines.engine
- pyretis.engines.external
- pyretis.engines.gromacs
- pyretis.engines.gromacs_steps
- pyretis.engines.internal
- pyretis.engines.lammps
- pyretis.engines.lammps_steps
- pyretis.engines.openmm
- pyretis.engines.ams
- pyretis.engines.ase
- pyretis.engines.factory
- pyretis.engines.turtlemd
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 per-ensemble .wfn restart for speed.
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.
-
class
pyretis.engines.cp2k.CP2KEngine(cp2k: str, input_path: str, timestep: float, subcycles: int, temperature: Optional[float] = None, extra_files: Optional[List[str]] = None, exe_path: Union[str, Path] = PosixPath('/tmp/pyretis-develop-pyvisa-figs/docs'), sleep: float = 0.1)[source]¶ 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 per-ensemble.wfnrestart for speed.Variables: - cp2k – The command for executing CP2K.
- input_path – The directory where the input files are stored.
- 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, used to wait for files to be ready.
-
__init__(cp2k: str, input_path: str, timestep: float, subcycles: int, temperature: Optional[float] = None, extra_files: Optional[List[str]] = None, exe_path: Union[str, Path] = PosixPath('/tmp/pyretis-develop-pyvisa-figs/docs'), sleep: float = 0.1)[source]¶ Set up the CP2K MD engine.
Parameters: - cp2k – The CP2K executable.
- input_path – The path to the directory containing CP2K input files.
- timestep – The time step used in the CP2K simulation.
- subcycles – The number of steps each CP2K run is composed of.
- temperature – The temperature of the simulation.
- extra_files – List of extra files which may be required to run CP2K.
- exe_path – The path on which the engine is executed
- sleep – A time in seconds, used to wait 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][source]¶ 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 – A name to use for the trajectory we are generating.
- path – This is the path we use to fill in phase-space points.
- system – The phase point to use as a starting point.
- ens_set – Settings for the ensembles.
- msg_file – An object we use for writing out messages that are useful for inspecting the status of the current propagation.
- reverse – If True, the system will be propagated backward in time.
Returns: 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: Union[str, Path]) Tuple[ndarray, ndarray, Optional[ndarray], Optional[List[str]]][source]¶ 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 – Path to the file to read. Returns: 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[source]¶ 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 – Path to the file containing the configuration to reverse velocities in.
- outfile – Path to file for storing the configuration with reversed velocities.
-
static
add_to_path(path, phase_point, left, right)[source]¶ Add a phase point and perform some checks.
This is the three-value variant (status, success, stop) that
_propagate_from()unpacks. It is kept verbatim from the inf base (the nativeEngineBase.add_to_pathreturns a four-tuple and uses a different acceptance check), so the propagation behaviour stays byte-identical.
-
property
beta¶ The thermodynamic temperature in units of the engine.
-
calculate_order(system, xyz=None, vel=None, box=None)[source]¶ Calculate the order parameter of the current system.
Overrides the native
ExternalMDEngine.calculate_orderbecause this engine’s_read_configuration()returns the box as the third element (xyz, vel, box, names), whereas the native method reads it as box-first. The body matches the inf base so the order-parameter evaluation stays byte-identical.
-
draw_maxwellian_velocities(vel, mass, beta, rgen, sigma_v=None)[source]¶ Draw velocities from a Gaussian distribution.
The native bases do not provide this helper, so it is restored verbatim from the inf base (
modify_velocitiescalls it). Thergenis the injected velocity-generation generator.
-
dump_phasepoint(phasepoint, deffnm='conf')[source]¶ 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 native external override instead setsconfig = (pos_file, None)). The inf scheduler (_tis_inf.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][source]¶ Modify the velocities of all particles.
Parameters: - system – The system whose particle velocities are to be modified.
- vel_settings – A dict containing the key
'zero_momentum'(boolean): if true we reset the linear momentum to zero after generating velocities internally.
Returns: 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.
Note
CP2K removes the center of mass motion by default, so we set the momentum to zero by default here. This method does not take care of constraints.
-
needs_order= True¶
-
step(system, name)[source]¶ 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 native external base declares it abstract).
-
pyretis.engines.cp2k.guess_particle_mass(particle_no: int, particle_type: str) float[source]¶ Guess a particle mass from its type and convert to CP2K units.
Parameters: - particle_no – The particle number. This is only used for output to the logger.
- particle_type – The particle type as a string. This should be an element from the periodic table.
Returns: The guessed particle mass as a float.
-
pyretis.engines.cp2k.write_for_run_vel(infile: Union[str, Path], outfile: Union[str, Path], timestep: float, nsteps: int, subcycles: int, posfile: str, vel: ndarray, name: str = 'md_step', restart_wfn: str = 'doesnotexist.wfn', print_freq: Optional[int] = None) None[source]¶ 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 – Path to the input template to use.
- outfile – Path to the input file to create.
- timestep – The time step to use for the simulation.
- nsteps – The number of PyRETIS steps to perform.
- subcycles – The number of sub-cycles to perform.
- posfile – The (base)name for the input file to read positions from.
- vel – The velocities to set in the input.
- name – A name for the CP2K project.
- print_freq – 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='/tmp/pyretis-develop-pyvisa-figs/docs', seed=0, conf='initial.xyz', template='cp2k.inp')[source]¶ 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='/tmp/pyretis-develop-pyvisa-figs/docs', seed=0, conf='initial.xyz', template='cp2k.inp')[source]¶ 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’).
-
_extract_frame(traj_file, idx, out_file)[source]¶ 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.
-
_prepare_shooting_point(input_file)[source]¶ Create initial configuration for a shooting move.
This creates a new initial configuration with random velocities.
2022.05.25: Note: This function is no longer in use as we now generate velocities internally. However we keep this function in case of 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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'¶
-
classmethod
get_default_units(settings=None)[source]¶ 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')[source]¶ 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).
- system (object like
-
modify_velocities(system, vel_settings=None, rgen=None)[source]¶ 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.
- momentum : boolean If True, we reset the linear momentum to zero after generating.
- 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.
- 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.
- system (object like
-
pyretis.engines.cp2k_steps.write_for_continue(infile, outfile, timestep, subcycles, name='md_continue')[source]¶ 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')[source]¶ Create input file for velocity generation.
2022.05.25: Note: This function is no longer in use as we now generate velocities internally. However we keep this function in case of 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)[source]¶ 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)[source]¶ 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)[source]¶ 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.
-
__getstate__()[source]¶ 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.
-
static
add_to_path(path, phase_point, left, right)[source]¶ 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.
- path (object like
-
abstract
calculate_order(system, xyz=None, vel=None, box=None)[source]¶ 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)[source]¶ Fail if the engine can’t be used with an empty order parameter.
-
default_units= None¶
-
engine_type= None¶
-
property
exe_dir¶ Return the directory we are currently using.
-
classmethod
get_default_units(settings=None)[source]¶ 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.
-
abstract
kick_across_middle(system, ens_set, middle, tis_settings, rgen)[source]¶ Force a phase point across the middle interface.
rgenis the velocity-generation random generator, injected explicitly (kept distinct from any integrationself.rgen).
-
load_restart_info(info=None)[source]¶ Load restart information.
Parameters: info (dict) – The dictionary with the restart information, should be similar to the dict produced by restart_info().
-
abstract
modify_velocities(system, vel_settings, rgen)[source]¶ 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.
- momentum : boolean, optional If True, we reset the linear momentum to zero after generating.
- 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 used to draw 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.
- system (object like
-
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.
-
restart_info()[source]¶ 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)[source]¶ 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)[source]¶ 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) – the latter previously hitNone.posvia the removedsystem.particlesattribute access.
-
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)[source]¶ 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)[source]¶ 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)[source]¶ Trim an engine log to its most-recent
maxsizebytes.Thin wrapper around
pyretis.engines._engine_logs.cap_engine_log().
-
_config_signature(filename)[source]¶ Return a hash identifying a configuration’s physical content.
Used to confirm that an interrupted propagation we are about to resume really belongs to the shot we are now re-attempting: 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
_engine_output_files(log_dir)[source]¶ Return the engine stdout/stderr log paths for a run directory.
Thin wrapper around
pyretis.engines._engine_logs.engine_output_files().
-
abstract
_extract_frame(traj_file, idx, out_file)[source]¶ 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)[source]¶ Keep stdout logs and discard stderr logs from successful runs.
Thin wrapper around
pyretis.engines._engine_logs.finalize_engine_output().
-
_frame_config_index(frame)[source]¶ 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.
-
static
_modify_input(sourcefile, outputfile, settings, delim='=')[source]¶ 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.
-
_name_output(basename)[source]¶ 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)[source]¶ 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)[source]¶ 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).
-
abstract
_propagate_from(name, path, system, ens_set, msg_file, reverse=False)[source]¶ 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.
-
abstract
_read_configuration(filename)[source]¶ 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='=')[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ Remove files from a directory.
Parameters: - dirname (string) – Where we are removing.
- files (list of strings) – A list with files to remove.
-
abstract
_reverse_velocities(filename, outfile)[source]¶ Reverse velocities in a given snapshot.
Parameters: - filename (string) – Input file with velocities.
- outfile (string) – File to write with reversed velocities.
-
_trajectory_filename(name)[source]¶ 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)[source]¶ Write (atomically and durably) the resume marker.
-
calculate_order(system, xyz=None, vel=None, box=None)[source]¶ 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).
- system (object like
-
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)[source]¶ 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.
- vel (numpy.ndarray) – The current velocities; only the shape
-
dump_config(config, deffnm='conf')[source]¶ 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.
-
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)[source]¶ 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)[source]¶ 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)[source]¶ 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.
- rescale_energy: boolean, determines if energy is re-scaled.
- 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.
- system (object like
-
propagate(path, ens_set, system, reverse=False)[source]¶ 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, used to build 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.
- path (object like
-
abstract
step(system, name)[source]¶ 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.
- system (object like
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='/tmp/pyretis-develop-pyvisa-figs/docs', maxwarn=0, gmx_format='gro', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', temperature=None, masses=False)[source]¶ 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='/tmp/pyretis-develop-pyvisa-figs/docs', maxwarn=0, gmx_format='gro', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', temperature=None, masses=False)[source]¶ 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)[source]¶ 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)[source]¶ 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')[source]¶ 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).
- system (object like
-
-
class
pyretis.engines.gromacs.GromacsRunner(cmd, trr_file, edr_file, exe_dir)[source]¶ 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¶
-
__exit__(exc_type, exc_val, exc_tb)[source]¶ Just stop execution and close file for a context manager.
-
__init__(cmd, trr_file, edr_file, exe_dir)[source]¶ 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.
-
pyretis.engines.gromacs.get_data(fileh, header)[source]¶ Read data from the TRR file.
Parameters: - fileh (file object) – The file we are reading.
- header (dict) – The previously read header. 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ Return a given frame from a TRR file.
-
pyretis.engines.gromacs.reopen_file(filename, fileh, inode, bytes_read)[source]¶ 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)[source]¶ 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)[source]¶ 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).
-
class
pyretis.engines.gromacs_steps.GromacsEngineSteps(gmx, mdrun=None, input_path=None, timestep=None, subcycles=None, exe_path='/tmp/pyretis-develop-pyvisa-figs/docs', maxwarn=0, gmx_format='gro', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', temperature=None, masses=False, conf=None, template='grompp.mdp', top='topol.top')[source]¶ Bases:
ExternalMDEngineA class for interfacing GROMACS.
This class defines the interface to GROMACS.
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.
- 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.
-
__init__(gmx, mdrun=None, input_path=None, timestep=None, subcycles=None, exe_path='/tmp/pyretis-develop-pyvisa-figs/docs', maxwarn=0, gmx_format='gro', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', temperature=None, masses=False, conf=None, template='grompp.mdp', top='topol.top')[source]¶ 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.
- 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);"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) used to draw 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’).
-
_draw_velocities_maxwell(system, vel_settings, rgen)[source]¶ 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;
momentum(or the inf-stylezero_momentum) requests a zero linear-momentum reset. - rgen (object like
RandomGenerator) – The velocity random generator, injected explicitly.
Returns: float – The new kinetic energy.
- system (object like
-
_ensure_tpr()[source]¶ Build the construction “.tpr” on first use (lazily).
The construction “.tpr” is only consumed by the trjconv frame-extraction branches (non-trr/non-g96 input and the domain-decomposition pass); typical trr/g96 runs never need it. Deferring it here lets the engine be constructed without invoking GROMACS, while keeping the byte output identical (the “.tpr” is deterministic). The preprocessor is always run in
input_path(where the “.tpr” lives), restoringexe_dirafterwards.
-
_execute_grompp(mdp_file, config, deffnm)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ Extract a frame from a .trr, .xtc or .trj file.
If the extension is different from .trr, .xtc or .trj, we will basically just copy the given input file.
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.
Note
This will only properly work if the frames in the input trajectory are uniformly spaced in time.
-
_load_masses(masses)[source]¶ 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).
-
_prepare_shooting_point(input_file)[source]¶ 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. 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)[source]¶ 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)[source]¶ 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.
-
_remove_gromacs_backup_files(dirname)[source]¶ 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)[source]¶ 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.
-
_trajectory_filename(name)[source]¶ 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'¶
-
classmethod
get_default_units(settings=None)[source]¶ 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)[source]¶ 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')[source]¶ 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).
- system (object like
-
modify_velocities(system, vel_settings, rgen)[source]¶ 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.
- momentum: boolean, optional If True, we reset the linear momentum to zero after generating.
- 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 random generator. Used only whenvelocity_generation == "maxwell"(the Python draw); in the default"engine"mode GROMACS regenerates the velocities internally via a zero-step run andrgenis unused.
Returns: - dek (float) – The change in the kinetic energy.
- kin_new (float) – The new kinetic energy.
- system (object like
-
static
select_energy_terms(terms)[source]¶ 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)[source]¶ 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 native 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.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)[source]¶ 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.
- c0 : float
Corresponds to
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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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.
- rgen (object like
-
class
pyretis.engines.internal.MDEngine(timestep, description, dynamics=None)[source]¶ 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, …).
-
__call__(system)[source]¶ 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)[source]¶ 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.
-
static
_draw_maxwellian(system, rgen, sigma_v=None)[source]¶ 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)[source]¶ Extract a single frame from a trajectory into its own file.
-
_ensure_dynamics_rgen()[source]¶ 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)[source]¶ 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)[source]¶ 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.
-
_is_streaming(system)[source]¶ Return True when
systemis a file-backed snapshot.The native 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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).
- system (object like
-
clean_up()[source]¶ Clean up after using the engine.
For the native 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)[source]¶ Dump a phase point to a file.
In the native 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)[source]¶ 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')[source]¶ 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).
- system (object like
-
integration_step(_)[source]¶ 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()[source]¶ 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)[source]¶ 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.
- rescale_energy: boolean, determines if energy is re-scaled.
- 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.
- system (object like
-
modify_velocities(system, vel_settings, rgen)[source]¶ 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.
- momentum : boolean, optional If True, we reset the linear momentum to zero after generating.
- 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.
- system (object like
-
propagate(path, ens_set, system, reverse=False)[source]¶ 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.
- path (object like
-
select_thermo_function(thermo='full')[source]¶ 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.
-
setup_streaming(settings)[source]¶ Build the file-backed (streaming) template for this engine.
Mirrors
TurtleMDEngine, which builds its own box / particles / potential in__init__: here we reuse the nativepyretis.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.Parameters: settings (dict) – The full (coordinator) settings dictionary. It carries the native [system]/[box]/[particles]/[potential]/[forcefield]/[engine]sections the native flow uses to build the system and force field.
-
streaming_energies(systems)[source]¶ 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 performed by
pyretis.core.pathstorage.PathStorage.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.
-
class
pyretis.engines.internal.RandomWalk(timestep, rgen=None, seed=0)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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()[source]¶ 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)[source]¶ Bases:
MDEngineThe Velocity Verlet MD integrator.
This class defines the Velocity Verlet integrator.
Variables: half_timestep (float) – Half of the timestep. -
__init__(timestep)[source]¶ Set up the Velocity Verlet integrator.
Parameters: timestep (float) – The time step in internal units.
-
integration_step(system)[source]¶ 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.
-
-
class
pyretis.engines.internal.Verlet(timestep)[source]¶ 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)[source]¶ Set up the Verlet MD integrator.
Parameters: timestep (float) – The time step in internal units.
-
integration_step(system)[source]¶ 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)[source]¶ Load restart information.
Parameters: info (dict) – The dictionary with the restart information, should be similar to the dict produced by restart_info().
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 LAMMPS run is built from a self-contained input template
(lammps.input) whose pyretis_* placeholders – timestep, number
of steps, subcycles, initial configuration, data file, temperature and
the per-segment thermostat seed – are substituted for each propagation.
The relaunch (start-and-stop) engine, which builds its input by
appending PyRETIS run commands to a force-field-only template, remains
available as 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='full', sleep=0.1)[source]¶ 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). - Velocity generation depends on units… only ‘real’ atm
- 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='full', sleep=0.1)[source]¶ 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).atom_styleandsleepare the only streaming-specific extras.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"(LAMMPS) or"maxwell"(Python draw); seeLAMMPSEngineSteps. - temperature (float, optional) – Temperature (K) for Maxwell-Boltzmann velocity generation.
- atom_style (string, optional) – The LAMMPS
atom_styleused to read masses from the data file. Default"full". - sleep (float, optional) – Seconds to wait between polls while reading the trajectory on
the fly. Default
0.1.
-
_extract_frame(traj_file: str, idx: int, out_file: str) None[source]¶ Extract a frame from a trajectory to a new file.
idxis a LAMMPS time step (the shared config-index convention); the on-the-fly dump stores one frame everysubcyclessteps, so the trajectory-frame number isidx // subcycles.
-
_frame_config_index(frame: int) int[source]¶ 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. This is the inverse of theidx // subcyclesmapping in_extract_frame().
-
_read_configuration(filename: str) Tuple[ndarray, ndarray, Optional[ndarray], Optional[list[str]]][source]¶ Read a configuration (a single frame trajectory).
-
_recompute_partial_orders(partial_traj, reverse)[source]¶ 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[source]¶ Reverse the velocities of a configuration.
-
static
add_to_path(path, phase_point, left, right)[source]¶ Add a phase point and perform some checks.
-
calculate_order(system, xyz=None, vel=None, box=None)[source]¶ 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 nativeExternalMDEngine.calculate_orderwhich expects the box first. We therefore keep the box-third unpacking here.
-
default_units= None¶
-
draw_maxwellian_velocities(vel, mass, beta, rgen, sigma_v=None)[source]¶ Draw velocities from a Gaussian distribution.
-
dump_config(config, deffnm='conf')[source]¶ 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 we pass the data file through unchanged (LAMMPS reads it viaread_datain the run input); 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.
- config (tuple) – The configuration as
-
dump_phasepoint(phasepoint, deffnm='conf')[source]¶ Dump the current configuration from a system object to a file.
-
engine_type= 'external'¶
-
classmethod
get_default_units(settings=None)[source]¶ 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][source]¶ Modify the velocities of all particles.
Parameters: - system – The system whose particle velocities are to be modified.
- vel_settings – A dict containing the key
'zero_momentum'(boolean): if true we reset the linear momentum to zero after generating velocities internally.
Returns: 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.
Note
This method does not take care of constraints.
-
needs_order= True¶
-
propagate(path, ens_set, system, reverse=False)[source]¶ Propagate by streaming a single persistent LAMMPS run.
The relaunch base (
LAMMPSEngineSteps) overridespropagatewith its relaunch-per-step driver. The streaming engine instead 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.
- Add possibility to use LAMMPS internally to modify the velocities
such that all constraints (e.g. between bonds) are fulfilled
(
-
pyretis.engines.lammps.get_atom_masses(lammps_data: Union[str, Path], atom_style) ndarray[source]¶ Read atom masses from a LAMMPS data file.
TODO: atom style dependent!!
Parameters: - lammps_data – Path to the LAMMPS data file to read.
- atom_style – The style used in lammps. Supports ‘full’ and ‘charge’.
Returns: An array with the masses read from the file.
-
pyretis.engines.lammps.read_energies(filename: str) Dict[str, ndarray][source]¶ 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 – The path to the LAMMPS log file to read. Returns: A dictionary containing the data we found in the file.
-
pyretis.engines.lammps.read_lammps_input(filename)[source]¶ 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) Tuple[ndarray, ndarray, ndarray, ndarray][source]¶ Read a single frame from a LAMMPS trajectory.
Parameters: - infile – The path to the file to read.
- frame – The index of the frame to read from infile.
- n_atoms – The number of atoms to read.
Returns: A tuple containing – - The id type for the particles. - The positions. - The velocities. - The simulation box.
Note
- The atoms are sorted according to their index, so that
- (index-based) order calculations are correct.
-
pyretis.engines.lammps.write_lammpstrj(outfile: str, id_type: ndarray, pos: ndarray, vel: ndarray, box: Optional[ndarray], append: bool = False, triclinic: bool = False) None[source]¶ Write a LAMMPS trajectory frame in .lammpstrj format.
This method assumes a dump format from LAMMPS of: dump id type x y z vx vy vz.
Parameters: - outfile – Path to the file to write.
- id_type
- pos – The positions to write.
- vel – The velocities to write.
- box – The simulation box to write (if available).
- append – If True, the outfile will be appended to, otherwise, outfile will be overwritten.
- triclinic – If true, write in triclinic box format.
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 relaunching the
executable once per order-parameter point (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)[source]¶ 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)[source]¶ 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);"maxwell"draws them in Python from a Maxwell-Boltzmann distribution via the injected random generator (one reproducible stream;'real'units; requirestemperature). - temperature (float, optional) – The temperature (K) used to draw Maxwell-Boltzmann velocities
when
velocity_generation == "maxwell".
-
_calculate_pyretis_order(system, traj, reverse=False)[source]¶ Calculate PyRETIS order parameters from a LAMMPS trajectory.
-
_draw_velocities_maxwell(system, vel_settings, rgen)[source]¶ 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.Parameters: - system (object like
System) – The state whose velocities we redraw. - vel_settings (dict) –
momentum(or the inf-stylezero_momentum) requests a zero linear-momentum reset. - 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).- system (object like
-
_extract_frame(traj_file, idx, out_file)[source]¶ Extract one LAMMPS trajectory frame as a data file.
-
_make_order_fix(ordername)[source]¶ 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)[source]¶ 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.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.
- system (object like
-
_propagate_from(name, path, system, ens_set, msg_file, reverse=False)[source]¶ 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)[source]¶ Parse a LAMMPS data file for the Python velocity draw.
Parameters: data_file (string) – The LAMMPS data file to read (as written by dump_frame).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, one per spatial dimension.
-
static
_trim_to_common_length(order, energy)[source]¶ Trim LAMMPS run data to the common sampled-frame length.
-
static
_write_velocity_dump(dump_file, ids, pos, vel, images, box)[source]¶ Write a LAMMPS dump frame (positions, velocities, image flags).
The columns
id x y z vx vy vz ix iy izmatch what the native engine’sread_dumpoverlay reads back.
-
add_input_files(dirname)[source]¶ 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)[source]¶ 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.
- system (object like
-
default_units= None¶
-
dump_phasepoint(phasepoint, deffnm='conf')[source]¶ Dump a phase point to a new file.
Note
We do not reverse the velocities here.
-
classmethod
get_default_units(settings=None)[source]¶ 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')[source]¶ 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).- system (object like
-
modify_velocities(system, vel_settings, rgen)[source]¶ 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; the
rescalekey is forwarded to LAMMPS. - 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.
- system (object like
-
needs_order= False¶
-
propagate(path, ens_set, system, reverse=False)[source]¶ 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.
- path (object like
-
read_energies(name)[source]¶ 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)[source]¶ 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)[source]¶ 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.
- system (object like
-
pyretis.engines.lammps_steps._add_generate_vel(settings)[source]¶ Add generation of velocities to the LAMMPS input.
-
pyretis.engines.lammps_steps._add_order_fix(settings)[source]¶ Add the fix for printing the order parameter for LAMMPS.
-
pyretis.engines.lammps_steps._add_stopping_condition(settings)[source]¶ Add the interface stopping condition to the LAMMPS input.
-
pyretis.engines.lammps_steps._add_traj_dump(settings)[source]¶ Add the dump commands for storing the LAMMPS trajectory.
-
pyretis.engines.lammps_steps._parse_dump_box(bounds)[source]¶ Return orthogonal box lengths from LAMMPS dump bounds.
-
pyretis.engines.lammps_steps._parse_lammps_dump_lines(lines, dimension, source='<lines>')[source]¶ 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).
Returns: frames (list of dict) – Each frame contains
step,box,posandvel.
-
pyretis.engines.lammps_steps.add_to_lammps_input(infile, outfile, to_add)[source]¶ 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.create_lammps_md_input(system, infile, outfile, settings)[source]¶ 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.
- system (object like
-
pyretis.engines.lammps_steps.read_lammps_dump(filename, dimension)[source]¶ 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
step,box,posandvelentries.
-
pyretis.engines.lammps_steps.read_lammps_input(filename)[source]¶ 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)[source]¶ 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.rename_lammps_energy_keys(energy)[source]¶ Rename LAMMPS thermo column labels to PyRETIS conventions.
-
pyretis.engines.lammps_steps.system_to_lammps(system, reverse_velocities, dimension)[source]¶ 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.
- system (object like
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)[source]¶ 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)[source]¶ 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).
-
calculate_order(system, xyz=None, vel=None, box=None)[source]¶ 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).
- system (object like
-
clean_up()[source]¶ Clean up after using the engine.
Currently, this is only included for compatibility with external integrators.
-
default_units= 'openmm'¶
-
engine_type= 'openmm'¶
-
classmethod
get_default_units(settings=None)[source]¶ 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)[source]¶ 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)[source]¶ 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.
- rescale_energy: boolean, determines if energy is re-scaled.
- rgen (object like
RandomGenerator) – This is the random generator that will be used.
Returns: Note
This function will update the system state.
- system (object like
-
modify_velocities(system, vel_settings, rgen)[source]¶ 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.
- momentum : boolean, optional If True, we reset the linear momentum to zero after generating.
- 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) – 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.
- system (object like
-
propagate(path, ens_set, system, reverse=False)[source]¶ 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.
- path (object like
pyretis.engines.ams module¶
A AMS external MD integrator interface.
This module defines a class for using AMS as an external engine.
-
class
pyretis.engines.ams.AMSEngine(input_path, timestep, subcycles)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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][source]¶ 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
infretis.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.
- system: object like
- 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)[source]¶ 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)[source]¶ 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)[source]¶ 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.
-
static
add_to_path(path, phase_point, left, right)[source]¶ Add a phase point to the path and check for crossings.
This override preserves the inf-flavour semantics expected by
_propagate_from: it returns a 3-tuple and lets a crossing of either interface win on the boundary (the native external base returns a 4-tuple with different maxlen handling).Parameters: Returns: - status (string) – A text description of the current status of the propagation.
- success (boolean) – True if we generated an acceptable path.
- stop (boolean) – True if the propagation should stop.
-
calculate_order(system, xyz=None, vel=None, box=None)[source]¶ 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 native 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).
- system (object like
-
dump_phasepoint(phasepoint, deffnm='conf')[source]¶ 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 native(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.
- phasepoint (object like
-
engine_type= 'internal'¶
-
modify_velocities(system: System, vel_settings: Dict[str, Any], rgen) Tuple[float, float][source]¶ Modify the velocities of the current state.
This method will modify the velocities of a time slice.
Parameters: - ensemble (dict) – It contains:
- system: object like
SystemThis is the system that contains the particles we are investigating.
- system: object like
- vel_settings (dict) – It contains:
- sigma_v: numpy.array, optional These values can be used to set a standard deviation (one for each particle) for the generated velocities.
- aimless: boolean, optional Determines if we should do aimless shooting or not.
- momentum: boolean, optional If True, we reset the linear momentum to zero after generating.
- rescale or rescale_energy: 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.
Returns: - dek (float) – The change in the kinetic energy.
- kin_new (float) – The new kinetic energy.
- ensemble (dict) – It contains:
-
needs_order= False¶
-
set_mdrun(md_items)[source]¶ 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 old states that are no longer in use, and updates the list of old states to the current states.
-
step(system, name, set_trajfile=True, set_step_to_zero=False)[source]¶ 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.
- system (object like
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: Union[str, Path] = PosixPath('/tmp/pyretis-develop-pyvisa-figs/docs'))[source]¶ 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: Union[str, Path] = PosixPath('/tmp/pyretis-develop-pyvisa-figs/docs'))[source]¶ 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)[source]¶ Order parameters per frame of a partial ASE
.trajdump.recalculate_orderhas no ASE-trajectory handler, so the frames are read directly via ASE.Trajectoryexposes only complete frames, so a final frame left half-written by an interruption is naturally excluded – the surviving frames are kept (“use the last good frame” recovery, as for the other engines).
-
static
add_to_path(path, phase_point, left, right)[source]¶ Add a phase point and check for stopping conditions.
Uses the inf logic where a crossing wins on the boundary; the engine’s
_propagate_fromunpacks the three returned values (status, success, stop).
-
calculate_order(system, xyz=None, vel=None, box=None)[source]¶ 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 native external base.
-
dump_phasepoint(phasepoint, deffnm='conf')[source]¶ 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][source]¶ Modify the velocities.
- TODO: what about fixcm with langevin integrator
- and zero_momentum?
-
needs_order= False¶
-
step(system, name)[source]¶ 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.
-
pyretis.engines.factory module¶
Engine factory for keyed engine creation (infRETIS flavour).
This module supplements pyretis.engines with the keyed-creation
helpers used by the infRETIS 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 two call paths are deliberately kept separate so that pyretis-old behaviour stays reachable while the infRETIS-flavour scheduler also works inside the same package:
from pyretis.setup.common import create_engine– pyretis-native single-engine creation, resolved through the untouchedpyretis.engines.ENGINE_MAP.from pyretis.engines.factory import create_inf_engine– infRETIS-flavour keyed creation, resolved through thebuild_engine_map()result (which shadows the nativecp2k/gromacs/lammpsentries with the_infclasses).ENGINE_MAPis never mutated.
-
pyretis.engines.factory._try_register(target: Dict[str, Dict[str, Any]], key: str, module_path: str, class_name: str) None[source]¶ Attempt to import
class_namefrommodule_path.Adds
{key: {'cls': cls}}totargeton success. Failures (typically missing optional dependencies for the engine itself) are silently ignored.
-
pyretis.engines.factory.assign_engines(engine_occ: Dict[str, list], eng_names, pin) Dict[Any, int][source]¶ 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]now owned bypin.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]][source]¶ Return ENGINE_MAP extended with infRETIS-ported 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[source]¶ Light-touch validation of an engine settings block.
Mirrors infretis
factory.check_engine: ensures the section exists and that file-format-bearing engines specify their format.
-
pyretis.engines.factory.create_engines(config: Dict[str, Any]) Tuple[Dict[Any, Any], Dict[Any, list]][source]¶ Build the engine pool for an infRETIS-style 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') Optional[Any][source]¶ Create an infRETIS engine from a settings section.
Counterpart to
pyretis.setup.common.create_engine()for the infRETIS scheduler: takes an expliciteng_keyso multiple named engines (engine,engine2, …) can coexist in one config, and resolves engine classes throughbuild_engine_map()(which shadows pyretis-nativecp2k/gromacs/lammpsentries with the_infflavours). The pyretis-nativepyretis.setup.common.create_engine()stays the entry point for pyretis-old runs.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: Optional[EngineBase] – The created engine, or the result of
pyretis.setup.common.create_external()if the engine class is not in the extended engine map.- settings (dict) – Full simulation settings. The engine settings live under
-
pyretis.engines.factory.import_external(settings: Dict[str, Any], key: str, required_methods: Optional[List[str]] = None) Any[source]¶ Import and instantiate a class described by
settings.Equivalent to
infretis.core.core.create_external: thesettingsdict 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 pyretis-native 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.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])[source]¶ 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])[source]¶ Initialize the TurtleMD engine.
Parameters: - timestep – The simulation timestep.
- subcycles – The number of subcycles to execute per InfRetis step.
- temperature – The temperature of the simulation.
- boltzmann – The value of Boltzmanns constant (kB).
- integrator – The name of the integrator to use for TurtleMD.
- potential – The name of the potential to use for TurtleMD.
- particles – The mass and name of the particles in the system.
- box – Definition of the simulation box.
-
_extract_frame(traj_file: str, idx: int, out_file: str) None[source]¶ 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 – The trajectory file to dump from.
- idx – The frame number we look for.
- out_file – The file to dump to.
-
_propagate_from(name: str, path: Path, system: System, ens_set: Dict[str, Any], msg_file: FileIO, reverse: bool = False) Tuple[bool, str][source]¶ 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, Optional[ndarray], List[str]][source]¶ 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 – The path to the file to read the configuration from. Returns: 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[source]¶ Reverse velocities in the given snapshot.
Parameters: - filename – The path to the file containing the configuration to reverse the velocities of.
- outfile – The path to the output file for storing the configuration with reversed velocities.
-
static
add_to_path(path, phase_point, left, right)[source]¶ Add a phase point and perform some checks.
-
property
beta¶ The thermodynamic temperature in units of the engine.
-
calculate_order(system, xyz=None, vel=None, box=None)[source]¶ Calculate the order parameter of the current system.
-
draw_maxwellian_velocities(vel, mass, beta, rgen, sigma_v=None)[source]¶ Draw velocities from a Gaussian distribution.
-
dump_phasepoint(phasepoint, deffnm='conf')[source]¶ Dump the current configuration from a system object to a file.
-
engine_type= 'internal'¶
-
modify_velocities(system: System, vel_settings: Dict[str, Any], rgen) Tuple[float, float][source]¶ 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.
Returns: - dek (float) – The change in kinetic energy from the velocity modification.
- kin_new (float) – The new kinetic energy of the system.
- system (object like
-
needs_order= False¶