pyretis.engines package¶
Definition of engines.
This package defines engines for PyRETIS. The engines are responsible for carrying out dynamics for a system. This can in principle both be molecular dynamics or Monte Carlo dynamics. Typically, with RETIS, this will be molecular dynamics in some form in order to propagate the equations of motion and obtain new trajectories.
Package structure¶
Modules¶
- cp2k.py (
pyretis.engines.cp2k) Defines an engine for use with CP2K.
- engine.py (
pyretis.engines.engine) Defines the base engine class.
- external.py (
pyretis.engines.external) Defines the interface for external engines.
- gromacs.py (
pyretis.engines.gromacs) Defines the canonical (streaming) engine for use with GROMACS. It runs GROMACS once per propagated segment and reads the frames on the fly.
- gromacs_steps.py (
pyretis.engines.gromacs_steps) Defines the relaunch implementation of the GROMACS engine, which starts and stops the GROMACS executable once per order-parameter point. Reached as
class = "gromacs_steps".- internal.py (
pyretis.engines.internal) Defines internal PyRETIS engines.
- lammps.py (
pyretis.engines.lammps) Defines the canonical (streaming) engine for use with LAMMPS.
- lammps_steps.py (
pyretis.engines.lammps_steps) Defines the relaunch implementation of the LAMMPS engine. Reached as
class = "lammps_steps".- openmm.py (
pyretis.engines.openmm) Defines an engine for use with OpenMM.
Important methods defined here¶
- engine_factory (
engine_factory()) A method to create engines from settings.
- get_engine_class (
get_engine_class()) Return the engine class matching a name.
- resolve_engine_class (
resolve_engine_class()) Resolve the engine class from full settings.
- get_default_units (
get_default_units()) Return the default unit system for an engine.
The engine classes re-exported here (e.g. MDEngine,
ExternalMDEngine, GromacsEngine) are documented on
their respective module pages listed below. The package itself also provides
the following engine-selection helpers:
- pyretis.engines.engine_factory(settings)¶
Create an engine according to the given settings.
This function is included as a convenient way of setting up and selecting an engine. It will return the created engine.
- Parameters:
settings (dict) – This defines how we set up and select the engine.
- Returns:
out (object like
EngineBase) – The object representing the engine to use in a simulation.
- pyretis.engines.get_engine_class(name)¶
Return the class matching a given engine name.
- pyretis.engines.resolve_engine_class(settings)¶
Resolve an engine class from the given settings.
- pyretis.engines.get_default_units(settings)¶
Return the default unit system for the selected engine.
List of submodules¶
pyretis.engines.cp2k module¶
A continuous CP2K external MD integrator interface.
This module defines the canonical CP2K engine, selected by
class = "cp2k". CP2K is run as a single persistent process for a
whole propagation segment and its position/velocity trajectories are
read on-the-fly, so the path is filled incrementally and CP2K is
terminated as soon as a stopping interface is crossed. The SCF of each
segment starts from CP2K’s initial guess: no wavefunction is carried
from one segment to another (see cp2k_cold_start()).
The relaunch (start-and-stop / restart-chain) engine, which advances
CP2K one order-parameter point at a time, is selected by
class = "cp2k_steps" (pyretis.engines.cp2k_steps).
Important classes defined here¶
- CP2KEngine (
CP2KEngine) The continuous CP2K engine.
- class pyretis.engines.cp2k.CP2KEngine(cp2k: str, input_path: str, timestep: float, subcycles: int, extra_files: list[str] | None = None, exe_path: str | Path | None = None, sleep: float = 0.1)¶
Bases:
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 SCF of each segment starts from CP2K’s initial guess, whatever segments ran before it. An MD run (anmd,md-nveormd-fluxtask) is the MD run of the relaunch engine (CP2KEngineSteps.integrate()): one CP2K run ofsubcyclesMD steps from each stored step to the next.- Variables:
cp2k – The command for executing CP2K.
input_path – The directory holding the input files the engine reads.
timestep – The time step used in the CP2K MD simulation.
subcycles – The number of steps each CP2K run is composed of.
extra_files – List of extra files which may be required to run CP2K.
sleep – A time in seconds, for waiting for files to be ready.
- __init__(cp2k: str, input_path: str, timestep: float, subcycles: int, extra_files: list[str] | None = None, exe_path: str | Path | None = None, sleep: float = 0.1)¶
Set up the CP2K MD engine.
- Parameters:
cp2k (str) – The CP2K executable.
input_path (str) – The path to the directory containing CP2K input files.
timestep (float) – The time step used in the CP2K simulation.
subcycles (int) – The number of steps each CP2K run is composed of.
extra_files (list, optional) – List of extra files which may be required to run CP2K.
exe_path (str or Path, optional) – The run directory: a relative
input_pathis resolved against it. None resolvesinput_pathagainst the working directory as the engine is created.sleep (float) – A time in seconds, for waiting for files to be ready.
- static _leg_project(name: str) str¶
Return the name of the CP2K project of a leg.
The CP2K run of a leg writes its output (
OUTPUT_FILES) under the name of its project, and_propagate_from()reads the frames and the energies of the leg from that output. The name of a leg comes from a counter of the PyRETIS process (ExternalMDEngine.propagate()), which starts at zero in every process, so a run started again in the directory of a stopped run runs legs of the names of the stopped run. CP2K runs in a session of its own. When a run stops on Ctrl+C or SIGTERM, the worker pool (aiorunner.close()) terminates the CP2K of each leg its workers run (process_sessions). A stop, or a SIGKILL, while the main process runs a leg (a kick other than the parallel kick) leaves its CP2K running: it then writes its output until its steps are done, and creates its output files again when they are removed. A SIGKILL of the main process leaves the workers running, and each of them goes on with its leg as usual. The project name is the name of the leg, the id of the process that runs it and a tag of 8 hexadecimal digits drawn for the leg from the random source of the operating system (secrets.token_hex()). The id alone does not tell the processes apart: the system gives the id of a process that has ended to a new process, each container with a process namespace of its own counts ids from 1, and each host that shares the directory counts its own ids. With the tag, the leg reads the output of its own CP2K run, also while a CP2K run of a stopped process with the same id still runs in the directory: two legs of the same name and id get the same tag with a chance of 1 in 2**32. The tag names files only; it draws on no random generator of the simulation and changes no result. The project names the output while CP2K runs: when the run has ended, the output of the project that is left takes the name of the leg (_rename_leg_output()).- Parameters:
name (str) – The name of the leg.
- Returns:
str – The name of the CP2K project of the leg,
<name>-<process id>-<tag>.
- _propagate_from(name: str, path: InfPath, system: System, ens_set: dict[str, Any], msg_file: FileIO, reverse: bool = False) tuple[bool, str]¶
Propagate with CP2K from the current system configuration.
Here, we assume that this method is called after the propagate() has been called in the parent. The parent is then responsible for reversing the velocities and also for setting the initial state of the system.
Note that the on-the-fly reading of data applies only to simulations of a fixed box (NVE, NVT), as no box information is read from CP2K.
The frames of the leg are written to its own trajectory,
<name>.<ext>in the directory the engine runs in, and frameiof the leg is frameiof that file. The leg reads its frames and energies from the output files of the CP2K run it starts, under a project name of its own (_leg_project()), so it reads no output of a CP2K run that an earlier process started in the directory and that still runs. Before CP2K runs, a trajectory of the leg’s name that an earlier run left in the directory is removed, and so is CP2K output of the leg’s project, should a file of that name exist (_remove_leg_files()). When the CP2K run has ended, after its last step, stopped at an interface or with an error, the output of the project that is left takes the name of the leg (_rename_leg_output()), beside the trajectory of the leg; a CP2K run that still runs after an error of PyRETIS writes on under its project.- Parameters:
name (str) – A name to use for the trajectory we are generating.
path (InfPath) – This is the path we use to fill in phase-space points.
system (System) – The phase point to use as a starting point.
ens_set (dict) – Settings for the ensembles.
msg_file (FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.
reverse (bool) – If True, the system will be propagated backward in time.
- Returns:
tuple – A tuple containing:
True if we generated an acceptable path, False, otherwise.
A text description of the status of the propagation. Can be used to interpret the reason for the path not being acceptable.
- Raises:
NotImplementedError – For a thermostat whose noise PyRETIS cannot seed (
refuse_unseeded_cp2k_noise()), before CP2K runs.FileExistsError – As
cp2k_cold_start()raises it, before CP2K runs.OSError – As
_remove_leg_files()raises it, before CP2K runs, and_rename_leg_output(), after CP2K has ended.
- static _read_configuration(filename: str | Path) tuple[ndarray, ndarray, ndarray | None, list[str] | None]¶
Read a CP2K output configuration from a file.
This streaming engine returns the box as the THIRD element (
xyz, vel, box, names). The relaunchCP2KEngineSteps._read_configuration()returnsboxfirst;calculate_order()and_propagate_from()rely on the box-third order, so this cannot be inherited. The methods inherited from the relaunch engine read a configuration box first, with_read_configuration_box_first().- Parameters:
filename (str or Path) – Path to the file to read.
- Returns:
tuple –
- A tuple containing:
The positions.
The velocities.
The box dimensions if we manage to read it.
The atom names found in the file.
- _read_configuration_box_first(filename: str | Path) tuple[ndarray | None, ndarray, ndarray, list[str] | None]¶
Read a configuration, with the box as its first item.
The methods this engine inherits from
CP2KEngineSteps, its MD run (CP2KEngineSteps.integrate()) among them, unpack a configuration box first, as the relaunch engine reads it; this engine’s_read_configuration()returns the box third.- Parameters:
filename (str or Path) – Path to the file to read.
- Returns:
tuple –
- A tuple containing:
The box dimensions if we manage to read it.
The positions.
The velocities.
The atom names found in the file.
- static _remove_leg_files(traj_file: str, out_files: dict[str, str]) None¶
Remove the files of a leg that an earlier run left.
A leg appends its frames to its trajectory,
traj_file, and names them from 0, and_propagate_from()reads the position and velocity output of the CP2K project of the leg as soon as it exists. The name of a leg comes from a counter of the PyRETIS process (ExternalMDEngine.propagate()), which starts at zero in every process, so the directory a leg runs in can hold a trajectory of the leg’s name that an earlier process left there: an initiation stopped by a signal or anEXITfile, and started again in the same directory, runs its legs under the names of the stopped one. Left in place, its frames would be named as frames of the leg. The project of the leg is a name of its own (_leg_project()), which no earlier run gave to its CP2K output, unless with a chance of 1 in 2**32; output files of the project are removed too, should they exist. The files are removed before CP2K runs, so the leg starts a trajectory of its own and CP2K starts the output files of the project. A CP2K run left running by a stopped process writes the output of its own project, which is not removed.- Parameters:
traj_file (str) – The trajectory of the leg.
out_files (dict of str) – The output files of the CP2K project of the leg, as
OUTPUT_FILESnames them.
- Raises:
OSError – If one of the files cannot be removed: the leg would read the frames of another run.
- static _rename_leg_output(exe_dir: str, project: str, name: str) None¶
Give the output of the CP2K run of a leg the name of the leg.
While the CP2K run of a leg runs, it writes its output under the project of the leg,
<leg>-<pid>-<tag>(_leg_project()). When it has ended,_propagate_from()removes the output it read (OUTPUT_FILES), and the files of the project that are left,<leg>-<pid>-<tag><suffix>, are renamed here to<leg><suffix>: the forces, the cell or the restart history that the template prints, for example. The files kept with the trajectory of a path ([output] keep_traj_fnames) are named<leg><suffix>, beside the trajectory of the leg,<leg>.<ext>. A file of the leg’s name that is there already, left by an earlier leg of that name, is replaced, as CP2K replaces its output files when a run of a project starts.- Parameters:
exe_dir (str) – The directory the CP2K run of the leg ran in.
project (str) – The CP2K project of the leg.
name (str) – The name of the leg.
- Raises:
OSError – If a file cannot be renamed.
- _reverse_velocities(filename: str, outfile: str) None¶
Reverse velocity in a given snapshot.
This override unpacks this engine’s box-third
_read_configuration()(xyz, vel, box, names); the relaunch base unpacks the box first, through_read_configuration_box_first().- Parameters:
filename (str) – Path to the file containing the configuration to reverse velocities in.
outfile (str) – Path to file for storing the configuration with reversed velocities.
- calculate_order(system, xyz=None, vel=None, box=None)¶
Calculate the order parameter of the current system.
Overrides
ExternalMDEngine.calculate_orderbecause this engine’s_read_configuration()returns the box as the third element (xyz, vel, box, names), whereas that method reads it as box-first. A frame that records no cell is evaluated in the cell of the input template (CP2KEngineSteps.frame_cell()), as the relaunch engine evaluates it.
- classmethod cp2k_template(engine_settings)¶
Return the name of the CP2K input the engine reads.
This engine reads
cp2k.inpwhatever the engine section sets.- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (string) –
cp2k.inp.
- dump_phasepoint(phasepoint, deffnm='conf')¶
Dump the current configuration from a system object to a file.
This override points the phase point at frame index
0of the dumped file viaset_pos; theExternalMDEnginemethod setsconfig = (pos_file, None).
- engine_type = 'external'¶
- modify_velocities(system: System, vel_settings: dict[str, Any], rgen) tuple[float, float]¶
Modify the velocities of all particles.
- Parameters:
system (System) – The system whose particle velocities are to be modified.
vel_settings (dict) – A dict containing the key
'zero_momentum'(boolean): if true we reset the linear momentum to zero after generating velocities internally. A missing key means False, the[tis]default. This engine draws the velocities of aimless shooting and leaves their energy as drawn, so a soft perturbation (asigma_vthat is not negative) and a positiverescaleare refused before the draw.
- Returns:
tuple – A tuple containing:
dek: The change in kinetic energy as a result of the velocity modification.
kin_new: The new kinetic energy of the system.
- Raises:
NotImplementedError – If
vel_settingsselect a soft perturbation (refuse_soft_perturbation()) or an energy re-scale (refuse_energy_rescale()), or ascp2k_constraints()raises it.ValueError – As
cp2k_constraints()raises it.
Notes
The velocity components that the
FIXED_ATOMSsections of the CP2K input fix are set to zero in the velocities of the shooting point and in the drawn ones, before the momentum is set to zero, so the kinetic energies are those of the velocities that CP2K propagates. Withzero_momentum, the momentum of the components that move is set to zero (reset_free_momentum()). The constraints that CP2K imposes in the first time step (cp2k_constraints()) are left to CP2K.
- needs_order = True¶
- path_sampling_warnings() list[str]¶
Return why a path sampling with this engine is not exact.
The schemes of the CP2K input template that a path-sampling run integrates with and warns about (
cp2k_path_sampling_warnings()), for an engine that runs CP2K once for each piece of trajectory.- Returns:
list of strings – One warning per scheme, naming it, why the path sampling is not exact, and what to use instead; empty for an input without such a scheme.
- set_mdrun(md_items: dict[str, Any]) None¶
Set the execute directory of the move.
Overrides
EngineBase.set_mdrun(); the infinite-swapping scheduler (seecore.moves) calls this before each move to point the engine at the scratch directory of the move. CP2K requiresexe_dirto be present, so it is read as a required key:md_itemswithout one raisesKeyError.
- step(system, name)¶
Raise NotImplementedError: the streaming engine runs no single step.
CP2K is propagated via
_propagate_from(), and a kick of this engine runs throughExternalMDEngine.propagate()(supports_step_kick = False). This override refuses the single CP2K run ofCP2KEngineSteps.step().
- supports_step_kick = False¶
- pyretis.engines.cp2k.write_for_run_vel(infile: str | Path, outfile: str | Path, timestep: float, nsteps: int, subcycles: int, posfile: str, vel: ndarray, name: str = 'md_step', print_freq: int | None = None, seeds: dict[str, int | None] | None = None) None¶
Create input file to perform n steps.
Note, a single step actually consists of a number of subcycles. But from PyRETIS’ point of view, this is a single step. The run starts from the positions of the xyz file
posfile(cp2k_frame_update()) and from the velocitiesvel, and its SCF from CP2K’s initial guess (cp2k_cold_start()).- Parameters:
infile (str or Path) – Path to the input template to use.
outfile (str or Path) – Path to the input file to create.
timestep (float) – The time step to use for the simulation.
nsteps (int) – The number of PyRETIS steps to perform.
subcycles (int) – The number of sub-cycles to perform.
posfile (str) – The name of the xyz file to read positions from, in the folder of
outfile.vel (np.ndarray) – The velocities to set in the input.
name (str) – A name for the CP2K project.
print_freq (int, optional) – How often we should print to the trajectory file.
seeds (dict, optional) – The seeds of the run, as
cp2k_run_seeds()returns them, written byadd_cp2k_seeds(). None leaves the random numbers as the template sets them.
- Raises:
ValueError – As
cp2k_global_update()andcp2k_frame_update()raise it.NotImplementedError – As
cp2k_frame_update()raises it.FileExistsError – As
cp2k_cold_start()raises it.
pyretis.engines.cp2k_steps module¶
A CP2K external MD integrator interface (relaunch / restart-chain).
This module defines the relaunch CP2K engine, selected by
class = "cp2k_steps". It advances CP2K one order-parameter point at a
time, relaunching the executable for each step and chaining the run
through previous.restart / previous.wfn files (the slower,
start-and-stop implementation; the canonical continuous engine, which
runs CP2K as a single persistent process and reads its trajectory
on-the-fly, lives in pyretis.engines.cp2k).
Important classes defined here¶
- CP2KEngineSteps (
CP2KEngineSteps) A class responsible for interfacing CP2K via relaunching.
- pyretis.engines.cp2k_steps.COLD_START_WFN = 'doesnotexist.wfn'¶
The wavefunction file that the first CP2K run of a leg, of a kick step and of an md task names (
WFN_RESTART_FILE_NAME), in place of a wavefunction file the template names. No file of this name is in the directory CP2K runs in (cp2k_cold_start()refuses one), so CP2K starts the SCF from its initial guess: the guess the template’sSCF_GUESSsets, and theATOMICguess forSCF_GUESS RESTART, for which CP2K warns that the file does not exist. No wavefunction is carried from one run to another; the relaunches of a leg or an md task continue its own trajectory fromprevious.wfn(write_for_continue()).
- class pyretis.engines.cp2k_steps.CP2KEngineSteps(cp2k, input_path, timestep, subcycles, extra_files=None, exe_path='/home/enrico/cache/twoway-retis/wt2/docs', seed=0, conf='initial.xyz', template='cp2k.inp', velocity_generation='maxwell')¶
Bases:
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) – The random generator that the seeds of each CP2K run are drawn on (cp2k_run_seeds()). The infinite-swapping scheduler replaces it with the random generator of each move.extra_files (list) – List of extra files which may be required to run CP2K.
temperature (float) – The temperature (K) the CP2K input states,
MOTION/MD TEMPERATURE(read_cp2k_temperatures()).beta (float) – The inverse temperature
1 / (k_B T)in 1/hartree, with the k_B of the engine,kb.engine_temperatures (object like
EngineTemperatures) – The temperatures read from the CP2K input.
- __init__(cp2k, input_path, timestep, subcycles, extra_files=None, exe_path='/home/enrico/cache/twoway-retis/wt2/docs', seed=0, conf='initial.xyz', template='cp2k.inp', velocity_generation='maxwell')¶
Set up the CP2K engine.
- Parameters:
cp2k (string) – The CP2K executable.
input_path (string) – The path to where the input files are stored.
timestep (float) – The time step used in the CP2K simulation.
subcycles (integer) – The number of steps each CP2K run is composed of.
extra_files (list) – List of extra files which may be required to run CP2K.
exe_path (string, optional) – The path on which the engine is executed.
seed (integer, optional) – A seed for the random number generator.
conf (string, optional) – The default configuration file (default is ‘initial.xyz’).
template (string, optional) – The CP2K input template (default is ‘cp2k.inp’).
velocity_generation (string, optional) – How shooting velocities are drawn.
"maxwell"(default) draws them in Python from a Maxwell-Boltzmann distribution via the injected random generator, using engine-level masses and the temperature of the CP2K input (so the draw does not require the system to carry masses). This mirrors thevelocity_generationknob of the GROMACS/LAMMPS engines.
- _ensure_velocity_setup()¶
Compute the engine-level masses on first use.
The masses are guessed from the initial-config atom types.
- _extract_frame(traj_file, idx, out_file)¶
Extract a frame from a trajectory file.
This method is used by self.dump_config when we are dumping from a trajectory file. It is not used if we are dumping from a single config file.
- Parameters:
traj_file (string) – The trajectory file to dump from.
idx (integer) – The frame number we look for.
out_file (string) – The file to dump to.
- static _find_backup_files(dirname)¶
Return backup-files in the given directory.
- static _input_folder(engine_settings)¶
Return the folder of the CP2K input of an engine section.
- Parameters:
engine_settings (dict) – The settings of the engine section, with
input_path.- Returns:
out (string) –
input_pathrelative toexe_path, the current directory when the section sets noexe_path.
- classmethod _input_template(engine_settings)¶
Return the CP2K input an engine section names.
The input is looked up as the engine looks it up when it is created: the file
cp2k_template()names, ininput_pathrelative toexe_path.- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (string) – The path of the CP2K input.
- classmethod _input_template_present(engine_settings)¶
Return whether an engine section names a CP2K input that is there.
- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (boolean) – True when the section sets
input_pathand that folder holds a file_input_template()can take (input_file_present()).
- _prepare_shooting_point(input_file)¶
Create initial configuration for a shooting move.
This creates a new initial configuration with random velocities.
Velocity generation runs internally (
modify_velocities()), so the engine does not call this method.- Parameters:
input_file (string) – The input configuration to generate velocities for.
- Returns:
output_file (string) – The name of the file created.
energy (dict) – The energy terms read from the CP2K energy file.
- _propagate_from(name, path, system, ens_set, msg_file, reverse=False)¶
Propagate with CP2K from the current system configuration.
Here, we assume that this method is called after the propagate() has been called in the parent. The parent is then responsible for reversing the velocities and also for setting the initial state of the system.
- Parameters:
name (string) – A name to use for the trajectory we are generating.
path (object like
PathBase) – This is the path we use to fill in phase-space points.system (object like
System) – The system to act on.ens_set (dict) – It contains the simulations info:
interfaces : list of floats These defines the interfaces for which we will check the crossing(s).
msg_file (object like
FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.reverse (boolean, optional) – If True, the system will be propagated backward in time.
- Returns:
success (boolean) – This is True if we generated an acceptable path.
status (string) – A text description of the current status of the propagation.
- Raises:
NotImplementedError – For a thermostat whose noise PyRETIS cannot seed (
refuse_unseeded_cp2k_noise()), before CP2K runs.FileExistsError – As
cp2k_cold_start()raises it, before CP2K runs.
- static _read_configuration(filename)¶
Read CP2K output configuration.
This method is used when we calculate the order parameter.
- Parameters:
filename (string) – The file to read the configuration from.
- Returns:
box (numpy.array) – The box dimensions if we manage to read it.
xyz (numpy.array) – The positions.
vel (numpy.array) – The velocities.
names (list of strings) – The atom names found in the file.
- _read_configuration_box_first(filename)¶
Read a configuration, with the box as its first item.
The methods of this class read a configuration with this method, which gives the items in the order of
_read_configuration()of this class, the box first. The streaming engine,CP2KEngine, inherits methods of this class, its MD run (integrate()) among them, and its_read_configurationreturns the box third: it overrides this method to give the box first.- Parameters:
filename (string) – The file to read the configuration from.
- Returns:
box (numpy.array) – The box dimensions if we manage to read it.
xyz (numpy.array) – The positions.
vel (numpy.array) – The velocities.
names (list of strings) – The atom names found in the file.
- _reverse_velocities(filename, outfile)¶
Reverse velocity in a given snapshot.
- Parameters:
filename (string) – The configuration to reverse velocities in.
outfile (string) – The output file for storing the configuration with reversed velocities.
- add_input_files(dirname)¶
Add required input files to a given directory.
- Parameters:
dirname (string) – The full path to where we want to add the files.
- property beta¶
Return the inverse temperature
1 / (k_B T)in 1/hartree.
- classmethod cp2k_template(engine_settings)¶
Return the name of the CP2K input the engine reads.
- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (string) – The
templateof the section,cp2k.inpwhen it sets none.
- default_units = 'cp2k'¶
- frame_cell()¶
Return the cell for a stored frame that records none.
CP2K’s
.xyzframes carry no cell; the cell is the one its input template defines.- Returns:
out (numpy.array or None) – The box
read_cp2k_box()reads from the CP2K input template.
- classmethod get_default_units(settings=None)¶
Return the default unit system for the CP2K engine.
- Parameters:
settings (dict, optional) – Full simulation settings or engine settings. This argument is ignored for the CP2K engine.
- Returns:
out (string) – The default unit system for the CP2K engine.
- classmethod input_path_sampling_problem(engine_settings)¶
Return why a path-sampling run cannot use a section’s CP2K input.
The input is looked up as
read_input_temperatures()looks it up, and is read aspath_sampling_problem()reads it (cp2k_path_sampling_problem()).- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (string or None) – The reason, or None when a path-sampling run can integrate with the input. None for a section without an input to read (
_input_template_present()): the run reports the missing input where it reads the temperature of the section (read_input_temperatures()) or creates the engine.- Raises:
ValueError – As
cp2k_path_sampling_problem()raises it.
- integrate(system, order_function, steps, thermo='full')¶
Propagate several integration steps.
This method will perform several integration steps using CP2K. It will also calculate the order parameter(s) and energy terms if requested. The first CP2K run starts its SCF from CP2K’s initial guess (
cp2k_cold_start()), also when an earlier md task left its files in the directory; the relaunches continue from the wavefunction of the previous one.- Parameters:
system (object like
System) – The system object gives the initial state for the integration.order_function (object like
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).
- Raises:
FileExistsError – As
cp2k_cold_start()raises it, before CP2K runs.
- modify_velocities(system, vel_settings=None, rgen=None)¶
Modify the velocities of the current state.
This method will modify the velocities of a time slice.
- Parameters:
system (object like
System) – System is used here since we need access to the particle list.vel_settings (dict, optional) – It contains info about the velocity settings:
sigma_v : numpy.array Negative values select aimless shooting. Zero or positive values set the standard deviation, one for each particle, for soft velocity perturbations.
zero_momentum : boolean If True, we reset the linear momentum to zero after generating. A missing key means False.
rescale : float In some NVE simulations, we may wish to re-scale the energy to a fixed value. If rescale is a float > 0, we will re-scale the energy (after modification of the velocities) to match the given float. The re-scale needs the potential energy of
system.
rgen (object like
RandomGenerator) – This is the random generator that will be used.
- Returns:
dek (float) – The change in the kinetic energy.
kin_new (float) – The new kinetic energy.
- Raises:
ValueError – If
rescaleis positive and the potential energy ofsystemis not known, or ascp2k_constraints()raises it.NotImplementedError – For constraints that PyRETIS cannot remove from the draw (
cp2k_constraints()andrefuse_projected_cp2k_constraints()).
Notes
The velocity components that the
FIXED_ATOMSsections of the CP2K input fix are set to zero in the velocities of the shooting point and in the drawn ones, before the momentum is set to zero and before the re-scale, so the kinetic energies are those of the velocities that CP2K propagates. Withzero_momentum, the momentum of the components that move is set to zero (reset_free_momentum()).
- path_sampling_problem()¶
Return why a path-sampling run cannot use this engine.
The ensemble and the thermostats of the CP2K input template (
cp2k_path_sampling_problem()): a path-sampling run refuses a deterministic thermostat or barostat that carries variables from one time step to the next, one without time reversibility, an ensemble whose cell changes in time, and thermostat noise that PyRETIS cannot seed.- Returns:
out (string or None) – The reason, naming the keyword and what to use instead, or None when a path-sampling run can use the engine.
- path_sampling_warnings()¶
Return why a path sampling with this engine is not exact.
The schemes of the CP2K input template that a path-sampling run integrates with and warns about (
cp2k_path_sampling_warnings()), for an engine that runs CP2K once for eachsubcyclessteps of a piece of trajectory.- Returns:
out (list of strings) – One warning per scheme, naming it, why the path sampling is not exact, and what to use instead; empty for an input without such a scheme.
- classmethod read_input_temperatures(engine_settings)¶
Read the temperature of the CP2K input of an engine section.
The input is looked up as the engine looks it up when it is created: the file
cp2k_template()names, ininput_pathrelative toexe_path.- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (object like
EngineTemperatures) – The temperatureread_cp2k_temperatures()reads.
- run_cp2k(input_file, proj_name)¶
Run the CP2K executable.
- Returns:
out (dict) – The files created by the run.
- step(system, name)¶
Perform a single step with CP2K.
Each call is a CP2K run of its own, which starts from the positions and velocities of
systemwith seeds drawn on the random generator of the engine, as the first run of a leg does: the state of a thermostat (the variables of a Nose-Hoover chain, the random number streams) starts anew at each call. The kick of an initiation (ExternalMDEngine.kick_across_middle()) draws all the velocities before each call.- Parameters:
system (object like
System) – The system we are integrating.name (string) – To name the output files from the CP2K step.
- Returns:
out (string) – The name of the output configuration, obtained after completing the step.
- Raises:
NotImplementedError – For a thermostat whose noise PyRETIS cannot seed (
refuse_unseeded_cp2k_noise()), before CP2K runs.FileExistsError – As
cp2k_cold_start()raises it, before CP2K runs.
- temperature_keys = 'MOTION/MD TEMPERATURE of the CP2K input'¶
- temperature_source = 'input'¶
- unmarked_section_temperature = True¶
- unmarked_system_temperature = True¶
- pyretis.engines.cp2k_steps.CP2K_ANNEALING_KEYWORDS = ('ANNEALING', 'ANNEALING_CELL')¶
The keywords of
MOTION%MDthat scale the velocities of the particles (ANNEALING) or of the cell (ANNEALING_CELL) by their value at every time step. The value 1, the default, scales nothing.
- pyretis.engines.cp2k_steps.CP2K_BAROSTAT_ENSEMBLES = ('NPT_I', 'NPT_IA', 'NPT_F', 'NPE_I', 'NPE_F')¶
The values of
MOTION%MD%ENSEMBLEwith a barostat, whose cell CP2K moves.
- pyretis.engines.cp2k_steps.CP2K_BAROSTAT_REASON = 'a barostat, whose box momentum CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store'¶
The reason a path-sampling run refuses an ensemble with a barostat.
- pyretis.engines.cp2k_steps.CP2K_BAROSTAT_THERMOSTAT = 'MOTION->MD->BAROSTAT->THERMOSTAT'¶
The thermostat section of the barostat, whose CSVR stream PyRETIS seeds.
- pyretis.engines.cp2k_steps.CP2K_CELL = 'FORCE_EVAL->SUBSYS->CELL'¶
The cell section of a CP2K input, whose
PERIODICkeyword (XYZ, the CP2K default, when it is absent) gives the directions in which the cell is periodic.
- pyretis.engines.cp2k_steps.CP2K_COORD = 'FORCE_EVAL->SUBSYS->COORD'¶
The section of a CP2K input that gives the names and the positions of the atoms.
- pyretis.engines.cp2k_steps.CP2K_COORD_FILE_KEYWORDS = (('FORCE_EVAL->SUBSYS->TOPOLOGY', 'COORD_FILE_NAME'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'COORD_FILE'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'COORD_FILE_FORMAT'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'COORDINATE'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'NUMBER_OF_ATOMS'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'NATOMS'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'NATOM'), ('FORCE_EVAL->SUBSYS->TOPOLOGY', 'USE_G96_VELOCITY'))¶
The keywords of
FORCE_EVAL%SUBSYS%TOPOLOGYthat read the system from a coordinate file, with the aliases of the CP2K input schema, in the form of theremove_keywordsargument ofupdate_cp2k_input: the name and the format of the file, the number of atoms of a file in theCP2Kformat and the velocities of aG96file.
- pyretis.engines.cp2k_steps.CP2K_COORD_FORMAT_KEYWORDS = ('COORD_FILE_FORMAT', 'COORDINATE')¶
The names of the
COORD_FILE_FORMATkeyword ofFORCE_EVAL%SUBSYS%TOPOLOGYin the CP2K input schema.
- pyretis.engines.cp2k_steps.CP2K_COORD_KEYWORDS = ('UNIT', 'SCALED')¶
The keywords of the
COORDsection of a CP2K input, which set how its lines give the positions.
- pyretis.engines.cp2k_steps.CP2K_CSVR_STREAM = 'Wiener process for Thermostat # 1'¶
The name of the CSVR stream in the record that PyRETIS writes.
- pyretis.engines.cp2k_steps.CP2K_FIXED_COMPONENTS = {'X': (0,), 'XY': (0, 1), 'XYZ': (0, 1, 2), 'XZ': (0, 2), 'Y': (1,), 'YZ': (1, 2), 'Z': (2,)}¶
The Cartesian components that each value of
COMPONENTS_TO_FIXof aFIXED_ATOMSsection fixes.
- pyretis.engines.cp2k_steps.CP2K_GLOBAL_KEYWORDS = {'PRINT_LEVEL': ('PRINT_LEVEL', 'IOLEVEL'), 'PROJECT': ('PROJECT_NAME', 'PROJECT'), 'RUN_TYPE': ('RUN_TYPE',)}¶
The keywords of
GLOBALthat PyRETIS sets in every CP2K input it writes, each with the names that the CP2K input schema gives it (PROJECTis an alias ofPROJECT_NAMEandIOLEVELofPRINT_LEVEL). The project names the files that PyRETIS reads after a run.
- pyretis.engines.cp2k_steps.CP2K_GLOBAL_REFUSED = {'OUTPUT_FILE_NAME': (('OUTPUT_FILE_NAME',), 'it names the output file of CP2K, and PyRETIS keeps the output of each run it starts'), 'PROGRAM_NAME': (('PROGRAM_NAME', 'PROGRAM'), 'PyRETIS runs the CP2K program only'), 'WALLTIME': (('WALLTIME', 'WALLTI'), 'it ends a run before the steps PyRETIS asks for')}¶
The keywords of
GLOBALthat PyRETIS refuses in a template, each with the names that the CP2K input schema gives it, and the reason.PROGRAM_NAMEis refused for a value other thanCP2K.
- pyretis.engines.cp2k_steps.CP2K_MD_TASKS = 'The md, md-nve and md-flux tasks accept it.'¶
What the md tasks do with an ensemble, a thermostat or a keyword that a path-sampling run refuses, in an input whose temperature the temperature reader reads (
read_cp2k_temperatures()), for the messages.
- pyretis.engines.cp2k_steps.CP2K_MOMENTUM_RESET_KEYWORDS = ('COMVEL_TOL', 'ANGVEL_TOL')¶
The keywords of
MOTION%MDthat set the velocity of the center of mass (COMVEL_TOL) or the angular momentum (ANGVEL_TOL) to zero when it exceeds their value. CP2K 2025.2 applies them at every time step whenever the input sets them, the value 0 included:COMVEL_TOLin every ensemble,ANGVEL_TOLwith a cell ofPERIODIC NONE. They change the velocities at the first step of a run from a frame with momentum (also inNVE), and at every step in which the forces or the thermostat change the momentum (LANGEVIN,AD_LANGEVIN,FIXED_ATOMS, in CP2K 2025.2).
- pyretis.engines.cp2k_steps.CP2K_PATH_SAMPLING_ADVICE = 'Use ENSEMBLE NVE, ENSEMBLE LANGEVIN, or ENSEMBLE NVT with a THERMOSTAT of TYPE CSVR and REGION GLOBAL.'¶
The thermostats and ensembles a path-sampling run integrates with.
- pyretis.engines.cp2k_steps.CP2K_PIECE_START = 'Each piece of trajectory that a path-sampling run generates starts CP2K from a stored frame, its positions and velocities: the variables that a thermostat or a barostat carries from one time step to the next start anew with each piece. A path-sampling run refuses the deterministic schemes with such variables or without time reversibility, and the ensembles whose cell changes in time.'¶
What a path-sampling run does with the state of a thermostat or a barostat, and the schemes it refuses.
- pyretis.engines.cp2k_steps.CP2K_POSITION_FORMATS = ('OFF', 'XYZ')¶
The values of
COORD_FILE_FORMATthat give CP2K the names and the positions of the atoms only:XYZreads an xyz file, andOFF, the default, reads theCOORDsection.
- pyretis.engines.cp2k_steps.CP2K_PROJECTED_CONSTRAINTS = ('COLLECTIVE', 'G3X3', 'G4X6', 'HBONDS', 'VIRTUAL_SITE')¶
The sections of
MOTION->CONSTRAINTwhose constraints CP2K imposes on the velocities in the first time step of a run.
- pyretis.engines.cp2k_steps.CP2K_REAL = re.compile('[+-]?(\\d+\\.?\\d*|\\.\\d+)([eEdD][+-]?\\d+)?')¶
A real number of a CP2K input, in Fortran notation.
- pyretis.engines.cp2k_steps.CP2K_REFUSED_ENSEMBLES = {'HYDROSTATICSHOCK': 'a shock scheme, whose cell velocity CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'MSST': 'a shock scheme, whose cell velocity CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'MSST_DAMPED': 'a shock scheme, whose cell velocity CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store, and a friction without time reversibility', 'NPE_F': 'a barostat, whose box momentum CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'NPE_I': 'a barostat, whose box momentum CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'NPT_F': 'a barostat, whose box momentum CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'NPT_I': 'a barostat, whose box momentum CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'NPT_IA': 'a barostat, whose box momentum CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store', 'NVT_ADIABATIC': 'Nose-Hoover chains on the fast and the slow degrees of freedom, whose variables CP2K carries from one time step to the next', 'REFTRAJ': 'which reads the frames of a reference trajectory and integrates no dynamics'}¶
The values of
MOTION%MD%ENSEMBLEthat a path-sampling run refuses, with the reason.
- pyretis.engines.cp2k_steps.CP2K_RESCALING_ENSEMBLES = {'ANNEALING_CELL': ('NPT_I', 'NPT_IA', 'NPT_F', 'NPE_I', 'NPE_F'), 'MOTION->MD->ADIABATIC_DYNAMICS': ('NVT_ADIABATIC',), 'MOTION->MD->BAROSTAT': ('NPT_I', 'NPT_IA', 'NPT_F', 'NPE_I', 'NPE_F')}¶
The sections of
CP2K_TEMP_TOL_KEYWORDSand the keywords ofCP2K_ANNEALING_KEYWORDSthat CP2K applies in some ensembles only, with these ensembles. In the other ensembles they take no effect. CP2K applies the others in every ensemble, and theTEMP_TOLofMOTION%MD%SHELLto the shells of a shell model.
- pyretis.engines.cp2k_steps.CP2K_SEEDED_THERMOSTAT = 'MOTION->MD->THERMOSTAT'¶
The thermostat section of the particles, whose CSVR stream PyRETIS seeds.
- pyretis.engines.cp2k_steps.CP2K_SEED_MAX = 2147483646¶
The largest seed that PyRETIS writes into a CP2K input. CP2K sets the six integers of the state of a random number stream from a single seed, and these integers stay below 4294944443.
- pyretis.engines.cp2k_steps.CP2K_SHELL_MODEL = 'FORCE_EVAL->MM->FORCEFIELD->SHELL'¶
The section of a CP2K input that gives atoms a shell (a shell model).
- pyretis.engines.cp2k_steps.CP2K_SHELL_THERMOSTAT = 'MOTION->MD->SHELL->THERMOSTAT'¶
The thermostat section of the shells of a shell model.
- pyretis.engines.cp2k_steps.CP2K_SHOCK_REASON = 'a shock scheme, whose cell velocity CP2K carries from one time step to the next, with a cell that changes in time, which a frame does not store'¶
The reason a path-sampling run refuses a shock ensemble.
- pyretis.engines.cp2k_steps.CP2K_TEMP_TOL_KEYWORDS = (('MOTION->MD', ('TEMP_TOL', 'TEMP_TO', 'TEMPERATURE_TOLERANCE')), ('MOTION->MD->THERMAL_REGION->DEFINE_REGION', ('TEMP_TOL',)), ('MOTION->MD->SHELL', ('TEMP_TOL',)), ('MOTION->MD->BAROSTAT', ('TEMP_TOL',)), ('MOTION->MD->ADIABATIC_DYNAMICS', ('TEMP_TOL_FAST', 'TEMP_TOL_SLOW')))¶
The keywords of a CP2K input that rescale velocities to a target temperature when the temperature deviates from it by more than their value, with the names that the CP2K input schema gives them. The value 0, the default, rescales nothing.
- pyretis.engines.cp2k_steps.CP2K_THERMAL_REGION = 'MOTION->MD->THERMAL_REGION'¶
The section of a CP2K input whose logical keyword
FORCE_RESCALINGmakes CP2K rescale, at the start of each of its runs, the velocities of the atoms of everyDEFINE_REGIONto theTEMPERATUREof the region (CP2K 2025.2: with the velocities of the input and with those of anEXT_RESTARTfile).
- pyretis.engines.cp2k_steps.CP2K_THERMOSTATTED_BAROSTAT_ENSEMBLES = ('NPT_F', 'NPT_I', 'NPT_IA')¶
The values of
MOTION%MD%ENSEMBLEwhose barostat CP2K couples to the thermostat ofCP2K_BAROSTAT_THERMOSTAT.
- pyretis.engines.cp2k_steps.CP2K_THERMOSTAT_SECTIONS = ('MOTION->MD->THERMOSTAT', 'MOTION->MD->SHELL->THERMOSTAT')¶
those of the particles and of the shells.
- Type:
The thermostat sections of a CP2K input with a
REGION
- pyretis.engines.cp2k_steps.CP2K_TOPOLOGY = 'FORCE_EVAL->SUBSYS->TOPOLOGY'¶
The section of a CP2K input that describes the topology.
- pyretis.engines.cp2k_steps.CP2K_WFN_RESTART_KEYWORDS = (('FORCE_EVAL->DFT', 'RESTART_FILE_NAME'), ('FORCE_EVAL->DFT', 'WFN_RESTART_FILE_NAME'))¶
The keywords of
FORCE_EVAL%DFTthat name the wavefunction file of the SCF guess (RESTART_FILE_NAMEis an alias ofWFN_RESTART_FILE_NAME), in the form of theremove_keywordsargument ofupdate_cp2k_input.
- pyretis.engines.cp2k_steps._cp2k_cell_periodic(nodes)¶
Return whether the cell of a CP2K input is periodic.
- Parameters:
nodes (list of objects like
SectionNode) – The root sections of the CP2K input.- Returns:
out (boolean) – False when a section
CP2K_CELLsetsPERIODIC NONE; True otherwise (XYZ, the CP2K default, or a cell periodic in some directions).
- pyretis.engines.cp2k_steps._cp2k_md_tasks(template)¶
Return what the md tasks do with a CP2K input path sampling refuses.
The
md,md-nveandmd-fluxtasks read the temperature of the CP2K input withread_cp2k_temperatures()and take the one temperature it holds, which decides the sentence (md_tasks_sentence()).- Parameters:
template (string) – The CP2K input file.
- Returns:
out (string) – A sentence that says that every task refuses the input, with the reason, for an input the reader refuses or that holds no temperature; else
CP2K_MD_TASKS.
- pyretis.engines.cp2k_steps._refused_ensemble(nodes, template)¶
Return why a path-sampling run refuses the ensemble of a CP2K input.
- Parameters:
nodes (list of objects like
SectionNode) – The root sections of the CP2K input.template (string) – The CP2K input file, for the message.
- Returns:
out (string or None) – The ensemble or the thermostat and why the run refuses it, or None for an ensemble the run integrates with.
- pyretis.engines.cp2k_steps._refused_force_rescaling(nodes, template)¶
Return why a path-sampling run refuses the region rescaling of CP2K.
- Parameters:
nodes (list of objects like
SectionNode) – The root sections of the CP2K input.template (string) – The CP2K input file, for the message.
- Returns:
out (string or None) – Why the run refuses
FORCE_RESCALINGofCP2K_THERMAL_REGIONgiven without a value or with a value that CP2K reads as true (cp2k_logical()), or None for an input that does not set it on.
- pyretis.engines.cp2k_steps._refused_momentum_reset(nodes, template)¶
Return why a path-sampling run refuses a momentum reset of CP2K.
- Parameters:
nodes (list of objects like
SectionNode) – The root sections of the CP2K input.template (string) – The CP2K input file, for the message.
- Returns:
out (string or None) – Why the run refuses a keyword of
CP2K_MOMENTUM_RESET_KEYWORDSthat CP2K applies:COMVEL_TOLwith any value,ANGVEL_TOLwith any value and a cell ofPERIODIC NONE; None for an input without them.
- pyretis.engines.cp2k_steps._refused_rescaling(nodes, template)¶
Return why a path-sampling run refuses a velocity rescaling of CP2K.
- Parameters:
nodes (list of objects like
SectionNode) – The root sections of the CP2K input.template (string) – The CP2K input file, for the message.
- Returns:
out (string or None) – The keyword and why the run refuses it, or None for an input whose velocities CP2K does not rescale. A keyword counts in the ensembles in which CP2K applies it (
CP2K_RESCALING_ENSEMBLES), and theTEMP_TOLofMOTION%MD%SHELLwith a shell model.- Raises:
ValueError – As
cp2k_real()raises it.
- pyretis.engines.cp2k_steps._refused_shell_thermostat(nodes, template)¶
Return why a path-sampling run refuses the shell thermostat of CP2K.
- Parameters:
nodes (list of objects like
SectionNode) – The root sections of the CP2K input.template (string) – The CP2K input file, for the message.
- Returns:
out (string or None) – Why the run refuses a Nose-Hoover thermostat of the shells of a shell model, or None.
- pyretis.engines.cp2k_steps._rescaling_applies(key, ensemble)¶
Return whether CP2K applies a velocity rescaling in an ensemble.
- Parameters:
key (string) – A section of
CP2K_TEMP_TOL_KEYWORDSor a keyword ofCP2K_ANNEALING_KEYWORDS, in upper case.ensemble (string) – The value of
MOTION%MD%ENSEMBLE, in upper case.
- Returns:
out (boolean) – True when CP2K applies the rescaling in the ensemble.
- pyretis.engines.cp2k_steps.add_cp2k_seeds(to_update, remove, seeds)¶
Add the seeds of a run to the changes that make its CP2K input.
GLOBAL%SEEDseeds the random numbers of CP2K itself, among them the initial state of a Nose-Hoover thermostat;FORCE_EVAL%SUBSYS% SEEDseeds the streams of the particles, which the Langevin ensemble and the AD_LANGEVIN thermostat draw from. AnRNG_INITsection ofFORCE_EVAL%SUBSYSholds the states of these streams and takes precedence over the seed, so it is removed. A CSVR thermostat of the particles or of the barostat draws from the stream of theRNG_INITrecord that replaces the one of its section; the sections of the record are added to an input that lacks them. TheSEEDkeyword ofFORCE_EVAL%SUBSYSis set and the other lines and the other subsections of that section are kept;SEEDis set in theGLOBALkeywords ofto_update, where it replaces theSEEDof the template.- Parameters:
to_update (dict) – The updates of the input, as
update_cp2k_input()takes them, with aGLOBALentry whose data is a dict of keywords and values (cp2k_global_update()). The entries are added in place.remove (list of strings) – The sections that the input removes, added to in place.
seeds (dict) – The seeds, as
cp2k_run_seeds()returns them. Onlyglobalis required; a missing or Nonesubsys,csvrorbarostatleaves the corresponding settings as they are.
- pyretis.engines.cp2k_steps.cp2k_barostat_thermostat_type(nodes)¶
Return the type of the thermostat of the barostat of a CP2K run.
CP2K couples the barostat of the ensembles of
CP2K_THERMOSTATTED_BAROSTAT_ENSEMBLESto the thermostat ofCP2K_BAROSTAT_THERMOSTAT, whoseTYPEdefaults toSAME_AS_PARTICLE: the type of the thermostat of the particles,CP2K_SEEDED_THERMOSTAT, whoseTYPEdefaults toNOSE. The ensemble defaults toNVE. Without aMOTION%MD%BAROSTATsection CP2K stops on such an ensemble, and PyRETIS gives it no thermostat of the barostat, so that the seeds never add the section and a pressure and time constant of CP2K that the template does not set.A path-sampling run refuses these ensembles before it starts (
cp2k_path_sampling_problem()), and the md tasks run CP2K with the seeds of the input (CP2KEngineSteps.integrate()): the seed of a CSVR thermostat of the barostat reaches the CP2K runs that a program starts through the engine itself, withpropagateorstep.- Parameters:
nodes (list of objects like
SectionNode) – The root sections of the CP2K input.- Returns:
out (string or None) – The type of the thermostat of the barostat, in upper case, or None for an ensemble without one and for an input without a
MOTION%MD%BAROSTATsection.
- pyretis.engines.cp2k_steps.cp2k_cold_start(infile, outfile)¶
Return the update that starts the SCF of a CP2K run anew.
The first CP2K run of a leg, of a kick step and of an md task starts the SCF from CP2K’s initial guess, whatever ran before it: the input names
COLD_START_WFNas its wavefunction file (WFN_RESTART_FILE_NAMEofFORCE_EVAL%DFT), and the caller removes the wavefunction keywords of the template (CP2K_WFN_RESTART_KEYWORDS). Without that keyword, a template withSCF_GUESS RESTARTwould read<project>-RESTART.wfnof the directory, which an earlier run of the same project may have left there.- Parameters:
infile (string) – The input template.
outfile (string) – The input file to create, in the directory CP2K runs in.
- Returns:
out (dict) – The
FORCE_EVAL->DFTnode of theupdateargument ofupdate_cp2k_input(), applied only to a template with aFORCE_EVAL%DFTsection.- Raises:
FileExistsError – For a template with a
FORCE_EVAL%DFTsection, if the directory ofoutfileholds a file namedCOLD_START_WFN: CP2K would start the SCF from it.
- pyretis.engines.cp2k_steps.cp2k_constraints(template, natoms)¶
Return the velocity components that the constraints of CP2K remove.
CP2K sets the velocity components that a
FIXED_ATOMSsection ofMOTION->CONSTRAINTfixes to zero before the first time step of a run, and imposes the constraints of the sections ofCP2K_PROJECTED_CONSTRAINTSon the velocities in the first time step. A section with aRESTRAINTsubsection is a restraint and removes no velocity component.- Parameters:
template (string) – The CP2K input file.
natoms (integer) – The number of atoms of the system.
- Returns:
fixed (numpy.array of booleans or None) – For each atom (row) and Cartesian component (column), True if a
FIXED_ATOMSsection fixes the component; None when no component is fixed.projected (list of strings) – The titles, in alphabetical order, of the sections of
CP2K_PROJECTED_CONSTRAINTSthat the input holds without aRESTRAINTsubsection.
- Raises:
NotImplementedError – As
read_cp2k_fixed_atoms()raises it.ValueError – As
read_cp2k_fixed_atoms()raises it.
- pyretis.engines.cp2k_steps.cp2k_continue_topology(template)¶
Return the changes of the topology of a continuation.
A continuation (
write_for_continue()) takes the positions and the velocities from itsEXT_RESTARTfile. For a coordinate file of a format ofCP2K_POSITION_FORMATS, which gives the names and the positions of the atoms only, the keywords ofCP2K_COORD_FILE_KEYWORDS, which read it, are removed. A coordinate file of another format gives more, among it the elements and the charges of a PDB file, and is kept: CP2K reads the names and the positions of theCOORDsection of theEXT_RESTARTfile in place of those of the file, and onlyUSE_G96_VELOCITYis removed. TheCENTER_COORDINATESsection, which moves the positions of a run before its first step, is removed, as the positions of a continuation are those of the run it continues. The other keywords and the subsections ofFORCE_EVAL%SUBSYS%TOPOLOGYare kept, among them the connectivity (CONN_FILE_NAME,CONN_FILE_FORMATand theGENERATEandMOL_SETsections) and the exclusions, so the continuation evaluates the force field of the run it continues. A topology section left without a keyword and without a subsection is removed, which gives the defaults of the section.- Parameters:
template (string) – The CP2K input file.
- Returns:
remove (list of strings) – The sections that the continuation removes, in the form of the
removeargument ofupdate_cp2k_input().remove_keywords (list of tuples of strings) – The lines of the topology that the continuation removes, in the form of the
remove_keywordsargument ofupdate_cp2k_input().
- Raises:
NotImplementedError – If the template has more than one
FORCE_EVAL%SUBSYS%TOPOLOGYsection, whose topologies a continuation cannot tell apart.
- pyretis.engines.cp2k_steps.cp2k_coord_columns(section)¶
Return the words after the position of the atoms of a section.
- Parameters:
section (object like
SectionNode) – AFORCE_EVAL%SUBSYS%COORDsection.- Returns:
out (list of lists of strings) – For each line of the section that gives an atom, the words after its fourth: the name of its molecule and of its residue. The lines of
CP2K_COORD_KEYWORDSgive no atom.
- pyretis.engines.cp2k_steps.cp2k_coordinate_data(template)¶
Describe what the coordinates of a template give beyond positions.
CP2K builds the atoms of a run from the coordinate file of
FORCE_EVAL%SUBSYS%TOPOLOGYand from theCOORDsection. A file of a format other than those ofCP2K_POSITION_FORMATSis read by a reader of its own and gives more than the names and the positions of the atoms, such as the elements, the residue and molecule names, and the charges thatCHARGE_EXTENDED,CHARGE_OCCUPandCHARGE_BETAread from a PDB file. A line of theCOORDsection with more than four words gives the molecule and the residue of its atom.- Parameters:
template (string) – The CP2K input file.
- Returns:
out (list of strings) – A description of each part of the coordinates of the template that gives more than the names and the positions of the atoms; empty when there is none.
- pyretis.engines.cp2k_steps.cp2k_coordinate_format(section)¶
Return the format of the coordinate file of a topology section.
- Parameters:
section (object like
SectionNode) – AFORCE_EVAL%SUBSYS%TOPOLOGYsection.- Returns:
out (string) – The value, in upper case, of the last line of the section that sets
COORD_FILE_FORMATunder one of its names (CP2K_COORD_FORMAT_KEYWORDS);OFF, the default of CP2K, when no line sets it.
- pyretis.engines.cp2k_steps.cp2k_draw_constraints(template, natoms, vel_settings)¶
Return the fixed velocity components for a draw, or refuse it.
- Parameters:
template (string) – The CP2K input file.
natoms (integer) – The number of atoms of the system.
vel_settings (dict) – The velocity settings handed to
modify_velocities.
- Returns:
out (numpy.array of booleans or None) – The fixed components, as
cp2k_constraints()returns them.- Raises:
NotImplementedError – As
cp2k_constraints()andrefuse_projected_cp2k_constraints()raise it.ValueError – As
cp2k_constraints()raises it.
- pyretis.engines.cp2k_steps.cp2k_frame_coord(template, frame)¶
Return the lines of a
COORDsection that give a frame.- Parameters:
template (string) – The CP2K input file the input is made from.
frame (string) – The xyz file of the frame.
- Returns:
out (list of strings) – For each atom of the frame, its name, its position and the words after the fourth of the line of the template’s
COORDsection for the atom (cp2k_coord_columns()).- Raises:
ValueError – If the
COORDsection of the template gives a number of atoms other than that of the frame, or the frame holds no configuration or a configuration of no atoms.
- pyretis.engines.cp2k_steps.cp2k_frame_update(template, outfile, posfile)¶
Return the changes of an input that starts a run from a frame.
The frame is the xyz file
posfilein the folder of the inputoutfile, where CP2K runs. For a template whose coordinates give the names and the positions of the atoms only (cp2k_coordinate_data()finds nothing more), the frame is the coordinate file ofFORCE_EVAL%SUBSYS%TOPOLOGY, in theXYZformat: the lines of the template that set a keyword ofCP2K_COORD_FILE_KEYWORDS, under any of its names, are removed,COORD_FILE_NAMEandCOORD_FILE_FORMATare set, and theCOORDsection is removed. For another template, the topology keeps its coordinate file, and theCOORDsection is replaced by a line for each atom of the frame: its name, its position, and the words after the fourth of the line of the template’sCOORDsection for the atom. CP2K reads the names and the positions of theCOORDsection in place of those of the coordinate file, and the rest of the coordinate file as the template gives it.USE_G96_VELOCITYis removed, so the velocities of the run are those of the input.- Parameters:
template (string) – The CP2K input file the input is made from.
outfile (string) – The input that is made.
posfile (string) – The name of the frame in the folder of
outfile.
- Returns:
update (dict) – The changes of
FORCE_EVAL%SUBSYS, in the form of entries of theupdateargument ofupdate_cp2k_input().remove (list of strings) – The sections that the input removes, in the form of the
removeargument ofupdate_cp2k_input().remove_keywords (list of tuples of strings) – The lines that the input removes, in the form of the
remove_keywordsargument ofupdate_cp2k_input().
- Raises:
NotImplementedError – If a template whose coordinates give more than the names and the positions of the atoms has more than one
FORCE_EVAL%SUBSYS%TOPOLOGYorFORCE_EVAL%SUBSYS%COORDsection.ValueError – If the
COORDsection of such a template gives a number of atoms other than that of the frame, and asrefuse_cp2k_replicated_topology()andrefuse_unread_cp2k_cell()raise it.
- pyretis.engines.cp2k_steps.cp2k_global_update(template, name)¶
Return the changes of the
GLOBALsection of a CP2K input.PyRETIS sets the keywords of
CP2K_GLOBAL_KEYWORDS: the projectname,RUN_TYPE MDandPRINT_LEVEL LOW. The lines of the template that set them, under any of their names, are removed, and the other keywords and the subsections ofGLOBALare kept as the template sets them.- Parameters:
template (string) – The CP2K input file the input is made from.
name (string) – The name of the CP2K project.
- Returns:
update (dict) – The update of
GLOBAL, in the form of an entry of theupdateargument ofupdate_cp2k_input(), whose data is a dict of keywords and values.remove_keywords (list of tuples of strings) – The lines of
GLOBALthat set the keywords of PyRETIS, in the form of theremove_keywordsargument ofupdate_cp2k_input().
- Raises:
ValueError – If the
GLOBALsection of the template sets a keyword ofCP2K_GLOBAL_REFUSED.
- pyretis.engines.cp2k_steps.cp2k_has_dft(template)¶
Tell whether a CP2K input has a
FORCE_EVAL%DFTsection.CP2K writes a wavefunction file (
<project>-RESTART.wfn) for a force evaluation with aDFTsection, and the relaunches of a leg start the SCF from it.- Parameters:
template (string) – The CP2K input file.
- Returns:
out (boolean) – True if the input has a
FORCE_EVAL%DFTsection.
- pyretis.engines.cp2k_steps.cp2k_keyword(section, keyword)¶
Return the value that a section of a CP2K input gives a keyword.
- Parameters:
section (object like
SectionNode) – The section to read.keyword (string) – The keyword, in upper case.
- Returns:
out (string or None) – The words after the keyword on the last line of the section that sets it, without a comment that starts with
#or!; an empty string for a keyword given without a value, and None when no line sets the keyword.
- pyretis.engines.cp2k_steps.cp2k_keyword_values(section, names)¶
Return every line of a CP2K section that sets a keyword.
- Parameters:
section (object like
SectionNode) – The section to read.names (tuple of strings) – The names of the keyword, in upper case.
- Returns:
out (list of tuples of strings) – For each line that sets the keyword, in the order of the lines, the name the line gives it and the words after the name, without a comment that starts with
#or!.
- pyretis.engines.cp2k_steps.cp2k_logical(value)¶
Return the truth of a logical keyword of a CP2K input.
- Parameters:
value (string or None) – The value
cp2k_keyword()returns for the keyword.- Returns:
out (boolean) – False for a keyword that is absent; True for a keyword given without a value, or with one of the values that CP2K reads as true.
- pyretis.engines.cp2k_steps.cp2k_md_ensemble(nodes)¶
Return the ensemble of the MD of a CP2K input.
- Parameters:
nodes (list of objects like
SectionNode) – The root sections of the CP2K input.- Returns:
out (string) – The value of
MOTION%MD%ENSEMBLE, in upper case, on the last line that sets it, andNVE, CP2K’s default, when no line sets it.
- pyretis.engines.cp2k_steps.cp2k_noise_problem(nodes, template)¶
Return why PyRETIS cannot seed the thermostat noise of a CP2K input.
CP2K seeds the streams of CSVR and GLE thermostats with a fixed seed that no input keyword sets, and reads a different state from the
RNG_INITsection of the thermostat type, with one record for each thermostat. PyRETIS writes that record for the CSVR thermostat ofCP2K_SEEDED_THERMOSTATwithREGION GLOBAL, the one thermostat of the particles, and for a CSVR thermostat of the barostat (cp2k_barostat_thermostat_type()), one thermostat. A CSVR thermostat with another region, a CSVR thermostat ofMOTION%MD%SHELLand a GLE thermostat would draw the same noise in each run.- Parameters:
nodes (list of objects like
SectionNode) – The root sections of the CP2K input.template (string) – The CP2K input file, for the message.
- Returns:
out (string or None) – The reason, naming the thermostat and what to use instead, or None when PyRETIS seeds the noise of every thermostat.
- pyretis.engines.cp2k_steps.cp2k_path_sampling_problem(template)¶
Return why a path-sampling run cannot integrate with a CP2K input.
A path-sampling run refuses a deterministic thermostat or barostat that carries variables from one time step to the next, and one without time reversibility: the ensembles of
CP2K_REFUSED_ENSEMBLES,ENSEMBLE NVTwith a thermostat ofTYPE NOSE(CP2K’s defaultTYPE) and without aTHERMOSTATsection, on which CP2K stops, a velocity rescaling ofCP2K_TEMP_TOL_KEYWORDS(a value other than 0) or ofCP2K_ANNEALING_KEYWORDS(a value other than 1) in an ensemble in which CP2K applies it,FORCE_RESCALINGofCP2K_THERMAL_REGIONon, a keyword ofCP2K_MOMENTUM_RESET_KEYWORDSthat CP2K applies, and a thermostat ofTYPE NOSEof the shells of a shell model. It refuses thermostat noise that PyRETIS cannot seed (cp2k_noise_problem()). The input is read as the engines read it (read_cp2k_template()). The refusal of a scheme ends with what the md tasks do with the input, as its temperature reader decides (_cp2k_md_tasks()).- Parameters:
template (string) – The CP2K input file.
- Returns:
out (string or None) – The reason, naming the keyword and what to use instead, or None when a path-sampling run can integrate with the input.
- Raises:
ValueError – As
cp2k_real()andread_cp2k_template()raise it.Exception – As
read_cp2k_temperatures()raises it for a refused scheme, other than itsValueError.
- pyretis.engines.cp2k_steps.cp2k_path_sampling_warnings(template, relaunch)¶
Return the schemes of a CP2K input that make path sampling inexact.
A path-sampling run integrates with these schemes and warns about each: a thermostat of
TYPE AD_LANGEVINinENSEMBLE NVT, whose friction restarts with each piece of trajectory; and the schemes that change the start of each piece: aMOTION%MD%CASCADEsection that is on, which CP2K applies at the start of each of its runs, also of a run that continues from a restart file, and a shell model (CP2K_SHELL_MODEL), whose shells a frame does not store. The velocities of each piece are given in the input, and CP2K applies noMOTION%MD%VELOCITY_SOFTENINGto given velocities.- Parameters:
template (string) – The CP2K input file.
relaunch (boolean) – True for the relaunch engine, which runs CP2K once for each
subcyclessteps of a piece; False for the streaming engine, which runs CP2K once for each piece.
- Returns:
out (list of strings) – One warning per scheme, naming it, why the path sampling is not exact, and what to use instead.
- Raises:
ValueError – As
cp2k_real()andread_cp2k_template()raise it.
- pyretis.engines.cp2k_steps.cp2k_real(value, template, keyword)¶
Return the number of a real keyword of a CP2K input.
- Parameters:
value (string) – The words after the keyword: an optional unit tag, as
[K], and the number, in Fortran notation.template (string) – The CP2K input file, for the message.
keyword (string) – The keyword with its section, as
MOTION%MD%TEMP_TOL, for the message.
- Returns:
out (float) – The number, in the unit of the tag.
- Raises:
ValueError – If the words are not one number after the unit tag.
- pyretis.engines.cp2k_steps.cp2k_rng_record(name, seed)¶
Return a CP2K record of a Gaussian random number stream.
A record of an
RNG_INITsection gives the state of a stream: its name (40 characters), its distribution (1, Gaussian), whether it draws antithetic numbers, whether it draws in extended precision, whether its buffer is filled, the buffer, and the six integers of each of its current state and of the starts of the stream and of its substream. This record sets the eighteen integers toseed, as CP2K sets the six integers of a stream from a single value of aSEEDkeyword, for a stream in extended precision with an empty buffer, the streams of the CSVR thermostat.- Parameters:
name (string) – The name of the stream, at most 40 characters.
seed (integer) – The seed, in
[1, CP2K_SEED_MAX].
- Returns:
out (string) – The record.
- pyretis.engines.cp2k_steps.cp2k_run_seeds(template, rgen)¶
Draw the seeds of a CP2K run that starts from a phase point.
- Parameters:
template (string) – The CP2K input file the run is made from.
rgen (object like
RandomGeneratoror numpy.random.Generator) – The random generator of the engine.
- Returns:
out (dict) – The seed of
GLOBAL%SEED(global), ofFORCE_EVAL%SUBSYS%SEED(subsys), of the random generator that draws theGLOBAL%SEEDof each relaunch of the relaunch engine (relaunch), of the stream of a CSVR thermostat of the particles (csvr; None without one) and of the stream of a CSVR thermostat of the barostat (barostat; None without one), drawn in this order onrgen. The streaming engine draws the same seeds and does not userelaunch, so both engines draw the same seeds for each leg.- Raises:
NotImplementedError – As
refuse_unseeded_cp2k_noise()raises it.
- pyretis.engines.cp2k_steps.cp2k_sections(nodes, target)¶
Return the sections of a CP2K input at a path of section titles.
- Parameters:
nodes (list of objects like
SectionNode) – The root sections, asread_cp2k_template()returns them.target (string) – The path of the sections, on the form
root->section->subsection.
- Returns:
out (list of objects like
SectionNode) – Every section attarget, also when several sections share the path.
- pyretis.engines.cp2k_steps.cp2k_thermostat_type(nodes, target)¶
Return the type of a thermostat section of a CP2K input.
- Parameters:
nodes (list of objects like
SectionNode) – The root sections of the CP2K input.target (string) – The path of the thermostat section, as
CP2K_SEEDED_THERMOSTAT.
- Returns:
out (string or None) – The value of
TYPE, in upper case, on the last line that sets it, andNOSE, CP2K’s default, for a section that does not set it; None for an input without the section.
- pyretis.engines.cp2k_steps.draw_cp2k_seed(rgen)¶
Draw a seed for a CP2K random number stream.
- Parameters:
rgen (object like
RandomGeneratoror numpy.random.Generator) – The random generator of the engine.- Returns:
out (integer) – A seed in
[1, CP2K_SEED_MAX].
- pyretis.engines.cp2k_steps.finish_cp2k_draw(vel, mass, fixed, zero_momentum)¶
Remove from drawn velocities what a CP2K run would not keep.
The velocity components that
fixedmarks are set to zero, as CP2K sets them before it propagates. Withzero_momentum, the linear momentum is then set to zero: of all the atoms without fixed components, and of the components that move (reset_free_momentum()) with them.- Parameters:
vel (numpy.array) – The drawn velocities, one row per atom.
mass (numpy.array) – The masses, one row per atom.
fixed (numpy.array of booleans or None) – The fixed components, as
cp2k_constraints()returns them.zero_momentum (boolean) – If True, the linear momentum is set to zero.
- Returns:
out (numpy.array) – The velocities.
- pyretis.engines.cp2k_steps.guess_particle_mass(particle_no, particle_type)¶
Guess a particle mass from its type and convert to CP2K units.
- Parameters:
particle_no (integer) – The particle number. Only used for the logger message.
particle_type (string) – The particle type as a string; an element of the periodic table.
- Returns:
out (float) – The guessed particle mass in the engine’s internal units.
- pyretis.engines.cp2k_steps.has_cp2k_restraint(section)¶
Return True if a constraint section of a CP2K input is a restraint.
A constraint section of
MOTION->CONSTRAINTwith aRESTRAINTsubsection adds a restraint potential, and CP2K leaves the velocities as they are.- Parameters:
section (object like
SectionNode) – The constraint section.- Returns:
out (boolean) – True if the section has a
RESTRAINTsubsection.
- pyretis.engines.cp2k_steps.read_cp2k_atom_list(section, natoms, template)¶
Return the atoms that the
LISTkeywords of a section select.- Parameters:
section (object like
SectionNode) – AFIXED_ATOMSsection.natoms (integer) – The number of atoms of the system.
template (string) – The CP2K input, as the error messages name it.
- Returns:
out (list of integers) – The indices of the atoms, counted from zero, of every
LISTline of the section. An entrya..bselects the atomsatob, counted from one as CP2K counts them.- Raises:
ValueError – If an entry is neither an atom index nor a range of them, or selects an atom outside
1tonatoms.
- pyretis.engines.cp2k_steps.read_cp2k_fixed_atoms(section, natoms, template)¶
Return the velocity components that a FIXED_ATOMS section fixes.
- Parameters:
section (object like
SectionNode) – AFIXED_ATOMSsection ofMOTION->CONSTRAINT.natoms (integer) – The number of atoms of the system.
template (string) – The CP2K input, as the error messages name it.
- Returns:
atoms (list of integers) – The indices of the fixed atoms, counted from zero (
read_cp2k_atom_list()).dims (tuple of integers) – The fixed Cartesian components of these atoms (
CP2K_FIXED_COMPONENTS).
- Raises:
NotImplementedError – If the section selects atoms with
MOLNAME,MM_SUBSYSorQM_SUBSYS, excludes the QM or the MM atoms, or fixes components thatCP2K_FIXED_COMPONENTSdoes not name: PyRETIS reads the fixed atoms fromLISTonly.ValueError – As
read_cp2k_atom_list()raises it.
- pyretis.engines.cp2k_steps.read_cp2k_frame(filename)¶
Read the names and the positions of the atoms of an xyz frame.
- Parameters:
filename (string) – The xyz file.
- Returns:
names (list of strings) – The names of the atoms.
xyz (numpy.array) – The positions of the atoms.
- Raises:
ValueError – If the file holds no frame, or its first frame has no atoms.
- pyretis.engines.cp2k_steps.refuse_cp2k_global_keywords(template)¶
Refuse a template whose
GLOBALsection PyRETIS cannot run.- Parameters:
template (string) – The CP2K input file.
- Raises:
ValueError – If a
GLOBALsection of the template sets a keyword ofCP2K_GLOBAL_REFUSED, under any of its names, or aPROGRAM_NAMEother thanCP2K.
- pyretis.engines.cp2k_steps.refuse_cp2k_replicated_topology(template)¶
Refuse a template whose topology replicates its coordinates.
A
MULTIPLE_UNIT_CELLkeyword ofFORCE_EVAL%SUBSYS%TOPOLOGYother than1 1 1makes CP2K replicate the atoms it reads. The frames that PyRETIS gives CP2K, the configuration of its input and the frames of CP2K’s trajectories, hold every atom of the system, so CP2K would replicate them again.MULTIPLE_UNIT_CELLofFORCE_EVAL%SUBSYS%CELL, which sets the cell only, is accepted (read_box_data()).- Parameters:
template (string) – The CP2K input file.
- Raises:
ValueError – If a
FORCE_EVAL%SUBSYS%TOPOLOGYsection of the template setsMULTIPLE_UNIT_CELLto a value other than1 1 1.
- pyretis.engines.cp2k_steps.refuse_projected_cp2k_constraints(vel_settings, projected, template)¶
Stop before a draw whose kinetic energy CP2K constraints change.
CP2K imposes the constraints of the sections of
CP2K_PROJECTED_CONSTRAINTSon the velocities in the first time step of a run and removes the kinetic energy of the velocity components along them. A re-scale torescale_energyand the Metropolis acceptance of a soft velocity perturbation use the kinetic energy of all the components, so both are refused with such constraints.- Parameters:
vel_settings (dict) – The velocity settings handed to
modify_velocities.projected (list of strings) – The constraint sections, as
cp2k_constraints()returns them.template (string) – The CP2K input, as the message names it.
- Raises:
NotImplementedError – If
projectedis not empty and the settings request a re-scale or a soft velocity perturbation.
- pyretis.engines.cp2k_steps.refuse_unseeded_cp2k_noise(template)¶
Stop before a CP2K run with thermostat noise that PyRETIS cannot seed.
- Parameters:
template (string) – The CP2K input file.
- Returns:
out (dict of booleans) –
csvr: True if the thermostat of the particles is a CSVR thermostat that PyRETIS seeds;barostat: True if the thermostat of the barostat is a CSVR thermostat that PyRETIS seeds.- Raises:
NotImplementedError – For a thermostat whose noise PyRETIS cannot seed (
cp2k_noise_problem()).
- pyretis.engines.cp2k_steps.reset_free_momentum(vel, mass, fixed)¶
Set the linear momentum of the components that move to zero.
For each Cartesian component, the centre-of-mass velocity of the atoms whose component is not fixed is subtracted from them, so the total momentum is zero and the fixed components stay zero.
- Parameters:
vel (numpy.array) – The velocities, one row per atom.
mass (numpy.array) – The masses, one row per atom.
fixed (numpy.array of booleans) – The fixed components, as
cp2k_constraints()returns them.
- Returns:
out (numpy.array) – The velocities with zero linear momentum.
- pyretis.engines.cp2k_steps.write_for_continue(infile, outfile, timestep, subcycles, name='md_continue', seed=None)¶
Create input file for a single step.
Note, the single step actually consists of a number of subcycles. But from PyRETIS’ point of view, this is a single step. Here, we make use of restart files named
previous.restartandprevious.wfnto continue a run. TheEXT_RESTARTsection restarts fromprevious.restartall that CP2K restarts by default, among it the positions, the velocities, the state of the particle thermostat (the variables of a Nose-Hoover chain, the random number stream of a CSVR thermostat) and the random number streams of the particles, so the relaunched steps of a leg continue one MD run. TheCOORDsection of the template is removed, as the positions come fromprevious.restart, and so are the keywords of the topology that read a coordinate file that gives the names and the positions of the atoms only; the other settings of the topology, among them the connectivity, are kept (cp2k_continue_topology()). For a template with aFORCE_EVAL%DFTsection, aRESTART_FILE_NAMEorWFN_RESTART_FILE_NAMEkeyword of that section is replaced byWFN_RESTART_FILE_NAME previous.wfn, so theSCF_GUESS RESTARTof a relaunch reads the wavefunction of the previous one.- Parameters:
infile (string) – The input template to use.
outfile (string) – The file to create.
timestep (float) – The time-step to use for the simulation.
subcycles (integer) – The number of sub-cycles to perform.
name (string, optional) – A name for the CP2K project.
seed (integer, optional) – The seed of
GLOBAL%SEED, which seeds the random numbers that CP2K draws outside the states it restarts. None leavesGLOBAL%SEEDas the template sets it.
- Raises:
ValueError – As
cp2k_global_update()raises it.NotImplementedError – As
cp2k_continue_topology()raises it.
- pyretis.engines.cp2k_steps.write_for_genvel(infile, outfile, posfile, seed, name='genvel')¶
Create input file for velocity generation.
Velocity generation runs internally, so only
CP2KEngineSteps._prepare_shooting_point(), which the engine does not call, writes this input.- Parameters:
infile (string) – The input template to use.
outfile (string) – The file to create.
posfile (string) – The (base)name for the input file to read positions from.
seed (integer) – A seed for generating velocities.
name (string, optional) – A name for the CP2K project.
- pyretis.engines.cp2k_steps.write_for_integrate(infile, outfile, timestep, subcycles, posfile, name='md_step', print_freq=None)¶
Create input file for a single step for the integrate method.
Here, we do minimal changes and just set the time step and subcycles and the starting configuration, the positions of the xyz file
posfile(cp2k_frame_update()). The SCF starts from CP2K’s initial guess (cp2k_cold_start()).- Parameters:
infile (string) – The input template to use.
outfile (string) – The file to create.
timestep (float) – The time-step to use for the simulation.
subcycles (integer) – The number of sub-cycles to perform.
posfile (string) – The name of the xyz file to read positions from, in the folder of
outfile.name (string, optional) – A name for the CP2K project.
print_freq (integer, optional) – How often we should print to the trajectory file.
- Raises:
ValueError – As
cp2k_global_update()andcp2k_frame_update()raise it.NotImplementedError – As
cp2k_frame_update()raises it.FileExistsError – As
cp2k_cold_start()raises it.
- pyretis.engines.cp2k_steps.write_for_step_vel(infile, outfile, timestep, subcycles, posfile, vel, name='md_step', print_freq=None, seeds=None)¶
Create input file for a single step.
Note, the single step actually consists of a number of subcycles. But from PyRETIS’ point of view, this is a single step. The run starts from the positions of the xyz file
posfile(cp2k_frame_update()) and from the velocitiesvel, and its SCF from CP2K’s initial guess (cp2k_cold_start()).- Parameters:
infile (string) – The input template to use.
outfile (string) – The file to create.
timestep (float) – The time-step to use for the simulation.
subcycles (integer) – The number of sub-cycles to perform.
posfile (string) – The name of the xyz file to read positions from, in the folder of
outfile.vel (numpy.array) – The velocities to set in the input.
name (string, optional) – A name for the CP2K project.
print_freq (integer, optional) – How often we should print to the trajectory file.
seeds (dict, optional) – The seeds of the run, as
cp2k_run_seeds()returns them, written byadd_cp2k_seeds(). None leaves the random numbers as the template sets them.
- Raises:
ValueError – As
cp2k_global_update()andcp2k_frame_update()raise it.NotImplementedError – As
cp2k_frame_update()raises it.FileExistsError – As
cp2k_cold_start()raises it.
- pyretis.engines.cp2k_steps.zero_fixed_components(vel, fixed)¶
Return velocities with the fixed components set to zero.
- Parameters:
vel (numpy.array) – The velocities, one row per atom.
fixed (numpy.array of booleans or None) – The fixed components, as
cp2k_constraints()returns them.
- Returns:
out (numpy.array) –
velitself whenfixedis None; otherwise a copy with the fixed components set to zero.
pyretis.engines.engine module¶
Definition of PyRETIS engines.
This module defines the base class for the engines.
Important classes defined here¶
- EngineBase (
EngineBase) The base class for engines.
Important methods defined here¶
- refuse_path_sampling_engine (
refuse_path_sampling_engine()) Refuse an engine whose integrator a path-sampling run cannot use.
- refuse_path_sampling_input (
refuse_path_sampling_input()) Refuse an engine input a path-sampling run cannot use (its integrator, then its thermostat or barostat), before the engine is built.
- path_sampling_warnings_of (
path_sampling_warnings_of()) Return why a path-sampling run with an engine is not exact.
- log_path_sampling_warnings (
log_path_sampling_warnings()) Log the warnings of the engine of a section.
- md_tasks_sentence (
md_tasks_sentence()) Return what the md tasks do with an input path sampling refuses.
- pyretis.engines.engine.BROWNIAN_DYNAMICS_ADVICE = 'For Brownian dynamics in path sampling, use the internal engine: set class = "Langevin" with high_friction = true in the engine section ([engine] for [engine], [engine1] for [engine1]). '¶
The advice of a refusal of Brownian dynamics in a path-sampling run. Path sampling of Brownian dynamics runs with the internal
Langevinengine withhigh_friction = true, whose path sampling the method validation covers, in the engine section of the refused engine (ENGINE_SECTION_TEXT).
- pyretis.engines.engine.BROWNIAN_DYNAMICS_TASK_ADVICE = 'For Brownian dynamics, use the internal engine: set class = "Langevin" with high_friction = true in the engine section ([engine] for [engine], [engine1] for [engine1]). '¶
an engine input whose Brownian dynamics states no temperature PyRETIS reads (the
brownianfixes of LAMMPS) is refused in themd,md-nveandmd-fluxtasks and in path sampling, and every task runs the internalLangevinengine withhigh_friction = true, in the engine section of the refused engine (ENGINE_SECTION_TEXT).- Type:
The advice of a refusal of Brownian dynamics in every task
- pyretis.engines.engine.CONTINUATION_REFUSAL = ' This input continues an earlier run: a continuation adds cycles to those that run sampled, so the run is not continued with what this message refuses (an integrator, a thermostat, a barostat, a change of the velocities or a force the integrator never applies). Start a new run from its paths ([initial-path] method = "load") with the dynamics the advice above names.'¶
Said after the refusal of an engine input a path-sampling run cannot use (its integrator, its thermostat, its barostat, a change of the velocities or a force its integrator never applies), when the input continues an earlier run (
refuse_path_sampling_input()): a continuation adds cycles to the cycles of that run, so the advice of the refusal is for a new run, which starts from the paths of the earlier one.
- pyretis.engines.engine.ENGINE_SECTION_TEXT = 'the engine section ([engine] for [engine], [engine1] for [engine1])'¶
The engine section, in the advice of a refusal of an engine whose section is not known. The refusal of the engine of a section names that section in its place (
_section_refusal()).
- class pyretis.engines.engine.EngineBase(description)¶
Bases:
objectAbstract base class for engines.
The engines perform molecular dynamics (or Monte Carlo) and they are assumed to act on a system. Typically they will integrate Newtons equation of motion in time for that system.
- Variables:
description (string) – Short string description of the engine. Used for printing information about the integrator.
exe_dir (string) – A directory where the engine is going to be executed.
engine_type (string or None) – Describe the type of engine as an “internal” or “external” engine. If this is undefined, this variable is set to None.
needs_order (boolean) – Determines if the engine needs an internal order parameter or not. If not, it is assumed that the order parameter is calculated by the engine.
supports_step_kick (boolean) – Whether
ExternalMDEngine.kick_across_middle()may drive its single-step advance through this engine’sstep(). Engines whosestepraisesNotImplementedError(CP2K and LAMMPS streaming, ASE, TurtleMD) set this to False sokick_across_middleuses the engine-agnosticpropagate()-based fallback instead. Only consulted byExternalMDEngine.kick_across_middle(); the internal- engine and OpenMMkick_across_middleoverrides define their own search and ignore this flag.temperature_source (string) – Where the engine takes the temperature it runs at:
SYSTEM_TEMPERATUREfor[system] temperature, andINPUT_TEMPERATUREfor the temperature the input of the engine states, which the engine reads when it is created (pyretis.engines.run_temperature).default_temperature (float or None) – The
[system] temperaturean engine that takes it runs at when the input sets none, or None when the input must set it. None here: only the internal integrators (pyretis.engines.internal.MDEngineand its subclasses) have a default, 1. Any other engine that runs at[system] temperature(TurtleMD, ASE, an engine of a module on this class) has none, and a run whose input sets none is refused (pyretis.engines.run_temperature); the default of atemperatureargument of its constructor is not taken either.system_temperature_unit (string or None) – For an engine that takes
[system] temperatureand has no default, the unit it takes the temperature in, as messages name it; None for an engine that takes it in the unit of[system] units.temperature_keys (string) – For an engine that reads its temperature from its input, the settings of that input that hold it, as messages name them.
temperature_input_keys (tuple of strings) – For an engine that reads its temperature from its input, the settings of its engine section the read needs (GROMACS:
input_path); the run refuses a section without one before it reads the temperature, naming the section and the setting (pyretis.engines.run_temperature.resolve_run_temperature()).temperature_module_key (string or None) – For an engine whose input is a Python module that its engine section names (OpenMM:
openmm_module), the setting of the section that names the module; None for an engine whose input is a file. Only a run imports such a module to read the temperature of the engine: the analysis does not (pyretis.engines.run_temperature.compare_analysed_engine_inputs()).unmarked_section_temperature (boolean) – For an engine that reads its temperature from its input: True when the
temperatureof its engine section, in a run file without thetemperature_rulemark ofpyretis.core.provenance, is a temperature the engine used: the temperature it ran, drew its velocities and accepted at, or of these the ones thatunmarked_unrecorded_use()does not name (pyretis.engines.run_temperature.earlier_engine_temperatures()).unmarked_system_temperature (boolean) – For an engine that reads its temperature from its input: True when
[system] temperature, in a run file without thetemperature_rulemark, is the temperature the engine of[engine]ran at.records_input_timestep (boolean) – For an engine that reads its temperature from its input: True when a run reads the time step of the engine from that input too, in the same read (
read_input_temperatures_and_timestepof the class, which returns the temperatures and the time step in ps), before any engine is built, and records it as thetimestepof the engine section (pyretis.engines.run_temperature.resolve_run_temperature()). True for OpenMM, whose time step is the step size of the integrator of its simulation.
- __eq__(other)¶
Check if two engines are equal.
- __getstate__()¶
Return the engine state for pickling, minus transient fields.
The order function is injected on the engine per use; it is not durable engine state and must not travel in restart pickles – it is restored separately from the ensemble settings and may itself be unpicklable (e.g. an order parameter whose class was imported from a standalone file). It falls back to the class-level
order_functiondefault after unpickling and is re-injected before the engine is next used.
- __init__(description)¶
Just add the description.
- __ne__(other)¶
Check if two engines are not equal.
- __str__()¶
Return the string description of the integrator.
- static add_to_path(path, phase_point, left, right)¶
Add a phase point and perform some checks.
This method is intended to be used by the propagate methods.
- abstractmethod calculate_order(system, xyz=None, vel=None, box=None)¶
Obtain the order parameter.
The order function is injected on the engine as
self.order_function;systemis the state to evaluate.
- classmethod can_use_order_function(order_function)¶
Fail if the engine can’t be used with an empty order parameter.
- abstractmethod clean_up()¶
Perform clean up after using the engine.
- default_temperature = None¶
- default_units = None¶
- abstractmethod dump_phasepoint(phasepoint, deffnm=None)¶
Dump phase point to a file.
- engine_type = None¶
- property exe_dir¶
Return the directory we are currently using.
- frame_cell()¶
Return the cell for a stored frame that records none.
An
.xyzframe need not record the simulation cell: the trajectories CP2K writes carry no box, and a box line can read# Box: 0.0000 0.0000 0.0000. A frame read back by format (pyretis.tools.recalculate_order.recalculate_order()) that records no cell is evaluated in the cell this method returns, the one the engine itself evaluates such a frame in.- Returns:
out (numpy.array or None) – The box lengths of the cell, or None for an engine that gives such a frame no cell.
- classmethod get_default_units(settings=None)¶
Return the default unit system for this engine.
- Parameters:
settings (dict, optional) – Full simulation settings or engine settings. Engines may override this method and use the settings to resolve their default units dynamically.
- Returns:
out (string or None) – The default unit system for the engine, or
Noneif the engine does not define one.
- classmethod input_path_sampling_problem(engine_settings)¶
Return why a path-sampling run cannot use an engine input.
The input an engine section names is read as the engine of the class reads it when it is created, without building the engine and without reading a temperature, and gives the reason of
path_sampling_problem(). The run set-up checks every engine section with it before it reads a temperature (refuse_path_sampling_input()), so the refusal of an integrator comes before a message about the temperature of the input.- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (string or None) – The reason, or None when a path-sampling run can use the input; None for every input of a class whose
path_sampling_problem()accepts every engine.
- abstractmethod integration_step(system)¶
Perform one time step of the integration.
- abstractmethod kick_across_middle(system, ens_set, middle, tis_settings, rgen)¶
Force a phase point across the middle interface.
rgenis the velocity-generation random generator, injected explicitly (kept distinct from any integrationself.rgen). Every kick is an aimless draw that follows the[tis]zero_momentumsetting intis_settings(make_kick_velocity_settings()).
- load_restart_info(info=None)¶
Load restart information.
- Parameters:
info (dict) – The dictionary with the restart information, should be similar to the dict produced by
restart_info().
- abstractmethod modify_velocities(system, vel_settings, rgen)¶
Modify the velocities of the current state.
- Parameters:
system (object like
System) – The state whose velocities we modify.vel_settings (dict) – It contains all the info for the velocity:
sigma_v : numpy.array, optional Negative values select aimless shooting. Zero or positive values set the standard deviation, one for each particle, for soft velocity perturbations.
zero_momentum : boolean, optional If True, we reset the linear momentum to zero after generating. A missing key means False, the
[tis]default;is_zero_momentum_setting()reads it.rescale : float, optional In some NVE simulations, we may wish to re-scale the energy to a fixed value. If rescale is a float > 0, we will re-scale the energy (after modification of the velocities) to match the given float.
rgen (object like
RandomGenerator) – The random generator for drawing the new velocities, injected explicitly per call. It is deliberately kept distinct from any integration random generator an engine may own asself.rgen(e.g. Langevin/random-walk dynamics), so modifying velocities never perturbs the dynamics stream.
- Returns:
dek (float) – The change in the kinetic energy.
kin_new (float) – The new kinetic energy.
- needs_order = True¶
- order_function = None¶
The order function is injected on the engine per use (by the simulation caller); this class-level default documents the attribute and gives a sane value before it is set. It is transient state – excluded from restart info – not durable engine config.
- path_sampling_problem()¶
Return why a path-sampling run cannot use this engine.
A path-sampling run reverses the velocities of a frame and draws new velocities at a frame, and integrates on from the positions of that frame. The new path starts at the frame only when the integrator stores the velocities at the time of the positions it stores. A leap-frog integrator stores them half a time step away from the positions, so the first step of a reversed or a shot path does not continue the frame it starts from. An engine whose integrator a path-sampling run cannot use returns the reason.
- Returns:
out (string or None) – The reason, naming the integrator and the integrators to use instead, or None when a path-sampling run can use the engine.
- path_sampling_warnings()¶
Return why a path-sampling run with this engine is not exact.
Every piece of trajectory a path-sampling run generates (the backward and the forward piece of a shooting move, the extension of a path in a swap move) starts the engine from a stored frame: positions, velocities and, where the frame stores it, the box. A thermostat or a barostat that carries a memory from one time step to the next restarts that memory with each piece, a coupling applied every N time steps counts the steps from the start of each piece, a temperature ramp starts again with each piece, and some schemes change the velocities or the positions at the start of a piece. A path then does not follow one dynamics from its first frame to its last. An engine whose settings select such a scheme returns one warning per scheme; the run goes on.
- Returns:
out (list of strings) – Each warning names the scheme, why the path sampling is not exact with it, and what to use instead. Empty when the engine selects no such scheme.
- abstractmethod propagate(path, ens_set, system, reverse=False)¶
Propagate equations of motion.
- records_input_timestep = False¶
- restart_info()¶
General method.
Returns the info to allow an engine exact restart.
- Returns:
info (dict) – Contains all the updated simulation settings and counters.
- set_mdrun(md_items)¶
Configure the run state of a move on the engine.
The engine keeps the run state the scheduler sets here; the transient
System/rgen/order function are injected per call. The infinite-swapping scheduler calls this before each move, with the run items of the move, to point the engine at the scratch directory of the move (and, for engines that launch an external command, at the launch command of the worker). The default handles the common case – setexe_dirfrommd_itemswhen provided; subclasses that need more (e.g. a per-workermdruncommand) override and extend it.- Parameters:
md_items (dict) – The run items of the move. The key
exe_dir(when present) sets the engine execution directory.
- static snapshot_to_system(system, snapshot)¶
Convert a snapshot to a system object.
This uses the
Systemproperty API (pos/vel/vpot/ekin), which routes tosystem.particleswhen particles are attached and otherwise stores the values directly on the snapshot-based system. It therefore works for a system with particles, as the internal integrators use, and for a snapshot-based system without particles, as the external and streaming engines may use.
- supports_step_kick = True¶
- system_temperature_unit = None¶
- temperature_input_keys = ()¶
- temperature_keys = ''¶
- temperature_module_key = None¶
- temperature_source = 'system'¶
- property time_per_step¶
Return the simulation time between two recorded path points.
This is
timestep * subcycles– the physical time per PyRETIS step, expressed in the engine’s own time unit – and is the factor that converts a path length (in steps) into a time when computing fluxes and rates. The time step belongs to the engine: each subclass 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.
- unmarked_section_temperature = False¶
- unmarked_system_temperature = False¶
- classmethod unmarked_unrecorded_use(engine_settings)¶
Return what an earlier engine did at a temperature not recorded.
For an engine with
unmarked_section_temperature, a run file without thetemperature_rulemark records thetemperatureof its engine section, which the PyRETIS that wrote it gave the engine. An engine that ran, drew its velocities and accepted at that temperature returns None.- Parameters:
engine_settings (dict) – The settings of the engine section, as the run file records them.
- Returns:
out (string or None) – None for an engine whose run the recorded temperature describes; else what the engine took from it, and what it did at the temperature of its own input of that run, which no run file records, as a warning states it.
- pyretis.engines.engine.INPUT_TEMPERATURE = 'input'¶
The
EngineBase.temperature_sourceof an engine that runs at the temperature its own input states.
- pyretis.engines.engine.SYSTEM_TEMPERATURE = 'system'¶
The
EngineBase.temperature_sourceof an engine that runs at[system] temperature.
- pyretis.engines.engine.log_path_sampling_warnings(section, warnings)¶
Log the warnings of the engine of a section of a path-sampling run.
- Parameters:
section (string) – The input section the engine is built from, as
engine1.warnings (list of strings) – The warnings of its engine (
path_sampling_warnings_of()). Each is logged as a warning, after the section:The engine of [engine1]: <warning>.
- pyretis.engines.engine.md_tasks_sentence(read_temperatures, filename, accepted)¶
Return what the md tasks do with an input path sampling refuses.
The
md,md-nveandmd-fluxtasks read the temperature of an engine input with the temperature reader of the engine (pyretis.inout.engine_temperature), which raises aValueErrorfor an input it refuses, and take the one temperature its settings hold (EngineTemperatures.agreed()), which raises aValueErrorfor an input that holds no temperature or different ones: every task refuses that input. The reader andEngineTemperatures.agreed()run on the input to word the message of a path-sampling refusal; the temperature is not used.- Parameters:
read_temperatures (callable) – The temperature reader of the engine, as
read_lammps_temperatures(), called withfilename; it returns anEngineTemperatures.filename (string) – The engine input the path-sampling run refuses.
accepted (string) – The sentence for an input the reader reads, which the
md,md-nveandmd-fluxtasks accept.
- Returns:
out (string) – For an input the reader refuses, or whose settings hold no temperature or different ones, a sentence that says that every task refuses it, followed by the reason;
acceptedfor an input whose settings hold one temperature.- Raises:
UnicodeError – As the reader raises it, for a file it cannot decode.
Exception – Every exception of the reader other than its
ValueError.
- pyretis.engines.engine.path_sampling_warnings_of(engine)¶
Return the warnings of the engine of a path-sampling run.
- Parameters:
engine (object like
EngineBase) – The engine of a path-sampling run, which a path-sampling run can use (refuse_path_sampling_engine()). An engine without the methodEngineBase.path_sampling_warnings()gives no warning.- Returns:
out (list of strings) – The warnings
EngineBase.path_sampling_warnings()gives, each once, in its order.
- pyretis.engines.engine.refuse_path_sampling_engine(engine, section=None)¶
Refuse an engine whose integrator a path-sampling run cannot use.
- Parameters:
engine (object like
EngineBase) – The engine of a path-sampling run. An engine without the methodEngineBase.path_sampling_problem()is accepted.section (string, optional) – The input section the engine is built from, as
engine1. When given, the message starts with the section,[engine1], and names that section and its integrator key in its advice (_section_refusal()).
- Raises:
ValueError – If the engine gives a reason why a path-sampling run cannot use it (
EngineBase.path_sampling_problem()). The message is the reason, after the section when one is given.
- pyretis.engines.engine.refuse_path_sampling_input(cls, engine_settings, section=None, continuation=False)¶
Refuse an engine input a path-sampling run cannot use.
- Parameters:
cls (type) – The engine class of the section. A class without the method
EngineBase.input_path_sampling_problem()is accepted.engine_settings (dict) – The settings of the engine section.
section (string, optional) – The engine section, as
engine1. When given, the message starts with the section,[engine1], and names that section and its integrator key in its advice (_section_refusal()).continuation (boolean, optional) – True when the input continues an earlier run (a restart or a resume): the message then ends with
CONTINUATION_REFUSAL.
- Raises:
ValueError – If the input gives a reason why a path-sampling run cannot use it (
EngineBase.input_path_sampling_problem()): the message ofrefuse_path_sampling_engine()for the engine built from the input, followed byCONTINUATION_REFUSALfor a continuation.
pyretis.engines.external module¶
Definition of external engines.
This module defines the base class for external MD engines.
Important classes defined here¶
- ExternalMDEngine (
ExternalMDEngine) The base class for external engines which defines the interface to external programs.
- class pyretis.engines.external.ExternalMDEngine(description, timestep, subcycles)¶
Bases:
EngineBaseBase class for interfacing external MD engines.
This class defines the interface to external programs. The interface will define how we interact with the external programs, how we write input files for them and read output files from them. New engines should inherit from this class and implement the following methods:
ExternalMDEngine.step()A method for performing a MD step with the external engine. Note that the MD step can consist of a number of subcycles.
ExternalMDEngine._read_configuration()For reading output (configurations) from the external engine. This is used for calculating the order parameter(s).
ExternalMDEngine._reverse_velocities()For reversing velocities in a snapshot. This method will typically make use of the method
ExternalMDEngine._read_configuration().
ExternalMDEngine._extract_frame()For extracting a single frame from a trajectory.
ExternalMDEngine._propagate_from()The method for propagating the equations of motion using the external engine.
ExternalMDEngine.modify_velocities()The method used for generating random velocities for shooting points. Note that this method is defined in
EngineBase.modify_velocities().
- Variables:
description (string) – A string with a description of the external engine. This can, for instance, be what program we are interfacing with. This is used for outputting information to the user.
timestep (float) – The time step used for the external engine.
subcycles (integer) – The number of steps the external step is composed of. That is: each external step is really composed of
subcyclesnumber of iterations.
- __init__(description, timestep, subcycles)¶
Set up the external engine.
Here we just set up some common properties which are useful for the execution.
- Parameters:
description (string) – A string with a description of the external engine. This can, for instance, be what program we are interfacing with. This is used for outputting information to the user.
timestep (float) – The time step used in the simulation.
subcycles (integer) – The number of sub-cycles each external integration step is composed of.
- _abc_impl = <_abc._abc_data object>¶
- _calculate_frame_order(system, config, xyz, vel, box)¶
Calculate the order parameter of one frame of a trajectory.
The order function sees the frame: the positions, the velocities and the box of
systemare those of the frame, ascalculate_order()sets them, andsystem.configisconfig, the (file, index) of the frame, which is the config the phase point of the frame stores.system.configis set back to its value before the call afterwards.- Parameters:
system (object like
System) – The state the order parameter is calculated on.config (tuple) – The (file, index) of the frame, as
dump_config()resolves it.xyz (numpy.array) – The positions of the frame.
vel (numpy.array) – The velocities of the frame.
box (numpy.array) – The box of the frame.
- Returns:
out (list of floats) – The order parameter of the frame.
- Raises:
ValueError – If the positions, the velocities or the box of the frame are missing:
calculate_order()would then read them from the first frame of the file ofconfig, not from this frame.
- static _cap_engine_log(path, maxsize)¶
Trim an engine log to its most-recent
maxsizebytes.Thin wrapper around
pyretis.engines._engine_logs.cap_engine_log().
- _config_signature(filename)¶
Return a hash identifying a configuration’s physical content.
Confirms that an interrupted propagation we are about to resume really belongs to the shot being re-attempted: the shooting point is regenerated deterministically on restart, so its positions/velocities are identical. We hash the coordinates (not the raw file bytes) so format-specific metadata such as a title line does not affect the comparison.
- static _copyfile(source, dest)¶
Copy file from source to destination.
- static _engine_output_files(log_dir)¶
Return the engine stdout/stderr log paths for a run directory.
Thin wrapper around
pyretis.engines._engine_logs.engine_output_files().
- abstractmethod _extract_frame(traj_file, idx, out_file)¶
Extract a frame from a trajectory file.
- Parameters:
traj_file (string) – The trajectory file to open.
idx (integer) – The frame number we look for.
out_file (string) – The file to dump to.
- static _finalize_engine_output(return_code, err_name)¶
Keep stdout logs and discard stderr logs from successful runs.
Thin wrapper around
pyretis.engines._engine_logs.finalize_engine_output().
- _frame_config_index(frame)¶
Map a trajectory-frame number to its configuration index.
The configuration index is what is stored in a snapshot’s
configtuple and later passed to_extract_frame(). For most engines it equals the trajectory-frame number; engines that index configurations by MD time step (the LAMMPS engines,LAMMPSEngineSteps._frame_config_index(), which storeframe * subcycles) override this.- Parameters:
frame (integer) – The trajectory-frame number (0-based).
- Returns:
out (integer) – The configuration index for that frame.
- _kick_across_middle_propagate(system, ens_set, middle, tis_settings, rgen)¶
Force a phase point across the middle interface via propagate().
Engine-agnostic fallback for engines with
supports_step_kick = False(no usable singlestep(): CP2K/LAMMPS streaming, ASE, TurtleMD). Mirrors the greedy hill-climb of the step()-basedkick_across_middle()above – kick velocities, advance exactly one step, keep the new point if it did not move away frommiddleand revert otherwise, repeat until the step straddlesmiddle– but advances usingpropagate()(aPathcapped atmaxlen=2) instead ofstep(), operating on in-memorySystem.copy()objects. The search keeps no files of its own: each engine’s_propagate_frommanages its trajectory files.- Parameters:
system (object like
System) – The working state we repeatedly kick and integrate. The order function is injected on the engine (self.order_function).ens_set (dict) – Ensemble settings. Each advance runs
propagate()on a shallow copy of them whoseinterfacesare[-inf, middle, +inf], soens_setis not changed and its own interfaces are not read. The crossing search compares against themiddleargument, which may differ fromens_set['interfaces'][1]for the body-ensemble edge case ingenerate_initial_path_kick().middle (float) – This is the value for the middle interface.
tis_settings (dict) – Settings for TIS.
kick_maxtriescaps the number of kick attempts (defaultKICK_MAXTRIES, at least 1), andzero_momentumselects the linear-momentum reset after each kick (a missing key means False). Every kick passes thevel_settingsof the step()-based search to the engine’smodify_velocities: an aimless draw with the energy left unscaled (make_kick_velocity_settings()).rgen (object like
RandomGenerator) – The velocity-generation random generator, injected per call (distinct from any integrationself.rgen).
- Returns:
Note
The two returned points are copies, and the caller’s
systemobject is not one of them: the first kick and step act on that object, and the search then continues on copies. Callers must use the return value (generate_initial_path_kick()does: it reassignsensemble['system']from the returned points).Each search iteration launches a fresh
propagate()call, which for a subprocess-based streaming engine (CP2K, LAMMPS) means a fresh external-process launch per step of the greedy search. This is a one-time bootstrap cost (kick runs once per ensemble, not once per cycle); turtlemd and ASE are pure in-process Python engines, so this primitive is cheap for them.
- static _modify_input(sourcefile, outputfile, settings, delim='=', key_name=None)¶
Modify input file for external software.
Here we assume that the input file has a syntax consisting of
keyword = setting. We will only replace settings for the keywords we find in the file that is also inside thesettingsdictionary. A replaced line keeps the keyword as the file spells it; the settings the file does not hold are added at its end.- Parameters:
sourcefile (string) – The path of the file to use for creating the output.
outputfile (string) – The path of the file to write.
settings (dict) – A dictionary with settings to write.
delim (string, optional) – The delimiter used for separation keywords from settings.
key_name (callable, optional) – Gives, for a keyword, the name the external program reads it as (for GROMACS,
mdp_key_name()). A keyword of the file is the keyword ofsettingswith the same name. Without it, the name of a keyword is the keyword itself.
- Raises:
ValueError – If two keywords of
settingshave the same name.
- static _movefile(source, dest)¶
Move file from source to destination.
- _name_output(basename)¶
Create a file name for the output file.
This method is used when we dump a configuration, to add the extension of the engine’s configurations,
self.ext(for GROMACS, gro or g96).- Parameters:
basename (string) – The base name to give to the file.
- Returns:
out (string) – The file name with the extension, in
self.exe_dir.
- static _open_engine_log(path)¶
Open an engine stdout/stderr log for appending, resiliently.
Thin wrapper around
pyretis.engines._engine_logs.open_engine_log().
- _prefill_partial(system, partial_traj, name)¶
Rebuild the surviving frames of an interrupted path.
Returns a tuple
(phase_points, cont_conf)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 caller,
propagate(), prepends the surviving frames to its path after_propagate_from(), so the engine’s ownupdate_energiesaligns with the continued frames only. The surviving frames’ energies are not recoverable from the trajectory and are therefore left unset (None).Returns
(None, None)when there are fewer than two readable frames (nothing worth resuming).
- abstractmethod _propagate_from(name, path, system, ens_set, msg_file, reverse=False)¶
Run the actual propagation using the specific engine.
This method is called by
propagate(), which handles the necessary preparations before the actual propagation (e.g. dumping of the configuration etc.).- Parameters:
name (string) – A name to use for the trajectory we are generating.
path (object like
PathBase) – This is the path we use to fill in phase-space points.system (object like
System) – The system object gives the initial state for the integration. The order function is injected on the engine (self.order_function).ens_set (dict) – Ensemble settings. It contains:
interfaces : list of floats These interfaces define the stopping criterion.
msg_file (object like
FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.reverse (boolean, optional) – If True, the system will be propagated backward in time.
- Returns:
success (boolean) – This is True if we generated an acceptable path.
status (string) – A text description of the current status of the propagation.
- abstractmethod _read_configuration(filename)¶
Read output configuration from external software.
- Parameters:
filename (string) – The file to open and read a configuration from.
- Returns:
out[0] (numpy.array) – The dimensions of the simulation box.
out[1] (numpy.array) – The positions found in the given filename.
out[2] (numpy.array) – The velocities found in the given filename.
- static _read_input_settings(sourcefile, delim='=')¶
Read input settings for simulation input files.
Here we assume that the input file has a syntax consisting of
keyword = setting, where=can be any string given in the input parameterdelim.- Parameters:
sourcefile (string) – The path of the file to use for creating the output.
delim (string, optional) – The delimiter used for separation keywords from settings.
- Returns:
settings (dict of strings) – The settings found in the file.
Note
Important: We are here assuming that there will ONLY be one keyword per line.
- _read_resume_marker(reverse, init_sig)¶
Return a resumable partial trajectory, or None.
A marker is resumable only when it records an incomplete propagation whose initial configuration matches
init_sig(same shot) and whose partial trajectory still exists on disk.- Parameters:
reverse (boolean) – The propagation direction we are about to (re)run.
init_sig (string) – Content signature of the current shot’s initial config.
- Returns:
out (string or None) – The path to the partial trajectory to resume from, or None.
- _recompute_partial_orders(partial_traj, reverse)¶
Order parameters for every readable frame, in file order.
Reads the surviving frames of an interrupted trajectory and recomputes their order parameters (the deterministic source of truth). A frame left broken by the interruption is tolerated: the underlying readers stop at the last readable frame.
- _remove_files(dirname, files)¶
Remove files from a directory.
- Parameters:
dirname (string) – Where we are removing.
files (list of strings) – A list with files to remove.
- _remove_resume_marker(reverse)¶
Remove the resume marker once a propagation has completed.
- static _removefile(filename)¶
Remove a given file if it exist.
- _resume_marker_path(reverse)¶
Return the path of the per-direction resume marker file.
- abstractmethod _reverse_velocities(filename, outfile)¶
Reverse velocities in a given snapshot.
- Parameters:
filename (string) – Input file with velocities.
outfile (string) – File to write with reversed velocities.
- _trajectory_filename(name)¶
Return the basename of the trajectory file for a propagation.
This is the file the engine writes frames to during
_propagate_from(). Engines whose trajectory format differs from their configuration format (e.g. GROMACS writes a.trrwhile configurations are.gro/.g96) override this.- Parameters:
name (string) – The trajectory label built in
propagate().- Returns:
out (string) – The trajectory file basename.
- _write_resume_marker(reverse, traj_file, init_sig, complete)¶
Write (atomically and durably) the resume marker.
- calculate_order(system, xyz=None, vel=None, box=None)¶
Calculate order parameter from configuration in a file.
Note, if
xyz,velandboxare all given, we will NOT read positions, velocity and box information from the current configuration file. If any of them is None, all three are read from that file.- Parameters:
system (object like
System) – This is the system that contains the particles we are investigating. The order function is injected on the engine asself.order_function.xyz (numpy.array, optional) – The positions to use, in case we have already read them somewhere else.
vel (numpy.array, optional) – The velocities to use, in case we already have read them.
box (numpy.array, optional) – The current box vectors, in case we already have read them.
- Returns:
out (list of floats) – The calculated order parameter(s).
- clean_up()¶
Will remove all files from the current directory.
- continue_interrupted = False¶
Opt-in resume of an interrupted propagation. When True, an abruptly interrupted propagation (e.g. a cluster wall-time kill) is continued on restart instead of being re-run from the shooting point: the frames that survived on disk are reused and the trajectory is propagated onward from the last good frame. The continued segment is a new, valid path (the integrator state is restarted from a configuration, so it is not bit-identical to an uninterrupted run); such paths are flagged via
path.resumed.False(the default) re-runs an interrupted propagation from the shooting point.
- static draw_maxwellian_velocities(vel, mass, beta, rgen, sigma_v=None)¶
Draw velocities from a Maxwell-Boltzmann distribution.
This is the engine-independent (Python) velocity draw used when an external engine is configured to generate shooting velocities via
velocity_generation = "maxwell"instead of delegating to the engine’s own generator. The velocities are drawn from the injected random generator so the whole shooting move stays on one reproducible stream.- Parameters:
vel (numpy.ndarray) – The current velocities; only the shape
(npart, dim)is used (the values are overwritten).mass (numpy.ndarray) – The particle masses, shape
(npart, 1).beta (float) – The inverse temperature
1 / (k_B T)in the engine’s unit system.rgen (object like
RandomGenerator) – The velocity random generator, injected explicitly. With the default PCG64 generator, itsnormaldraw is that ofnumpy.random.Generator.normal.sigma_v (numpy.ndarray, optional) – Per-particle standard deviation. When
None(or any negative entry) it is computed frombetaandmass.
- Returns:
vel (numpy.ndarray) – The newly drawn velocities, shape
(npart, dim).sigma_v (numpy.ndarray) – The standard deviation used for the draw.
- dump_config(config, deffnm='conf')¶
Extract configuration frame from a system if needed.
- Parameters:
config (tuple) – The configuration given as (filename, index).
deffnm (string, optional) – The base name for the file we dump to.
- Returns:
out (string) – The file name we dumped to,
_name_output()ofdeffnm. A configuration of a single frame (index None) is copied to it, unless it is that file.
Note
If the velocities should be reversed, this is handled elsewhere.
- dump_frame(system, deffnm='conf')¶
Just dump the frame from a system object.
- dump_phasepoint(phasepoint, deffnm='conf')¶
Just dump the frame from a system object.
- engine_log_maxsize = None¶
Optional cap (in bytes) on the retained
engine.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) leaves the log unbounded. Set it on the class or an instance, e.g.engine.engine_log_maxsize = 100 * 1024 * 1024for a 100 MB cap. A failing command’s log is never trimmed.
- engine_type = 'external'¶
- execute_command(cmd, cwd=None, inputs=None)¶
Execute an external command for the engine.
We are here executing a command and then waiting until it finishes. The standard out and standard error are piped to files during the execution and can be inspected if the command fails. This method returns the return code of the issued command.
- Parameters:
cmd (list of strings) – The command to execute.
cwd (string or None, optional) – The current working directory to set for the command.
inputs (bytes or None, optional) – Additional inputs to give to the command. These are not arguments but more akin to keystrokes etc. that the external command may take.
- Returns:
out (int) – The return code of the issued command.
- integration_step(system)¶
Perform a single time step of the integration.
For external engines, it does not make much sense to run single steps unless we absolutely have to. We therefore just fail here: an external engine runs an MD task through its
integratemethod, where it has one.If it’s absolutely needed, there is a
step()method which can be used, for instance in the initialisation.- Parameters:
system (object like
System) – A system to run the integration step on.
- kick_across_middle(system, ens_set, middle, tis_settings, rgen)¶
Force a phase point across the middle interface.
This is accomplished by repeatedly kicking the phase point so that it crosses the middle interface.
- Parameters:
system (object like
System) – The working state we repeatedly kick and integrate. The order function is injected on the engine (self.order_function).ens_set (dict) – Ensemble settings, which only the
propagate()-based search (_kick_across_middle_propagate()) reads; the argument belongs to the signature ofEngineBase.kick_across_middle().middle (float) – This is the value for the middle interface.
tis_settings (dict) – This dictionary contains settings for TIS. Explicitly used here:
zero_momentum: boolean, determines if the momentum is zeroed after each kick. A missing key means False.
kick_maxtries: integer, caps the number of kick attempts (default
KICK_MAXTRIES, at least 1).
Every kick is an aimless draw with the energy left unscaled (
make_kick_velocity_settings()).rgen (object like
RandomGenerator) – The velocity-generation random generator, injected per call (distinct from any integrationself.rgen).
- Returns:
Note
This function will update the input system state.
Note
This is the step()-based search, used when
self.supports_step_kickis True. Engines that cannot drive a singlestep()(supports_step_kick = False: CP2K/LAMMPS streaming, ASE, TurtleMD) are dispatched to the engine-agnostic_kick_across_middle_propagate()– see there for that fallback.
- propagate(path, ens_set, system, reverse=False)¶
Propagate the equations of motion with the external code.
This method will explicitly do the common set-up, before calling more specialised code for doing the actual propagation.
- Parameters:
path (object like
PathBase) – This is the path we use to fill in phase-space points. We are here not returning a new path - this since we want to delegate the creation of the path to the method that is running propagate.ens_set (dict) – Ensemble settings. It contains:
interfaces : list of floats These interfaces define the stopping criterion.
path_ensemble : optional, for building the working-file name prefix when present.
system (object like
System) – The system object gives the initial state for the integration. It is mutated in place (configuration file and velocity-reversal flag) during propagation; the caller owns the lifecycle and passes a fresh copy per call. The order function and random generator are injected on the engine (self.order_function/self.rgen).reverse (boolean, optional) – If True, the system will be propagated backward in time.
- Returns:
success (boolean) – This is True if we generated an acceptable path.
status (string) – A text description of the current status of the propagation.
- abstractmethod step(system, name)¶
Perform a single step with the external engine.
- Parameters:
system (object like
System) – The system we are integrating.name (string) – To name the output files from the external engine.
- Returns:
out (string) – The name of the output configuration, obtained after completing the step.
pyretis.engines.gromacs module¶
A GROMACS external MD integrator interface (canonical streaming engine).
This module defines the canonical GROMACS engine, selected by
class = "gromacs". It runs GROMACS as a single persistent process and
reads the output TRR file on the fly, rather than starting and stopping
the executable once per order-parameter point. The slower relaunch
implementation is selected by class = "gromacs_steps", in
pyretis.engines.gromacs_steps.
Important classes defined here¶
- GromacsEngine (
GromacsEngine) A class responsible for interfacing GROMACS by streaming.
- class pyretis.engines.gromacs.GromacsEngine(gmx, mdrun=None, input_path=None, timestep=None, subcycles=None, exe_path='/home/enrico/cache/twoway-retis/wt2/docs', maxwarn=0, gmx_format='g96', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', masses=False, conf=None)¶
Bases:
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='/home/enrico/cache/twoway-retis/wt2/docs', maxwarn=0, gmx_format='g96', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', masses=False, conf=None)¶
Set up the GROMACS engine.
- Parameters:
gmx (string) – The GROMACS executable.
mdrun (string, optional) – The GROMACS mdrun executable. May be omitted when the engine is driven by the infinite-swapping scheduler, which supplies a per-worker mdrun command via
set_mdrun.input_path (string) – The absolute path to where the input files are stored.
timestep (float) – The time step used in the GROMACS MD simulation.
subcycles (integer) – The number of steps each GROMACS MD run is composed of.
exe_path (string, optional) – The absolute path at which the main PyRETIS simulation will be run.
maxwarn (integer, optional) – Setting for the GROMACS
grompp -maxwarnoption.gmx_format (string, optional) –
'g96'or'gro'– seeGromacsEngineSteps.write_vel (boolean, optional) – Determines if GROMACS should write velocities or not.
write_force (boolean, optional) – Determines if GROMACS should write forces or not.
domain_decomp (boolean, optional) – Whether GROMACS uses domain decomposition or not. This will not set the domain decomposition behavior, the user should know this.
velocity_generation (string, optional) –
"engine"(default) or"maxwell"– seeGromacsEngineSteps.masses (list or string, optional) – Particle masses for the
"maxwell"velocity draw.conf (string, optional) – The starting configuration file in
input_path– seeGromacsEngineSteps.
- static _check_frame_step(trr_file, index, frame_step, step, steps)¶
Check that a frame of the
.trris at the MD step of its index.- Parameters:
trr_file (string) – The trajectory file the frame is read from.
index (integer) – The index of the frame in the trajectory, 0 for the first.
frame_step (integer) – The MD step of the frame, as its header stores it: a 32-bit signed integer, into which GROMACS wraps (modulo
2**32) an MD step outside its range.step (integer) – The MD step of the frame of this index in the run,
init-step + index * subcycles.steps (integer) – The number of frames of the run.
- Raises:
RuntimeError – If
indexisstepsor more, or ifframe_stepis notstepas the header stores it.
- _energy_records(edr_file, begin, end)¶
Return the records of a time window of an
.edrfile.- Parameters:
edr_file (string) – The GROMACS energy file to read from.
begin (float) – The start of the window, in ps (
gmx energy -b; a negative time is given as 0).end (float) – The end of the window, in ps (
gmx energy -e).
- Returns:
times (list of float) – The time of each record read, in ps, as
gmx energyprints it: the first column of the data rows of the xvg.energy (dict of numpy.arrays) – The energies of the records read, in the same order, as
get_energies()returns them.
- _get_frame_energies(edr_file, step, time, max_attempts=100)¶
Read one frame’s energies from a streamed
.edr, tolerating lag.The energies of a frame are those of the
.edrrecord of its MD step. GROMACS gives the record of the MD stepsthe timetinit + s * dt, andgmx energyprints that time from its double precision value with six decimals, in both precisions of GROMACS. The record of the MD step is the one printed attimeto within a quarter ofdt; the record of another MD step is at leastdtaway. The time window given togmx energyonly bounds the records read: a mixed-precision build selects them comparing times in single precision, so at large times it also returns the records of neighbouring MD steps.The
.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 the record of the MD step is in the file; the final attempt is left to raise so a genuine, persistent failure is still surfaced.- Parameters:
edr_file (string) – The GROMACS energy file to read from.
step (integer) – The MD step of the frame.
time (float) – The time of the MD step,
tinit + step * dt, in ps.max_attempts (integer, optional) – Maximum number of retries while the energy file catches up.
- Returns:
energy (dict of numpy.arrays) – The energies of the record of the MD step, one value per term.
- Raises:
RuntimeError – If the
.edrholds no record at the MD step aftermax_attemptsreads, or the records read are not one at the MD step (_record_of_step()).
- _propagate_from(name, path, system, ens_set, msg_file, reverse=False)¶
Propagate with GROMACS from the current system configuration.
Here, we assume that this method is called after the propagate() has been called in the parent. The parent is then responsible for reversing the velocities and also for setting the initial state of the system.
- Parameters:
name (string) – A name to use for the trajectory we are generating.
path (object like
PathBase) – This is the path we use to fill in phase-space points.system (object like
System) – The system object gives the initial state for the integration. The order function is injected on the engine (self.order_function).ens_set (dict) – Ensemble settings. It contains:
interfaces : list of floats These interfaces define the stopping criterion.
msg_file (object like
FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.reverse (boolean, optional) – If True, the system will be propagated backward in time.
- Returns:
success (boolean) – This is True if we generated an acceptable path.
status (string) – A text description of the current status of the propagation.
- Raises:
ValueError – Before GROMACS runs, if
init-stepis not a multiple of the currentsubcycles(_refuse_init_step()).
- _record_of_step(records, step, time, edr_file)¶
Return the energies of the record of one MD step, if read.
- Parameters:
records (tuple) – The times and the energies of the records read, as
_energy_records()returns them.step (integer) – The MD step.
time (float) – The time of the MD step, in ps.
edr_file (string) – The energy file the records are read from.
- Returns:
out (dict of numpy.arrays or None) – The energies of the one record at
time, to within a quarter ofdt, or None if no record at or aftertimeis read: the.edrhas not reached the MD step yet.- Raises:
RuntimeError – If two or more records are at
time, or if a record aftertimeis read and none at it: the.edrpassed the MD step without its record, so the energies are not written at the MD steps of the frames.
- _run_start(mdp_file)¶
Return the first MD step of a run and its
tinit.GROMACS gives step
sof a run the MD stepinit-step + sand the timetinit + (init-step + s) * dt, with theinit-stepandtinitof its mdp file (0 if the file does not set them) anddt, the timestep of the engine. The mdp file of a PyRETIS run setsnstxoutandnstenergytosubcycles: GROMACS writes a frame to the.trrand a record to the.edrat each MD step that is a multiple ofsubcycles. The engine refuses, when it is set up, aninit-stepthat is not a multiple ofsubcycles(_refuse_init_step()), so the first frame of the run is at the MD stepinit-step.- Parameters:
mdp_file (string) – The mdp file of the run.
- Returns:
out[0] (integer) –
init-step, the MD step of the first frame of the run.out[1] (float) –
tinit, in ps.
- Raises:
ValueError – If the run starts at a negative time,
tinit + init-step * dt < 0: the energies are read from the time 0 on (_energy_records()).
- integrate(system, order_function, steps, thermo='full')¶
Perform several integration steps.
This method will perform several integration steps using GROMACS. It will also calculate order parameter(s) and energy terms if requested.
- Parameters:
system (object like
System) – The system object gives the initial state for the integration. At each step, its positions, velocities and box are those of the frame of the step.order_function (object like
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 of step
i, which are those of frameiof the trajectory GROMACS writes, at the MD stepinit-step + i * subcycles(frame 0 is the starting configuration):'order', the order parameter of the frame (with an order function), calculated withsystem.confignaming the frame,(trr file, i), and'thermo', the energies of the.edrrecord of the MD step of the frame.- Raises:
ValueError – Before GROMACS runs, if the mdp file starts the run at a negative time (
_run_start()). Aninit-stepthat is not a multiple ofsubcyclesis refused when the engine is set up (_refuse_init_step()).RuntimeError – If a frame of the
.trris not at the MD step of its index, if mdrun writes another number of frames thansteps, or if the.edrdoes not hold one record at the MD step of a frame (_get_frame_energies()).
- classmethod mdp_template(engine_settings)¶
Return the name of the mdp file the engine reads.
This engine reads
grompp.mdpwhatever the engine section sets.- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (string) –
grompp.mdp.
- class pyretis.engines.gromacs.GromacsRunner(cmd, trr_file, edr_file, exe_dir)¶
Bases:
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 (list of strings) – The command for executing GROMACS.
trr_file (string) – The GROMACS TRR file we are going to read.
edr_file (string) – A .edr file we are going to read.
exe_dir (string) – Path to where we are currently running GROMACS.
fileh (file object) – The current open file object.
running (None or object like
subprocess.Popen) – The process running GROMACS.bytes_read (integer) – The number of bytes read so far from the TRR file.
ino (integer) – The current inode we are using for the file.
stop_read (boolean) – If this is set to True, we will stop the reading.
SLEEP (float) – How long we wait after an unsuccessful read before reading again.
data_size (integer) – The size of the data (x, v, f, box, etc.) in the TRR file.
header_size (integer) – The size of the header in the TRR file.
- SLEEP = 0.1¶
- __del__()¶
Just stop execution and close file.
- __enter__()¶
Start running GROMACS, for a context manager.
The
withstatement calls__exit__()only when this method has returned, so this method stops GROMACS (stop()) when the start raises, as when mdrun ends with an error before it creates its files: the error of the start is passed on once mdrun has ended, the slot of the worker in the registry ofprocess_sessionsis empty and the files are closed.- Returns:
out (object like
GromacsRunner) – This runner, with mdrun started.
- __exit__(exc_type, exc_val, exc_tb)¶
Just stop execution and close file for a context manager.
- __init__(cmd, trr_file, edr_file, exe_dir)¶
Set the GROMACS command and the files we need.
- Parameters:
cmd (list of strings) – The command for executing GROMACS.
trr_file (string) – The GROMACS TRR file we are going to read.
edr_file (string) – A .edr file we are going to read.
exe_dir (string) – Path to where we are currently running GROMACS.
- _drain_remaining_frames()¶
Yield every complete frame left on disk from the boundary.
Called once mdrun has terminated cleanly. Because
self.bytes_readis on a frame boundary, a final frame whose data finished flushing only as mdrun exited is read here – the incremental path and this drain deliver the same frame sequence for the same on-disk bytes.- Yields:
data (dict) – The data for each remaining complete frame, with the MD step of the frame (from its header) under
'step'.
- _read_one_frame()¶
Read one whole frame from the TRR, or
Noneif not ready.The frame is the atomic unit of consumption:
self.bytes_readmarks the start of the next not-yet-read frame and is advanced only once the whole frame (header + data) is on disk and has been read. On any partial or torn read the file handle is seeked back to that boundary (see_reseek_after_partial_read()), so the invariantfileh.tell() == self.bytes_readon a frame boundary always holds. This makes the delivered frame a pure function of the bytes on disk, independent of when the reader samples the file.The header is re-read (reset to
None) on every call so a torn/partial header (EOFError) can never reuse a stale header from a previous frame, mirroringread_remaining_trr().- Returns:
data (dict or None) – The frame data, with the MD step of the frame (from its header) under
'step', orNoneif a complete frame is not yet available on disk.
- _reseek_after_partial_read(frame_start)¶
Restore
filehto a frame boundary after a partial read.A header read may advance
self.filehpastframe_startbefore the frame turns out to be incomplete (its data has not been flushed yet), or the file may have been rotated (a new inode). In both cases the file handle must be put back exactly on the frame boundary so the next read – the incremental retry or the clean-exit drain – starts there, never mid-frame.- Parameters:
frame_start (integer) – The byte offset of the frame boundary to seek back to. This is always
self.bytes_read(which is never advanced past a complete frame).
- check_poll()¶
Check the current status of the running subprocess.
- close()¶
Close the file, in case that is explicitly needed.
- get_gromacs_frames()¶
Read the GROMACS TRR file on-the-fly.
Frames are yielded in trajectory order with no gaps or duplicates:
self.bytes_readis only advanced across a whole frame, so it always sits on a frame boundary. When mdrun terminates, a non-zero exit raises loudly incheck_poll(); a clean exit drains every complete frame still on disk from that boundary. Both the incremental read and the drain therefore return exactly the complete frames mdrun wrote, so the same input yields the same frame sequence on every run regardless of reader/writer timing.- Yields:
data (dict) – The data for each TRR frame, with the MD step of the frame (from its header) under
'step'.
- start()¶
Start execution of GROMACS and wait for output file creation.
- stop()¶
Stop the current GROMACS execution.
- pyretis.engines.gromacs.get_data(fileh, header)¶
Read data from the TRR file.
- Parameters:
fileh (file object) – The file we are reading.
header (dict) – The header read from the file. Contains sizes and what to read.
- Returns:
data (dict) – The data read from the file.
data_size (integer) – The size of the data read.
- pyretis.engines.gromacs.read_gromacs_gro_file(filename)¶
Read a single configuration GROMACS GRO file.
This method will read the first configuration from the GROMACS GRO file and return the data as given by
read_gromacs_lines(). It will also explicitly return the matrices with positions, velocities and box size.- Parameters:
filename (string) – The file to read.
- Returns:
frame (dict) – This dict contains all the data read from the file.
xyz (numpy.array) – The positions. The array is (N, 3) where N is the number of particles.
vel (numpy.array) – The velocities. The array is (N, 3) where N is the number of particles.
box (numpy.array) – The box dimensions.
- pyretis.engines.gromacs.read_gromos96_file(filename)¶
Read a single configuration GROMACS .g96 file.
- Parameters:
filename (string) – The file to read.
- Returns:
rawdata (dict of list of strings) – This is the raw data read from the file grouped into sections. Note that this does not include the actual positions and velocities as these are returned separately.
xyz (numpy.array) – The positions.
vel (numpy.array) – The velocities.
box (numpy.array) – The simulation box.
- pyretis.engines.gromacs.read_remaining_trr(filename, fileh, start)¶
Read remaining frames from the TRR file.
- Parameters:
filename (string) – The file we are reading from.
fileh (file object) – The file object we are reading from.
start (integer) – The current position we are at.
- Yields:
out[0] (dict) – The header read from the file
out[1] (dict) – The data read from the file.
out[2] (integer) – The size of the data read.
- pyretis.engines.gromacs.read_trr_frame(filename, index)¶
Return a given frame from a TRR file.
- pyretis.engines.gromacs.read_xvg_file(filename)¶
Return data in xvg file as numpy array.
- pyretis.engines.gromacs.reopen_file(filename, fileh, inode, bytes_read)¶
Reopen a file if the inode has changed.
- Parameters:
filename (string) – The name of the file we are working with.
fileh (file object) – The current open file object.
inode (integer) – The current inode we are using.
bytes_read (integer) – The position we should start reading at.
- Returns:
out[0] (file object or None) – The new file object.
out[1] (integer or None) – The new inode.
- pyretis.engines.gromacs.write_gromacs_gro_file(outfile, txt, xyz, vel=None, box=None)¶
Write configuration in GROMACS GRO format.
- Parameters:
outfile (string) – The name of the file to create.
txt (dict of lists of strings) – This dict contains the information on residue-numbers, names, etc. required to write the GRO file.
xyz (numpy.array) – The positions to write.
vel (numpy.array, optional) – The velocities to write.
box (numpy.array, optional) – The box matrix.
- pyretis.engines.gromacs.write_gromos96_file(filename, raw, xyz, vel, box=None)¶
Write configuration in GROMACS .g96 format.
- Parameters:
filename (string) – The name of the file to create.
raw (dict of lists of strings) – This contains the raw data read from a .g96 file.
xyz (numpy.array) – The positions to write.
vel (numpy.array) – The velocities to write.
box (numpy.array, optional) – The box matrix.
pyretis.engines.gromacs_steps module¶
A GROMACS external MD integrator interface.
This module defines a class for using GROMACS as an external engine.
Important classes defined here¶
- GromacsEngineSteps (
GromacsEngineSteps) A class responsible for interfacing GROMACS by relaunching the executable once per order-parameter point (the slower, relaunch implementation; the canonical streaming engine lives in
pyretis.engines.gromacs).
- pyretis.engines.gromacs_steps.CONFIG_SUFFIXES = ('.g96', '.gro')¶
Configuration file suffixes. A
.g96file holds one configuration and a.grofile one or more;_extract_frameselects a frame of either by its index.
- pyretis.engines.gromacs_steps.GROMACS_PCOUPL = ('no', 'berendsen', 'isotropic', 'crescale', 'parrinellorahman', 'mttk')¶
The values of the mdp key
pcouplgrompp accepts, in the formmdp_option()gives them. grompp readsisotropicasberendsen.
- pyretis.engines.gromacs_steps.GROMACS_TCOUPL = ('no', 'berendsen', 'yes', 'nosehoover', 'andersen', 'andersenmassive', 'vrescale')¶
The values of the mdp key
tcouplgrompp accepts, in the formmdp_option()gives them. grompp readsyesasberendsen.
- class pyretis.engines.gromacs_steps.GromacsEngineSteps(gmx, mdrun=None, input_path=None, timestep=None, subcycles=None, exe_path='/home/enrico/cache/twoway-retis/wt2/docs', maxwarn=0, gmx_format='g96', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', masses=False, conf=None, template='grompp.mdp', top='topol.top')¶
Bases:
ExternalMDEngineA class for interfacing GROMACS.
This class defines the interface to GROMACS.
The configuration format handed between steps is
INTERNAL_CONFIG_FORMAT, independent of thegmx_formatsetting. Input is read in whichever format each file actually is.- Variables:
gmx (string) – The command for executing GROMACS. Note that we are assuming that we are using version 5 (or later) of GROMACS.
mdrun (string) – The command for executing GROMACS mdrun. In some cases, this executable can be different from
gmx mdrun.mdrun_c (string) – The command for executing GROMACS mdrun when continuing a simulation. This is derived from the
mdruncommand.input_path (string) – The directory where the input files are stored. The engine only reads from it.
work_path (string) – A directory of this engine’s own in the run directory (
exe_path), holding the files it derives from the input: the staged configuration converted to the other format,pyretis.mdpand the.tpr. It is removed with the engine.subcycles (int,) – The number of simulation steps of the external engine for each PyRETIS step (e.g. interaction between the softwares frequency)
exe_path (string, optional) – The absolute path at which the main PyRETIS simulation will be run.
maxwarn (integer) – Setting for the GROMACS
grompp -maxwarnoption.write_vel (boolean, optional) – True if we want to output the velocities.
write_force (boolean, optional) – True if we want to output the forces.
domain_decomp (boolean, optional) – Whether gromacs uses domain decomposition (DD) or not. This does not set domain decomposition. The user should know whether DD is executed or not.
temperature (float) – The temperature (K) the mdp file states (
read_gromacs_temperatures()):gen-temp, the temperature of the velocities GROMACS draws, and theref-tof eachtc-grpsgroup of a run coupled to a thermostat, which must all be equal.beta (float) – The inverse temperature
1 / (k_B T)in mol/kJ, with the k_B of the engine,kb.engine_temperatures (object like
EngineTemperatures) – The temperatures read from the mdp file.gen_temp_key (string) – The key the mdp file sets
gen-tempwith (mdp_key_as_written()), under which the velocity draw ofvelocity_generation = "engine"writestemperature.init_step (int) – The
init-stepof the mdp file (0 if it sets none), the MD step each GROMACS run of the engine starts at: a multiple ofsubcycles(_refuse_init_step()).
- INTERNAL_CONFIG_FORMAT = 'g96'¶
The configuration format the engine writes and reads back between steps.
grostores three decimals per coordinate, 1e-3 nm, which can move a cutoff- or threshold-based order parameter across a write/read round trip;g96carries enough digits that the round trip is exact. Input in either format is read.
- SUBCYCLE_MDP_KEYS = ('nsteps', 'nstxout', 'nstvout', 'nstfout', 'nstlog', 'nstcalcenergy', 'nstenergy')¶
The MDP keys
subcyclesis written into. Changingsubcyclesmoves the trajectory, the energy record and the log cadence together, which is what makes a temporary change (multiresolution wire fencing) a change of more than resolution.
- __init__(gmx, mdrun=None, input_path=None, timestep=None, subcycles=None, exe_path='/home/enrico/cache/twoway-retis/wt2/docs', maxwarn=0, gmx_format='g96', write_vel=True, write_force=False, domain_decomp=False, velocity_generation='engine', masses=False, conf=None, template='grompp.mdp', top='topol.top')¶
Set up the GROMACS engine.
- Parameters:
gmx (string) – The GROMACS executable.
mdrun (string) – The GROMACS mdrun executable.
input_path (string) – The absolute path to where the input files are stored.
timestep (float) – The time step used in the GROMACS MD simulation.
subcycles (integer) – The number of steps each GROMACS MD run is composed of.
exe_path (string, optional) – The absolute path at which the main PyRETIS simulation will be run. The engine creates its
work_pathin it.maxwarn (integer, optional) – Setting for the GROMACS
grompp -maxwarnoption.gmx_format (string, optional) –
'g96'or'gro'; another value raisesValueError. The engine reads each configuration in the format of its file and hands configurations between steps inINTERNAL_CONFIG_FORMAT;'gro'is warned about.write_vel (boolean, optional) – Determines if GROMACS should write velocities or not.
write_force (boolean, optional) – Determines if GROMACS should write forces or not.
domain_decomp (boolean, optional) – Whether domain decomposition (DD) is executed by GROMACS or not. User should know if this happens or not.
velocity_generation (string, optional) – How shooting-move velocities are generated.
"engine"(default) delegates to GROMACS (a zero-stepgen_velrun, which removes the centre-of-mass motion, so it requireszero_momentum = true);"maxwell"draws them in Python from a Maxwell-Boltzmann distribution via the injected random generator at the temperature of the mdp file (one reproducible stream,g96format only, requiresmasses).masses (list or string, optional) – The masses of the particles, in g/mol, for the
"maxwell"draw, one per particle of the configuration: a list of numbers, or the name of a file ininput_paththat lists them separated by spaces, commas or line breaks (_load_masses()). Only required whenvelocity_generation == "maxwell".conf (string, optional) – The starting configuration file in
input_path(e.g. ‘conf.gro’). When it is not given, the configuration is resolved from theconf.g96andconf.grostaged there (_find_staged_conf()).template (string, optional) – The GROMACS mdp template (default is ‘grompp.mdp’).
top (string, optional) – The GROMACS topology file (default is ‘topol.top’).
- _check_mass_count(npart, conf)¶
Refuse masses that are not one per particle of the configuration.
Engines without masses (
velocity_generation = "engine") pass.- Parameters:
npart (integer) – The number of particles of the configuration the engine starts from.
conf (string) – The name of that configuration, for the message.
- Raises:
ValueError – If
self.massesdoes not hold one mass per particle.
- _convert_configuration(source, name)¶
Convert a staged configuration into the work directory.
gmx editconfwrites the configuration in the format the extension ofnameselects. It runs inwork_path, which also receives its log.- Parameters:
source (string) – The staged configuration file.
name (string) – The file name of the converted configuration.
- Returns:
out (string) – The path to the converted configuration.
- _draw_velocities_maxwell(system, vel_settings, rgen)¶
Draw shooting velocities in Python (Maxwell-Boltzmann).
The g96 frame’s positions are kept; only the velocity block is redrawn from the injected random generator.
systemis updated in place (config + kinetic energy) and the potential energy is left unchanged (a velocity draw does not change the configuration).- Parameters:
system (object like
System) – The state whose velocities we redraw.vel_settings (dict) – Velocity-modification settings;
zero_momentumrequests a zero linear-momentum reset (a missing key means False).rgen (object like
RandomGenerator) – The velocity random generator, injected explicitly.
- Returns:
float – The new kinetic energy.
- _ensure_tpr()¶
Build the construction “.tpr” on first use (lazily).
The construction “.tpr” is consumed by the energy rerun of a relaunch propagation and by the trjconv frame-extraction branches (non-trr/non-g96 input and the domain-decomposition pass). Deferring it here lets the engine be constructed without running grompp; a “.tpr” built later holds the same inputs (its bytes differ only in a few process-dependent header bytes), so the run output does not depend on when it is built. The preprocessor is always run in
work_path(where the “.tpr” lives), restoringexe_dirafterwards.
- _execute_grompp(mdp_file, config, deffnm)¶
Execute the GROMACS preprocessor.
- Parameters:
mdp_file (string) – The path to the mdp file.
config (string) – The path to the GROMACS config file to use as input.
deffnm (string) – A string used to name the GROMACS files.
- Returns:
out_files (dict) – This dict contains files that were created by the GROMACS preprocessor.
- _execute_grompp_and_mdrun(config, deffnm)¶
Execute GROMACS
gromppandmdrun.Here we use the input file given in the input directory.
- Parameters:
config (string) – The path to the GROMACS config file to use as input.
deffnm (string) – A string used to name the GROMACS files.
- Returns:
out_files (dict of strings) – The files created by this command.
- _execute_mdrun(tprfile, deffnm)¶
Execute GROMACS mdrun.
This method is intended as the initial
gmx mdrunexecuted. That is, we here assume that we do not continue a simulation.- Parameters:
tprfile (string) – The .tpr file to use for executing GROMACS.
deffnm (string) – To give the GROMACS simulation a name.
- Returns:
out_files (dict) – This dict contains the output files created by
mdrun. Note that we here hard code the file names.
- _execute_mdrun_continue(tprfile, cptfile, deffnm)¶
Continue the execution of GROMACS.
Here, we assume that we have already executed
gmx mdrunand that we are to append and continue a simulation.- Parameters:
tprfile (string) – The .tpr file which defines the simulation.
cptfile (string) – The last checkpoint file (.cpt) from the previous run.
deffnm (string) – To give the GROMACS simulation a name.
- Returns:
out_files (dict) – The output files created/appended by GROMACS when we continue the simulation.
- _extend_and_execute_mdrun(tpr_file, cpt_file, deffnm)¶
Extend GROMACS and execute mdrun.
- Parameters:
tpr_file (string) – The location of the “current” .tpr file.
cpt_file (string) – The last checkpoint file (.cpt) from the previous run.
deffnm (string) – To give the GROMACS simulation a name.
- Returns:
out_files (dict) – The files created by GROMACS when we extend.
- _extend_gromacs(tprfile, time)¶
Extend a GROMACS simulation.
- Parameters:
tprfile (string) – The file to read for extending.
time (float) – The time (in ps) to extend the simulation by.
- Returns:
out_files (dict) – The files created by GROMACS when we extend.
- _extract_frame(traj_file, idx, out_file)¶
Extract a frame from a GROMACS trajectory or configuration file.
A frame of a .trr, .xtc or .trj trajectory, or of a .gro or .g96 configuration file, is written to a .gro or .g96
out_filein the format the name ofout_filegives. A configuration file with another destination, or a source of another format, is converted withgmx trjconv.- Parameters:
traj_file (string) – The GROMACS file to open.
idx (integer) – The frame number we look for.
out_file (string) – The file to dump to.
- Raises:
ValueError – If a configuration file holds fewer than
idx + 1frames.
Note
This will only properly work if the frames in the input trajectory are uniformly spaced in time.
- _find_staged_conf()¶
Return the staged configuration file name to start from.
The configuration is resolved by
staged_configuration(): the one ofconf.g96andconf.grostaged in the input directory,conf.g96when both are staged and hold the same configuration, andconf.g96when neither is staged, leaving the missing-file diagnostic tolook_for_input_files().- Returns:
out (string) – The configuration file name, relative to
input_path.- Raises:
ValueError – If
conf.g96andconf.groare both staged and hold different configurations.
- static _gen_vel_seed(rgen)¶
Draw a reproducible GROMACS
gen_seedfor an aimless kick.The engine-mode aimless velocity draw regenerates the shooting point’s velocities with a zero-step GROMACS
gen_velrun. That draw is seeded by the mdpgen_seedkeyword; the GROMACS default of-1is a time-random seed, so every shooting move would kick the point with different velocities and the whole sampled path would change from run to run. Drawing the seed from the injected velocity random generator (rgen, the same generator the Python Maxwell draw consumes) pins the kick to the controlled random stream, mirroring_ld_seed(), so the generated velocities – hence the propagated path – are byte-reproducible.- Parameters:
rgen (object like
RandomGeneratoror None) – The velocity random generator injected intomodify_velocities(). When it isNone(no controlled generator is wired) we fall back to a fixed seed so the result is at least deterministic.- Returns:
seed (int) – A positive integer seed in
[1, 2147483646].
- _grompp_and_mdrun_run(config, deffnm, gmx_steps)¶
Preprocess and run a single
mdrunofgmx_stepssteps.Unlike
_execute_grompp_and_mdrun()(which usesnsteps=subcycles), this overridesnstepsso the wholeintegratetrajectory is produced by one continuousmdrunwith no checkpoint-restart. The resulting.edris therefore free of the corrupt potential energies of checkpoint continuations (see_recompute_energies_via_rerun()).- Parameters:
config (string) – The path to the GROMACS config file to use as input.
deffnm (string) – A string used to name the GROMACS files.
gmx_steps (integer) – The total number of integration steps for the single run.
- Returns:
out_files (dict of strings) – The files created by this command.
- static _input_folder(engine_settings)¶
Return the folder of the input files of an engine section.
- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (string) –
input_pathrelative toexe_path, the folder the engine reads its input files from when it is created.- Raises:
ValueError – If the section sets no
input_path.
- classmethod _input_mdp(engine_settings)¶
Return the mdp file an engine section names.
The file is looked up as the engine looks it up when it is created: the file
mdp_template()names, ininput_pathrelative toexe_path.- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (string) – The path of the mdp file.
- classmethod _input_mdp_present(engine_settings)¶
Return whether an engine section names an mdp file that is there.
- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (boolean) – True when the section sets
input_pathand that folder holds a file_input_mdp()can take (input_file_present()).
- _ld_seed()¶
Draw a reproducible GROMACS
ld-seedfrom the engine rgen.The GROMACS stochastic integrators (
sd,bd) and the stochastic thermostats (tcoupl = v-rescale,andersen,andersen-massive) draw their random numbers fromld-seed; left unset GROMACS defaults it to-1(a time-random seed), which makes each segment irreproducible. Drawing the seed from the engine’s integration random generator (self.rgen, wired by the infinite-swapping scheduler) pins it to the controlled random stream, mirroring the LAMMPS thermostat-seed injection so such GROMACS segments are byte-reproducible. When no engine rgen is present we fall back to a fixed seed so the result is at least deterministic. A run without random numbers (mdormd-vvwithout a stochastic thermostat) does not readld-seed.- Returns:
seed (int) – A positive integer seed in
[1, 2147483646].
- _load_masses(masses)¶
Load the particle masses of the Python Maxwell-Boltzmann draw.
The masses are numbers in g/mol, each finite and positive: a list of numbers, or the name of a file in
input_pathwhose masses are separated by spaces, commas or line breaks. The count is checked against the configuration by_check_mass_count().- Parameters:
masses (list or string) – The list of masses, or the name of the file that lists them.
- Returns:
numpy.ndarray – The masses reshaped to
(npart, 1).- Raises:
ValueError – If no masses are given, if
massesis neither a list nor a file name, if an entry is not a number (a boolean or a string in the list, a word in the file), or if a mass is not finite and positive.FileNotFoundError – If the file is not in
input_path.
- _mdp_overrides(write_vel, write_force)¶
Return the MDP settings PyRETIS imposes on the user’s input.
- Parameters:
write_vel (boolean) – Whether GROMACS should write velocities.
write_force (boolean) – Whether GROMACS should write forces.
- Returns:
out (dict) – The keys to override, and their values.
continuation = nomakes anmd-vvrun start from the velocities of its configuration as those at its time; withyesit takes them as those half a time step before.
- static _mdp_path_sampling_problem(template)¶
Return why a path-sampling run cannot use an mdp file.
- Parameters:
template (string) – The path of the mdp template.
- Returns:
out (string or None) – The reason
path_sampling_problem()gives, or None forintegrator = md-vv. A refusal ends with what the md tasks do with the mdp file (_gromacs_md_tasks()).
- static _modify_input(sourcefile, outputfile, settings, delim='=', key_name=<function mdp_key_name>)¶
Write an mdp file: a template with the given keys set.
A key of the template is replaced when grompp reads it as a key of
settings(mdp_key_name(): case,-and_, and the old names), and keeps its spelling; the keys the template does not hold are added at its end. The written file holds each key once, as grompp requires.- Parameters:
sourcefile (string) – The mdp template.
outputfile (string) – The mdp file to write.
settings (dict) – The keys to set, and their values.
delim (string, optional) – The delimiter of keys and values.
key_name (callable, optional) – Gives the name grompp reads a key as; the default is
mdp_key_name().
- _prepare_shooting_point(input_file, rgen=None)¶
Create the initial configuration for a shooting move.
This creates a new initial configuration with random velocities. Here, the random velocities are obtained by running a zero-step GROMACS simulation.
- Parameters:
input_file (string) – The input configuration to generate velocities for.
rgen (object like
RandomGeneratoror None, optional) – The velocity random generator for drawing a reproducible GROMACSgen_seed(see_gen_vel_seed()). With the GROMACS default ofgen_seed = -1the draw is time-random and the shooting move – hence the whole sampled path – would differ on every run.
- Returns:
output_file (string) – The name of the file created.
energy (dict) – The energy terms read from the GROMACS .edr file.
- _propagate_from(name, path, system, ens_set, msg_file, reverse=False)¶
Propagate with GROMACS from the current system configuration.
Here, we assume that this method is called after the propagate() has been called in the parent. The parent is then responsible for reversing the velocities and also for setting the initial state of the system.
- Parameters:
name (string) – A name to use for the trajectory we are generating.
path (object like
pyretis.core.path.PathBase) – This is the path we use to fill in phase-space points.system (object like
System) – The system object gives the initial state for the integration. The order function is injected on the engine (self.order_function).ens_set (dict) – Ensemble settings. It contains:
interfaces: list of floats These interfaces define the stopping criterion.
msg_file (object like
FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.reverse (boolean, optional) – If True, the system will be propagated backward in time.
- Returns:
success (boolean) – This is True if we generated an acceptable path.
status (string) – A text description of the current status of the propagation.
- _read_configuration(filename)¶
Read output from GROMACS .g96/gro files.
- Parameters:
filename (string) – The file to read the configuration from.
- Returns:
box (numpy.array) – The box dimensions.
xyz (numpy.array) – The positions.
vel (numpy.array) – The velocities.
- static _read_init_step(mdp_file)¶
Return the
init-stepof an mdp file.- Parameters:
mdp_file (string) – The mdp file.
- Returns:
out (integer) – The
init-stepthe file sets, as grompp reads the key (read_mdp_settings()), or 0, the GROMACS default, if the file does not set it.- Raises:
ValueError – If the file sets an
init-stepthat is not an integer, which grompp refuses.
- _read_masses_file(masses, source)¶
Return the masses a file of
[engine] masseslists.- Parameters:
masses (string) – The file name
[engine] massesgives.source (string) – The file, in
input_path.
- Returns:
list of floats – The masses, in the order of the file; spaces, commas and line breaks separate them.
- Raises:
FileNotFoundError – If the file is not in
input_path.ValueError – If an entry of the file is not a number.
- _recompute_energies_via_rerun(tprfile, trrfile, name)¶
Recompute per-frame potential energy with
mdrun -rerun.The relaunch propagation accumulates its
.edrthrough repeatedconvert-tpr -extend+mdrun -cpi -appendcontinuations. The kinetic energy and temperature written there are correct, but the potential energy of every segment after the first is corrupt. Because the.trrframes (positions) ARE correct, the potential is recovered exactly by re-evaluating the trajectory in a singlemdrun -rerunagainst one consistent.tpr; this reproduces the streamingGromacsEngineand plain GROMACS byte-for-byte.-rerundoes not integrate velocities, so the resulting.edrholds only the potential terms (no kinetic energy or temperature); the caller keeps those from the appended.edr.- Parameters:
tprfile (string) – A
.tprconsistent with the trajectory topology.trrfile (string) – The completed
.trr(positions) to re-evaluate, relative toself.exe_dir.name (string) – The propagation name. The rerun writes to
{name}_rerun.*so it never clobbers the source trajectory.
- Returns:
energy (dict of numpy.ndarray) – The energies read from the rerun
.edr. Thepotentialentry is the corrected per-frame potential energy.
- _refuse_init_step(run=False)¶
Refuse an
init-stepthat is not a multiple ofsubcycles.GROMACS gives step
sof a run the MD stepinit-step + s, with theinit-stepof the mdp file (init_step), and writes a frame to the.trrand a record to the.edrat the MD steps that are multiples ofnstxoutandnstenergy, which the engine sets tosubcycles. With aninit-stepthat is not a multiple ofsubcycles, the first frame of a run is not its start: the first phase point of a leg would not be its shooting point, which no leg would hold, and the first step of an MD run would not be its starting configuration. The engine refuses such aninit-stepwhen it is set up, and before each run whose output strides it sets from the currentsubcycles: multiresolution wire fencing runs its sub-paths with the subcycles of[tis] mwf_subcycle_small_by_ensembleormwf_subcycle_small(by default[engine] subcycles // 5) in their place.- Parameters:
run (boolean, optional) – False (the default) when the engine is set up, with the
subcyclesof its section; True before a GROMACS run, whosesubcycles(a multiple of whichinit-stepis when the engine is set up) differ only for a sub-path of multiresolution wire fencing. The message says what to set in each case.- Raises:
ValueError – If
init-stepis not a multiple ofsubcycles.
- _remove_gromacs_backup_files(dirname)¶
Remove files GROMACS has backed up.
These are files starting with a ‘#’
- Parameters:
dirname (string) – The directory where we are to remove files.
- _reverse_velocities(filename, outfile)¶
Reverse velocity in a given snapshot.
- Parameters:
filename (string) – The configuration to reverse velocities in.
outfile (string) – The output file for storing the configuration with reversed velocities.
- _seeded_input(name, extra=None)¶
Create a per-segment mdp with a fresh
ld-seedinjected.The relaunch engine builds its
pyretis.mdponce at construction, so a varying per-segmentld-seedmust be written into a fresh mdp before eachgrompp. This copies the one-timepyretis.mdpto{name}.mdpin the run directory with the seed updated (see_ld_seed()).The keys in
SUBCYCLE_MDP_KEYSare also rewritten from the currentsubcycles. Multiresolution wire fencing changessubcycleson a live engine, andext_timefollows that change; the segment length and the.trr/.edrstrides must follow it too, so that each extension writes one frame and one energy record. Aninit-stepthat is not a multiple of the currentsubcyclesis refused (_refuse_init_step()).- Parameters:
name (string) – A name used for the per-segment mdp file.
extra (dict, optional) – Additional
keyword: valuemdp settings, applied last so they override both theld-seedand the subcycle keys (e.g. annstepsoverride for the single continuousintegraterun).
- Returns:
mdp_file (string) – The path to the per-segment mdp file with the seed injected.
- Raises:
ValueError – If
init-stepis not a multiple of the currentsubcycles, before the mdp file is written.
- _subcycle_settings(write_vel, write_force)¶
Return the MDP keys set from the current
subcycles.- Parameters:
write_vel (boolean) – Whether GROMACS should write velocities. If not,
nstvoutis 0.write_force (boolean) – Whether GROMACS should write forces. If not,
nstfoutis 0.
- Returns:
out (dict) – Each key of
SUBCYCLE_MDP_KEYSwith its value.
- _trajectory_filename(name)¶
GROMACS writes frames to a
.trrregardless ofself.ext.self.extis the configuration format (gro/g96); the trajectory the propagation appends frames to is the.trrnamed after the propagationname(seeout_files['trr']).
- _trr_frame_order(system, traj_file, index, offset)¶
Calculate the order parameter of a frame of a .trr file.
The positions, the velocities and the box of the system are set to those of the frame, and the velocities are reversed when
system.vel_revis True, as inpyretis.engines.external.ExternalMDEngine.calculate_order().- Parameters:
system (object like
System) – The system the order function sees.traj_file (string) – The .trr file that holds the frame.
index (integer) – The index of the frame in
traj_file.offset (integer) – The byte offset at which the frame starts in
traj_file, where the frame before it ended (0 for the first frame).
- Returns:
out[0] (list of floats) – The order parameter(s) of the frame.
out[1] (integer) – The byte offset at which the next frame starts.
- default_units = 'gromacs'¶
- dump_config(config, deffnm='conf')¶
Write a configuration to a file in the engine’s own format.
A configuration
(filename, None)is a single frame. When that file is a configuration in the other GROMACS format – a system built from an input directory staged with.growhile the engine works in.g96– it is converted throughself.top, as_extract_frame()converts a single staged frame, so the file GROMACS reads matches its name. Every other configuration is handled byExternalMDEngine.dump_config().- Parameters:
config (tuple) – The configuration given as (filename, index).
deffnm (string, optional) – The base name for the file we dump to.
- Returns:
out (string) – The file name we dumped to.
- property ext_time¶
The simulation time one trajectory extension covers, in ps.
Derived from the current
subcycles: multiresolution wire fencing changessubcycleson a live engine throughmultires_wf._temporary_subcyclesto shoot a sub-segment at a finer stride, so an extension taken during a fine segment runs for the fine segment’s time.Note that
subcyclesdrives more than this. It is written into seven MDP keys –nsteps,nstxout,nstvout,nstfout,nstlog,nstcalcenergyandnstenergy– so a temporary change alters the trajectory, the energy record and the log cadence together, not just the output stride.- Returns:
out (float) –
timestep * subcycles.
- classmethod get_default_units(settings=None)¶
Return the default unit system for the GROMACS engine.
- Parameters:
settings (dict, optional) – Full simulation settings or engine settings. This argument is ignored for the GROMACS engine.
- Returns:
out (string) – The default unit system for the GROMACS engine.
- get_energies(energy_file, begin=None, end=None)¶
Return energies from a GROMACS run.
- Parameters:
energy_file (string) – The file to read energies from.
begin (float, optional) – Select the time for the first frame to read.
end (float, optional) – Select the time for the last frame to read.
- Returns:
energy (dict of numpy.arrays) – The energies read from the produced GROMACS xvg file.
- classmethod input_path_sampling_problem(engine_settings)¶
Return why a path-sampling run cannot use the mdp file of a section.
The mdp file is looked up as
read_input_temperatures()looks it up, and its integrator is checked aspath_sampling_problem()checks it.- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (string or None) – The reason, or None for
integrator = md-vv. None for a section without an mdp file to read (_input_mdp_present()): the run reports the missing file where it reads the temperature of the section (read_input_temperatures()) or creates the engine.
- integrate(system, order_function, steps, thermo='full')¶
Perform several integration steps.
This method will perform several integration steps using GROMACS. It will also calculate order parameter(s) and energy terms if requested.
- Parameters:
system (object like
System) – The system object gives the initial state for the integration. With an order function, its configuration is the final configuration of the run when the integration is done.order_function (object like
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).
- classmethod mdp_template(engine_settings)¶
Return the name of the mdp file the engine reads.
- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (string) – The
templateof the section,grompp.mdpwhen it sets none.
- modify_velocities(system, vel_settings, rgen)¶
Modify the velocities of the current state.
This method will modify the velocities of a time slice.
- Parameters:
system (object like
System) – This is the system that contains the particles we are investigating.vel_settings (dict) – It contains:
sigma_v: numpy.array, optional Negative values select aimless shooting. Zero or positive values set the standard deviation, one for each particle, for soft velocity perturbations.
zero_momentum: boolean, optional If True, we reset the linear momentum to zero after generating. A missing key means False. In
"engine"mode GROMACSgen_velremoves the centre-of-mass motion of the velocities it generates, so this mode requires True.rescale: float, optional The energy to re-scale the drawn velocities to, the
[tis]rescale_energy. GROMACS does not re-scale, so a positive value is refused in both modes (refuse_energy_rescale()).
rgen (object like
RandomGenerator) – The velocity random generator. In"maxwell"mode it draws the velocities directly (the Python draw); in the default"engine"mode it seeds the GROMACSgen_veldraw via a reproduciblegen_seed(see_gen_vel_seed()). Both modes therefore consume the controlled random stream, so the kick is byte-reproducible.
- Returns:
dek (float) – The change in the kinetic energy.
kin_new (float) – The new kinetic energy.
- Raises:
NotImplementedError – If energy re-scaling or a soft velocity change is requested, or if
zero_momentumis False in"engine"mode.
- path_sampling_problem()¶
Return why a path-sampling run cannot use this engine.
The integrator of the mdp template (
integrator, GROMACS’s defaultmdwhen it is not set; grompp reads the value ignoring case,-and_) must bemd-vv: velocity Verlet stores the velocities at the time of the positions.mdandsdare leap-frog integrators, which store them half a time step away from the positions;bdintegrates without velocities (Brownian dynamics, which a path-sampling run runs with the internalLangevinengine andhigh_friction);md-vv-avektakes the velocities of the configuration a run starts from as those half a time step before it; the other integrators run no dynamics. Withmd-vv, the thermostat and the barostat must be ones a path-sampling run accepts (gromacs_coupling_problem()).- Returns:
out (string or None) – The reason, or None for
integrator = md-vvwith a coupling a path-sampling run accepts.
- path_sampling_warnings()¶
Return why a path-sampling run with this engine is not exact.
The thermostat and the barostat of the mdp template, with the time step of the engine (
gromacs_coupling_warnings()).- Returns:
out (list of strings) – The warnings; empty when the template selects no such scheme.
- classmethod read_input_temperatures(engine_settings)¶
Read the temperatures of the mdp file an engine section names.
The mdp file is looked up as the engine looks it up when it is created (
_input_mdp()).- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (object like
EngineTemperatures) – The temperaturesread_gromacs_temperatures()reads.
- static rename_energies(gmx_energy)¶
Rename GROMACS energy terms to PyRETIS convention.
- static select_energy_terms(terms)¶
Select energy terms to extract from GROMACS.
- Parameters:
terms (string) – This string will name the terms to extract:
'full'or'path'; any other value selects'path'.
- set_mdrun(md_items)¶
Configure the per-worker mdrun command and execution directory.
Extends the base (which sets
exe_dir): the infinite-swapping scheduler points each worker at its ownwmdrunlaunch command, so buildself.mdrun/self.mdrun_cfrom it. Without awmdruninmd_items, the command given at construction is left untouched.- Parameters:
md_items (dict) – The run items of the move.
exe_dir(set by the base) and the optionalwmdrunbase mdrun command of the worker.
- step(system, name)¶
Perform a single step with GROMACS.
- Parameters:
system (object like
System) – The system we are integrating.name (string) – To name the output files from the GROMACS step.
- Returns:
out (string) – The name of the output configuration, obtained after completing the step.
- temperature_input_keys = ('input_path',)¶
- temperature_keys = 'gen-temp, and the ref-t of each tc-grps group of a run coupled to a thermostat, in the mdp file'¶
- temperature_source = 'input'¶
- unmarked_section_temperature = True¶
- pyretis.engines.gromacs_steps.MASSES_FORMS = 'the masses of the particles, [engine] masses, in g/mol, one per particle: a list of numbers, or the name of a file in input_path that lists them separated by spaces, commas or line breaks.'¶
The forms of
[engine] masses, as the refusals name them.
- pyretis.engines.gromacs_steps.MDP_OLD_NAMES = {'nstxtcout': 'nstxoutcompressed', 'unconstrainedstart': 'continuation'}¶
The old names of the mdp keys PyRETIS sets, which grompp reads as the key of the current name and refuses together with it, in the form
mdp_key_name()gives them.
- pyretis.engines.gromacs_steps.NSTCOUPLE_DEFAULT_MOST = 100¶
GROMACS 2025.4’s coupling interval for
nsttcouple = -1andnstpcouple = -1when the time constant allows it, and when no time constant is positive.
- pyretis.engines.gromacs_steps.NSTCOUPLE_STEPS_PER_TAU = {'crescale': 25, 'vrescale': 5}¶
GROMACS 2025.4’s fewest time steps per tau-t (
tcoupl = v-rescale) and per tau-p (pcoupl = c-rescale) at which its grompp couples every time step whennsttcoupleornstpcoupleis -1: it couples everyint(tau / (steps * dt))steps, at least 1 and at most 100, reduced to a divisor of 100, with tau the shortest positive tau-t or tau-p and dt the time step of the run. The coupling interval is above 1 when tau is at least twicesteps * dt. grompp resolves -1 by the rule of its GROMACS version: another version can choose another interval.
- pyretis.engines.gromacs_steps.PATH_SAMPLING_REFUSED_PCOUPL = {'berendsen': 'the Berendsen barostat, a deterministic rescaling of the box that is not time reversible and carries the pressure of the last coupling step', 'isotropic': 'the Berendsen barostat (grompp reads isotropic as berendsen), a deterministic rescaling of the box that is not time reversible and carries the pressure of the last coupling step', 'mttk': 'the MTTK barostat, whose box velocity and thermostat variables carry a memory from one time step to the next', 'parrinellorahman': 'the Parrinello-Rahman barostat, whose box velocity carries a memory from one time step to the next'}¶
deterministic, and with a memory between time steps or without time reversibility.
- Type:
The barostats a path-sampling run refuses
- pyretis.engines.gromacs_steps.PATH_SAMPLING_REFUSED_TCOUPL = {'berendsen': 'the Berendsen thermostat, a deterministic rescaling of the velocities that is not time reversible', 'nosehoover': 'the Nose-Hoover thermostat (a chain with md-vv), a deterministic thermostat whose friction variables carry a memory from one time step to the next', 'yes': 'the Berendsen thermostat (grompp reads yes as berendsen), a deterministic rescaling of the velocities that is not time reversible'}¶
deterministic, and with a memory between time steps or without time reversibility.
- Type:
The thermostats a path-sampling run refuses
- pyretis.engines.gromacs_steps.TAU_P_DEFAULT = 5.0¶
GROMACS 2025.4’s tau-p, in ps, which its grompp takes when an mdp file does not set it.
- pyretis.engines.gromacs_steps._COUPLING_KEYS = {'crescale': ('pcoupl', 'nstpcouple'), 'vrescale': ('tcoupl', 'nsttcouple')}¶
The mdp key that selects each coupling of
NSTCOUPLE_STEPS_PER_TAU, and the key of its interval.
- pyretis.engines.gromacs_steps._GROMACS_PIECE_START = 'Every new piece of trajectory of a path-sampling run (the backward and the forward piece of a shooting move, the extension of a path) starts GROMACS afresh from a stored frame (positions, velocities and box)'¶
What a path-sampling run with GROMACS starts each piece of trajectory from, for the messages.
- pyretis.engines.gromacs_steps._andersen_massive_warning(settings, template, tcoupl, time_step)¶
Return the warning of the massive Andersen thermostat.
- Parameters:
settings (dict of string) – The mdp settings (
read_mdp_settings()).template (string) – The mdp file.
tcoupl (string) – The value of
tcouplas the template writes it.time_step (float) – The time step of the run, in ps: the
[engine] timestep, which every run writes asdt.
- Returns:
out (string) – The warning, with the randomisation interval
round(tau-t / dt)of the first group, as GROMACS takes it.
- pyretis.engines.gromacs_steps._coupled_taus(settings, scheme, template)¶
Return the time constants of the groups a coupling acts on.
- Parameters:
settings (dict of string) – The mdp settings (
read_mdp_settings()).scheme (string) –
'vrescale'or'crescale'.template (string) – The mdp file, for the message.
- Returns:
out (list of float) – The time constants in ps: the tau-t of each group with tau-t 0 or above (mdrun couples no group with a negative tau-t), or the tau-p (
TAU_P_DEFAULTwhen the template does not set it).
- pyretis.engines.gromacs_steps._coupling_interval_problem(settings, template, tcoupl, pcoupl)¶
Return why a path-sampling run refuses a coupling interval.
grompp resolves
nsttcouple = -1, andnstpcouple-1 or below, by the rule of its GROMACS version (GROMACS 2025.4: from the time constants,_resolved_interval()), and grompp of GROMACS 2025.4 keeps every other value.tcoupl = v-rescalewithnsttcouple = 0never acts, while its reference temperature is read as the temperature of the run; withnsttcouplebelow -1, mdrun couples with a negative interval and the velocities become not a number.pcoupl = c-rescalewithnstpcouple = 0never acts.- Parameters:
settings (dict of string) – The mdp settings (
read_mdp_settings()).template (string) – The mdp file, for the message.
tcoupl (string) – The value of
tcoupl, as the template writes it.pcoupl (string) – The value of
pcoupl, as the template writes it.
- Returns:
out (string or None) – The reason, naming each interval, or None.
- pyretis.engines.gromacs_steps._coupling_interval_warning(settings, scheme, template, time_step)¶
Return the warning of the coupling interval of a scheme, or None.
An interval above 1 is warned of, and so is the default -1 (and an
nstpcouplebelow -1, which grompp reads as -1), which leaves the interval to grompp: grompp resolves it by the rule of its GROMACS version, and the warning names the interval grompp of GROMACS 2025.4 resolves (_resolved_interval()). An interval of 1, and a coupling that acts on no group, give no warning;gromacs_coupling_problem()refuses the other values before.- Parameters:
settings (dict of string) – The mdp settings (
read_mdp_settings()).scheme (string) – The coupling, a key of
NSTCOUPLE_STEPS_PER_TAU.template (string) – The mdp file, for the message.
time_step (float) – The time step of the run, in ps: the
[engine] timestep, which every run writes asdt.
- Returns:
out (string or None) – The warning, or None.
- pyretis.engines.gromacs_steps._gromacs_md_tasks(template)¶
Return what the md tasks do with an mdp file path sampling refuses.
The
md,md-nveandmd-fluxtasks read the temperature of the mdp file withread_gromacs_temperatures()and take the one temperature its settings hold, which decides the sentence (md_tasks_sentence()).- Parameters:
template (string) – The mdp file.
- Returns:
out (string) – A sentence that says that every task refuses the mdp file, with the reason, for a file the reader refuses or whose settings hold no temperature or different ones; else that the
md,md-nveandmd-fluxtasks accept it.
- pyretis.engines.gromacs_steps._interval_warning(template, coupling, key, interval)¶
Return the warning of a coupling set to every N > 1 time steps.
- Parameters:
template (string) – The mdp file.
coupling (string) – The coupling, as
tcoupl = v-rescale.key (string) –
'nsttcouple'or'nstpcouple'.interval (int) – The interval the template sets, in time steps.
- Returns:
out (string) – The warning.
- pyretis.engines.gromacs_steps._mass_from_number(value)¶
Return the mass an entry of a masses list gives.
- Parameters:
value (object) – One entry of the list: a real number, a numpy one included.
- Returns:
float – The entry, as a float.
- Raises:
ValueError – If the entry is not a real number: a boolean is not read as 1 or 0.
- pyretis.engines.gromacs_steps._mass_from_word(word, source)¶
Return the mass a word of a masses file gives.
- Parameters:
word (string) – One entry of the file.
source (string) – The file, for the message.
- Returns:
float – The number the word holds.
- Raises:
ValueError – If the word is not a number.
- pyretis.engines.gromacs_steps._mdp_number(settings, name, template, default, kind=<class 'float'>)¶
Return a number of the mdp settings.
- Parameters:
settings (dict of string) – The mdp settings (
read_mdp_settings()).name (string) – The key, as the message names it (
nsttcouple).template (string) – The mdp file, for the message.
default (number) – The GROMACS default, for a key the template does not set.
kind (type, optional) –
floatorint.
- Returns:
out (number) – The value.
- Raises:
ValueError – If the value is not a number of the kind (grompp refuses it).
- pyretis.engines.gromacs_steps._mdp_numbers(settings, name, template)¶
Return the numbers of an mdp key that holds one per group.
- Parameters:
settings (dict of string) – The mdp settings (
read_mdp_settings()).name (string) – The key, as the message names it (
tau-t).template (string) – The mdp file, for the message.
- Returns:
out (list of float) – The values; empty when the template does not set the key.
- Raises:
ValueError – If a value is not a number (grompp refuses it).
- pyretis.engines.gromacs_steps._remove_directory(dirname)¶
Remove a directory and its content when it exists.
- Parameters:
dirname (string) – The directory to remove.
- pyretis.engines.gromacs_steps._resolved_interval(taus, scheme, time_step)¶
Return the interval grompp of GROMACS 2025.4 gives the default -1.
grompp of GROMACS 2025.4 resolves
nsttcouple = -1, andnstpcouple-1 or below, from the shortest positive time constant and the time step of the run (NSTCOUPLE_STEPS_PER_TAU), and toNSTCOUPLE_DEFAULT_MOSTwhen no time constant is positive. grompp resolves the default by the rule of its GROMACS version: another version can choose another interval.- Parameters:
taus (list of float) – The time constants of the groups the coupling acts on, in ps (
_coupled_taus()), at least one.scheme (string) – The coupling, a key of
NSTCOUPLE_STEPS_PER_TAU.time_step (float) – The time step of the run, in ps: the
[engine] timestep, which every run writes asdt.
- Returns:
interval (int) – The interval in time steps, 1 when GROMACS 2025.4 couples at every time step.
how (string) – What GROMACS 2025.4 resolves the interval from.
- pyretis.engines.gromacs_steps.gromacs_coupling_problem(settings, template)¶
Return why a path-sampling run refuses the coupling of an mdp file.
A path-sampling run refuses
tcouplberendsen(also writtenyes) andnose-hoover, andpcouplberendsen(also writtenisotropic),parrinello-rahmanandmttk: deterministic thermostats and barostats with a memory between time steps or without time reversibility. Every new piece of trajectory starts GROMACS from a stored frame, with the memory of the coupling at its initial value. Values are compared as grompp compares them (mdp_option()); a template without the key couples with the GROMACS defaultno. A coupling interval at which mdrun never couples, or couples with a negative interval, is refused too (_coupling_interval_problem()). The refusal of a coupling ends with what the md tasks do with the mdp file, as its temperature reader decides (md_tasks_sentence()).- Parameters:
settings (dict of string) – The mdp settings (
read_mdp_settings()).template (string) – The mdp file, for the message and for the temperature reader (
read_gromacs_temperatures()).
- Returns:
out (string or None) – The reason, naming each refused coupling and what to use instead, or None.
- Raises:
Exception – As
read_gromacs_temperatures()raises it for a refused coupling, other than itsValueError.
- pyretis.engines.gromacs_steps.gromacs_coupling_warnings(settings, template, time_step)¶
Return why a path-sampling run with an mdp file is not exact.
A warning is given for:
pcoupl = c-rescale, a stochastic barostat that carries the pressure of the last coupling step; atcoupl = v-rescaleorpcoupl = c-rescalecoupling applied every N > 1 time steps (nsttcouple,nstpcoupleabove 1) or at the interval grompp chooses (the default -1; the warning names the interval grompp of GROMACS 2025.4 resolves withtime_step,_coupling_interval_warning()); andtcoupl = andersen-massive, which randomises every velocity at the first time step of each run and then every tau-t / dt steps. Every new piece of trajectory starts GROMACS from a stored frame at time step 0. Anannealingother thanno, a temperature ramp, is refused in every task by the temperature reader (read_gromacs_temperatures()).- Parameters:
settings (dict of string) – The mdp settings (
read_mdp_settings()), with a couplinggromacs_coupling_problem()accepts.template (string) – The mdp file, for the message.
time_step (float) – The time step of the run, in ps: the
[engine] timestep, which every run writes asdt.
- Returns:
out (list of strings) – The warnings, each naming the scheme, why the path sampling is not exact with it, and what to use instead.
- pyretis.engines.gromacs_steps.mdp_key_name(keyword)¶
Return the name grompp reads an mdp key as.
grompp compares mdp keys ignoring case and the characters
-and_(Continuation,continuationandref_t,ref-t), and reads an old name of a key as the key (MDP_OLD_NAMES:unconstrained-startiscontinuation).- Parameters:
keyword (string) – The key as written in an mdp file.
- Returns:
out (string) – The key in lower case without
-and_, its current name for an old name.
- pyretis.engines.gromacs_steps.mdp_option(value)¶
Return an mdp option the way grompp compares it.
- Parameters:
value (string) – The option as written in an mdp file.
- Returns:
out (string) –
valuein lower case without-and_(Nose-Hooverisnosehoover).
pyretis.engines.internal module¶
Definition of numerical MD integrators.
These integrators are representations of engines for performing molecular dynamics. Typically they will propagate Newtons equations of motion in time numerically.
Important classes defined here¶
- MDEngine (
MDEngine) Base class for internal MDEngines.
- RandomWalk (
RandomWalk) A Random Walk integrator.
- Verlet (
Verlet) A Verlet MD integrator.
- VelocityVerlet (
VelocityVerlet) A Velocity Verlet MD integrator.
- Langevin (
Langevin) A Langevin MD integrator.
- class pyretis.engines.internal.Langevin(timestep, gamma, rgen=None, seed=0, high_friction=False)¶
Bases:
MDEngineThe Langevin MD integrator.
This class defines a Langevin integrator.
- Variables:
rgen (object like
RandomGenerator) – This is the class that handles the generation of random numbers.gamma (float) – The friction parameter.
high_friction (boolean) – Determines if we are in the high friction limit and should do the over-damped version.
init_params (boolean) – If true, we will initiate parameters for the Langevin integrator when integration_step is invoked.
param_high (dict) –
This contains the parameters for the high friction limit. Here we integrate the equations of motion according to:
r(t + dt) = r(t) + dt * f(t)/m*gamma + dr. The items in the dict are:sigma : float standard deviation for the positions, used when drawing dr.
bddt : numpy.array Equal to
dt*gamma/masses, since the masses is a numpy.array this will have the same shape.
param_iner (dict) –
This dict contains the parameters for the non-high friction limit where we integrate the equations of motion according to:
r(t + dt) = r(t) + c1 * dt * v(t) + c2*dt*dt*a(t) + drandv(r + dt) = c0 * v(t) + (c1-c2)*dt*a(t) + c2*dt*a(t+dt) + dv. The dict contains:c0 : float Corresponds to
c0in the equation above.a1 : float Corresponds to
c1*dtin the equation above.a2 : numpy.array Corresponds to
c2*dt*dt/massin the equation above. Here we divide by the masses in order to use the forces rather than the acceleration. Since the masses might be different for different particles, this will result in a numpy.array with shape equal to the shape of the masses.b1 : numpy.array Corresponds to
(c1-c2)*dt/massin the equation above. Here we also divide by the masses, resulting in a numpy.array.b2 : numpy.array Corresponds to
c2*dt/massin the equation above. Here we also divide by the masses, resulting in a numpy.array.mean : numpy.array (2,) The means for the bivariate Gaussian distribution.
cov : numpy.array (2,2) This array contains the covariance for the bivariate Gaussian distribution. param_iner[‘mean’] and param_iner[‘cov’] are used as parameters when drawing
dranddvfrom the bivariate distribution.
Note
Outside the high friction limit, the
dranddvof each particle are drawn together with themultivariate_normalmethod ofrgen, from the Cholesky factor of the covariance that the parameters hold (param_iner['cho'], computed once with the other parameters). In the high friction limit,dris drawn with thenormalmethod ofrgen.- __init__(timestep, gamma, rgen=None, seed=0, high_friction=False)¶
Set up the Langevin integrator.
Actually, it is very convenient to set some variables for the different particles. However, to have a uniform initialisation for the different integrators, we postpone this. This initialisation can be done later by calling explicitly the function self._init_parameters(system) or it will be called the first time self.integration_step is invoked.
- Parameters:
timestep (float) – The time step in internal units.
gamma (float) – The gamma parameter for the Langevin integrator.
rgen (string, optional) – This string can be used to pick a particular random generator, which is useful for testing.
seed (integer, optional) – A seed for the random generator.
high_friction (boolean, optional) – Determines if we are in the high_friction limit and should do the over-damped version.
- _init_parameters(system)¶
Extra initialisation of the Langevin integrator.
- Parameters:
system (object like
System) – The system to integrate/act on. Assumed to have a particle list insystem.particles.- Returns:
out (None) – Does not return anything, but updates
self.param.
- integration_step(system)¶
Langevin integration, one time step.
- Parameters:
system (object like
System) – The system to integrate/act on. Assumed to have a particle list insystem.particles.- Returns:
out (None) – Does not return anything, but alters the state of the given system.
- integration_step_inertia(system)¶
Langevin integration, one time step.
- Parameters:
system (object like
System) – The system to integrate/act on. Assumed to have a particle list insystem.particles.- Returns:
out (None) – Does not return anything, but alters the state of the given system.
- integration_step_overdamped(system)¶
Over damped Langevin integration, one time step.
- Parameters:
system (object like
System) – The system to integrate/act on. Assumed to have a particle list insystem.particles.- Returns:
out (None) – Does not return anything, but alters the state of the given system.
- load_restart_info(info)¶
Load restart information.
- Parameters:
info (dict) – The dictionary with the restart information, should be similar to the dict produced by
restart_info().
- restart_info()¶
Return restart info.
The restart info for the engine Langevin.
- Returns:
info (dict) – Contains all the updated simulation settings and counters.
- class pyretis.engines.internal.MDEngine(timestep, description, dynamics=None)¶
Bases:
EngineBaseBase class for internal MD integrators.
This class defines an internal MD integrator. This class of integrators work with the positions and velocities of the system object directly. Further, we make use of the system object in order to update forces etc.
- Variables:
timestep (float) – Time step for the integration.
description (string) – Description of the MD integrator.
dynamics (str) – A short string to represent the type of dynamics produced by the integrator (NVE, NVT, stochastic, …).
section (string) – The input section the engine is built from:
engine, or the sectionpyretis.engines.factory.create_inf_engine()builds it from (engine0,engine1, …).setup_streaming()reads the engine’ssubcyclesthere.subcycles (integer) – The number of integration steps between two stored frames of a path: a streamed path, and a path
propagate()andkick_across_middle()generate in memory.
- __call__(system)¶
To allow calling MDEngine(system).
Here, we are just calling self.integration_step(system).
- Parameters:
system (object like
System) – The system we are integrating.- Returns:
out (None) – Does not return anything, but will update the particles.
- __init__(timestep, description, dynamics=None)¶
Set up the integrator.
- Parameters:
timestep (float) – The time step for the integrator in internal units.
description (string) – A short description of the integrator.
dynamics (string or None, optional) – Description of the kind of dynamics the integrator does.
- _calculate_order_streaming(system)¶
Order parameter for a file-backed snapshot System.
- static _draw_maxwellian(system, rgen, sigma_v=None)¶
Draw Maxwellian velocities for
systemusingrgen.Replicates
RandomGenerator.draw_maxwellian_velocities()exactly (samesigma_vfrombeta/imassand the samenormaldraw) but accepts the rawnumpy.random.Generatorthe infinite-swap scheduler injects as the velocity-generation random generator (pens['rgen-eng']), which does not carry the pyretisdraw_maxwellian_velocitiesmethod.
- _dump_config_streaming(config, deffnm)¶
Extract a single frame from a trajectory into its own file.
- _ensure_dynamics_rgen()¶
Wrap a raw numpy dynamics rgen in the pyretis generator API.
Stochastic integrators (Langevin / random walk) draw their dynamics noise from
self.rgenusing the pyretis generator surface (notablymultivariate_normal(..., cho=...)). The infinite-swap scheduler, however, injects a rawnumpy.random.Generatorontoengine.rgenper move, and the kick initiation, sequential or parallel, per ensemble (initiate_path_ensemble_kick()). To keep the dynamics draws working – and deterministic – wrap that raw generator inPCG64Generator, which exposes the pyretis surface while drawing from the very same (deterministic) underlying stream.propagate()andkick_across_middle()call it before they integrate, in memory as in the streaming loop. Engines withoutself.rgen(Verlet / velocity-Verlet) and already-wrapped generators are left untouched.
- _evaluate_potential_and_force(system)¶
Evaluate potential/force using the engine’s forcefield.
On first call, lazily acquires the forcefield from the system if not yet set via
set_forcefield().
- _fresh_stream_system(pos, vel)¶
Return a working in-memory System seeded with pos/vel.
Copies the streaming template (so the box, masses, particle names and force field are all in place) and writes the given positions and velocities into it. The template’s own state is never mutated.
- static _get_force(system)¶
Return the force array of a system.
- _integrate_frame(system, reverse)¶
Integrate an in-memory system from one stored frame to the next.
A frame of a path is
subcyclesintegration steps after the frame before it, in the in-memory loop as in a streamed path (_propagate_streaming()).- Parameters:
system (object like
System) – The system, changed in place.reverse (boolean) – If True, the system is integrated backward in time: its velocities are reversed around each step.
- _is_streaming(system)¶
Return True when
systemis a file-backed snapshot.The in-memory loop always hands the engine a
Systemwith particles attached; the coordinator hands it a snapshot without particles whoseconfigpoints at a trajectory file. Streaming additionally requires the engine to have a template (set bysetup_streaming()).
- _materialize_system(system)¶
Read the frame
system.configpoints at into a System.Returns the working in-memory
Systemplus the raw 3-columnpos/vel/boxarrays read from disk (kept so the produced frames are written back at full xyz width).
- _modify_velocities_streaming(system, vel_settings, rgen)¶
Draw shooting velocities for a file-backed snapshot System.
Mirrors
TurtleMDEngine.modify_velocities(): read the current frame, draw new velocities (or perturb them) with the injected random generator, write agenvel.xyzfile and point the system at it. The kinetic-energy change is returned.
- _propagate_streaming(path, ens_set, system, reverse)¶
Propagate a file-backed snapshot System (coordinator loop).
Counterpart of
TurtleMDEngine._propagate_from()for the internal integrators: materialise the starting frame, run the in-memory integrator forward (or backward) one recorded frame at a time, write each frame to an xyz trajectory, and build snapshotSystemobjects pointing at it.self.stepscounts the integration steps, for the scheduler’s subcycle accounting.
- calculate_order(system, xyz=None, vel=None, box=None)¶
Return the order parameter.
This method is just to help to calculate the order parameter in cases where only the engine can do it.
- Parameters:
system (object like
System) – This is the system that contains the particles we are investigating. The order function is injected on the engine (self.order_function).xyz (numpy.array, optional) – The positions to use. Typically for internal engines, this is not needed. It is included here as it can be used for testing and also to be compatible with the generic function defined by the parent.
vel (numpy.array, optional) – The velocities to use.
box (numpy.array, optional) – The current box vectors.
- Returns:
out (list of floats) – The calculated order parameter(s).
- clean_up()¶
Clean up after using the engine.
For the in-memory loop there is nothing to clean (no files are produced and no streaming template is attached), so this is a no-op. Only when the engine runs in the streaming (file-backed) loop (a template was attached by
setup_streaming()) and the scheduler has handed it a privateexe_dirdo we remove the working files there so a re-used engine starts from a clean directory.
- default_temperature = 1.0¶
- default_units = 'lj'¶
- dump_phasepoint(phasepoint, deffnm=None)¶
Dump a phase point to a file.
In the in-memory loop the phase points carry their own particles and there is nothing to dump, so this is a no-op (
EngineBase.dump_phasepoint()declares the method for every engine). In the streaming (file-backed) loop the phase point is a snapshot whoseconfigpoints into a trajectory file; we extract that single frame to its own file and re-point the phase point at it, exactly as the external base does.
- engine_type = 'internal'¶
- classmethod get_default_units(settings=None)¶
Return the default unit system for internal engines.
- Parameters:
settings (dict, optional) – Full simulation settings or engine settings. This argument is ignored for internal engines.
- Returns:
out (string) – The default unit system for internal engines.
- integrate(system, order_function, steps, thermo='full')¶
Perform several integration steps.
This method will perform several integration steps, but it will also calculate order parameter(s) if requested and energy terms.
- Parameters:
system (object like
System) – The system we are integrating.order_function (object like
OrderParameteror None) – An order function can be specified if we want to calculate the order parameter along with the simulation.steps (integer) – The number of steps we are going to perform. Note that we do not integrate on the first step (e.g. step 0) but we do obtain the other properties. This is to output the starting configuration.
thermo (string, optional) – Select the thermodynamic properties we are to calculate.
- Yields:
results (dict) – The result of a MD step. This contains the state of the system and also the order parameter(s) (if calculated) and the thermodynamic quantities (if calculated).
- integration_step(_)¶
Perform a single time step of the integration.
- Parameters:
- (place holder)
- Returns:
out (None) – Does not return anything, in derived classes it will typically update the given System.
- invert_dt()¶
Invert the time step for the integration.
- Returns:
out (boolean) – True if the time step is positive, False otherwise.
- kick_across_middle(system, ens_set, middle, tis_settings, rgen)¶
Force a phase point across the middle interface.
This is accomplished by repeatedly kicking the phase point so that it crosses the middle interface.
- Parameters:
system (object like
System) – The working state we repeatedly kick and integrate. The order function is injected on the engine (self.order_function).ens_set (dict) – Ensemble settings, unused here; the argument belongs to the signature of
EngineBase.kick_across_middle().middle (float) – This is the value for the middle interface.
tis_settings (dict) – This dictionary contains settings for TIS. Explicitly used here:
zero_momentum: boolean, determines if the momentum is zeroed after each kick. A missing key means False.
rescale_energy: float or False, the total energy each kick is re-scaled to; False, or a value that is not positive, leaves the kicked velocities unscaled.
Every kick is an aimless draw (
make_kick_velocity_settings()).rgen (object like
RandomGenerator) – The velocity-generation random generator, injected per call (distinct from the integrationself.rgen).
- Returns:
Note
This function will update the system state.
- modify_velocities(system, vel_settings, rgen)¶
Modify the velocities of the current state.
This method will modify the velocities of a time slice. And it is part of the integrator since it, conceptually, fits here: we are acting on the system and modifying it.
- Parameters:
system (object like
System) – This is the system that contains the particles we are investigating.vel_settings (dict) – It contains all the info for the velocity:
sigma_v : numpy.array, optional Negative values select aimless shooting. Zero or positive values set the standard deviation, one for each particle, for soft velocity perturbations.
zero_momentum : boolean, optional If True, we reset the linear momentum to zero after generating. A missing key means False.
rescale : float, optional In some NVE simulations, we may wish to re-scale the energy to a fixed value. If rescale is a float > 0, we will re-scale the energy (after modification of the velocities) to match the given float.
rgen (object like
RandomGenerator) – The velocity-generation random generator, injected per call. It is kept distinct from the integrationself.rgenthat stochastic integrators (Langevin, random walk) own, so a shooting-move velocity kick never perturbs the dynamics random stream. Anumpy.random.Generatoris drawn from through aPCG64Generatorover its stream.
- Returns:
dek (float) – The change in the kinetic energy.
kin_new (float) – The new kinetic energy.
- propagate(path, ens_set, system, reverse=False)¶
Generate a path by integrating until a criterion is met.
This function will generate a path by calling the function specifying the integration step repeatedly. The integration is carried out until the order parameter has passed the specified interfaces or if we have integrated for more than a specified maximum number of steps.
- Parameters:
path (object like
PathBase) – This is the path we use to fill in phase-space points. We are here not returning a new path, this since we want to delegate the creation of the path (type) to the method that is running propagate.ens_set (dict) – Ensemble settings. It contains:
interfaces : list of floats These interfaces define the stopping criterion.
system (object like
System) – The system object gives the initial state for the integration; it is mutated in place during propagation. The order function is injected on the engine (self.order_function).reverse (boolean, optional) – If True, the system will be propagated backward in time.
- Returns:
success (boolean) – This is True if we generated an acceptable path.
status (string) – A text description of the current status of the propagation.
- select_thermo_function(thermo='full')¶
Select function for calculating thermodynamic properties.
- Parameters:
thermo (string, or None, optional) – String which selects the kind of thermodynamic output.
- Returns:
thermo_func (callable or None) – The function matching the requested thermodynamic output.
- set_forcefield(forcefield)¶
Attach a force field for system-independent evaluation.
- setup_streaming(settings)¶
Build the file-backed (streaming) template for this engine.
Mirrors
TurtleMDEngine, which builds its own box / particles / potential in__init__: here we reuse thepyretis.setup.createsystem.create_system()andpyretis.setup.createforcefield.create_force_field()to build a fully-attached in-memorySystemtemplate (particles, box, masses, force field). Each streaming propagation materialises a fresh working copy of this template, fills in the positions and velocities read from disk, runs the existing in-memory integrator, and writes the produced frames back out as an xyz trajectory.The engine streams with the
subcyclesof the section it is built from, itssectionattribute:[engine]for the engine of[engine], and the pool section itself ([engine0],[engine1], …) for an engine of a pool.- Parameters:
settings (dict) – The full (coordinator) settings dictionary. It carries the canonical
[system]/[box]/[particles]/[potential]/[forcefield]/[engine]sections that the system and force field are built from, and the engine section the engine is built from.
- streaming_beta()¶
Return the inverse temperature of the system the engine streams.
In the file-backed (streaming) loop the engine integrates, and draws velocities for, a copy of its streaming template (
setup_streaming()): the System that[system] temperatureand[system] unitsgive, whosebetais1 / (k_B * temperature)with the Boltzmann constant of the unit system. A file-backed snapshot the engine is handed carries no temperature of its own.- Returns:
out (float or None) – The
betaof the streaming template, or None for an engine without one (the in-memory loop, which takes thebetaof the System it is handed).
- streaming_energies(systems)¶
Recompute
(vpot, ekin)for file-backed snapshot systems.The potential energy is a function of the positions and the kinetic energy a function of the velocities, both stored in each system’s trajectory frame, so the energy terms are recovered exactly by re-reading the frame and evaluating this engine’s force field. This restores the per-frame energies on paths rebuilt from disk (initial paths, swaps, and the reload done by
SchedulerPathStorage.output()), whose snapshot phase points carry positions and velocities but no in-memory energy. Each distinct trajectory file is read once.- Parameters:
systems (iterable of objects like
System) – File-backed snapshot systems without particles: eachconfigis a(filename, frame_index)pair.- Returns:
list of tuple of float – One
(vpot, ekin)pair per input system, in input order.
- streaming_orders(systems)¶
Recompute the order parameter for file-backed snapshot systems.
The order parameter is a function of the stored frame, so it is recovered exactly by re-reading that frame and evaluating this engine’s
order_function. Used when the configured order function differs from the order data a path was loaded with – a restart that added or removed collective variables (seepyretis.core.path_load.align_order_width()).This is the batch counterpart of evaluating each phase point on its own: each distinct trajectory file is read ONCE and its frames are held while the phase points that reference them are evaluated. Frame-at-a-time evaluation re-reads the file from the start for every frame, which is quadratic in the path length – the reason this method exists.
- Parameters:
systems (iterable of objects like
System) – File-backed snapshot systems without particles: eachconfigis a(filename, frame_index)pair.- Returns:
list of lists of floats – One order-parameter list per input system, in input order.
- system_with_particles(system)¶
Return a phase point with particles in the state of its frame.
The phase point
systemholds no particles and names its frame byconfig. The phase point returned is a copy of the streaming template (setup_streaming()), with the box, the masses, the particle names and the force field of the engine, in the state of that frame (_materialize_system()): the positions and the velocities of the frame, the velocities negated whenvel_revis True, and the potential energy and the forces evaluated. Such a phase point is held in memory:propagate(),modify_velocities()andkick_across_middle()act on it as on the system the in-process kick initiation starts from, and write no frame files for it.- Parameters:
system (object like
System) – A phase point without particles that names its frame byconfig.- Returns:
out (object like
System) – The phase point with particles.- Raises:
ValueError – If
systemholds particles or names no frame, if the engine has no streaming template, or if the file holds no frame at the indexconfignames.
- class pyretis.engines.internal.RandomWalk(timestep, rgen=None, seed=0)¶
Bases:
MDEngineA Random Walker integrator.
This class defines a Random walker integrator.
- Variables:
timestep (float) – The length of the step.
- __init__(timestep, rgen=None, seed=0)¶
Set up the Random walker integrator.
- Parameters:
timestep (float) – The time step in internal units.
rgen (string, optional) – This string can be used to pick a particular random generator, which is useful for testing.
seed (integer, optional) – A seed for the random generator.
- integration_step(system)¶
Random Walker integration, one time step.
- Parameters:
system (object like
System) – The system to integrate/act on. Assumed to have a particle list insystem.particles.- Returns:
out (None) – Does not return anything, but alters the state of the given system.
- load_restart_info(info)¶
Load restart information for the RandomWalk engine.
- Parameters:
info (dict) – The dictionary with the restart information, should be similar to the dict produced by
restart_info().
- restart_info()¶
Return restart info for the RandomWalk engine.
The integration random generator (
rgen) is persisted so that a restart – including a re-run of an interrupted shot – resumes the exact same stochastic stream (bit-identical dynamics).- Returns:
info (dict) – Contains all the updated simulation settings and counters.
- class pyretis.engines.internal.VelocityVerlet(timestep)¶
Bases:
MDEngineThe Velocity Verlet MD integrator.
This class defines the Velocity Verlet integrator.
- Variables:
half_timestep (float) – Half of the timestep.
- __init__(timestep)¶
Set up the Velocity Verlet integrator.
- Parameters:
timestep (float) – The time step in internal units.
- integration_step(system)¶
Velocity Verlet integration, one time step.
- Parameters:
system (object like
System) – The system to integrate/act on. Assumed to have a particle list insystem.particles.- Returns:
out (None) – Does not return anything, but alters the state of the given system.
- load_restart_info(info)¶
Load restart information.
- Parameters:
info (dict) – The dictionary with the restart information, should be similar to the dict produced by
restart_info().
- restart_info()¶
Return some restart info.
The restart info for the engine VelocityVerlet.
- Returns:
info (dict,) – Contains all the updated simulation settings and counters.
- class pyretis.engines.internal.Verlet(timestep)¶
Bases:
MDEngineThe Verlet MD integrator.
This class defines the position Verlet (Störmer-Verlet) MD integrator. The positions follow the Verlet recursion
x(t + dt) = 2 x(t) - x(t - dt) + a(t) dt**2, and the velocities are the central differences of the positions,v(t) = (x(t + dt) - x(t - dt)) / (2 dt).The state of the integrator is the phase point of the system: its positions, velocities and forces. A step takes the positions one time step back from the phase point (
previous_positions()) and leaves the system in the phase point one time step later, the positions and the velocities of the same time. A step therefore starts from the phase point the system holds, whether a velocity draw, a velocity reversal or a frame of a path gave it, and a step from a phase point with negated velocities retraces the step that led to it. In exact arithmetic, the trajectory from a phase point is the one ofVelocityVerlet.- Variables:
half_idt (float) – Half of the inverse time step: 0.5 / timestep.
timestepsq (float) – Squared time step: timestep**2.
- __init__(timestep)¶
Set up the Verlet MD integrator.
- Parameters:
timestep (float) – The time step in internal units.
- integration_step(system)¶
Perform one Verlet integration step.
The step goes from the phase point of
systemat timetto the phase point at timet + dt. The positions follow the Verlet recursion from the positions one time step back (previous_positions()),x(t + dt) = 2 x(t) - x(t - dt) + a(t) dt**2. The forces are evaluated atx(t + dt), and the velocities are the central difference at the new time,v(t + dt) = (x(t + 2 dt) - x(t)) / (2 dt), withx(t + 2 dt)the next term of the recursion,2 x(t + dt) - x(t) + a(t + dt) dt**2.- Parameters:
system (object like
System) – The system to integrate/act on. Assumed to have a particle list insystem.particles, with the forces of its positions.- Returns:
out (None) – Does not return anything, but alters the state of the given system.
- load_restart_info(info)¶
Load restart information.
- Parameters:
info (dict) – The dictionary with the restart information, should be similar to the dict produced by
restart_info().
- previous_positions(system)¶
Return the positions one time step before the phase point.
The positions are those of the second-order Taylor expansion of the trajectory through the phase point,
x(t - dt) = x(t) - v(t) dt + a(t) dt**2 / 2. The central difference of the Verlet step from them,(x(t + dt) - x(t - dt)) / (2 dt), is the velocityv(t)of the phase point.- Parameters:
system (object like
System) – The phase point: its positions, velocities and forces.- Returns:
out (numpy.array) – The positions
x(t - dt).
- restart_info()¶
Return restart info.
The restart info for the engine Verlet.
- Returns:
info (dict,) – Contains all the updated simulation settings and counters.
pyretis.engines.lammps module¶
A streaming LAMMPS external MD engine.
This module defines the canonical LAMMPS engine, selected by
class = "lammps". LAMMPS is run as a single persistent process and
its dump trajectory is read on-the-fly, so the path is filled
incrementally and LAMMPS is terminated as soon as a stopping interface
is crossed. The input of the LAMMPS run of a propagation is built as for
the relaunch engine
(LAMMPSEngineSteps._prepare_lammps_run()): PyRETIS appends its
commands to a copy of lammps.in
(create_lammps_md_input()). They are, in this order:
the start configuration, and the commands that reverse its velocities for a propagation that reverses them;
the thermo output, with
thermo_modify flush yes;the trajectory dump;
with
order_mode = "lammps", the order-parameter output oforder.inand thefix haltcommands that stop the run at the outer interfaces;the
runof the number of steps,path.maxlen * subcycles;the
undumpof the trajectory dump.
When the engine has a random generator, the command line defines the
LAMMPS variable pyretis_seed, a seed drawn from it for each run.
Each fix and pair style of lammps.in that draws random numbers takes
it as its seed: the engine refuses another seed before LAMMPS runs
(refuse_lammps_fixed_seeds()). Frame k of the dump of a
run is named by the time step k * subcycles, and the engine refuses
a dump whose frames it read have other time steps
(check_lammps_dump_steps()).
The relaunch engine, which reads the trajectory once the LAMMPS run has
ended, is class = "lammps_steps"
(pyretis.engines.lammps_steps).
Important classes defined here¶
- LAMMPSEngine (
LAMMPSEngine) The streaming LAMMPS engine.
- class pyretis.engines.lammps.LAMMPSEngine(lmp, input_path, subcycles, extra_files=None, order_mode='pyretis', timestep=None, velocity_generation='engine', atom_style=None, sleep=0.1)¶
Bases:
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), as the two GROMACS engines do. Withorder_mode = "pyretis", the two engines build the identical LAMMPS input of a propagation (via the inheritedLAMMPSEngineSteps._prepare_lammps_run()) and differ in how the trajectory is consumed: this engine runs LAMMPS as a single persistent process and reads the trajectory on the fly, terminating LAMMPS early when an interface is crossed. This engine takesorder_mode = "pyretis"only, its default (the relaunch engine defaults to"lammps"), and draws the velocities in PyRETIS in bothvelocity_generationmodes (modify_velocities()).The order parameter of a frame is evaluated on the unwrapped positions of its atoms from the lower bounds of its box, in a box of the box lengths of the frame (
_frame_for_order()), as the relaunch engine evaluates it (LAMMPSEngineSteps._calculate_pyretis_order()), so the two engines give the same order parameter for a configuration, also one of an atom that has crossed a periodic boundary.TO DO:
Add possibility to use LAMMPS internally to modify the velocities such that all constraints (e.g. between bonds) are fulfilled (
external_orderparameter : boolean).The velocity draw supports LAMMPS
realunits only, and refuses others (modify_velocities()).Fix “exe_path” and “exe_dir”, use one but not both…
Fix mpi in cp2k?
For small systems the engine is so fast that whole trajectory finishes before we managed to check for a crossing, leading to large files.
Make LAMMPS remove and replace commands in input instead of making variables. Much easier to run md with the same input file
external_orderparameter. If this is set to true, we read in the orderparameter from and external file. May be useful when the orderparameter is calculated internally in LAMMPS for expensive calculations such as in nucleation, or any other fancy stuff.
- __init__(lmp, input_path, subcycles, extra_files=None, order_mode='pyretis', timestep=None, velocity_generation='engine', atom_style=None, sleep=0.1)¶
Set up the streaming LAMMPS engine.
The signature matches
LAMMPSEngineSteps, so the same[engine]settings and input directory drive either engine.sleepis the only streaming-specific extra, andorder_modetakes"pyretis"only, its default here (the relaunch engine defaults to"lammps").- Parameters:
lmp (string) – The LAMMPS executable.
input_path (string) – Directory with the LAMMPS input files (
lammps.in,system.data, 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, and stops a run on its values:
"pyretis", the default and the one mode it accepts.timestep (float, optional) – Cross-check only; the time step is read from
lammps.in.velocity_generation (string, optional) –
"engine"(the default) or"maxwell". In both modes this engine draws the velocities in PyRETIS, from a Maxwell-Boltzmann distribution at the temperature oflammps.inon the injected random generator, and resets the linear momentum as[tis] zero_momentumselects (modify_velocities()), so the two modes draw the same velocities.atom_style (string, optional) – The LAMMPS atom style of the
Atomsrows of a data file, from which the engine reads the masses at set-up and the positions of a configuration held in a data file. Of this setting, theAtoms # styleannotation of the data file and theatom_stylecommand oflammps.in, the ones that are given must name styles of one row layout (bond,angleandmolecularshare one, and a style with an accelerator suffix, asfull/kk, has the layout of the style), and aValueErroris raised otherwise. The rows are read in the style of the first of the three that is given, and inatomicwhen none is. Anatom_stylecommand oflammps.inset by a LAMMPS variable is not a source, and without another source aValueErroris raised (resolve_lammps_atom_style()). The data file is read byread_lammps_data_file(): at set-up without its box (get_atom_masses()), and for the velocity draw and the order parameter of a configuration held in a data file with its box, which refuses a triclinic box.sleep (float, optional) – Seconds to wait between polls while reading the trajectory on the fly. Default
0.1.
- Raises:
NotImplementedError – If
lammps.inhas amasscommand: the engine takes the masses of the atoms from theMassessection ofsystem.data(refuse_lammps_mass_command()). Also asget_atom_masses()raises it forsystem.data.ValueError – If
order_modeis not"pyretis": with"lammps", LAMMPS would stop a run onv_op_1oforder.inwhile the engine samples on the PyRETIS order parameter. Also asLAMMPSEngineStepsraises it, and asget_atom_masses()raises it forsystem.data.
- _extract_frame(traj_file: str, idx: int, out_file: str) None¶
Extract a frame from a trajectory to a new file.
idxis the time step of the frame in the dump, the configuration index of a frame of a LAMMPS dump (LAMMPSEngineSteps._frame_config_index()); None names the frame of time step 0. The selected frame is rewritten as a canonical, timestep-zero dump with explicit image flags.
- _frame_for_order(pos: ndarray, bounds: ndarray, images: ndarray | None = None) tuple[ndarray, ndarray]¶
Return the positions and the box of a frame for its order.
The positions are the unwrapped positions of the atoms from the lower bounds of the box, along the axes of the system (
lammps_order_positions()), and the box has the box lengthshi - loof x, y and z, as the relaunch engine evaluates the order parameter of a frame (LAMMPSEngineSteps._calculate_pyretis_order()).- Parameters:
pos (np.ndarray) – The positions of the atoms, shape
(N, 3): the unwrapped positions, or, withimages, the positions of the frame.bounds (np.ndarray) – The box bounds of the frame, a row
lo hifor each of x, y and z, with the tilt factors in a third column for a dump of a triclinic box.images (np.ndarray, optional) – The image flags of the atoms, shape
(N, 3).
- Returns:
tuple –
- A tuple containing:
The positions for the order parameter, shape
(N, 3).The box lengths of x, y and z.
- Raises:
NotImplementedError – If the frame has a triclinic box with a tilt factor other than 0 (
refuse_tilted_lammps_box()).
- _locate_data_file(data_file)¶
Return the path of the LAMMPS data file of a configuration.
A configuration names its data file by a path, absolute or relative to the working directory, or by a bare file name, as the initial configuration can name the
system.dataofinput_pathbefore it is staged inexe_dir. A path or a name that is a file is that file; a path with a directory is resolved against the working directory only, as the propagation resolves it (LAMMPSEngineSteps._prepare_lammps_run()). A bare name that is not a file is the file of that name inexe_dir, and, whenexe_dirhas none and the name is that of thesystem.dataof the engine input, thatsystem.data.- Parameters:
data_file (string) – The data file that the configuration names.
- Returns:
out (string) – The path of the data file.
- Raises:
FileNotFoundError – If
data_fileis none of these files; the message namesdata_file.
- _read_configuration(filename: str) tuple[ndarray, ndarray, ndarray | None, list[str] | None]¶
Read a configuration (a single frame trajectory).
- Parameters:
filename (string) – The dump whose first frame is read.
- Returns:
tuple –
- A tuple containing:
The unwrapped positions of the atoms from the lower bounds of the box (
_frame_for_order()).The velocities of the atoms.
The box lengths of x, y and z.
None, for the atom names.
- _read_data_configuration(data_file: str) tuple[ndarray, ndarray, ndarray]¶
Read the configuration held in a LAMMPS data file.
The data file is the one
_locate_data_file()finds. Its positions, image flags and box bounds are read byLAMMPSEngineSteps._read_lammps_data_frame(), and the positions are unwrapped with the box of its header, from the lower bounds of the box (_frame_for_order()), as those of the frame of a dump are. The velocities are those of itsVelocitiessection (read_lammps_data_velocities()); a data file without one has zero velocities, the velocities LAMMPSread_datagives its atoms, as the GROMACS and CP2K engines read a configuration without velocities.- Parameters:
data_file (string) – The data file that the configuration names.
- Returns:
tuple –
- A tuple containing:
The unwrapped positions from the lower bounds of the box, shape
(N, 3).The velocities, shape
(N, 3).The box lengths of x, y and z.
- Raises:
FileNotFoundError – If
_locate_data_file()does not find the data file.NotImplementedError, ValueError – As
read_lammps_data_file()andread_lammps_data_velocities()raise them for the data file.
- _recompute_partial_orders(partial_traj, reverse)¶
Order parameters per frame of a partial
.lammpstrjdump.The dump frames are read directly, each with the unwrapped positions of its atoms from the lower bounds of its box and its box lengths (
_frame_for_order()), as the propagation reads them. Only complete frames are read: a final frame left half-written by an interruption (an incomplete block) is skipped, keeping the surviving frames – the same “use the last good frame” recovery used for the other engines. The order function sees each frame named bysystem.config, the dump and the time step of the frame (_calculate_frame_order()), the config the rebuilt phase point of the frame stores.
- _reverse_velocities(filename: str, outfile: str) None¶
Reverse the velocities of a configuration.
- _velocity_draw_data_file(system)¶
Return the LAMMPS data file that a velocity draw reads.
The draw reads the data file of the configuration of
systemwhere it is (_locate_data_file()), and writes no file before the data file is read.- Parameters:
system (object like
System) – The state whose velocities are drawn, at a data file.- Returns:
out (string) – The data file.
- Raises:
FileNotFoundError – If
_locate_data_file()does not find the data file.
- calculate_order(system, xyz=None, vel=None, box=None)¶
Calculate the order parameter of the current system.
This engine’s
_read_configurationreturns the box as its THIRD element (pos, vel, box, names), unlikeExternalMDEngine.calculate_order, which expects the box first. We therefore unpack the box third here.The configuration is read when
xyz,velorboxis not given. A frame of a dump has the unwrapped positions of the atoms from the lower bounds of its box and the box lengths of the frame (_read_configuration()). A configuration held in a LAMMPS data file (_locate_data_file()) has the unwrapped positions of the atoms of the file, from their positions and image flags, from the lower bounds of the box of its header, the box lengths of x, y and z of its header and the velocities of itsVelocitiessection (_read_data_configuration()).- Parameters:
system (object like
System) – The state whose order parameter is calculated; its positions, velocities (negated whenvel_revis True) and box are set to those of the configuration.xyz (numpy.array, optional) – The positions to use.
vel (numpy.array, optional) – The velocities to use.
box (numpy.array, optional) – The box lengths to use.
- Returns:
out (list of floats) – The order parameter of the configuration.
- Raises:
FileNotFoundError – If the configuration names a data file that
_locate_data_file()does not find.NotImplementedError, ValueError – As
read_lammps_data_file()andread_lammps_data_velocities()raise them for the data file of the configuration, for a triclinic box among others. AValueErroralso if the engine has no order parameter, and, before the configuration is read, if it is held in a LAMMPS restart file (LAMMPSEngineSteps.refuse_restart_configuration()).
- default_units = None¶
- dump_config(config, deffnm='conf')¶
Extract a configuration frame, honouring the data-file case.
The shared convention stores the initial configuration as a LAMMPS data file (
system.data), which is a single configuration and cannot be sliced frame-wise like a trajectory dump. In that case the data file (_locate_data_file()) is copied unchanged to<deffnm>.datainexe_dir; otherwise we defer to the generic trajectory-frame extraction.- Parameters:
config (tuple) – The configuration as
(filename, index).deffnm (string, optional) – The base name for the dumped file.
- Returns:
out (string) – The file name we dumped to.
- Raises:
FileNotFoundError – If
confignames a data file that_locate_data_file()does not find.ValueError – Before any file is read or written, if
configis held in a LAMMPS restart file (LAMMPSEngineSteps.refuse_restart_configuration()).
- dump_phasepoint(phasepoint, deffnm='conf')¶
Dump the current configuration from a system object to a file.
- engine_draw_reads_set_temp = False¶
- engine_type = 'external'¶
- classmethod get_default_units(settings=None)¶
Return the default unit system for the LAMMPS engine.
The unit system is read from the
unitscommand in the LAMMPS input file. This mirrors how the engine time step is recovered at settings-parse time (pyretis.core.engine_time._engine_timestep_from_input()), which also inspectslammps.in, so unit and time-step auto-detection stay consistent.- Parameters:
settings (dict, optional) – Full simulation settings or engine settings.
- Returns:
out (string) – The default unit system for the LAMMPS engine.
- Raises:
ValueError – If the LAMMPS input file can not be read, or if no
unitscommand is found in that file.
- modify_velocities(system: System, vel_settings: dict[str, Any], rgen) tuple[float, float]¶
Modify the velocities of all particles.
The velocities are drawn in PyRETIS, from a Maxwell-Boltzmann distribution at the temperature of
lammps.in, in bothvelocity_generationmodes. A configuration held in a LAMMPS data file, as thesystem.dataa run starts from, is drawn byLAMMPSEngineSteps._draw_velocities_maxwell(), which reads its positions, image flags and masses from that file (read_lammps_data_file()) where it is (_velocity_draw_data_file()), and writesgenvel.lammpstrjinexe_dironce the file is read. Any other configuration is a frame of a LAMMPS dump: its positions and image flags come from the frame, and the masses from the data file of the engine input. The frame that this draw writes (write_lammpstrj()) keeps the image flags of the frame, and its velocities along the axes the system does not have (dimensionbelow 3) are 0.- Parameters:
system (System) – The system whose particle velocities are to be modified.
vel_settings (dict) – A dict containing the key
'zero_momentum'(boolean): if true we reset the linear momentum to zero after generating velocities internally. A missing key means False, the[tis]default. This engine draws the velocities of aimless shooting and leaves their energy as drawn, so a soft perturbation (asigma_vthat is not negative) and a positiverescaleare refused before the draw.rgen (object like
RandomGenerator) – The velocity random generator the Maxwell-Boltzmann draw is made from, in bothvelocity_generationmodes.
- Returns:
tuple – A tuple containing:
dek: The change in kinetic energy as a result of the velocity modification.
kin_new: The new kinetic energy of the system.
- Raises:
NotImplementedError – If
vel_settingsselect a soft perturbation (refuse_soft_perturbation()) or an energy re-scale (refuse_energy_rescale()), or if LAMMPS runslammps.inin units other thanreal, those of its lastunitscommand after its lastclearcommand, also in a file it includes (refuse_lammps_draw_units()). Also, for a configuration held in a data file, asread_lammps_data_file()raises it for the file: for a triclinic box, orAtomsrows of an atom style that is not supported.ValueError – If the LAMMPS script runs in other units than
realthrough a file it includes, so the engine has nobeta. Also, for a configuration held in a data file, for each refusal of the file that the Raises section ofread_lammps_data_file()lists.FileNotFoundError – For a configuration that names a data file that
_locate_data_file()does not find.
Notes
This method does not take care of constraints. The errors of the Raises section come before any random number is drawn or any file is written, and, first of all, a configuration held in a LAMMPS restart file is refused with a
ValueError(LAMMPSEngineSteps.refuse_restart_configuration()).
- needs_order = True¶
- propagate(path, ens_set, system, reverse=False)¶
Propagate by streaming a single persistent LAMMPS run.
The relaunch base (
LAMMPSEngineSteps) overridespropagatewith a driver that makes one LAMMPS run of up topath.maxlen * subcyclessteps and reads its trajectory when the run has ended. The streaming engine uses the generic external-engine driver, which dispatches topyretis.engines.lammps.LAMMPSEngine._propagate_from()– a single persistent LAMMPS process whose trajectory is read on the fly and stopped early on an interface crossing.- Parameters:
- Returns:
success (boolean) – True if the propagation produced an acceptable path.
status (string) – A textual status of the propagation.
- restart_configuration_what = 'The streaming LAMMPS engine (class "lammps")'¶
- set_mdrun(md_items: dict[str, Any]) None¶
Set the executional directory for workers.
- step(system, name)¶
Perform a single step with the engine.
LAMMPS is propagated via
_propagate_from; a singlestep()is not supported, and this override refuses the single LAMMPS run ofLAMMPSEngineSteps.step().
- supports_step_kick = False¶
- pyretis.engines.lammps.get_atom_masses(lammps_data: str | Path, atom_style, input_style: str | None = None) ndarray¶
Read the mass of each atom of a LAMMPS data file.
The file is read by
read_lammps_data_file(), the reader of the velocity draw and of the order parameter of a configuration held in a data file (LAMMPSEngineSteps._read_lammps_data_frame()), without its box (read_box=False), so the masses of a data file of a triclinic box are read too. Each atom has the mass of theMassesrow that starts with its atom type.- Parameters:
lammps_data (str or Path) – Path to the LAMMPS data file to read.
atom_style – The
[engine] atom_style, or None when it is not set. Supportsfull,molecular,bond,angle,chargeandatomic, each also with an accelerator suffix, asfull/kk.input_style (str, optional) – The style of the
atom_stylecommand oflammps.in(lammps_input_atom_style()).
- Returns:
np.ndarray – The mass of each atom, in the order of the atom IDs, the order in which
read_lammpstrj()gives the atoms of a dump frame, shape(N, 1).- Raises:
ValueError, NotImplementedError – As
read_lammps_data_file()raises them without the box, forAtomsrows of an atom style that is not supported among others.
- pyretis.engines.lammps.read_energies(filename: str) dict[str, ndarray]¶
Read energies from a LAMMPS log file.
This method is used to read the thermodynamic output from a simulation (e.g., potential and kinetic energies).
- Parameters:
filename (str) – The path to the LAMMPS log file to read.
- Returns:
dict – A dictionary containing the data we found in the file.
- pyretis.engines.lammps.read_lammps_input(filename)¶
Read a LAMMPS input file.
This will read in a LAMMPS input file and can be used to read the value of particular settings, for instance the time step. The commands are read as LAMMPS reads them (
pyretis.inout.engine_temperature.lammps_script_commands()): the lines that&or an odd number of triple quotes join are one command, and the comment of a command starts at the first#outside quotes. A line inside a command, such as a line of a triple-quotedprinttext, is not a command of its own.- Parameters:
filename (string) – The path to the LAMMPS input file.
- Returns:
out (list of tuples) – The settings found in the LAMMPS input file. The tuples are on the form (keyword, setting), the first word of a command and its other words joined by single spaces.
- Raises:
ValueError – If a line of the file holds bytes that are not UTF-8, or a command, without its comment, a character that is not ASCII (
pyretis.inout.engine_temperature.lammps_script_commands()).
- pyretis.engines.lammps.read_lammpstrj(infile: str, frame: int, n_atoms: int, images: bool = False) tuple[ndarray, ...]¶
Read a single frame from a LAMMPS trajectory.
- Parameters:
infile (str) – The path to the file to read.
frame (int) – The index of the frame to read from infile.
n_atoms (int) – The number of atoms to read.
images (bool, optional) – If True, the image flags
ix iy izof the atoms are returned too, with 0 for an axis whose column the dump does not have.
- Returns:
tuple –
- A tuple containing:
The id type for the particles.
The positions.
The velocities.
The simulation box.
With images, the image flags (one row of three integers per atom).
Notes
- The atoms are sorted according to their index, so that
(index-based) order calculations are correct.
Both engine dumps with a
typecolumn and Maxwell-generated dumps without one are accepted; columns are located from the atom header.The positions of a dump of the scaled columns
xs ys zsare those the box of the frame gives them (lammps_scaled_positions()), and a dump of unwrapped positions (xuorxsuand so on) gives the wrapped positions and image flags whose unwrapped positions they are, with or without wrapped positions beside them (_lammpstrj_axis_positions()).
- pyretis.engines.lammps.write_lammpstrj(outfile: str, id_type: ndarray, pos: ndarray, vel: ndarray, box: ndarray | None, append: bool = False, triclinic: bool = False, images: ndarray | None = None) None¶
Write a LAMMPS trajectory frame in .lammpstrj format.
This method writes the LAMMPS dump fields:
id type x y z vx vy vz ix iy iz.- Parameters:
outfile (str) – Path to the file to write.
id_type (np.ndarray)
pos (np.ndarray) – The positions to write.
vel (np.ndarray) – The velocities to write.
box (np.ndarray, optional) – The simulation box to write (if available).
append (bool) – If True, the outfile will be appended to, otherwise, outfile will be overwritten.
triclinic (bool) – If true, write in triclinic box format.
images (np.ndarray, optional) – The image flags
ix iy izof each atom, one row per atom in the order of pos. Without them every flag is written as 0.
pyretis.engines.lammps_steps module¶
This module defines the class for interfacing LAMMPS.
Important classes defined here¶
- LAMMPSEngineSteps (
LAMMPSEngineSteps) The class responsible for interfacing with LAMMPS by launching the executable once per propagation and reading its trajectory when the LAMMPS run has ended (the slower, relaunch implementation; the canonical streaming engine lives in
pyretis.engines.lammps).
- class pyretis.engines.lammps_steps.LAMMPSEngineSteps(lmp, input_path, subcycles, extra_files=None, order_mode='lammps', timestep=None, velocity_generation='engine', atom_style=None)¶
Bases:
ExternalMDEngineA class for interfacing LAMMPS.
- Variables:
lmp (string) – The command for executing LAMMPS
input_path (string) – The directory where the input files are stored.
input_files (dict of strings) – The names of the input files.
temperature (float) – The temperature
lammps.instates (read_lammps_temperatures()), in kelvin, or reduced inunits lj.beta (float or None) – The inverse temperature
1 / (k_B T)in mol/kcal, with the k_B of LAMMPSrealunits,kb, for a script inunits real; None in the other unit systems, in which PyRETIS draws no LAMMPS velocities (refuse_lammps_draw_units()).engine_temperatures (object like
EngineTemperatures) – The temperatures read fromlammps.in.
- __init__(lmp, input_path, subcycles, extra_files=None, order_mode='lammps', timestep=None, velocity_generation='engine', atom_style=None)¶
Set up the LAMMPS engine.
- Parameters:
lmp (string) – The LAMMPS executable.
input_path (string) – The absolute path to where the input files are stored.
subcycles (integer) – The frequency of output of data by LAMMPS.
extra_files (list of strings, optional) – Additional files needed to run the LAMMPS simulation.
order_mode (string, optional) – Select where order parameters are evaluated.
"lammps", the default, prints the variables oforder.infor each frame and stops a run onv_op_1; each variable must read the positions and the box only (refuse_velocity_dependent_lammps_orders())."pyretis"reads dumped LAMMPS frames and evaluates the PyRETIS order parameter and collective variables in Python.timestep (float, optional) – The LAMMPS time step is read from the LAMMPS input file; this optional
[engine]value is only used as a cross-check and must equal the value in the input file (otherwise an error is raised). For alammps.inthat reads a restart file, the time step is the one LAMMPS runs with: the one of the lasttimestepcommand after the lastread_restart, else the one of the restart file (read_lammps_restarts()).velocity_generation (string, optional) – How shooting-move velocities are generated.
"engine"(default) delegates to LAMMPS (velocity create, with themomkeyword set from[tis] zero_momentum);"maxwell"draws them in Python from a Maxwell-Boltzmann distribution at the temperature oflammps.invia the injected random generator (one reproducible stream). The"maxwell"draw uses the constants of LAMMPSrealunits and refuses alammps.inwithoutunits real(refuse_lammps_draw_units()). It takes the masses from theMassessection of a data file (_velocity_draw_data_file()): for a frame of a dump, the data file that LAMMPSwrite_datawrites for the frame, whoseMassessection holds the masses of themasscommands oflammps.in; for a configuration held in a data file, that file, and the draw of such a configuration refuses alammps.inwith amasscommand (refuse_lammps_mass_command()).atom_style (string, optional) – The LAMMPS atom style of the
Atomsrows of a data file, from which the"maxwell"draw reads the positions, image flags and masses of a configuration held in a data file. Of this setting, theAtoms # styleannotation of the data file, which a data file written by LAMMPS carries, and theatom_stylecommand oflammps.in, the ones that are given must name styles of one row layout (bond,angleandmolecularshare one, and a style with an accelerator suffix, asfull/kk, has the layout of the style), and the draw raises aValueErrorotherwise. The rows are read in the style of the first of the three that is given, and inatomicwhen none is. Anatom_stylecommand oflammps.inset by a LAMMPS variable is not a source, and without another source the draw raises aValueError(resolve_lammps_atom_style()).
- Raises:
ValueError – If
order_modeis not a mode ofORDER_MODES, ifvelocity_generationis neither"engine"nor"maxwell", asread_lammps_temperatures()andrefuse_draw_without_set_temp()raise it for the temperature oflammps.in, iftimestepdiffers from the time step oflammps.in, and, withorder_mode = "lammps", if a variable oforder.inreads the velocities or a word that PyRETIS cannot tell to be independent of them (refuse_velocity_dependent_lammps_orders()).
- _calculate_pyretis_order(system, traj, reverse=False)¶
Calculate PyRETIS order parameters from a LAMMPS trajectory.
The order parameter of each frame is evaluated on the unwrapped positions of its atoms from the lower bounds of its box, in a box of its box lengths (
lammps_order_positions()), withsystem.confignaming the frame: the dump and the time step of the frame (_frame_config_index()), the config a phase point of the frame stores.- Parameters:
system (object like
System) – The template of the system the order parameter is evaluated on; it is not changed.traj (string) – The LAMMPS dump to read (
read_lammps_dump()).reverse (boolean, optional) – If True, the velocities of the frames are negated.
- Returns:
out (numpy.ndarray) – The order parameter of each frame.
- Raises:
ValueError – If the engine has no order parameter.
NotImplementedError – If a frame has a triclinic box with a tilt factor other than 0 (
refuse_tilted_lammps_box()).
- _draw_velocities_maxwell(system, vel_settings, rgen)¶
Draw shooting velocities in Python (Maxwell-Boltzmann).
Mirrors the engine path’s contract – sets
system.configto a dump frame the next propagation reads viaread_dumpand updatessystem.ekin– but draws the velocities from the injected random generator instead of LAMMPS’svelocity create. The positions, image flags, masses and box bounds of x, y and z are those of the data file of_velocity_draw_data_file()(_read_lammps_data_frame()), and the draw writesgenvel.lammpstrjinexe_dironce the file is read.- Parameters:
system (object like
System) – The state whose velocities we redraw.vel_settings (dict) –
zero_momentumrequests a zero linear-momentum reset; a missing key means False.rgen (object like
RandomGenerator) – The velocity random generator, injected explicitly.
- Returns:
float – The new kinetic energy (in
(g/mol)(Angstrom/fs)^2; transient – the propagation overwrites it with LAMMPS energies).
- _evaluate_drawn_order(system)¶
Set the order parameter of the frame of a velocity draw.
The frame of
system.configis the dump that_draw_velocities_maxwell()writes, of one frame. Withorder_mode = "pyretis"its order parameter is evaluated on that frame (_calculate_pyretis_order()), and an engine without an order parameter, as a script can make one, setssystem.orderto None. Withorder_mode = "lammps"LAMMPS evaluates it, in a run of zero time steps from the frame,genvel_order, on a copy ofsystem, so that the configuration and the energies ofsystemstay those of the draw.- Parameters:
system (object like
System) – The state of the draw; itsorderis set.
- _extract_frame(traj_file, idx, out_file)¶
Extract one LAMMPS trajectory frame as a data file.
- Parameters:
traj_file (string) – The LAMMPS dump to extract the frame from.
idx (integer or None) – The time step of the frame in the dump, its configuration index (
_frame_config_index()); None names the frame of time step 0.out_file (string) – The data file to write.
- _frame_config_index(frame)¶
Return the configuration index of a frame of a LAMMPS dump.
A frame of a LAMMPS dump is named by its time step, the number below its
ITEM: TIMESTEPline (pyretis.tools.recalculate_order.lammpstrj_timesteps()). A run of the engine starts at time step 0 and dumps a frame everysubcyclessteps, so frameframeof its dump has the time stepframe * subcycles; the engines check the time steps of the frames of each run (check_lammps_dump_steps()).- Parameters:
frame (integer) – The frame number in the dump, from 0.
- Returns:
out (integer) – The time step of the frame.
- static _input_script(engine_settings)¶
Return the input path and the LAMMPS script of an engine section.
The script is looked up as the engine looks it up when it is created:
lammps.inininput_path.- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out[0] (string) – The absolute
input_path.out[1] (string) – The path of the script.
- static _input_script_present(engine_settings)¶
Return whether an engine section names a script that is there.
- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (boolean) – True when the section sets
input_pathand that folder holds a file_input_script()can take (input_file_present()).
- _lammps_run_seed(steps, seeded)¶
Return the value of
pyretis_seedfor a LAMMPS run.A run that integrates time steps takes a seed drawn on the random generator of the engine,
self.rgen, one draw per run in[1, 899999999]: the generator of the move in a path-sampling run, of the path ensemble in a kick initiation, and of the task in an MD task (draws_run_seeds). A run of zero steps integrates none and draws nothing: it takesPYRETIS_SEED_WITHOUT_STEPS. A run of steps on an engine without a random generator, which a script can start through the Python API, takesPYRETIS_SEED_WITHOUT_STEPSas well whenlammps.indraws no random numbers, and is refused when it does.- Parameters:
steps (integer) – The number of time steps of the run.
seeded (list of strings) – The fixes and pair styles of
lammps.inand of the files it reads that draw random numbers (refuse_lammps_fixed_seeds()).
- Returns:
out (integer) – The value of
pyretis_seedfor the run.- Raises:
ValueError – If the run integrates time steps, the engine has no random generator, and
seededis not empty.
- _make_order_fix(ordername)¶
Create a LAMMPS fix for the order parameter.
Note that we here make LAMMPS also output for step zero.
- _prepare_lammps_run(system, settings, name)¶
Write the LAMMPS input script and return the run command.
This is the input-preparation half of
run_lammps(). The streaming engine (pyretis.engines.lammps.LAMMPSEngine) builds its LAMMPS input with it too: withorder_mode = "pyretis", the one order mode the streaming engine takes, the two engines ask LAMMPS to do the same in a propagation and differ in how the trajectory is consumed. Withorder_mode = "lammps"the input also carries the fix that prints the order parameter oforder.in(_make_order_fix()).A configuration held in a data file is copied to the file of the name of the
system.dataof the input inexe_dir, whichlammps.inreads. A bare file name names the file of that name inexe_dir, where the input files are staged; a path with a directory, absolute or relative to the working directory, names that file, as it does forExternalMDEngine.dump_config()and for the streaming engine (pyretis.engines.lammps.LAMMPSEngine._locate_data_file()).- Parameters:
system (object like
System) – Defines the initial configuration to start from.settings (dict) – LAMMPS input settings; mutated in place with the trajectory, order, subcycle, timestep, dimension and order-fix entries.
name (string) – Base name for the LAMMPS input script and output files.
- Returns:
cmd (list of strings) – The command (with arguments) to launch LAMMPS.
- Raises:
ValueError – If a fix or a pair style of
lammps.inor of a file it reads draws random numbers with a seed other than the seed of the run,${pyretis_seed}(refuse_lammps_fixed_seeds()), asadd_input_files()raises it for a restart file oflammps.in, and, before any file is staged, for a configuration held in a LAMMPS restart file (refuse_restart_configuration()).
- _propagate_from(name, path, system, ens_set, msg_file, reverse=False)¶
Propagate with LAMMPS from the current system configuration.
- Parameters:
name (string) – A name to use for the trajectory we are generating.
path (object like
PathBase) – This is the path we use to fill in phase-space points.system (object like
System) – The system object gives the initial state. The order function is injected on the engine (self.order_function).ens_set (dict) – Ensemble settings. It contains:
interfaces: list of floats These interfaces define the stopping criterion.
msg_file (object like
FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.reverse (boolean, optional) – If True, the system will be propagated backward in time.
- Returns:
success (boolean) – This is True if we generated an acceptable path.
status (string) – A text description of the current status of the propagation.
- classmethod _read_lammps_data_frame(data_file, atom_style=None, input_style=None)¶
Parse a LAMMPS data file for a velocity draw or order parameter.
The file is read by
read_lammps_data_file(), with its box, the reader of the masses of the streaming engine (pyretis.engines.lammps.get_atom_masses()), which reads it without the box. The order parameter of a data file is that of the streaming engine (pyretis.engines.lammps.LAMMPSEngine.calculate_order()).- Parameters:
data_file (string) – The LAMMPS data file to read.
atom_style (string, optional) – Engine-configured atom style.
input_style (string, optional) – The style of the
atom_stylecommand oflammps.in(lammps_input_atom_style()).
- Returns:
ids (list of int) – The atom ids, sorted ascending.
positions (numpy.ndarray) – The per-atom positions, shape
(N, 3).images (numpy.ndarray) – The per-atom image flags, shape
(N, 3).masses (numpy.ndarray) – The per-atom masses, shape
(N, 1).box (list of tuple) – The
(lo, hi)box bounds of x, y and z, from the header of the file.
- Raises:
ValueError, NotImplementedError – As
read_lammps_data_file()raises them, for a data file of a triclinic box among others.
- _refuse_disagreeing_orders(system, order, settings)¶
Refuse a frame whose two order parameters differ.
With
order_mode = "lammps"LAMMPS evaluates the order parameter of the frames it propagates, one column per variable oforder.in(lammps_order_columns()), and stops a run whenv_op_1crosses an interface. A run with an[orderparameter]evaluates it and its collective variables in PyRETIS for the frames it reads back, as the frames of a load: on the unwrapped positions of the atoms from the lower bounds of the box and on the velocities of the path (_calculate_pyretis_order()). Both are evaluated on each frame of the run, and the run stops at the first frame whose two order parameters have another number of columns or a column whose values differ by more thanLAMMPS_ORDER_AGREEMENT_TOLERANCE: its paths would hold, and its runs stop on, values of another order parameter than the one of the frames it reads. Without an order parameter on the engine, LAMMPS gives the only value.- Parameters:
system (object like
System) – The template of the system the order parameter is evaluated on.order (numpy.ndarray) – The order parameters LAMMPS gives the frames of the run, one row per frame,
v_op_1first.settings (dict) – The settings of the run: the dump
trajandreverse_order_velocities.
- Raises:
ValueError – If the two order parameters have another number of columns, or if a column of a frame differs.
- _reverse_velocities(filename, outfile)¶
Reverse the velocities for a given configuration.
- static _trim_to_common_length(order, energy)¶
Trim LAMMPS run data to the common sampled-frame length.
- _velocity_draw_data_file(system)¶
Return the LAMMPS data file that a velocity draw reads.
The configuration of
systemis written to a data file inexe_dir(dump_frame()), by LAMMPS for a frame of a dump, and by a copy for a whole data file, before the draw reads it. A data file that the reader refuses is left inexe_dir.- Parameters:
system (object like
System) – The state whose velocities are drawn.- Returns:
out (string) – The data file.
- _warn_skipped_rescale(name, system, rescale)¶
Log the warning of a velocity re-scale LAMMPS skipped.
The warnings are those of
pyretis.core.particlefunctions.rescale_velocities()for the same two cases.- Parameters:
name (string) – The base name of the LAMMPS run that created the velocities.
system (object like
System) – The state of that run; itsvpotis thepeLAMMPS compared withrescale.rescale (float) – The target energy of the re-scale.
- static _write_velocity_dump(dump_file, ids, pos, vel, images, box)¶
Write a LAMMPS dump frame (positions, velocities, image flags).
The columns
id x y z vx vy vz ix iy izmatch what theread_dumpcommand of the engine’s run input (READ_DUMP) reads back.
- add_input_files(dirname)¶
Add required input files to a given directory.
Every LAMMPS run of the engines runs in the directory, after this method. The restart files that the
read_restartcommands oflammps.inread, and the files of itsincludeandjumpcommands, are then checked where LAMMPS opens them (refuse_lammps_restart_files(),refuse_unstaged_lammps_files()).- Parameters:
dirname (string) – The path to the directory where we want to add the files.
- Raises:
ValueError – As
refuse_lammps_restart_files()andrefuse_unstaged_lammps_files()raise it.
- calculate_order(system, xyz=None, vel=None, box=None)¶
Return the order parameter of the configuration of a system.
The engine evaluates the order parameter of each configuration it makes: of the last frame of each run of LAMMPS that collects it (
run_lammps()), astep()and the run ofvelocity_generation = "engine"among them, and of the frame of eachvelocity_generation = "maxwell"draw (_evaluate_drawn_order()). This method returns that value,system.order.- Parameters:
system (object like
System) – The state whose order parameter we return.xyz (numpy.array, optional) – Unused; present to match the base signature.
vel (numpy.array, optional) – Unused; present to match the base signature.
box (numpy.array, optional) – Unused; present to match the base signature.
- Returns:
out (list of floats) – The last seen order parameter for the system.
- default_units = None¶
- draws_run_seeds = True¶
- dump_config(config, deffnm='conf')¶
Extract a configuration frame, as the external engines do.
The configuration is refused first when it is held in a LAMMPS restart file (
refuse_restart_configuration()).- Parameters:
config (tuple) – The configuration as
(filename, index).deffnm (string, optional) – The base name for the dumped file.
- Returns:
out (string) – The file name we dumped to (
ExternalMDEngine.dump_config()).- Raises:
ValueError – As
refuse_restart_configuration()raises it.
- dump_phasepoint(phasepoint, deffnm='conf')¶
Dump a phase point to a new file.
Note
We do not reverse the velocities here.
- engine_draw_reads_set_temp = True¶
- classmethod get_default_units(settings=None)¶
Return the default unit system for the LAMMPS engine.
This is read from the
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.
- classmethod input_path_sampling_problem(engine_settings)¶
Return why a path-sampling run cannot use the script of a section.
The script is looked up as
read_input_temperatures()looks it up, and its fixes, with those of the files it reads ininput_path, are read aspath_sampling_problem()reads them (lammps_path_sampling_problem()). The files the engine stages are files ofinput_path, so LAMMPS reads the same files.- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (string or None) – The reason, or None when every fix stores the velocities at the time of the positions. None for a section without a script to read (
_input_script_present()): the run reports the missing script where it reads the units or the temperature of the section (get_default_units(),read_input_temperatures()) or creates the engine.- Raises:
NotImplementedError – As
lammps_named_commands()raises it.
- integrate(system, order_function, steps, thermo='full')¶
Propagate several integration steps with LAMMPS.
- Parameters:
system (object like
System) – The system to integrate.order_function (object like
OrderParameteror None) – An order function can be specified if we want to calculate the order parameter along with the simulation.steps (integer) – The number of integration steps to perform. The LAMMPS run length is
max(steps - 1, 0)subcycles so that the first frame is the initial configuration.thermo (string, optional) – Truthy values include a
'thermo'key in each returned step dict with the energy terms read from the LAMMPS log.
- Returns:
out (list of dict) – A list of step dicts each containing the integrated
'system'(and'order'/'thermo'when requested).
- modify_velocities(system, vel_settings, rgen)¶
Modify velocities.
- Parameters:
system (object like
System) – The state whose velocities we modify.vel_settings (dict) – It contains all the info for the velocity modification. For LAMMPS only aimless settings are supported. In
"engine"mode a positiverescaleis written into the LAMMPS input, which re-scales the created velocities so that the energype + keLAMMPS evaluates equals it (per atom underthermo_modify norm yes, the LAMMPS default forljunits). For apeabove that energy, or akethat is zero, LAMMPS keeps the created velocities and the warning ofpyretis.core.particlefunctions.rescale_velocities()is logged (_warn_skipped_rescale()). The"maxwell"draw leaves the energy as drawn, so it refuses a positiverescale(refuse_energy_rescale()).zero_momentumrequests a zero linear momentum after the draw (a missing key means False): in"engine"mode it sets themomkeyword of the LAMMPSvelocity createcommand toyesorno, and the keyword is always written because the LAMMPS default ismom yes. In"engine"mode, with a fix oflammps.in, or of a file it reads, that constrains the velocities (lammps_constraint_fixes(), which reads an included file as LAMMPS reads it fromexe_dir, where the input files are staged), the velocities that the setup of a run constrains are re-scaled toSET_TEMP, with the constrained degrees of freedom counted, before the re-scale torescale(_add_generate_vel()).rgen (object like
RandomGenerator) – The velocity random generator, injected explicitly per call. In the defaultvelocity_generation = "engine"mode it draws the LAMMPSvelocity createseed; in"maxwell"mode it draws the velocities directly.
- Returns:
dek (float) – The change in the kinetic energy.
kin_new (float) – The new kinetic energy.
- Raises:
NotImplementedError – If, in
"maxwell"mode,rescaleis positive, LAMMPS runslammps.inin units other thanreal, those of its lastunitscommand after its lastclearcommand, also in a file it includes (refuse_lammps_draw_units()), or the configuration is held in a data file, a.datafile, andlammps.inhas amasscommand (refuse_lammps_mass_command()). Also, in"maxwell"mode, asread_lammps_data_file()raises it for the data file of the draw: for a triclinic box, orAtomsrows of an atom style that is not supported. The data file that LAMMPSwrite_datawrites for a frame of a dump in a triclinic box has thexy xz yzline of the box, so every draw in a triclinic box raises it. In"engine"mode, before the draw, for a constraint fix that the draw refuses (refuse_lammps_constraint_fixes()), as fix shake, and for afixcommand that names its style, or anincludeorjumpcommand that names its file, by a LAMMPS variable (lammps_fix_commands()).ValueError – If
sigma_vselects a soft velocity perturbation. Also, in"maxwell"mode, for each refusal of the data file of the draw that the Raises section ofread_lammps_data_file()lists. The data file is written inexe_dirbefore it is read (_velocity_draw_data_file()). In both modes, before anything else, if the configuration ofsystemis held in a LAMMPS restart file (refuse_restart_configuration()).
- needs_order = False¶
- path_sampling_problem()¶
Return why a path-sampling run cannot use this engine.
The fixes of
lammps.inand of the files it reads, staged with the input files of the engine, are read aslammps_path_sampling_problem()reads them. A fix of Brownian dynamics (brownian,brownian/sphere,brownian/asphere,brownian/poly) integrates without inertia, and a Gronbech-Jensen-Farago Langevin fix withvhalf(fix langevinwithgjf vhalf,fix gjfwithoutvel vfull) stores the velocities half a time step away from the positions. A thermostat or barostat fix of the Nose-Hoover equations (fix nvt,npt,nphand their variants, the rigidnvt,nptandnphstyles,bocs,tgnvt/drude,tgnpt/drude,nphug,pimd/nvt) or of a shock wave (msst,qbmsst) carries variables of its own from one time step to the next, which a frame does not store;fix temp/berendsen,temp/rescale,press/berendsen,heatandehexrescale,nve/limit,viscosityandthermal/conductivitychange the velocities, andfix deform/pressurewith a pressure control moves the box, deterministically and without time reversibility.- Returns:
out (string or None) – The reason, or None when a path-sampling run can use every fix.
- Raises:
NotImplementedError – As
lammps_named_commands()raises it.
- path_sampling_warnings()¶
Return why path sampling with this engine is not exact.
The fixes and pair styles of
lammps.inand of the files it reads, staged with the input files of the engine, are read aslammps_path_sampling_warnings()reads them. A warning namesfix gle,gld,press/langevin,ttmand its variants, andfix langevinwithgjf vfull, whose memory between time steps restarts with each piece of trajectory,fix viscous,viscous/sphere,viscous/nonlinear,damping/cundall,deformanddeform/pressure, which change the dynamics of a piece by the direction of time or by its first time step, pair styledpd/fdt/energy, whose internal energies a frame does not store, and a thermostat whose target temperature can change during a run.- Returns:
out (list of strings) – The warnings, each naming the command, why path sampling with it is not exact and what to use instead.
- Raises:
NotImplementedError – As
lammps_named_commands()raises it.
- propagate(path, ens_set, system, reverse=False)¶
Propagate the equations of motion with the external code.
This is a LAMMPS-specific override: unlike the generic
ExternalMDEngine.propagate(), LAMMPS reverses the velocities through its own input file rather than via_reverse_velocities(), so the common set-up is handled here directly.- Parameters:
path (object like
PathBase) – This is the path we use to fill in phase-space points. We are here not returning a new path - this since we want to delegate the creation of the path to the method that is running propagate.ens_set (dict) – Ensemble settings. It contains:
interfaces: list of floats These interfaces define the stopping criterion.
system (object like
System) – The system object gives the initial state for the integration. The initial state is stored and the system is reset to the initial state when the integration is done. The order function is injected on the engine (self.order_function).reverse (boolean, optional) – If True, the system will be propagated backward in time.
- Returns:
success (boolean) – This is True if we generated an acceptable path.
status (string) – A text description of the current status of the propagation.
- Raises:
ValueError – Before any file is written, if the configuration of
systemis held in a LAMMPS restart file (refuse_restart_configuration()), and asrun_lammps()raises it.
- read_energies(name)¶
Read energies obtained in a LAMMPS run.
Here, we assume that the energies can be found in a log file in the current execute directory.
- classmethod read_input_temperatures(engine_settings)¶
Read the temperatures of the LAMMPS script of an engine section.
The script is looked up as the engine looks it up when it is created:
lammps.inininput_path. The script of an engine that draws its velocities with LAMMPS must defineSET_TEMP(refuse_draw_without_set_temp()).- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (object like
EngineTemperatures) – The temperaturesread_lammps_temperatures()reads.- Raises:
ValueError – As
read_lammps_temperatures()andrefuse_draw_without_set_temp()raise it.
- read_order_parameters(ordername)¶
Read order parameters as calculated by LAMMPS.
We assume here that these can be found in the current execute directory in a file named ordername, and further that they contain the step number in the first column, followed by the order parameters in following columns.
- refuse_draw_without_beta(engine)¶
Refuse a velocity draw of an engine without a
beta.The engine draws with the k_B of LAMMPS
realunits, and has abetawhen the script runs inunits real(engine_temperatures).refuse_lammps_draw_units()refuses a draw in other units first, from the units LAMMPS runs the script in (read_lammps_units()); this check stops a draw where the reader of the temperature finds other units.- Parameters:
engine (string) – The engine that draws, as the message names it at its start.
- Raises:
ValueError – If the engine has no
beta.
- classmethod refuse_draw_without_set_temp(temperatures, velocity_generation)¶
Refuse a LAMMPS draw of the velocities without
SET_TEMP.With
velocity_generation = "engine"the relaunch engine asks LAMMPS to create the velocities at the variableSET_TEMPoflammps.in(GENERATE_VEL), so the script must define it; a thermostat fix or a velocity command states the temperature of the run, but not the one LAMMPS draws at. An engine that draws the velocities in PyRETIS (a class withengine_draw_reads_set_tempFalse, andvelocity_generation = "maxwell") reads noSET_TEMP.- Parameters:
temperatures (object like
EngineTemperatures) – The temperatures read fromlammps.in.velocity_generation (string) – The
velocity_generationof the engine.
- Raises:
ValueError – If the engine draws the velocities with LAMMPS and
lammps.indoes not defineSET_TEMP. The message names the variable.
- refuse_restart_configuration(config)¶
Refuse to start from a configuration held in a restart file.
Each method of the engine that reads a configuration, or runs LAMMPS from it, calls this method first (
refuse_lammps_restart_configuration()), so that no file is read or written and LAMMPS does not run: the propagation (propagate(), and every LAMMPS run, through_prepare_lammps_run()), the velocity draw (modify_velocities()) anddump_config().- Parameters:
config (tuple) – The file and the index of the configuration.
- Raises:
ValueError – If the configuration is held in a LAMMPS restart file, from the working directory or from
exe_dir.
- restart_configuration_what = 'The relaunch LAMMPS engine (class "lammps_steps")'¶
- run_lammps(system, settings, name)¶
Execute LAMMPS.
This method will handle input files, run LAMMPS and return some data after the run.
- Parameters:
system (object like
System) – The system defines the initial state we are using. 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.
- Raises:
ValueError – As
_prepare_lammps_run()raises it, and if a framekof the dump of the run has a time step other thank * subcycles(check_lammps_dump_steps()).
- step(system, name)¶
Perform a single step with LAMMPS.
The step is a run of
subcyclestime steps, and the order parameter of its last frame becomessystem.order(run_lammps()), in both order modes.- Parameters:
system (object like
System) – The system we are integrating.name (string) – To name the output files from the LAMMPS step.
- Returns:
out (string) – The name of the output configuration, obtained after completing the step.
- temperature_keys = 'variable SET_TEMP, the thermostat fixes and the velocity commands of lammps.in'¶
- temperature_source = 'input'¶
- unmarked_section_temperature = True¶
- classmethod unmarked_unrecorded_use(engine_settings)¶
Return what an earlier LAMMPS engine did at its lammps.in.
The PyRETIS of a run file without the
temperature_rulemark gave a LAMMPS engine thetemperatureof its engine section, and the engine computed the beta of its acceptance at it. It drew its velocities in PyRETIS at it too, except the relaunch engine (engine_draw_reads_set_temp) withvelocity_generation = "engine", which asked LAMMPS to draw them at theSET_TEMPoflammps.in(GENERATE_VEL). The dynamics ran at the thermostat fixes oflammps.in. No run file records thelammps.inof that run.- Parameters:
engine_settings (dict) – The settings of the engine section, as the run file records them.
- Returns:
out (string) – What the engine took from the recorded temperature, and what it did at the
lammps.inof that run, as a warning states it.
- pyretis.engines.lammps_steps.LAMMPS_ORDER_AGREEMENT_TOLERANCE = 1e-06¶
The largest difference between an order-parameter column that LAMMPS gives a frame (a variable of
order.in) and the value of the column of the[orderparameter]and the collective variables of the frame, withorder_mode = "lammps": the two are one order parameter at the precision of the dump.
- pyretis.engines.lammps_steps._add_generate_vel(settings)¶
Add generation of velocities to the LAMMPS input.
- Parameters:
settings (dict) – The LAMMPS input settings. Its
generate_velentry, when present, holds theseedof the draw, therescaleenergy,zero_momentum, which selects themomkeyword of thevelocity createcommand, andconstrained, True when a fix of a style ofLAMMPS_PROJECTING_FIXESconstrains the velocities (a missing key means False).velocity createscales the velocities it creates toSET_TEMP, and a run of 0 steps follows it. Withconstrained, the setup of that run constrains the velocities, andGENERATE_VEL_SCALEre-scales them toSET_TEMP, with the degrees of freedom that the fixes constrain counted, as the LAMMPS documentation of thevelocitycommand gives for rigid bodies and constraints; the constraints are linear in the velocities, so the re-scaled velocities satisfy them. A positiverescalethen re-scales the velocities so that the energype + keLAMMPS evaluates equals it (RESCALE_ENERGY), whenpeis not above it andkeis positive; otherwise LAMMPS keeps the velocities and printsRESCALE_SKIPPED_PEorRESCALE_SKIPPED_KE(RESCALE_CONDITION). Withconstrained, a run of 0 steps before this re-scale evaluatespeandkefor the velocities ofGENERATE_VEL_SCALE.- Returns:
lines (list of strings) – The LAMMPS commands that create the velocities; empty when
settingsrequests no velocity generation.
- pyretis.engines.lammps_steps._add_order_fix(settings)¶
Add the fix for printing the order parameter for LAMMPS.
- pyretis.engines.lammps_steps._add_stopping_condition(settings)¶
Add the interface stopping condition to the LAMMPS input.
- pyretis.engines.lammps_steps._add_traj_dump(settings)¶
Add the dump commands for storing the LAMMPS trajectory.
- pyretis.engines.lammps_steps._check_lammps_data_keyword_line(tokens, index, lines, data_file, previous)¶
Refuse a line that LAMMPS
read_datastops at as a keyword line.LAMMPS reads the first line below the header, and the first line below the rows of a section, that is neither blank nor a comment, as the keyword line of a section, unless it is the last line of the file (
_read_lammps_data_sections()).- Parameters:
tokens (list of strings) – The words of the line, without its comment.
index (integer) – The index of the line in
lines.lines (list of strings) – The lines of the data file.
data_file (string) – The data file, as the error messages name it.
previous (tuple or None) – The keyword, the number of rows and the line number, from 1, of the first row of the section whose rows the line follows; None for the line below the header.
- Raises:
ValueError – If the line is not the keyword line of a
MassesorAtomssection, and follows the rows of a section and starts with a number, as a row beyond the number of rows of the header does, or has a keyword of a header line (_lammps_data_header_keyword()); the message names the line.
- pyretis.engines.lammps_steps._counted(number, noun)¶
Return a number and a noun, in the plural for a number other than 1.
- Parameters:
number (integer) – The number.
noun (string) – The noun in the singular, as
roworatom type.
- Returns:
out (string) –
numberandnoun, with ansappended tonounfor anumberother than 1, as1 rowand3 rows.
- pyretis.engines.lammps_steps._is_one_lammps_word(value)¶
Return True if a value of a LAMMPS variable is one plain word.
- Parameters:
value (string) – A word of a
variablecommand after its style.- Returns:
out (boolean) – True if
valueis not empty and holds no white space (LAMMPS_WHITESPACE) and no$.
- pyretis.engines.lammps_steps._is_other_lammps_data_header(tokens)¶
Return whether a line is a header line that PyRETIS does not read.
These are the lines
N bonds,N bond types,N extra bond per atomand the like (LAMMPS_DATA_OTHER_COUNTSandLAMMPS_DATA_EXTRA_PER_ATOM), with the numberNin digits, which LAMMPSread_datareads by their keywords after the number, as it readsN atoms, and ignores the words after the keywords.- Parameters:
tokens (list of strings) – The words of the line, without its comment.
- Returns:
out (boolean) – True if
tokensis one of these lines.
- pyretis.engines.lammps_steps._iter_lammps_dump_lines(lines, dimension, source='<lines>')¶
Parse LAMMPS custom dump frames from an iterator of text lines.
The frames are yielded one at a time:
read_lammps_dump()reads them all, andwrite_lammps_dump_frame()stops at the frame it writes. The parser is strict: a frame truncated mid-way raises, so a caller must hand it complete frames only.The positions of a dump of scaled positions (
xs,xsuand so on) are those its box gives them (lammps_scaled_positions()). The unwrapped position of an atom is its wrapped position plus the edge vectors of the box times its image flags:x + ix * Lwith the box lengthLof the axis in an orthogonal box, andx + ix * a + iy * b + iz * cin a triclinic box (lammps_box_vectors()), whose image flags are read from the dump.- Parameters:
lines (iterator of strings) – The dump lines to parse.
dimension (integer) – Number of spatial dimensions to extract.
source (string, optional) – Name used in error messages (the originating file).
- Yields:
frame (dict) – A frame containing its timestep, box, atom IDs, wrapped/unwrapped positions, image flags and velocities.
- pyretis.engines.lammps_steps._lammps_command_words(command)¶
Return the words of a LAMMPS command, as LAMMPS reads them.
The comment of the command is left out (
_strip_lammps_comment()), the characters ofLAMMPS_UTF8_SUBSTITUTIONSare replaced, and the words are split as LAMMPS splits them (_split_lammps_words()). LAMMPS variables are not evaluated: a word with a$names one.- Parameters:
command (string) – A command, as
_lammps_input_commands()returns it.- Returns:
out (list of strings) – The words of the command; the first is the name of the command.
- pyretis.engines.lammps_steps._lammps_commands_of_name(variables, name)¶
Return the
variablecommands that define one variable.- Parameters:
variables (list of tuples) – The
variablecommands, each the file that holds it and the words of the command aftervariable.name (string) – The name of the variable.
- Returns:
out (list of tuples) – The commands whose first word is
name.
- pyretis.engines.lammps_steps._lammps_compute_argument_dependence(name, style, word, definitions, seen)¶
Return why an argument of a compute is not a position function.
- Parameters:
name (string) – The ID of the compute.
style (string) – The style of the compute, without its accelerator suffix.
word (string) – The argument, without an index in brackets.
definitions (dict) – The commands of the input (
lammps_order_definitions()).seen (set of tuples) – The variables and computes read so far; changed in place.
- Returns:
out (tuple of strings or None) – The compute and why the argument is not a function of the positions; None when it is one.
- pyretis.engines.lammps_steps._lammps_compute_dependence(name, definitions, seen)¶
Return why a LAMMPS compute is not a function of the positions.
A compute is a function of the positions when each command that defines it has a style of
LAMMPS_POSITION_COMPUTE_STYLES, without its accelerator suffix, a group that is not dynamic, and arguments that are: the attributes ofproperty/atomare ofLAMMPS_POSITION_ATOM_PROPERTIES, the arguments ofreduceare ofLAMMPS_REDUCE_WORDS, positions and integers (and the region first forreduce/region), and for each style a reference to a variable, a compute or a fix (v_,c_,f_) is read by_lammps_word_dependence()and a velocity is refused.- Parameters:
name (string) – The ID of the compute.
definitions (dict) – The commands of the input (
lammps_order_definitions()).seen (set of tuples) – The variables and computes read so far; changed in place.
- Returns:
out (tuple of strings or None) – The word that the compute reads and why it is not a function of the positions; None when it is one.
- pyretis.engines.lammps_steps._lammps_data_header_keyword(tokens)¶
Return the first keyword of a header line that a line has.
The words are compared in lower case, so
XLOis the keywordxlo, which LAMMPSread_datareads in lower case only.- Parameters:
tokens (list of strings) – The words of the line, without its comment.
- Returns:
out (string or None) – The keyword, in lower case, of the first word of
tokensthat isatomsor a keyword of the box (LAMMPS_DATA_BOX_WORDS), or of the wordsatom types; None whentokenshas none of them.
- pyretis.engines.lammps_steps._lammps_data_integer(text, row, column)¶
Return a column of a data-file row that holds an integer.
- Parameters:
text (string) – The column.
row (string) – The row, as the error message names it.
column (string) – What the column holds, as the error message names it.
- Returns:
out (integer) – The integer that
textwrites.- Raises:
ValueError – If
textdoes not write an integer, as1.0or-0.82.
- pyretis.engines.lammps_steps._lammps_data_number(text, row, column)¶
Return a column of a data-file row that holds a number.
- Parameters:
text (string) – The column.
row (string) – The row, as the error message names it.
column (string) – What the column holds, as the error message names it.
- Returns:
out (float) – The number that
textwrites.- Raises:
ValueError – If
textdoes not write a number (LAMMPS_DATA_NUMBER).
- pyretis.engines.lammps_steps._lammps_data_reads(section, count, first, data_file)¶
Return how LAMMPS
read_datareads a section, for a message.- Parameters:
section (string) – The keyword of the section, a key of
LAMMPS_DATA_VELOCITY_SECTIONS.count (integer) – The number of rows of the section, from the header.
first (integer) – The line number, from 1, of the first row.
data_file (string) – The data file, as the message names it.
- Returns:
out (string) – The clause of a message, without a full stop.
- pyretis.engines.lammps_steps._lammps_data_section_rows(lines, index, count, data_file)¶
Return the rows of a section of a data file that PyRETIS reads.
The section is a
Masses,AtomsorVelocitiessection (LAMMPS_DATA_VELOCITY_SECTIONS). LAMMPSread_dataskips the line below the keyword line of a section, whatever it holds, and reads thecountlines from the second line below the keyword line as the rows of the section, one for each atom type or atom of the header. The words of a row are those of_lammps_data_words().- Parameters:
lines (list of strings) – The lines of the data file.
index (integer) – The index in
linesof the keyword line of the section.count (integer) – The number of rows of the section, from the header.
data_file (string) – The data file, as the error messages name it.
- Returns:
out (list of tuples) – The line and the words of each row.
- Raises:
ValueError – If the file ends before the last row, or a row is a blank line or a comment, which LAMMPS stops at; the message names the line.
- pyretis.engines.lammps_steps._lammps_data_words(line)¶
Return the words of a row of a LAMMPS data file, without a comment.
LAMMPS
read_datareads a row of theMassesandAtomssections up to its first word that starts with#, so a#inside a word, as in1.0#H, is part of that word.- Parameters:
line (string) – The line of the row.
- Returns:
out (list of strings) – The words of
linebefore its first word that starts with#.
- pyretis.engines.lammps_steps._lammps_deform_pressure_problem(source, words, template)¶
Return why a path-sampling run cannot use a fix deform/pressure.
The parameters and keywords of the command are read as LAMMPS reads them, from the word after N on (
LAMMPS_DEFORM_PRESSURE_PARAMETERS,LAMMPS_DEFORM_PRESSURE_KEYWORDS); LAMMPS applies the last value of a keyword that the command repeats. A style ofLAMMPS_DEFORM_PRESSURE_FEEDBACK, and the stylevolumewithvol/balance/p yes, move the box by the deviation of the pressure from a target, deterministically and without time reversibility, as fix press/berendsen does.- Parameters:
source (string) – The file that holds the command.
words (list of strings) – The words of the command after
fix, of the styleLAMMPS_DEFORM_PRESSURE.template (string) – The path of
lammps.in, for the sentence on the md tasks (_lammps_md_tasks()).
- Returns:
out (string or None) – The reason, for a pressure control and for a word at the place of a parameter, a style or a keyword that is not one or that holds a LAMMPS variable; None for a fix that changes the box as fix deform does.
- pyretis.engines.lammps_steps._lammps_fix_variable_problem(source, words, checked, one_word)¶
Return why the words of a LAMMPS fix command cannot be read.
- Parameters:
source (string) – The file that holds the command.
words (list of strings) – The words of the command after
fix.checked (integer) – The number of the words of
words, from the first, whose variables must give one word.one_word (set of strings) – The variables that give one word (
lammps_one_word_variables()).
- Returns:
out (string or None) – The reason, for the first word that reads by substitution a variable not in
one_word; None when there is none.
- pyretis.engines.lammps_steps._lammps_fix_warnings(source, words, style, variables)¶
Return the path-sampling warnings of one LAMMPS fix command.
- Parameters:
source (string) – The file that holds the command.
words (list of strings) – The words of the command after
fix.style (string) – The style of the fix without its accelerator suffix.
variables (list of tuples) – The
variablecommands oflammps.inand of the files it reads (lammps_named_commands()).
- Returns:
out (list of strings) – The warnings: for a fix of
LAMMPS_MEMORY_FIXES, ofLAMMPS_MOMENTUM_FIXESwith an N other than 1 (_lammps_momentum_warning()), ofLAMMPS_START_CHANGING_FIXES, and forfix langevinandfix langevin/effwithgjf vfull.
- pyretis.engines.lammps_steps._lammps_formula_dependence(formula, definitions, seen)¶
Return what makes a LAMMPS formula other than a position function.
A formula is a function of the positions of the atoms and of the box of a frame when each word it reads is one: a number, an operator, a word of
LAMMPS_FORMULA_BOX_KEYWORDS,LAMMPS_FORMULA_CONSTANTS,LAMMPS_FORMULA_MATH_FUNCTIONSorLAMMPS_FORMULA_POSITION_ATOMS, a group or region function ofLAMMPS_FORMULA_POSITION_GROUP_FUNCTIONSof a group that is not dynamic, or a variable or a compute that is one (_lammps_word_dependence()).- Parameters:
formula (string) – The formula, or a value of a variable of another style.
definitions (dict) – The commands of the input (
lammps_order_definitions()).seen (set of tuples) – The variables and computes read so far; changed in place.
- Returns:
out (tuple of strings or None) – The word that the formula reads and why it is not a function of the positions; None when the formula is one.
- pyretis.engines.lammps_steps._lammps_gjf_choice(words, style)¶
Return the value of the keyword that chooses the GJF velocities.
The keywords are read as
_lammps_gjf_problem()reads them.- Parameters:
words (list of strings) – The words of the command after
fix.style (string) – The style of the fix without its accelerator suffix, a key of
LAMMPS_GJF_FIXES.
- Returns:
out (string or None) – The last value of the keyword, or the value LAMMPS takes when the command does not give it; None when a word at the place of a keyword is not a keyword of the style or holds a LAMMPS variable.
- pyretis.engines.lammps_steps._lammps_gjf_problem(source, words, style, template)¶
Return why a path-sampling run cannot use a GJF Langevin fix.
The keywords of the command are read as LAMMPS reads them, from the word
LAMMPS_GJF_FIRST_KEYWORDafterfixon, each with the number of valuesLAMMPS_GJF_FIXESgives; the last value of the keyword that chooses the velocities is the one LAMMPS applies.- Parameters:
source (string) – The file that holds the command.
words (list of strings) – The words of the command after
fix.style (string) – The style of the fix without its accelerator suffix, a key of
LAMMPS_GJF_FIXES.template (string) – The path of
lammps.in, for the sentence on the md tasks (_lammps_md_tasks()).
- Returns:
out (string or None) – The reason, for a fix that stores the velocities half a time step away from the positions, for a keyword or the value of the keyword that chooses the velocities given by a LAMMPS variable, and for a word at the place of a keyword that is not one of
LAMMPS_GJF_FIXES; None for a fix that stores the velocities at the time of the positions.
- pyretis.engines.lammps_steps._lammps_if_commands(arguments)¶
Return the commands of every branch of a LAMMPS
ifcommand.- Parameters:
arguments (list of strings) – The words of the
ifcommand afterif: the condition,thenand its commands, and for eachelifits condition and commands, and forelseits commands.- Returns:
out (list of strings) – The commands of all branches, in their order.
- pyretis.engines.lammps_steps._lammps_immediate_end(command, index)¶
Return the index past the immediate variable that starts at index.
As LAMMPS reads an immediate variable,
$(starts it and the parenthesis that closes its(ends it, with the parentheses in between counted. An immediate variable that is not closed runs to the end of the command; LAMMPS stops at such a command.- Parameters:
command (string) – A command of a LAMMPS input.
index (integer) – The index of the
$of$(incommand.
- Returns:
out (integer) – The index of the character after the closing parenthesis, or the length of
command.
- pyretis.engines.lammps_steps._lammps_input_commands(text)¶
Return the commands of a LAMMPS input text, one string each.
The lines are joined as LAMMPS joins them: a line whose last printable character is
&continues on the next line, without the&and the line break, and a command whose lines so far hold an odd number of triple quotes, three double quotes in a row, continues on the next line, after a line break.- Parameters:
text (string) – The text of a LAMMPS input file.
- Returns:
out (list of strings) – The commands, each line without its white space at the end (
LAMMPS_WHITESPACE).
- pyretis.engines.lammps_steps._lammps_keyword_seeds(words, keyword, offset, first)¶
Return the seeds that a keyword of a LAMMPS command gives.
- Parameters:
words (list of strings) – The words of the command after its name.
keyword (tuple of strings) – The words of the keyword.
offset (integer) – The position of the seed after the first word of the keyword.
first (integer) – The position of the first word of
wordsthat may be a keyword.
- Returns:
out (list) – For each place of the keyword in
words, the word at the position of its seed, or None when the command ends before it.
- pyretis.engines.lammps_steps._lammps_md_tasks(template)¶
Return what the md tasks do with a LAMMPS input path sampling refuses.
The
md,md-nveandmd-fluxtasks read the temperature oflammps.inwithread_lammps_temperatures()and take the one temperature its settings hold, which decides the sentence (md_tasks_sentence()).- Parameters:
template (string) – The path of
lammps.in.- Returns:
out (string) – A sentence that says that every task refuses the input, with the reason, for an input the reader refuses or whose settings hold no temperature or different ones; else that the
md,md-nveandmd-fluxtasks accept it.
- pyretis.engines.lammps_steps._lammps_momentum_warning(words, style, variables)¶
Return the warning of a fix of
LAMMPS_MOMENTUM_FIXES.- Parameters:
words (list of strings) – The words of the command after
fix.style (string) – The style of the fix without its accelerator suffix.
variables (list of tuples) – The
variablecommands oflammps.inand of the files it reads (lammps_named_commands()).
- Returns:
out (string or None) – The warning; None when its N, the word at
LAMMPS_MOMENTUM_INTERVAL, is 1 as_lammps_number()reads it: the fix then acts at the end of every time step.
- pyretis.engines.lammps_steps._lammps_number(word, variables)¶
Return the number that a word of a LAMMPS command gives.
- Parameters:
word (string) – The word: a number (
LAMMPS_NUMBER), or${name}or$xof a variable that everyvariablecommand of its name defines with a style ofLAMMPS_VALUE_VARIABLE_STYLESand one number.variables (list of tuples) – The
variablecommands oflammps.inand of the files it reads (lammps_named_commands()).
- Returns:
out (float or None) – The number; None for another word, or for a variable that is defined with two numbers that differ or in another way.
- pyretis.engines.lammps_steps._lammps_pimd_ensemble(words)¶
Return the ensemble of a fix of
LAMMPS_PIMD_LANGEVIN_FIXES.- Parameters:
words (list of strings) – The words of the command after
fix.- Returns:
out (string) – The value of the last keyword
LAMMPS_PIMD_ENSEMBLE_KEYWORDamong the keywords after the style, orLAMMPS_PIMD_DEFAULT_ENSEMBLEwhen the command does not give it.
- pyretis.engines.lammps_steps._lammps_pimd_memory(style, ensemble)¶
Return what a fix of
LAMMPS_PIMD_LANGEVIN_FIXEScarries.- Parameters:
style (string) – The style of the fix without its accelerator suffix.
ensemble (string) – Its ensemble (
_lammps_pimd_ensemble()).
- Returns:
out (string) – What the fix integrates with this ensemble, and what carries from one time step to the next that a frame does not store.
- pyretis.engines.lammps_steps._lammps_restart_configuration_reason(config, run_dir=None, named=None)¶
Tell why a configuration is held in a LAMMPS restart file.
A configuration is held in a LAMMPS restart file when its file is named
.restartand it is the one configuration of the file (index 0 or None), or when its file starts with the magic string of a LAMMPS restart file (is_lammps_restart_file()), whatever its name and index. The file is looked for where PyRETIS reads it, from the working directory, and, for a relative name, where LAMMPS reads it, inrun_dir.- Parameters:
config (tuple) – The file and the index of the configuration.
run_dir (string, optional) – The directory that LAMMPS runs in.
named (string, optional) – The file as the message names it, in place of the file of
config(a staged copy stands for the file it is a copy of).
- Returns:
out (string or None) – Why the configuration is held in a restart file, for a message; None when it is not.
- pyretis.engines.lammps_steps._lammps_rigid_body_keyword(words)¶
Return the keyword with which rigid bodies keep their velocities.
The setup of a run of a fix rigid style sets the velocities of its bodies from the velocities of their atoms, unless the command has the keyword
infile(LAMMPS_RIGID_INFILE), with which the bodies take their velocities from the file, or its last keywordreinit(LAMMPS_RIGID_REINIT), the one LAMMPS applies, has a value other than one ofLAMMPS_TRUE_WORDS, with which the bodies take their velocities from their atoms at the setup of the first run only. A value that holds a LAMMPS variable is not one ofLAMMPS_TRUE_WORDS.- Parameters:
words (list of strings) – The words of the fix command after
fix.- Returns:
out (string or None) –
infileand its value, or else the lastreinitand its value, as the command has them; None when the command has noinfileand noreinit, or a lastreinitwith a value ofLAMMPS_TRUE_WORDS.
- pyretis.engines.lammps_steps._lammps_row_layout(style)¶
Return the row layout of an atom style, or its base style.
- pyretis.engines.lammps_steps._lammps_substituted_variables(word)¶
Return the LAMMPS variables that a word reads by substitution.
LAMMPS replaces
${name}and$x(a name of one character) by the value of the variable before it splits a command into words. An immediate variable$(...)is replaced by one number.- Parameters:
word (string) – A word of a LAMMPS command, as
_lammps_command_words()returns it.- Returns:
out (list of strings) – The names of the variables of
${name}and$x, in the order the word reads them.
- pyretis.engines.lammps_steps._lammps_thermostat_problem(source, words, style, template)¶
Return why a path-sampling run cannot use a thermostat or barostat.
Every piece of trajectory that a path-sampling run generates is a LAMMPS run of its own from a stored frame. A fix of the Nose-Hoover equations (
LAMMPS_NOSE_HOOVER_ROOTS,LAMMPS_NOSE_HOOVER_FIXES) or of a shock wave (LAMMPS_SHOCK_FIXES) carries variables of its own from one time step to the next, which the frame does not store and which LAMMPS starts anew for each piece, and so does a fix ofLAMMPS_PIMD_LANGEVIN_FIXESwith an ensemble without its thermostat (nve, nph:_lammps_pimd_memory()). A fix ofLAMMPS_RESCALING_FIXESrescales the velocities, or the box, deterministically and is not time reversible, and a fix ofLAMMPS_IRREVERSIBLE_FIXESchanges the velocities deterministically and is not time reversible.- Parameters:
source (string) – The file that holds the command.
words (list of strings) – The words of the command after
fix.style (string) – The style of the fix without its accelerator suffix.
template (string) – The path of
lammps.in, for the sentence on the md tasks (_lammps_md_tasks()).
- Returns:
out (string or None) – The reason, naming the fix and the fixes to use instead; None for a fix of none of these styles.
- pyretis.engines.lammps_steps._lammps_variable_dependence(name, definitions, seen)¶
Return why a LAMMPS variable is not a function of the positions.
Each command that defines the variable is read: the formula of an
equal,vectororatomvariable and the values of anindex,string,worldoruniversevariable by_lammps_formula_dependence(), and the variable of aformatvariable. Alooporuloopvariable is a number; a variable of another style is not read as a position function.- Parameters:
name (string) – The name of the variable.
definitions (dict) – The commands of the input (
lammps_order_definitions()).seen (set of tuples) – The variables and computes read so far; changed in place.
- Returns:
out (tuple of strings or None) – The word that the variable reads and why it is not a function of the positions; None when it is one.
- pyretis.engines.lammps_steps._lammps_word_dependence(word, follows, definitions, seen)¶
Return why a word of a LAMMPS formula is not a position function.
- Parameters:
word (string) – A name that the formula reads.
follows (string) – The character after the word and its white space:
(for a function,[for an atom value or an element.definitions (dict) – The commands of the input (
lammps_order_definitions()).seen (set of tuples) – The variables and computes read so far; changed in place.
- Returns:
out (tuple of strings or None) – The word and why it is not a function of the positions; None when it is one.
- pyretis.engines.lammps_steps._locate_lammps_file(name, run_dir, staged)¶
Return the file that LAMMPS reads for a file name of a command.
LAMMPS reads a file that a command names by a relative path from the directory it runs in,
run_dir. A file ofrun_dirthat is not there is the copy that the engine stages there before the run, of the file of its name instaged.- Parameters:
name (string) – The file name of the command.
run_dir (string) – The directory that LAMMPS runs in.
staged (dict of strings) – The files that the engine stages in
run_dir, as the name of the copy -> the path of the file.
- Returns:
out (string or None) – The path of the file that LAMMPS reads; None when there is none, as LAMMPS then stops at the command.
- pyretis.engines.lammps_steps._parse_dump_box(bounds)¶
Return orthogonal box lengths from LAMMPS dump bounds.
- pyretis.engines.lammps_steps._parse_lammps_dump_lines(lines, dimension, source='<lines>')¶
Return all the frames of a LAMMPS dump iterator.
- pyretis.engines.lammps_steps._read_lammps_commands(source, files, commands)¶
Add the commands of a LAMMPS input file and of the files it reads.
The file is read as UTF-8 text, and a byte that is not UTF-8 is read as the replacement character, which no LAMMPS command name or style holds.
- Parameters:
source (string) – The path of the file.
files (dict) – The directory LAMMPS runs in, the staged files and the files read so far, as
_scan_lammps_command()describes.commands (dict of lists) – The commands read so far; changed in place, as
_scan_lammps_command()describes.
- pyretis.engines.lammps_steps._read_lammps_data(data_file, styles, read_box, read_velocities)¶
Read the header and the sections of a LAMMPS data file.
The file is read as
read_lammps_data_file()describes, and, withread_velocities, itsVelocitiessection too (_read_lammps_data_sections()).- Parameters:
data_file (string) – The LAMMPS data file.
styles (tuple of strings) – The
[engine] atom_styleand the style of theatom_stylecommand oflammps.in, each None when not given.read_box (boolean) – True to read the box of the header, as
read_lammps_data_file()reads it.read_velocities (boolean) – True to read the
Velocitiessection.
- Returns:
type_masses (list of tuples) – The atom type and the mass of each row of the
Massessection.atoms (dict) – The atom type, the positions and the image flags of each atom, by atom ID.
velocities (dict or None) – The velocity of each atom, by atom ID; None without
read_velocitiesand for a file without aVelocitiessection.box (list of tuple or None) – The
(lo, hi)box bounds of x, y and z; None whenread_boxis False.
- Raises:
ValueError, NotImplementedError – As
read_lammps_data_file()and_read_lammps_data_sections()raise them.
- pyretis.engines.lammps_steps._read_lammps_data_atoms(style, rows, data_file)¶
Read the rows of the
Atomssection of a LAMMPS data file.- Parameters:
style (string) – The atom style of the rows (
resolve_lammps_atom_style()).rows (list of tuples) – The line and the words of each row of the section (
_lammps_data_section_rows()).data_file (string) – The data file, as the error messages name it.
- Returns:
out (dict) – The atom type, the positions and the image flags of each atom, by atom ID.
- Raises:
ValueError – As
read_lammps_data_file()raises it for anAtomsrow.NotImplementedError – If the atom style of the rows is not supported (
lammps_atom_columns()).
- pyretis.engines.lammps_steps._read_lammps_data_bounds(tokens, line, axis, box)¶
Read a box-bounds line of the header of a LAMMPS data file.
- Parameters:
tokens (list of strings) – The words of the line, without its comment: the lo and hi bounds and the keywords of the axis (
LAMMPS_DATA_BOUNDS).line (string) – The line, as the error messages name it.
axis (integer) – The axis of the bounds, 0 for x, 1 for y and 2 for z.
box (dict or None) – The
(lo, hi)bounds of the header by axis, which the line adds to; None for a read without the box.
- Raises:
ValueError – If a bound is not a number, or the hi bound is not above the lo bound, which LAMMPS
read_datastops at. Ifboxis not None and gives the bounds ofaxis, from an earlier line.
- pyretis.engines.lammps_steps._read_lammps_data_header(tokens, line, counts, box)¶
Read a line of the header of a LAMMPS data file.
The line is read as LAMMPS
read_datareads it, by the keywords at fixed positions of the line, and the words after them are ignored:N atomsandN atom types, with the numberNin digits (LAMMPS_DATA_COUNTS);lo hi xlo xhi,lo hi ylo yhiandlo hi zlo zhi, the bounds of an axis (LAMMPS_DATA_BOUNDS);three numbers and
xy xz yz,avec,bvec,cvecorabc origin, a line of a triclinic box (LAMMPS_DATA_TRICLINIC).
The other header lines of LAMMPS, as
N bondswith trailing words or none (_is_other_lammps_data_header()), and a line without the keywords of these lines are not read.- Parameters:
tokens (list of strings) – The words of the line, without its comment.
line (string) – The line, as the error messages name it.
counts (dict) – The numbers of the header, by the keys
atomsandatom types, which the line adds to.box (dict or None) – The
(lo, hi)bounds of the header by axis, 0 for x, 1 for y and 2 for z (LAMMPS_DATA_BOUNDS), which a bounds line adds to. None for a read without the box: a line of the box is then read for its form only.
- Raises:
NotImplementedError – If
boxis not None and the line is a line of a triclinic box.ValueError – If the line has a keyword of these lines and is none of them, nor another header line of LAMMPS (
_lammps_data_header_keyword()), or gives a number of atoms or atom types that is not written in digits, which LAMMPS stops at with “Unknown identifier in data file”; if a bound, or a number of a line of a triclinic box, is not a number; if a hi bound is not above its lo bound, which LAMMPS stops at. Ifboxis not None and the line gives the bounds of an axis that an earlier line of the header gives.
- pyretis.engines.lammps_steps._read_lammps_data_masses(rows, n_types, data_file)¶
Read the rows of the
Massessection of a LAMMPS data file.- Parameters:
rows (list of tuples) – The line and the words of each row of the section (
_lammps_data_section_rows()).n_types (integer) – The number of atom types that the header of the file gives.
data_file (string) – The data file, as the error messages name it.
- Returns:
out (list of tuples) – The atom type and the mass of each row.
- Raises:
ValueError – If a row does not hold an integer atom type and a number, or holds an atom type outside 1 to
n_typesor a mass that is not positive, which LAMMPSread_datastops at.
- pyretis.engines.lammps_steps._read_lammps_data_sections(lines, index, counts, data_file, styles, *, read_velocities=False)¶
Read the
MassesandAtomssections of a LAMMPS data file.The lines from
index, the first line below the header, are read as LAMMPSread_datareads them: the first line that is neither blank nor a comment is a keyword line (_check_lammps_data_keyword_line()), the rows of aMassesorAtomssection follow it (_lammps_data_section_rows()), and so does the keyword line of the next section. The keyword line of another section and the line below it are skipped, and so are the lines below them up to the nextMassesorAtomskeyword line. LAMMPS reads a keyword line together with the line below it, and at a keyword line that is the last line of the file it ends the read without the section, so such a line is not read. Withread_velocities, aVelocitiessection is read as theMassesandAtomssections are (_read_lammps_data_velocity_rows()), below theAtomssection, as LAMMPSread_datarequires.- Parameters:
lines (list of strings) – The lines of the data file.
index (integer) – The index in
linesof the first line below the header.counts (dict) – The numbers of the header, by the keys
atomsandatom types.data_file (string) – The data file, as the error messages name it.
styles (tuple of strings) – The
[engine] atom_styleand the style of theatom_stylecommand oflammps.in, each None when not given (resolve_lammps_atom_style()).read_velocities (boolean, optional) – True to read the
Velocitiessection too. False (the default) to skip it as another section.
- Returns:
type_masses (list of tuples) – The atom type and the mass of each row of the last
Massessection, empty for a file without one.atoms (dict or None) – The atom type, the positions and the image flags of each atom, by atom ID (
_read_lammps_data_atoms()); None for a file without anAtomssection.velocities (dict or None) – The velocity of each atom, by atom ID (
_read_lammps_data_velocity_rows()); None withoutread_velocities, and for a file without aVelocitiessection.
- Raises:
ValueError, NotImplementedError – As
read_lammps_data_file()raises them for the lines below the header. Withread_velocities, aValueErroralso for aVelocitiessection above theAtomssection, which LAMMPSread_datastops at, for a secondVelocitiessection, and as_lammps_data_section_rows()and_read_lammps_data_velocity_rows()raise it for the rows of the section.
- pyretis.engines.lammps_steps._read_lammps_data_velocity_rows(rows, atoms, data_file)¶
Read the rows of the
Velocitiessection of a LAMMPS data file.Each row is
atom-ID vx vy vz, the row of the atom styles whoseAtomsrows PyRETIS reads (LAMMPS_DATA_ATOM_COLS), with the velocity of the atom of that ID of theAtomssection.- Parameters:
rows (list of tuples) – The line and the words of each row of the section (
_lammps_data_section_rows()).atoms (dict) – The atoms of the
Atomssection, by atom ID (_read_lammps_data_atoms()).data_file (string) – The data file, as the error messages name it.
- Returns:
out (dict) – The velocity of each atom,
[vx, vy, vz], by atom ID.- Raises:
ValueError – If a row has another number of columns than 4, an atom ID that is not an integer, a velocity that is not a number, the atom ID of no atom of the
Atomssection, which LAMMPSread_datastops at, or the atom ID of an earlier row.
- pyretis.engines.lammps_steps._read_lammps_data_velocity_section(rows, atoms, velocities, index, data_file)¶
Read a
Velocitiessection below theAtomssection.- Parameters:
rows (list of tuples) – The line and the words of each row of the section (
_lammps_data_section_rows()).atoms (dict or None) – The atoms of the
Atomssection read so far, by atom ID; None when noAtomssection is above theVelocitiessection.velocities (dict or None) – The velocities of a
Velocitiessection read so far; None when noVelocitiessection is above this one.index (integer) – The index of the keyword line of the section in the lines of the file.
data_file (string) – The data file, as the error messages name it.
- Returns:
out (dict) – The velocity of each atom, by atom ID (
_read_lammps_data_velocity_rows()).- Raises:
ValueError – If no
Atomssection is above the section, which LAMMPSread_datastops at, or aVelocitiessection is, and as_read_lammps_data_velocity_rows()raises it.
- pyretis.engines.lammps_steps._refuse_lammps_variable(word, command, source, what)¶
Refuse a word of a LAMMPS command that holds a LAMMPS variable.
- Parameters:
word (string) – The word of the command.
command (string) – The command, as the message names it.
source (string) – The file that holds the command.
what (string) – What the word names, as the message names it.
- Raises:
NotImplementedError – If
wordholds a$, the reference to a LAMMPS variable.
- pyretis.engines.lammps_steps._scan_lammps_command(words, source, files, commands)¶
Add the commands of one LAMMPS command to
commands.A command whose name is a key of
commandsis added to its list. The commands of a file that anincludecommand, or ajumpcommand to a file other thanSELF, names are read at that command (_read_lammps_commands()), and the commands of every branch of anifcommand are read, as commands that LAMMPS may run. Anunfixcommand removes no command fromcommands.- Parameters:
words (list of strings) – The words of the command (
_lammps_command_words()).source (string) – The file that holds the command.
files (dict) – The
run_dirandstagedof_locate_lammps_file(), and inreadthe set of the paths of the files read so far; a file is read once.commands (dict of lists) – The name of a command -> the commands of the name read so far, each the file that holds it and the words of the command after its name; changed in place.
- Raises:
NotImplementedError – If a
fixcommand names its style by a LAMMPS variable, or holds fewer than three words afterfixand a LAMMPS variable, whose value may hold the style, if apair_stylecommand names its style by a LAMMPS variable, or if anincludeorjumpcommand names its file by a LAMMPS variable.
- pyretis.engines.lammps_steps._split_lammps_words(command)¶
Return the words of a LAMMPS command without its comment.
A word is separated from the next by white space (
LAMMPS_WHITESPACE), and a word in single, double or triple quotes is the text between the quotes. A quote that is not closed makes the rest of the command one word; LAMMPS stops at such a command. An immediate variable$(...)outside quotes belongs to the word it starts in, white space included: LAMMPS replaces it by its value before it splits the command into words (_lammps_immediate_end()).- Parameters:
command (string) – A command from
_strip_lammps_comment().- Returns:
out (list of strings) – The words of the command.
- pyretis.engines.lammps_steps._strip_lammps_comment(command)¶
Return a LAMMPS command without its comment.
The comment starts at the first
#that is not between single, double or triple quotes. A quote that is not closed leaves the rest of the command as it is; LAMMPS stops at such a command.- Parameters:
command (string) – A command from
_lammps_input_commands().- Returns:
out (string) – The command up to its comment.
- pyretis.engines.lammps_steps.add_to_lammps_input(infile, outfile, to_add)¶
Add PyRETIS specific settings to an input file for LAMMPS.
This method will append settings needed by PyRETIS to an input file for LAMMPS.
- Parameters:
infile (string) – Path to a file which contains the LAMMPS settings.
outfile (string) – Path to the file we should create.
to_add (list of strings) – The settings to add for PyRETIS.
- pyretis.engines.lammps_steps.check_lammps_atom_row(style, count, row)¶
Refuse an
Atomsrow that fits no row layout of an atom style.A row of a supported style (
LAMMPS_ATOM_STYLE_LAYOUT) ends with the three positions, or with the positions and the three image flags, so it has one of two column counts.- Parameters:
style (string) – The atom style of the rows, whose base style (
lammps_base_atom_style()) is a key ofLAMMPS_ATOM_STYLE_LAYOUT.count (integer) – The number of columns of the row.
row (string) – The row, as the error message names it.
- Raises:
ValueError – If
countis neither of the two column counts ofstyle.
- pyretis.engines.lammps_steps.check_lammps_dump_steps(filename, subcycles, nframes=None)¶
Check that frame
kof a LAMMPS dump has the stepk * subcycles.The engines name frame
kof the dump of a LAMMPS run by the time stepk * subcycles(LAMMPSEngineSteps._frame_config_index()), the time step at which a run that starts at time step 0 and dumps everysubcyclessteps writes it.- Parameters:
filename (string) – Path to the LAMMPS dump of a run.
subcycles (integer) – The number of steps between two frames of the dump.
nframes (integer, optional) – The number of frames to check from the start of the dump; all frames when None. With 0, the dump is not read.
- Raises:
ValueError – If a frame of those checked has another time step, or the dump has fewer than
nframesframes.
- pyretis.engines.lammps_steps.create_lammps_md_input(system, infile, outfile, settings)¶
Create MD input file for LAMMPS.
We will here write to a new file, by appending text to the given template.
- Parameters:
system (object like
System) – The system contains the current particle state, and this determines the initial configuration and if we are to modify velocities in some way (e.g. reversing them before running or drawing new ones).infile (string) – Path to a file which contains the LAMMPS settings.
settings (dict) – The settings we are going to use for creating the LAMMPS file.
- Returns:
out (list of strings) – The LAMMPS commands written to the output file.
- pyretis.engines.lammps_steps.is_pyretis_seed_word(word)¶
Return True if a word of a LAMMPS command gives the seed of the run.
The engines define the LAMMPS variable
pyretis_seed(PYRETIS_SEED_VARIABLE) for each LAMMPS run, a seed drawn on their random generator. A word gives that seed when it is the variable,${pyretis_seed}, or an immediate expression that reads it, as$(v_pyretis_seed+1).- Parameters:
word (string) – A word of a LAMMPS command, as
_lammps_command_words()returns it.- Returns:
out (boolean) – True if
wordgives the seed of the run.
- pyretis.engines.lammps_steps.lammps_atom_columns(style)¶
Return the atom-type and first position column of a style’s rows.
- Parameters:
style (string) – A LAMMPS atom style, in lower case, with or without an accelerator suffix (
lammps_base_atom_style()).- Returns:
out (tuple of integers) – The 0-based atom-type column and first position column of the
Atomsrows ofstyle: those of the row layout of its base style (LAMMPS_ATOM_STYLE_LAYOUT) inLAMMPS_DATA_ATOM_COLS.- Raises:
NotImplementedError – If the base style of
styleis not a key ofLAMMPS_ATOM_STYLE_LAYOUT; the message namesstyle.
- pyretis.engines.lammps_steps.lammps_atom_masses(atom_types, type_masses, data_file)¶
Return the mass of each atom from the
Massesrows of a data file.Each row of the
Massessection of a LAMMPS data file starts with the atom type whose mass it gives, and the rows can come in any order of the types. An atom has the mass of the row of its type.- Parameters:
atom_types (sequence of numbers) – The atom type of each atom, from its
Atomsrow.type_masses (sequence of pairs of numbers) – The atom type and the mass of each row of the
Massessection.data_file (string) – The data file, as the error messages name it.
- Returns:
out (numpy.ndarray) – The mass of each atom, in the order of
atom_types, shape(N, 1).- Raises:
ValueError – If the
Massessection gives an atom type twice, or does not give the atom type of an atom.
- pyretis.engines.lammps_steps.lammps_base_atom_style(style)¶
Return a LAMMPS atom style without its accelerator suffix.
LAMMPS names the variant of an atom style of an accelerator package by the style and a suffix after a
/, asfull/kkorfull/kk/deviceof the KOKKOS package, andread_datareads theAtomsrows of the variant in the columns of the style.- Parameters:
style (string) – A LAMMPS atom style, in lower case.
- Returns:
out (string) – The text of
stylebefore its first/.
- pyretis.engines.lammps_steps.lammps_base_fix_style(style)¶
Return a LAMMPS fix or pair style without its accelerator suffix.
LAMMPS names the variant of a style in an accelerator package by the style and a suffix after a
/(LAMMPS_ACCELERATOR_SUFFIXES), asrigid/nve/ompof the OPENMP package, and the variant computes what the style computes.- Parameters:
style (string) – A LAMMPS fix or pair style.
- Returns:
out (string) –
stylewithout its accelerator suffix.
- pyretis.engines.lammps_steps.lammps_box_vectors(bounds)¶
Return the origin and the edge vectors of the box of a dump frame.
A dump of an orthogonal box has a row
lo hifor each of x, y and z. A dump of a triclinic box has the rowsxlo_bound xhi_bound xy,ylo_bound yhi_bound xzandzlo_bound zhi_bound yz: the bounds of the orthogonal box that holds the tilted box, and the tilt factors. As the LAMMPSdumpcommand defines these bounds, the origin of the box is(xlo, ylo, zlo)and its edge vectors area = (xhi - xlo, 0, 0),b = (xy, yhi - ylo, 0)andc = (xz, yz, zhi - zlo), withxlo = xlo_bound - min(0, xy, xz, xy + xz),xhi = xhi_bound - max(0, xy, xz, xy + xz),ylo = ylo_bound - min(0, yz)andyhi = yhi_bound - max(0, yz). The unwrapped position of an atom of the image flagsix iy izis its position plusix * a + iy * b + iz * c. A box without tilt factors has the tilt factors 0.- Parameters:
bounds (array_like) – The box bounds of the frame, a row for each of x, y and z.
- Returns:
origin (numpy.ndarray) – The origin
(xlo, ylo, zlo)of the box.vectors (numpy.ndarray) – The edge vectors
a,bandcof the box, one per row.
- pyretis.engines.lammps_steps.lammps_constraint_fixes(template, run_dir, staged=None)¶
Return the fixes of a LAMMPS input that constrain the velocities.
A constraint fix is a fix command of
lammps.inor of a file it reads (lammps_fix_commands()) whose style, without its accelerator suffix (lammps_base_fix_style()), is a style ofLAMMPS_PROJECTING_FIXESor ofLAMMPS_REFUSED_CONSTRAINT_FIXES.- Parameters:
template (string) – The path of
lammps.in.run_dir (string) – The directory that LAMMPS runs in.
staged (dict of strings, optional) – The files that the engine stages in
run_dirbefore the run, aslammps_fix_commands()takes them.
- Returns:
out (list of tuples) – For each constraint fix, the file that holds it, the words of the command after
fixand the style without its accelerator suffix.- Raises:
NotImplementedError – As
lammps_fix_commands()raises it.
- pyretis.engines.lammps_steps.lammps_derived_image_flags(unwrapped, wrapped, length, label, atom_ids, source)¶
Return the image flags that wrapped and unwrapped positions give.
The image flag of an atom along x of a dump with the columns
xandxuand withoutixis the integer nearest to(xu - x) / (xhi - xlo); so along y and z. Wrapped and unwrapped columns printed with few significant digits can miss an exact box multiple by a few units of their last place, far below the half box length at which the nearest integer changes, sox + ix * Lis accepted within1e-5 * max(1, L)ofxu.- Parameters:
unwrapped (float or numpy.ndarray) – The unwrapped positions of the atoms along the axis.
wrapped (float or numpy.ndarray) – The wrapped positions of the atoms along the axis.
length (float) – The box length of the axis,
xhi - xloalong x.label (string) – The axis,
x,yorz.atom_ids (integer or numpy.ndarray) – The LAMMPS ids of the atoms, as the message of a refusal names them.
source (string) – The dump, as the message of a refusal names it.
- Returns:
out (numpy.ndarray) – The image flags of the atoms along the axis, integers in the shape of
unwrapped.- Raises:
ValueError – If
xu - xof an atom is not an integer box length.
- pyretis.engines.lammps_steps.lammps_fix_commands(template, run_dir, staged=None)¶
Return the fix commands of
lammps.inand of the files it reads.The commands are read as
lammps_named_commands()reads them.- Parameters:
template (string) – The path of
lammps.in.run_dir (string) – The directory that LAMMPS runs in.
staged (dict of strings, optional) – The files that the engine stages in
run_dirbefore the run, as the name of the copy -> the path of the file.
- Returns:
out (list of tuples) – For each
fixcommand, the file that holds it and the words of the command afterfix: the fix ID, the group, the style and the arguments of the style.- Raises:
NotImplementedError – As
lammps_named_commands()raises it.
- pyretis.engines.lammps_steps.lammps_fix_seeds(words)¶
Return the seeds of a LAMMPS fix command.
The seeds of a fix style, without its accelerator suffix (
lammps_base_fix_style()), are the words at the positions ofLAMMPS_FIX_SEED_ARGUMENTSand after the keywords ofLAMMPS_FIX_SEED_KEYWORDSandLAMMPS_FIX_DEFAULT_SEED_KEYWORDS. A LAMMPS variable in a word is read as one word.- Parameters:
words (list of strings) – The words of the command after
fix: the fix ID, the group, the style and the arguments of the style.- Returns:
out (list) – The word of each seed, or None for a seed that the command does not give: a position after its last word, or a keyword of
LAMMPS_FIX_DEFAULT_SEED_KEYWORDSthat it does not have, with which LAMMPS seeds the fix with a seed of its own. Empty for a style that draws no random numbers.
- pyretis.engines.lammps_steps.lammps_input_atom_style(settings)¶
Return the style that the
atom_stylecommand of an input sets.- Parameters:
settings (dict) – The commands of a LAMMPS input file, as keyword -> arguments, from
read_lammps_input().- Returns:
out (string or None) – The first argument of the
atom_stylecommand, in lower case, or as written when it holds a$, the reference to a LAMMPS variable; None when the input has noatom_stylecommand with an argument.
- pyretis.engines.lammps_steps.lammps_named_commands(template, run_dir, staged=None, names=('fix',))¶
Return the commands of some names of
lammps.inand its files.The commands are read as LAMMPS reads them (
_lammps_command_words()), fromtemplateand, at the command that names it, from each file that anincludecommand, or ajumpcommand to a file other thanSELF, names, and from the branches of theifcommands (_scan_lammps_command()). A file named by a relative path is the one that LAMMPS reads from the directory it runs in (_locate_lammps_file()). A file that is not there is not read, as LAMMPS stops at its command, and a file is read once. Every command of the names that is read is returned: those of the branches of anifcommand, which LAMMPS may not run, of the commands that ajumpcommand skips, and a fix that anunfixcommand deletes.- Parameters:
template (string) – The path of
lammps.in.run_dir (string) – The directory that LAMMPS runs in.
staged (dict of strings, optional) – The files that the engine stages in
run_dirbefore the run, as the name of the copy -> the path of the file.names (tuple of strings, optional) – The names of the commands to return.
- Returns:
out (dict of lists) – For each name of
names, the commands of the name, each the file that holds it and the words of the command after its name.- Raises:
NotImplementedError – As
_scan_lammps_command()raises it: for afixor apair_stylecommand that names its style, or anincludeorjumpcommand that names its file, by a LAMMPS variable, a word with a$.
- pyretis.engines.lammps_steps.lammps_one_word_variables(variables)¶
Return the LAMMPS variables whose substitution gives one word.
A variable gives one word when every
variablecommand that defines it has a style ofLAMMPS_NUMBER_VARIABLE_STYLES, or a style ofLAMMPS_WORD_VARIABLE_STYLESand words after the style that are each one plain word (_is_one_lammps_word()). The engines definepyretis_seed(PYRETIS_SEED_VARIABLE) as a number on the command line of each LAMMPS run, a definition of styleindex.- Parameters:
variables (list of tuples) – The
variablecommands oflammps.inand of the files it reads, each the file that holds it and the words of the command aftervariable(lammps_named_commands()).- Returns:
out (set of strings) – The names of the variables that give one word.
- pyretis.engines.lammps_steps.lammps_order_columns(order_file)¶
Return the variables that LAMMPS prints as order-parameter columns.
With
order_mode = "lammps"LAMMPS prints, for each frame, the value of every variable that avariablecommand oforder.innames, in the order of the commands: columnkof the order parameter of the frame is thek-th variable.- Parameters:
order_file (string) – The path of
order.in.- Returns:
out (list of strings) – The names of the variables, one per column.
- pyretis.engines.lammps_steps.lammps_order_definitions(template, order_file, run_dir, staged=None)¶
Return the variables, computes and groups an order parameter reads.
The
variable,computeandgroupcommands are read fromlammps.inand the files it reads, aslammps_named_commands()reads them, and fromorder.inwhenlammps.indoes not read it.- Parameters:
template (string) – The path of
lammps.in.order_file (string) – The path of
order.in.run_dir (string) – The directory that LAMMPS runs in.
staged (dict of strings, optional) – The files that the engine stages in
run_dirbefore the run, as the name of the copy -> the path of the file.
- Returns:
out (dict) –
variable: the name of a variable -> the words after the name of each command that defines it (the style first);compute: the ID of a compute -> the words after the ID of each command that defines it (the group, then the style);dynamic: the IDs of the dynamic groups.
- pyretis.engines.lammps_steps.lammps_order_positions(pos, bounds, dimension, images=None)¶
Return the positions of a LAMMPS frame for its order parameter.
The order parameter of a frame, of both LAMMPS engines and of a frame read back from a dump, is evaluated on the configuration of LAMMPS translated by the lower bounds of its box: the unwrapped positions of the atoms from the lower bounds, in a box of the box lengths
xhi - xlo,yhi - yloandzhi - zlowhose lower bounds are 0. Along x the position isx + ix * (xhi - xlo) - xlo, thexuof LAMMPS minusxlo, and so on along y and z, for the axes of the system; a position along an axis that the system does not have (dimensionbelow 3) is kept. A frame of a triclinic box is evaluated when its tilt factors are 0, in the orthogonal box of its bounds, and refused otherwise (refuse_tilted_lammps_box()).- Parameters:
pos (numpy.ndarray) – The positions of the atoms, one row per atom: the unwrapped positions, or, with
images, the positions of the frame.bounds (array_like) – The box bounds of the frame, a row
lo hifor each of x, y and z, with the tilt factors in a third column for a dump of a triclinic box.dimension (integer) – The number of axes of the system.
images (numpy.ndarray, optional) – The image flags of the atoms, in the shape of
pos. Without them the positions are taken as unwrapped.
- Returns:
out (numpy.ndarray) – The positions from the lower bounds, in the shape of
pos.- Raises:
NotImplementedError – If the frame has a triclinic box with a tilt factor other than 0 (
refuse_tilted_lammps_box()).
- pyretis.engines.lammps_steps.lammps_pair_seeds(words)¶
Return the seeds of a LAMMPS pair_style command.
Each word of the command that is a pair style of
LAMMPS_PAIR_SEED_ARGUMENTS, without its accelerator suffix (lammps_base_fix_style()), is a style of the command, the first word or a sub-style of ahybridstyle, and its seed is the word at the position that the table gives after it. A LAMMPS variable in a word is read as one word.- Parameters:
words (list of strings) – The words of the command after
pair_style.- Returns:
out (list) – The word of each seed, or None for a seed that the command does not give, a position after its last word. Empty for a command without a style of the table.
- pyretis.engines.lammps_steps.lammps_path_argument(path)¶
Return a file path as one argument of a LAMMPS command.
LAMMPS splits a line of its input into arguments at white space, reads the text from a
#on as a comment and the text from a$as a variable, except between quotes: a text in double or in single quotes is one argument, read without its quotes. A path with none of these characters is returned as it is. Any other path is put in double quotes, or in single quotes if it holds a double quote.- Parameters:
path (string) – The path of a file that a
dump,read_dumporwrite_datacommand reads or writes.- Returns:
out (string) – The path, as LAMMPS reads it as one argument.
- Raises:
ValueError – If the path holds a line break, which ends the line of the command; three double quotes in a row, which LAMMPS reads as the start of a text over several lines, also between single quotes; a
*, which LAMMPS replaces by a time step in the file name of these commands, or a%, which it replaces by the rank of a processor in the file name of adump, whereread_dumpthen expects one file per processor; or both a double and a single quote.
- pyretis.engines.lammps_steps.lammps_path_sampling_problem(template, run_dir, staged=None)¶
Return why a path-sampling run cannot use the fixes of a LAMMPS input.
The
fixandvariablecommands are read fromlammps.inand the files it reads, aslammps_named_commands()reads them: every fix command that LAMMPS may run counts, also one that anunfixcommand deletes or a later fix of its ID replaces. A fix of a style ofLAMMPS_BROWNIAN_FIXESintegrates Brownian dynamics, without inertia. A fix of a style ofLAMMPS_GJF_FIXESstores the velocities half a time step away from the positions with the valuevhalfof its keyword (_lammps_gjf_problem()). LAMMPS substitutes the variables of a command before it reads its words, so the fix ID and the group of every fix, and every word of a fix ofLAMMPS_GJF_FIXES, must read only variables that give one word (lammps_one_word_variables()). When every fix passes these checks, a thermostat or barostat fix that carries variables of its own from one time step to the next, or that changes the velocities deterministically without time reversibility, is refused (_lammps_thermostat_problem()), and so is a fix deform/pressure that controls the pressure (_lammps_deform_pressure_problem()): the reason of an integrator comes first. The other fixes, asfix nveand the thermostat fixesfix langevinwithoutgjf vhalf,fix temp/csvrandfix temp/csld, withrun_style verletorrespa, store the velocities at the time of the positions;lammps_path_sampling_warnings()names those of them that path sampling runs with a warning. The refusal of a fix of Brownian dynamics, of a GJF Langevin fix withvhalf, of a thermostat or barostat fix and of a fix deform/pressure ends with what the md tasks do withlammps.in, as its temperature reader decides (_lammps_md_tasks()).- Parameters:
template (string) – The path of
lammps.in.run_dir (string) – The directory that LAMMPS runs in.
staged (dict of strings, optional) – The files that the engine stages in
run_dirbefore the run, aslammps_named_commands()takes them.
- Returns:
out (string or None) – The reason, for the first fix command that a path-sampling run cannot use or cannot read, by the checks of the integrator first; None when there is none.
- Raises:
NotImplementedError – As
lammps_named_commands()raises it.Exception – As
read_lammps_temperatures()raises it for a refused fix, other than itsValueError(md_tasks_sentence()).
- pyretis.engines.lammps_steps.lammps_path_sampling_warnings(template, run_dir, staged=None)¶
Return why path sampling with a LAMMPS input is not exact.
The
fixandvariablecommands are read fromlammps.inand the files it reads, aslammps_named_commands()reads them. Every piece of trajectory that a path-sampling run generates is a LAMMPS run of its own from a stored frame. A warning names a fix that carries a memory from one time step to the next which restarts with each piece (LAMMPS_MEMORY_FIXES,fix langevinwithgjf vfull), and a fix that changes the dynamics of a piece by the direction of time or by its first time step (LAMMPS_START_CHANGING_FIXES, andLAMMPS_MOMENTUM_FIXESthat act every N > 1 time steps). The other fixes with such a memory or such a change, the pair styles with one and a thermostat whose target temperature changes during a run set the temperature in a way the temperature reader refuses in every task (read_lammps_temperatures()).- Parameters:
template (string) – The path of
lammps.in.run_dir (string) – The directory that LAMMPS runs in.
staged (dict of strings, optional) – The files that the engine stages in
run_dirbefore the run, aslammps_named_commands()takes them.
- Returns:
out (list of strings) – The warnings, each once, in the order of the commands.
- Raises:
NotImplementedError – As
lammps_named_commands()raises it.
- pyretis.engines.lammps_steps.lammps_scaled_positions(columns, values, bounds, source=None)¶
Return the positions that the scaled columns of a dump row give.
A LAMMPS dump gives the position of an atom along x as
x(wrapped into the box),xu(unwrapped),xs(wrapped and scaled) orxsu(unwrapped and scaled), and so on along y and z. A scaled position is in units of the edge vectors of the box (lammps_box_vectors()): the atom of the scaled position(xs, ys, zs)is atorigin + xs * a + ys * b + zs * c, as the LAMMPSdumpcommand defines it, and the atom of(xsu, ysu, zsu)is at the unwrapped position of that sum. In an orthogonal box, and in a triclinic box whose tilt factors are 0, this isx = xlo + xs * (xhi - xlo)along x, and so on, for each scaled column of the row. In a box with a tilt factor other than 0 each position mixes the scaled positions of the axes, and the row gives its positions when it has the three scaled columns of the set.- Parameters:
columns (dict) – The index of each column of the row, by its name in the
ITEM: ATOMSheader of the dump.values (sequence) – The values of the row, numbers or the words of the dump.
bounds (array_like) – The box bounds of the frame, a row for each of x, y and z, with the tilt factors in a third column for a dump of a triclinic box.
source (string, optional) – The dump of the row, as the message of a refusal names it.
- Returns:
out (dict) – The position of each axis that a scaled column gives, by the name of its column (
x,y,z,xu,yuorzu), for a name thatcolumnsdoes not have; empty when the row has no scaled column.- Raises:
ValueError – If the box has a tilt factor other than 0 and the row has some, but not all three, scaled columns of a set.
- pyretis.engines.lammps_steps.lammps_word_variables(word)¶
Return the names of the LAMMPS variables that a word reads.
A word reads a variable as
$x(a name of one character),${name}, orv_namein an immediate variable$(...).- Parameters:
word (string) – A word of a LAMMPS command, as
_lammps_command_words()returns it.- Returns:
out (list of strings) – The names of the variables, in the order the word reads them.
- pyretis.engines.lammps_steps.read_lammps_data_file(data_file, atom_style=None, input_style=None, read_box=True)¶
Read the box, the atoms and their masses from a LAMMPS data file.
This is the one reader of the
Atomsrows of a data file, for the masses of the streaming engine at set-up, for the velocity draw of a configuration held in a data file, of both LAMMPS engines, and for the order parameter of such a configuration, of the streaming engine (pyretis.engines.lammps.LAMMPSEngine.calculate_order()), whose velocitiesread_lammps_data_velocities()reads. The file is read in the layout that LAMMPSread_datareads:The first line is the title.
The header is the lines below the title up to the first line that does not start with a number, blank lines and comments aside. Each line is read by the keywords at fixed positions of the line, and the words after them are ignored, in any order of the lines (
_read_lammps_data_header()): the number of atoms (N atoms), the number of atom types (N atom types) and the box bounds, a linelo hi xlo xhifor x,lo hi ylo yhifor y andlo hi zlo zhifor z. An axis whose line the header leaves out has the bounds-0.5 0.5, the default of LAMMPSread_data(LAMMPS_DATA_DEFAULT_BOUNDS), as the z axis of a 2D system often has. The other lines of the header, asN bonds, are not read.A section is a keyword line and its rows. The rows of the
MassesandAtomssections are the lines from the second line below the keyword line, whatever the line below the keyword line holds, one for each atom type, the atom type and its mass, and one for each atom of the header (_lammps_data_section_rows()). The first line below the header, and the first line below the rows of a section, that is neither blank nor a comment, is the keyword line of the next section, with no blank line needed above it. A keyword line that is the last line of the file is not read: LAMMPS reads a keyword line together with the line below it, and ends the read there. The keyword line of another section, asVelocities, the line below it and the lines below them are skipped up to the nextMassesorAtomskeyword line (_read_lammps_data_sections()).In the header and in a keyword line, the text from a
#is a comment; in a row, the words from its first word that starts with#(_lammps_data_words()). The comment of theAtomskeyword line is the# styleannotation of the atom style.
The
Atomsrows are read in the atom style thatresolve_lammps_atom_style()gives for theAtomskeyword line,atom_styleandinput_style, in the columns of its row layout (lammps_atom_columns()). Each row has a column count of the style (check_lammps_atom_row()), the column count of the first row, as LAMMPSread_datarequires, a positive integer atom ID, an integer atom type, numbers for the positions and, when it ends with them, integer image flags. Each atom has the mass that theMassessection gives its atom type (lammps_atom_masses()).- Parameters:
data_file (string) – The LAMMPS data file.
atom_style (string, optional) – The
[engine] atom_style.input_style (string, optional) – The style of the
atom_stylecommand oflammps.in(lammps_input_atom_style()).read_box (boolean, optional) – True (the default) to read the box of the header. False to read the atoms and masses only, as the set-up of the streaming engine does: the lines of the box are then read for their form only, and a data file of a triclinic box is read as any other.
- Returns:
ids (list of int) – The atom IDs, in ascending order. The other outputs give the atoms in this order, the order in which
read_lammps_dump()andpyretis.engines.lammps.read_lammpstrj()give the atoms of a dump frame.positions (numpy.ndarray) – The positions of the atoms, shape
(N, 3).images (numpy.ndarray) – The image flags of the atoms, zero for a row without them, shape
(N, 3).masses (numpy.ndarray) – The masses of the atoms, shape
(N, 1).box (list of tuple or None) – The
(lo, hi)box bounds of x, y and z, in this order; None whenread_boxis False.
- Raises:
NotImplementedError – If
read_boxis True and the header gives a triclinic box, with anxy xz yzline or anavec,bvec,cvecorabc originline of a general triclinic box: the box is read from theloandhibounds only, as an orthogonal box. Also if the atom style of theAtomsrows is not supported (lammps_atom_columns()).ValueError – If the header of the
Atomssection has an empty#annotation, or the sources of the atom style disagree, or the style oflammps.inis a LAMMPS variable and no other source gives one (resolve_lammps_atom_style()). With a message that names the file, and the line or the row for a line or a row, for each of these, which LAMMPSread_datastops at unless said otherwise: * a header line that has a keyword of the lines of the header in another form, and is no other header line of LAMMPS (_read_lammps_data_header()), as0 40 zlo zhj, a number of atoms or atom types that is not written in digits, a bound, or a number of a line of a triclinic box, that is not a number, or a hi bound that is not above its lo bound; ifread_boxis True, two lines of the header for the bounds of one axis, of which LAMMPS takes the last; * aMassesorAtomssection without a number of atom types or atoms in the header, or with a blank line or a comment among its rows, or with fewer rows than the header gives before the end of the file (_lammps_data_section_rows()); * a line below the rows of a section, the first that is neither blank nor a comment, that starts with a number, as a row beyond the number of the header does; LAMMPS stops at it with “Unknown identifier in data file”, and leaves it out when it is the last line of the file. Also that line, or the line below the header, when it has a keyword of the lines of the header (_check_lammps_data_keyword_line()); * a file with noAtomssection with rows, or with two; * anAtomsrow that fits no row layout of the style (check_lammps_atom_row()), has another number of columns than the first row, has an atom ID, atom type or image flag that is not an integer, an atom ID that is not positive or a position that is not a number, or repeats the atom ID of an earlier row; * aMassesrow that is not an integer atom type and a number, or has an atom type outside 1 to the number of atom types of the header, or a mass that is not positive; aMassessection that gives an atom type twice, or not the atom type of an atom (lammps_atom_masses()).
- pyretis.engines.lammps_steps.read_lammps_data_velocities(data_file, atom_style=None, input_style=None)¶
Read the velocities of the atoms from a LAMMPS data file.
The file is read as
read_lammps_data_file()reads it, without its box, and itsVelocitiessection too: the section of the keyword lineVelocities, below theAtomssection, with one rowatom-ID vx vy vzfor each atom of the header, as LAMMPSread_datareads it (_read_lammps_data_sections()). The velocities are in the velocity units of theunitsof LAMMPS, as the velocities of a dump frame are.- Parameters:
data_file (string) – The LAMMPS data file.
atom_style (string, optional) – The
[engine] atom_style.input_style (string, optional) – The style of the
atom_stylecommand oflammps.in(lammps_input_atom_style()).
- Returns:
out (numpy.ndarray or None) – The velocities of the atoms, shape
(N, 3), in the order of the atom IDs ofread_lammps_data_file(); None for a file without aVelocitiessection.- Raises:
ValueError, NotImplementedError – As
read_lammps_data_file()raises them without the box. AValueErroralso for aVelocitiessection above theAtomssection, which LAMMPSread_datastops at, for a secondVelocitiessection, for aVelocitiessection with fewer rows than the atoms of the header before the end of the file, or with a blank line or a comment among its rows (_lammps_data_section_rows()), and for a row of another number of columns than 4, an atom ID that is not an integer, of no atom or of an earlier row, or a velocity that is not a number (_read_lammps_data_velocity_rows()).
- pyretis.engines.lammps_steps.read_lammps_dump(filename, dimension)¶
Read custom LAMMPS dump frames written by the PyRETIS engine.
The parser expects the custom dump produced by
TRAJ_DUMP, i.e. one atom table per frame with anidcolumn, position columns, velocity columns, and optional image flags. Atoms are returned sorted by LAMMPS id.- Parameters:
filename (string) – Path to a LAMMPS dump trajectory.
dimension (integer) – Number of spatial dimensions to extract.
- Returns:
frames (list of dict) – Each frame contains its timestep, box, atom IDs, wrapped/unwrapped positions, image flags and velocities.
- pyretis.engines.lammps_steps.read_lammps_dump_steps(filename, nframes=None)¶
Return the time steps of the frames of a LAMMPS dump.
The time step of a frame is the number on the line after its
ITEM: TIMESTEPline.- Parameters:
filename (string) – Path to a LAMMPS dump trajectory.
nframes (integer, optional) – The number of frames to read from the start of the dump; all frames when None.
- Returns:
out (list of integers) – The time step of each frame read, in the order of the frames.
- pyretis.engines.lammps_steps.read_lammps_input(filename)¶
Read a LAMMPS input file.
This will read in a LAMMPS input file and can be used to read the value of particular settings, for instance the time step. The commands are read as LAMMPS reads them (
pyretis.inout.engine_temperature.lammps_script_commands()): the lines that&or an odd number of triple quotes join are one command, and the comment of a command starts at the first#outside quotes. A line inside a command, such as a line of a triple-quotedprinttext, is not a command of its own.- Parameters:
filename (string) – The path to the LAMMPS input file.
- Returns:
out (list of tuples) – The settings found in the LAMMPS input file. The tuples are on the form (keyword, setting), the first word of a command and its other words joined by single spaces.
- Raises:
ValueError – If a line of the file holds bytes that are not UTF-8, or a command, without its comment, a character that is not ASCII (
pyretis.inout.engine_temperature.lammps_script_commands()).
- pyretis.engines.lammps_steps.read_lammps_log(filename)¶
Read some info from a LAMMPS log file.
In particular, this method is used to read the thermodynamic output from a simulation (e.g. potential and kinetic energies).
- Parameters:
filename (string) – The path to the LAMMPS log file.
- Returns:
out (dict) – A dict containing the data we found in the file.
- pyretis.engines.lammps_steps.read_lammps_rescale_skip(filename)¶
Read which velocity re-scale LAMMPS skipped from its log file.
LAMMPS echoes each command of its input to the log, so the line of
RESCALE_CONDITIONholds the two skip lines inside quotes; the output of itsprintcommand is the whole line.- Parameters:
filename (string) – The path to the LAMMPS log file of a velocity generation.
- Returns:
out (string or None) –
RESCALE_SKIPPED_PEorRESCALE_SKIPPED_KEwhen a line of the log is that line, and None when no line is either.
- pyretis.engines.lammps_steps.refuse_lammps_constraint_fixes(fixes, engine)¶
Refuse the constraint fixes that a
velocity createdraw cannot use.The draw creates the velocities with
velocity createand, for the fixes of the styles ofLAMMPS_PROJECTING_FIXES, re-scales them toSET_TEMPafter the setup of a run has constrained them (_add_generate_vel()). It refuses a fix of a style ofLAMMPS_REFUSED_CONSTRAINT_FIXES, and a fix rigid style whose bodies keep their velocities over the setup of a run (_lammps_rigid_body_keyword()).- Parameters:
fixes (list of tuples) – The constraint fixes of the input, from
lammps_constraint_fixes().engine (string) – The engine that draws, as the message names it at its start.
- Raises:
NotImplementedError – For the first fix of
fixesthat the draw refuses.
- pyretis.engines.lammps_steps.refuse_lammps_draw_units(template, engine)¶
Refuse a velocity draw in LAMMPS units other than
real.PyRETIS draws LAMMPS velocities with the constants of LAMMPS
realunits: k_B in kcal/(mol K), and velocities in Å/fs. The units are those LAMMPS runslammps.inwith (read_lammps_units()): the lastunitscommand after the lastclearcommand, oflammps.inor of a file it includes; LAMMPS runs a script without one inljunits.- Parameters:
template (string) – The path of
lammps.in.engine (string) – The engine that draws, as the message names it at its start.
- Raises:
NotImplementedError – If LAMMPS runs
lammps.inin units other thanreal.
- pyretis.engines.lammps_steps.refuse_lammps_fixed_seeds(template, run_dir, staged=None)¶
Refuse a LAMMPS input that seeds its random numbers the same each run.
The engines run
lammps.infor every LAMMPS run, and a fix or a pair style that draws random numbers (LAMMPS_FIX_SEED_ARGUMENTS,LAMMPS_FIX_SEED_KEYWORDS,LAMMPS_FIX_DEFAULT_SEED_KEYWORDS,LAMMPS_PAIR_SEED_ARGUMENTS) draws the same numbers in every run when its seed is the same. Each seed of thefixandpair_stylecommands oflammps.inand of the files it reads (lammps_named_commands()) must be the seed of the run (is_pyretis_seed_word()).- Parameters:
template (string) – The path of
lammps.in.run_dir (string) – The directory that LAMMPS runs in.
staged (dict of strings, optional) – The files that the engine stages in
run_dirbefore the run, aslammps_named_commands()takes them.
- Returns:
out (list of strings) – The commands of the fixes and pair styles that draw random numbers, each as
<file>: <command>; empty when there is none.- Raises:
ValueError – For the first seed that is not the seed of the run: a number, a LAMMPS variable other than
pyretis_seed, or a seed that the command does not give.NotImplementedError – As
lammps_named_commands()raises it.
- pyretis.engines.lammps_steps.refuse_lammps_mass_command(template, engine)¶
Refuse a
masscommand oflammps.in.A
masscommand, which LAMMPS runs afterread_data, sets the mass of atom types in LAMMPS in place of theMassesrows of the data file. PyRETIS takes the masses from theMassessection (read_lammps_data_file()) and does not readmasscommands. The commands are those oflammps.initself; PyRETIS does not read a file thatlammps.inincludes.- Parameters:
template (string) – The path of
lammps.in.engine (string) – The engine that takes the masses from the data file, as the message names it at its start.
- Raises:
NotImplementedError – If
templatehas amasscommand; the message names each.
- pyretis.engines.lammps_steps.refuse_lammps_restart_configuration(config, what, run_dir=None, named=None)¶
Refuse a configuration held in a LAMMPS restart file.
PyRETIS cannot start a LAMMPS run from a restart file. The input of the run would read it with
read_restartafterlammps.in, and LAMMPS defines no fix before the simulation box, which the restart file defines; so no fix would integrate the motion of the atoms, and the frames of the run would all hold the configuration of the file.- Parameters:
config (tuple) – The file and the index of the configuration.
what (string) – What starts from the configuration, as the message names it at its start.
run_dir (string, optional) – The directory that LAMMPS runs in, where a relative file name is also looked for (
_lammps_restart_configuration_reason()).named (string, optional) – The file as the message names it, in place of the file of
config: the file of a load folder whose staged copy the load reads.
- Raises:
ValueError – If the configuration is held in a restart file.
- pyretis.engines.lammps_steps.refuse_lammps_restart_files(restarts, run_dir, staged=None)¶
Refuse a restart file of
lammps.inthat contradicts the script.LAMMPS opens the file that a
read_restartcommand oflammps.in(or of a file it includes) names in the directory it runs in, where the engine stages its input files (_locate_lammps_file()). The reader oflammps.inchecks the restart file in the input directory (read_lammps_restarts()); this check, made before each LAMMPS run, checks the file that LAMMPS opens: its unit system, and its time step (refuse_lammps_restart_file()).- Parameters:
restarts (object like
LammpsRestarts) – Theunitscommand, the restart files and the time step oflammps.in.run_dir (string) – The directory that LAMMPS runs in.
staged (dict of strings, optional) – The files that the engine stages in
run_dirbefore the run, as the name of the copy -> the path of the file.
- Raises:
ValueError – If a restart file is not where LAMMPS opens it, or
read_lammps_restart_header()orrefuse_lammps_restart_file()refuses it.
- pyretis.engines.lammps_steps.refuse_lammps_restart_phasepoints(phasepoints, what)¶
Refuse phase points whose configuration is a LAMMPS restart file.
- Parameters:
phasepoints (iterable of objects like
System) – The phase points, each with itsconfig.what (string) – What holds the phase points, as the message names it at its start.
- Raises:
ValueError – As
refuse_lammps_restart_configuration()raises it for the first phase point held in a restart file.
- pyretis.engines.lammps_steps.refuse_tilted_lammps_box(bounds, source=None)¶
Refuse the order parameter of a frame of a tilted LAMMPS box.
PyRETIS evaluates the order parameter of a frame of a LAMMPS dump in an orthogonal box, of the box lengths
hi - loof the frame (lammps_order_positions()). The box of a dump with tilt factors (lammps_box_vectors()) is that orthogonal box when its tilt factors are all 0, and a frame of a box with a tilt factor other than 0 is refused.- Parameters:
bounds (array_like) – The box bounds of the frame, a row for each of x, y and z, with the tilt factors
xy,xzandyzin a third column.source (string, optional) – The dump of the frame, as the message names it.
- Raises:
NotImplementedError – If a tilt factor of the frame is not 0.
- pyretis.engines.lammps_steps.refuse_unstaged_lammps_files(script_files, script_dir, run_dir)¶
Refuse an include or a jump file that LAMMPS reads elsewhere.
PyRETIS reads the file of each
includecommand, and of eachjumpcommand to another file, oflammps.inin the directory oflammps.in(pyretis.inout.engine_temperature.lammps_script_files()), for the temperature and the time step of the script. LAMMPS opens the file in the directory it runs in, where the engines stage the input files by their names (LAMMPSEngineSteps.add_input_files()): the configuration,order.inand the files ofextra_files. Each such file must be there and hold the text PyRETIS reads.- Parameters:
script_files (list of tuples) – The files of the
includeandjumpcommands, aspyretis.inout.engine_temperature.lammps_script_files()gives them.script_dir (string) – The directory of
lammps.in, where PyRETIS reads them.run_dir (string) – The directory that LAMMPS runs in, with the staged files.
- Raises:
ValueError – If LAMMPS would not find such a file in
run_dir, or would find a file there whose text is not the one PyRETIS reads.
- pyretis.engines.lammps_steps.refuse_velocity_dependent_lammps_orders(template, order_file, run_dir, staged=None)¶
Refuse an
order.incolumn that is not a function of positions.With
order_mode = "lammps"LAMMPS evaluates the variables oforder.in(lammps_order_columns()) on the velocities of the LAMMPS run. The frames of a backward leg hold the velocities of the run, which are those of the path reversed (vel_rev), and PyRETIS evaluates the order parameter of such a frame on the velocities of the path. A variable is a column of the order parameter of every frame, of both legs, when it reads the positions of the atoms and the box only (_lammps_variable_dependence()).- Parameters:
template (string) – The path of
lammps.in.order_file (string) – The path of
order.in.run_dir (string) – The directory that LAMMPS runs in.
staged (dict of strings, optional) – The files that the engine stages in
run_dirbefore the run, as the name of the copy -> the path of the file.
- Raises:
ValueError – If a variable of
order.inreads the velocities, or a word that PyRETIS cannot tell to be independent of them.
- pyretis.engines.lammps_steps.rename_lammps_energy_keys(energy)¶
Rename LAMMPS thermo column labels to PyRETIS conventions.
- pyretis.engines.lammps_steps.resolve_lammps_atom_style(header, configured=None, input_style=None)¶
Resolve and validate the atom style used by a data
Atomsblock.LAMMPS reads the rows of a data file with the
atom_styleof its input, and withatomicwhen the input sets none. The style is the first given of the engine settingconfigured, the# styleannotation of theAtomsheader and theatom_stylecommand oflammps.in(input_style), andatomicwhen none of the three is given. Any two of the three that are given must name styles of the same row layout (LAMMPS_ATOM_STYLE_LAYOUT):bond,angleandmolecularshare one. The layout of a style is that of its base style, the style without an accelerator suffix (lammps_base_atom_style()), sofull/kkagrees withfull, and a style without a row layout agrees with the styles of its base style only, asspherewithsphere/kk.A style of
lammps.inthat holds a$is set by a LAMMPS variable, which PyRETIS does not evaluate, and it is not a source: the rows are read in the style of the setting or of the annotation, and without either of them the style is refused.- Parameters:
header (string) – The
Atomsheader line of the data file.configured (string, optional) – The
[engine] atom_style.input_style (string, optional) – The style of the
atom_stylecommand oflammps.in(lammps_input_atom_style()).
- Returns:
out (string) – The atom style of the rows, in lower case, as its source gives it, with its accelerator suffix.
- Raises:
ValueError – If the header has an empty
#annotation; if two of the given sources name styles of different row layouts, and the message names both as their sources give them; or if the style oflammps.inholds a$and neitherconfigurednor an annotation is given.
- pyretis.engines.lammps_steps.system_to_lammps(system, reverse_velocities, dimension)¶
Convert a LAMMPS system into LAMMPS commands for loading it.
This method will convert a system created by LAMMPS into LAMMPS commands, so that LAMMPS can read the given snapshot and use it.
- Parameters:
system (object like
System) – The system we are converting.reverse_velocities (boolean) – True if the velocities in the system are to be reversed.
dimension (integer) – The number of dimensions used in the LAMMPS simulation.
- Returns:
out (list of strings) – The commands needed by LAMMPS to read the configuration.
- Raises:
ValueError – If the configuration is held in a LAMMPS restart file (
refuse_lammps_restart_configuration()): no input reads one.
- pyretis.engines.lammps_steps.write_lammps_dump_frame(infile, step, outfile, dimension)¶
Write one referenced dump step in PyRETIS’s canonical dump format.
Wrapped and unwrapped input coordinates are reconciled by
_iter_lammps_dump_lines(); when image flags are absent they are derived fromxu/yu/zu. The frames are parsed one at a time up to the selected step, which alone is kept, so a large file-backed initial path is not duplicated or retained in memory.
pyretis.engines.openmm module¶
Definition of the OpenMM engine.
This module defines the class for the OpenMM MD engine.
Important classes defined here¶
- OpenMMEngine (
OpenMMEngine) The class for running the OpenMM engine.
- class pyretis.engines.openmm.OpenMMEngine(openmm_simulation, subcycles=1, openmm_module=None, timestep=None)¶
Bases:
EngineBaseA class for interfacing with OpenMM.
This class defines the interface to OpenMM.
- Variables:
simulation (OpenMM.simulation) – OpenMM simulation object.
subcycles (int) – Number of OpenMM steps per PyRETIS step.
temperature (float or None) – The temperature (K) of the integrator and of the forces with a temperature (a thermostat or a barostat) of the simulation (
openmm_temperatures()), or None for a simulation without an integrator.beta (float or None) – The inverse temperature
1 / (k_B T)in mol/kJ, with the k_B of theopenmmunit system, or None without a temperature.engine_temperatures (object like
EngineTemperatures) – The temperatures read from the simulation, or None for a simulation without an integrator.simulation_source (string) – The module the simulation comes from, or
'the OpenMM simulation'for a simulation given as an object; it names the simulation in the messages about its temperature.
Notes
Each leg of MD, a call of
propagate()or a crossing search ofkick_across_middle(), starts in_start_leg(): the random numbers of the integration are drawn from seeds ofrgen, the random generator of the move, the context parameters and the integrator parameters are those the context held when the engine was built, and the context starts at step count 0. The paths of a move are then a function of its start frame, of its random stream, of the platform and of its settings, whichever worker runs the move and whichever legs that worker ran before.- __init__(openmm_simulation, subcycles=1, openmm_module=None, timestep=None)¶
Set up the OpenMM Engine.
- Parameters:
openmm_simulation (OpenMM.simulation, or string) – The OpenMM simulation object or the variable name if module is not None.
subcycles (int) – Number of OpenMM integration steps per PyRETIS step.
openmm_module (string, optional) – If defined and simulation is a string, try loading simulation from module.
timestep (float, optional) – The OpenMM time step is the step size of the integrator (
simulation_step_size()); this optional value of the engine section, in ps, is a cross-check and must equal it. A run records the step size there.
- Raises:
RuntimeError – If OpenMM is not installed, or
openmm_simulationis a string that is not loaded from a module.ValueError – If the simulation steps with a variable step (
refuse_variable_step_integrator()); if the integrators itsCompoundIntegratorholds have different step sizes (simulation_step_size()); iftimestepdiffers from the step size of the integrator; if the simulation steps with aCustomIntegratorthat holds a variable namedkTfrom which PyRETIS reads no temperature (another letter case, or per degree of freedom), or aCustomIntegratorthat draws random numbers and has no global variablekT, alone or in aCompoundIntegrator(openmm_temperatures()); if agetTemperature()returns no temperature Quantity; if the simulation states no temperature: neither its integrator, nor an integrator itsCompoundIntegratorholds, nor a force of its System (a thermostat or a barostat) carries one (openmm_temperatures()); if a temperature it states is not positive; or if it states different temperatures (EngineTemperatures.agreed()).
- _constrain_velocities(system)¶
Remove the velocity components along the constraints.
The integrator removes these components when it propagates, so the kinetic energy that a re-scale sets is the kinetic energy of the run only for constrained velocities. The projection keeps the linear momentum, and scaling constrained velocities by one factor keeps them constrained. A System without constraints, or a simulation that holds no OpenMM System, is left as it is.
- Parameters:
system (object like
System) – The state whose velocities are constrained, in place, with the constraint tolerance of the integrator.
- _draw_leg_seeds()¶
Draw the random number seeds of a leg of MD from
rgen.The parts of the simulation that draw random numbers (
random_number_owners()) take seeds drawn fromrgen, inSEED_RANGE: one seed for the integrators and theAndersenThermostatforces, drawn first, and then one seed for each other force with a seed, in the order of the forces of the System. Nothing is drawn for a simulation without such parts, or for an engine withoutrgen.- Returns:
out (list of tuple) – One
(part, seed)pair for each part that draws random numbers; empty when nothing is drawn.
- static _input_simulation(engine_settings)¶
Import the simulation an engine section names.
The simulation is imported as the engine imports it when it is created:
openmm_simulationfrom the moduleopenmm_module.- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out[0] (object like
openmm.app.Simulation) – The simulation.out[1] (string) – The module.
- Raises:
ValueError – If the section names no
openmm_module.
- _leg_file()¶
Return the name of a new trajectory file for the frames of a leg.
The file is
<exe_dir>/<n>_openmm.xyzin the main process of a run and<exe_dir>/w<k>_<n>_openmm.xyzin the scheduler worker of indexk(worker_index()), withnfromcounter(), which gives a new number at each call of a process: no two legs of a run, in one process or in two, name the same file.- Returns:
out (string) – The name of the file.
- _materialize_if_filebacked(system)¶
Populate
pos/velfromsystem.configwhen needed.A coordinator
load_dirphasepoint arrives file-backed: its positions live in an XYZ frame referenced bysystem.configand the in-memorysystem.posisNone. OpenMM integrates in memory (integration_steppushessystem.posinto the OpenMM context), so read the referenced frame into the system before propagating – mirroring the streaming internal engine’spyretis.engines.internal.MDEngine._materialize_system(). A system that already carries positions (system.posset) is left untouched.The system gets the box a read-back by format gives the frame (
xyz_frame_box()): the box of its box line, or, for a frame whose box line is absent or all zero, the cell offrame_cell(). The order parameter is evaluated, and the OpenMM context propagates the frame, in that box. A box line with a length ofinfor 0 gives an unbounded dimension, which stops the run where the box would reach the OpenMM context (periodic_box_vectors()).- Parameters:
system (object like
System) – The phase point to materialise in place.
- _set_context_state(system)¶
Synchronize the OpenMM context with a PyRETIS system.
The positions, the velocities and, when the system has a box, its box vectors (
periodic_box_vectors()) are set in the context.- Parameters:
system (object like
System) – The state to set, in nm and nm/ps.- Returns:
out (object like
openmm.Context) – The context of the simulation.- Raises:
ValueError – If the box of the system is not a periodic cell with finite components and positive lengths; the context is then left as it was.
- _set_frame_state(system, snapshot)¶
Set the state of a stored frame on a phase point.
The phase point gets the positions and the velocities of the frame, the velocities negated when its
vel_revis True, the masses and the temperature of the OpenMM simulation (_template_system()), and the box a read-back by format gives the frame (xyz_frame_box()): the box of its box line, or, for a box line that is absent or all zero, the cell offrame_cell().- Parameters:
system (object like
System) – The phase point to set, in place.snapshot (dict) – The frame, as
read_xyz_file()reads it.
- _start_leg()¶
Start a leg of MD from a defined state of the context.
The seeds come from
rgen(_draw_leg_seeds()), the random generator of the move, which the scheduler sets for each move (run_md()), and the kick initiation, sequential or parallel, for each ensemble (initiate_path_ensemble_kick()). OpenMM reads the seeds of an integrator and of a force when it builds a context, so with seeds drawn the context is rebuilt (Context.reinitialize(preserveState=False)), and the random number generators start from the new seeds. Withoutrgenno seed is drawn, and the integrator goes on with its random numbers from where they are.The context is then given the state it held when the engine was built (
Context.setState): its context parameters and its integrator parameters, which hold the state of aNoseHooverIntegratorthermostat chain and the global and per-degree-of-freedom variables of aCustomIntegrator; the MD of the leg sets the positions, the velocities and the box of the phase point it starts from. A leg is then the same leg whichever legs the engine ran before, as for an engine built anew in another worker or in a restarted run.The step count and the time of the context are set to 0, so a force that acts at the steps whose count is a multiple of its frequency, a
CMMotionRemover, acts at the same steps of every leg.
- _template_system()¶
Return the engine’s reference pyretis
System(cached).Built from the OpenMM
Simulation(particles, masses, box and the thermodynamictemperature/betaat the temperature the engine runs at,temperature,_system_from_simulation()), it supplies the engine-level state absent from a file-backed XYZ frame. Cached, as it is constant for the simulation’s lifetime.
- _write_frame(filename, system, *, step=None, append=False, reverse=False)¶
Write the state of a system as a frame of an
.xyzfile.The frame holds the positions (nm), the velocities (nm/ps) and, on its box line, the box parameters of
system.box(nm,FRAME_BOX_FMT), the format_materialize_if_filebacked()reads back. The file is recorded forclean_up().- Parameters:
filename (string) – The file to write to.
system (object like
System) – The state to write.step (integer, optional) – The frame number written to the header.
append (boolean, optional) – If True, the frame is added to the end of the file; if False, the file is written anew with this frame.
reverse (boolean, optional) – If True, the velocities are written negated: the frame then holds them in the direction of the MD of a backward propagation, and the phase point that names it carries
vel_rev = True, which negates them when it is read back.
- calculate_order(system, xyz=None, vel=None, box=None)¶
Return the order parameter.
This method is just to help to calculate the order parameter in cases where only the engine can do it.
- Parameters:
system (object like
System) – This is the system that contains the particles we are investigating.xyz (numpy.array, optional) – The positions to use. Typically for internal engines, this is not needed. It is included here as it can be used for testing and also to be compatible with the generic function defined by the parent.
vel (numpy.array, optional) – The velocities to use.
box (numpy.array, optional) – The current box vectors.
- Returns:
out (list of floats) – The calculated order parameter(s).
- clean_up()¶
Remove the frame files this engine wrote in
exe_dir.The engine writes the frames of the phase points it stores into
exe_dir(_write_frame()). Storing an accepted path moves its frame files into the path archive (SchedulerPathStorage); the files of a trial that is not stored stay behind until this method removes them. The scheduler pointsexe_dirat the directory of the ensemble whose move the engine runs next, which no other move uses until the coordinator has stored the outcome of this one; the files the engine wrote in that directory and that are still there are removed. The files it wrote in another directory, which a move of another worker may be using, and every file the engine did not write are left in place.
- default_units = 'openmm'¶
- dump_phasepoint(phasepoint, deffnm=None)¶
Write the frame of a stored phase point to a file of its own.
A phase point with particles is held in memory only, and it is left as it is. A phase point without particles names its frame by
config, a(file, index)pair; that frame is copied, as it is stored, into<exe_dir>/<deffnm>.xyzandconfignames the copy. The velocity directionvel_revand the state the phase point holds in memory are kept.- Parameters:
phasepoint (object like
System) – The phase point to write.deffnm (string, optional) – The base name of the file;
confby default.
- Raises:
ValueError – If the file
confignames holds no frame at its index.
- engine_type = 'openmm'¶
- file_backed_path(path, filename)¶
Return a copy of a path whose phase points name stored frames.
The phase points of a path the in-process initiation generates hold their state in their particles. Each one is written, in the order of the path, as a frame of the trajectory
filename(_write_frame()): its positions, its velocities and its box, as the frames of the MD are stored (propagate()). The phase points of the copy hold no particles. Each names its frame byconfig, withvel_revFalse since the frame holds the velocities of the phase point, and keeps the order parameter, the box and the energies of the phase point, which storing the copy (SchedulerPathStorage) writes into theenergy.txtof the path.- Parameters:
path (object like
Path) – The path, with phase points that hold particles.filename (string) – The trajectory file to write, in the directory the path is stored in.
clean_up()leaves it in place.
- Returns:
out (object like
Path) – The copy, with phase points without particles.
- frame_cell()¶
Return the cell for a stored frame that records none.
A frame staged for a load may have no box line, or the box line
# Box: 0.0000 0.0000 0.0000. Such a frame is evaluated in the periodic box vectors of the OpenMM simulation, as_template_system()reads them; a phase point built from the simulation (_system_from_simulation()) carries the same box into its MD. The frames the engine stores itself carry their own box (_write_frame()), the frames of the initial paths of a kick initiation included (file_backed_path()).- Returns:
out (numpy.array) – The box parameters in nm:
xx, yy, zz, followed byxy, xz, yx, yz, zx, zyfor a triclinic box (box_matrix_to_list()).
- frame_energies(systems)¶
Return the potential and kinetic energies of stored frames.
Each phase point names its frame by
config, a(file, index)pair of an.xyztrajectory, and the frame is read as_materialize_if_filebacked()reads it (_set_frame_state()). The potential energy is the energy of the OpenMM System at the positions and in the box of the frame (potential_energy()), and the kinetic energy the energy of the velocities of the frame with the masses of the OpenMM System (calculate_kinetic_energy()), both in kJ/mol, aspropagate()records them for the frames of its MD. Each file is read once.The state of the last frame is left in the OpenMM context. The MD sets the state of its phase point in the context before each integration step (
_set_context_state()).- Parameters:
systems (iterable of objects like
System) – The phase points; each names its frame byconfigand its velocity direction byvel_rev.- Returns:
out (list of tuple of float) – One
(vpot, ekin)pair per phase point, in the order ofsystems.- Raises:
ValueError – If the file of a phase point is not an
.xyzfile or holds no frame at its index, or if the box of a frame is not a periodic cell with finite components and positive lengths (periodic_box_vectors()).
- classmethod get_default_units(settings=None)¶
Return the default unit system for the OpenMM engine.
- Parameters:
settings (dict, optional) – Full simulation settings or engine settings. This argument is ignored for the OpenMM engine.
- Returns:
out (string) – The default unit system for the OpenMM engine.
- classmethod input_path_sampling_problem(engine_settings)¶
Return why a path-sampling run cannot use a section’s simulation.
The simulation is imported as
read_input_temperatures()imports it, and its integrator and its scheme are checked aspath_sampling_problem()checks them (path_sampling_integrator_problem(), thenpath_sampling_scheme_problem()).- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (string or None) – The reason, or None when a path-sampling run can use the integrator and the scheme of the simulation. None for a section that names no
openmm_module, names a module file that is not there, or gives the simulation object itself: the run refuses the first two where it reads the temperature of the section (read_input_temperatures()) or creates the engine, andpath_sampling_problem()checks the engine built from the third.
- integration_step(system)¶
Perform one integration step of n subcycles.
- Parameters:
system (object like
System) – The system to integrate/act on. Assumed to have a particle list insystem.particles.- Returns:
out (None) – Does not return anything, but alters the state of the given system.
- kick_across_middle(system, ens_set, middle, tis_settings, rgen)¶
Force a phase point across the middle interface.
This is accomplished by repeatedly kicking the phase point so that it crosses the middle interface.
- Parameters:
system (object like
System) – This is the system that contains the particles we are investigating.ens_set (dict) – It contains the ensemble settings. This method does not use it directly, but it is part of the common interface.
middle (float) – This is the value for the middle interface.
tis_settings (dict) – This dictionary contains settings for TIS. Explicitly used here:
zero_momentum: boolean, determines if the momentum is zeroed after each kick. A missing key means False. A re-scaled kick on a System with a
CMMotionRemoverrequires True (refuse_momentum_with_remover()).rescale_energy: float or False, the total energy each kick is re-scaled to; False, or a value that is not positive, leaves the kicked velocities unscaled.
Every kick is an aimless draw (
make_kick_velocity_settings()).rgen (object like
RandomGenerator) – This is the random generator that will be used.
- Returns:
Note
This function will update the system state. The search starts with
_start_leg(): its integration steps draw their random numbers from seeds ofself.rgen, the integration random generator of the engine, and the kicks draw their velocities from the argumentrgen.
- modify_velocities(system, vel_settings, rgen)¶
Modify the velocities of the current state.
This method will modify the velocities of a time slice. And it is part of the integrator since it, conceptually, fits here: we are acting on the system and modifying it.
- Parameters:
system (object like
System) – This is the system that contains the particles we are investigating.vel_settings (dict) – It contains info about velocity settings:
sigma_v : numpy.array, optional Negative values select aimless shooting. Zero or positive values set the standard deviation, one for each particle, for soft velocity perturbations, in nm/ps. A soft perturbation is refused for an OpenMM System with constraints (
refuse_constrained_soft_perturbation()). Without a re-scale, on a System with aCMMotionRemoverits kinetic-energy change starts from the old velocities without their centre-of-mass motion, which the run does not keep.zero_momentum : boolean, optional If True, we reset the linear momentum to zero after generating. A missing key means False. A re-scale or a soft perturbation on a System with a
CMMotionRemoverrequires True (refuse_momentum_with_remover()).rescale : float, optional In some NVE simulations, we may wish to re-scale the energy to a fixed value. If rescale is a float > 0, we will re-scale the energy (after modification of the velocities) to match the given float. The velocities of a System with constraints are constrained before the re-scale (
_constrain_velocities()), so the total energy is the given float for the velocities the integrator propagates.
rgen (object like
RandomGenerator) – This is the random generator that will be used.
- Returns:
dek (float) – The change in the kinetic energy, in kJ/mol.
kin_new (float) – The new kinetic energy, in kJ/mol.
- Raises:
NotImplementedError – If sigma_v selects a soft velocity perturbation and the OpenMM System has constraints, or if the settings request a re-scale or a soft perturbation with zero_momentum False and the System holds a
CMMotionRemover.
Notes
A system without particles, a phase point of the infinite-swapping scheduler, is materialised from the frame it names (
_materialize_if_filebacked()), and the state with its new velocities is written to<exe_dir>/genvel.xyz(_write_frame()), whichconfigthen names, withvel_rev = False.
- path_sampling_problem()¶
Return why a path-sampling run cannot use this engine.
- Returns:
out (string or None) – The reason (
path_sampling_integrator_problem(), thenpath_sampling_scheme_problem()), or None when a path-sampling run can use the integrator and the forces of the simulation.
- path_sampling_warnings()¶
Return why a path-sampling run with this engine is not exact.
- Returns:
out (list of strings) – The warnings (
openmm_path_sampling_warnings()); empty when the simulation selects no such scheme.
- potential_energy(system)¶
Return the system potential energy in kJ/mol.
- Parameters:
system (object like
System) – The PyRETIS state whose coordinates and box are evaluated.- Returns:
float – The OpenMM potential energy in the engine’s native kJ/mol units.
- propagate(path, ens_set, system, reverse=False)¶
Generate a path by integrating until a criterion is met.
This function will generate a path by calling the function specifying the integration step repeatedly. The integration is carried out until the order parameter has passed the specified interfaces or if we have integrated for more than a specified maximum number of steps. The given system defines the initial state and the system is reset to its initial state when this method is done.
- Parameters:
path (object like
PathBase) – This is the path we use to fill in phase-space points. We are here not returning a new path - this since we want to delegate the creation of the path (type) to the method that is running propagate.ens_set (dict) – It contains the ensemble settings. Explicitly used here:
interfaces : list of floats These interfaces define the stopping criterion.
system (object like
System) – The system object gives the initial state for the integration. The initial state is stored and the system is reset to the initial state when the integration is done.reverse (boolean, optional) – If True, the system will be propagated backward in time.
- Returns:
success (boolean) – This is True if we generated an acceptable path.
status (string) – A text description of the current status of the propagation.
Notes
Every phase point holds its positions, velocities and box in memory. A system without particles, a phase point of the infinite-swapping scheduler, is also stored on disk: the frames of the leg are written to a trajectory file of the leg in
exe_dir(_leg_file(),_write_frame()), which the first frame writes anew, and each phase point names its frame byconfigandvel_rev, as the streaming internal engine does (MDEngine._propagate_streaming()). A path stored by the scheduler (SchedulerPathStorage) then names the frames of its MD, and a stored frame read back (_materialize_if_filebacked()) gives the positions, velocities and box of the MD at that frame, to the nine decimals of the file.The MD starts from the velocities the system holds in memory, or, for a system without them, from the velocities of its stored frame, negated when
vel_revis True. The two agree: the velocities in memory are those of the stored frame with the signvel_revgives, and a time reversal of a phase point (System.reverse_velocities()) negates the velocities in memory as it togglesvel_rev.The MD starts with
_start_leg(): it draws its random numbers from seeds ofrgen, the random generator of the move, a new seed for each call, it starts from the context parameters and the integrator parameters the context held when the engine was built, and it starts at step count 0.
- classmethod read_input_temperatures(engine_settings)¶
Read the temperatures of the simulation an engine section names.
The simulation is imported as the engine imports it when it is created (
_input_simulation()).- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (object like
EngineTemperatures) – The temperaturesopenmm_temperatures()reads.- Raises:
ValueError – If the section names no
openmm_module; if the simulation steps with a variable step (refuse_variable_step_integrator(), checked before the temperature, as the engine checks it when it is built); if the simulation steps with aCustomIntegratorthat holds a variable namedkTfrom which PyRETIS reads no temperature (another letter case, or per degree of freedom), or aCustomIntegratorthat draws random numbers and has no global variablekT, alone or in aCompoundIntegrator(openmm_temperatures()); if agetTemperature()returns no temperature Quantity; if the simulation states no temperature: neither its integrator, nor an integrator itsCompoundIntegratorholds, nor a force of its System (a thermostat or a barostat) carries one (openmm_temperatures()); or if a temperature it states is not positive.
- classmethod read_input_temperatures_and_timestep(engine_settings)¶
Read the temperatures and the time step of a section’s simulation.
The simulation is imported once, as
read_input_temperatures()imports it, and its temperatures are read as that method reads them; then its time step, the step size of its integrator in ps (simulation_step_size()), the value the engine takes when it is built.- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out[0] (object like
EngineTemperatures) – The temperaturesopenmm_temperatures()reads.out[1] (float) – The step size of the integrator, in ps.
- Raises:
ValueError – As
read_input_temperatures()raises it, and assimulation_step_size()raises it for aCompoundIntegratorwhose integrators have different step sizes.
- records_input_timestep = True¶
- system_with_particles(system)¶
Return a phase point with particles in the state of its frame.
The phase point
systemholds no particles and names its frame byconfig. The phase point returned is a copy of the system built from the OpenMM simulation (_template_system()), whose particles carry the masses and the names of the simulation, in the state of that frame (_materialize_if_filebacked()): the positions and the velocities of the frame, the velocities negated whenvel_revis True, and the box of the frame. Such a phase point is held in memory:propagate()andmodify_velocities()write no frame files for it, as for the system the in-process kick initiation starts from (make_pyretis_system()).
- temperature_keys = 'the temperature of the integrator and of each force with a temperature, a thermostat or a barostat, of the OpenMM simulation'¶
- temperature_module_key = 'openmm_module'¶
- temperature_source = 'input'¶
- pyretis.engines.openmm.custom_integrator_temperature(integrator)¶
Return the temperature a
CustomIntegratorgives, in K.A
CustomIntegratorgives its temperature by its global variablekT(CUSTOM_THERMAL_ENERGY), the thermal energy in kJ/mol (thermal_energy_temperature()).- Parameters:
integrator (object like
openmm.Integrator) – An OpenMM integrator.- Returns:
out (float or None) – The temperature, or None for an integrator that is not a
CustomIntegratoror has no global variablekT.
- pyretis.engines.openmm.molar_gas_constant()¶
Return the molar gas constant of OpenMM, in kJ/(mol K).
- Returns:
out (float) –
MOLAR_GAS_CONSTANT_Rof OpenMM, in kJ/(mol K).
- pyretis.engines.openmm.path_sampling_integrator_problem(simulation)¶
Return why a path-sampling run cannot use an OpenMM simulation.
A path-sampling run reverses the velocities of a frame and draws new velocities at a frame, and integrates on from the positions of that frame, so the velocities of a frame must be those at the time of its positions. The integrators of OpenMM other than
CustomIntegratorare refused: the leap-frog integrators (LEAP_FROG_INTEGRATORS) store the velocities half a time step away from the positions,BrownianIntegratorintegrates Brownian dynamics without velocities (a path-sampling run of Brownian dynamics runs with the internalLangevinengine withhigh_friction), and the others are not known to store velocities at the time of the positions. ACustomIntegrator, except the leap-frog ones ofLEAP_FROG_INTEGRATORS, is accepted; aCustomIntegratoraCompoundIntegratorholds is theCustomIntegratorof OpenMM, and one with the global variables and steps of an accelerated-MD integrator (accelerated_md_class()) is refused as that integrator is. The steps of an accepted one must give the velocities at the time of its positions, as velocity Verlet and BAOAB Langevin dynamics do (MTSIntegratorandMTSLangevinIntegratorof OpenMM are such integrators;MTSIntegratorhas nokT, so a simulation with it takes its temperature from a force of the System with a temperature, a thermostat or a barostat, and one without such a force is refused,openmm_temperatures()).- Parameters:
simulation (object like
openmm.app.Simulation) – The OpenMM simulation.- Returns:
out (string or None) – The reason, naming the integrator (or each integrator of a
CompoundIntegrator) and the integrators to use instead, or None when a path-sampling run can use the simulation.
- pyretis.engines.openmm.path_sampling_scheme_problem(simulation)¶
Return why a path-sampling run refuses the scheme of a simulation.
The integrators of the simulation are ones a path-sampling run can use (
path_sampling_integrator_problem()). A deterministicCustomIntegratorwith a memory between time steps (deterministic_memory_problem()) is refused, and so is a force that acts only in anaddUpdateContextState()step beside aCustomIntegratorwithout one (context_state_force_problem()). ACustomIntegratorthat draws random numbers and holds no global variableCUSTOM_THERMAL_ENERGYgives no reason here: the run refuses it, first, where it reads the temperature of the simulation (pyretis.inout.engine_temperature.openmm_temperatures()).- Parameters:
simulation (object like
openmm.app.Simulation) – The OpenMM simulation.- Returns:
out (string or None) – The reason, or None when a path-sampling run can use the scheme of the simulation.
- pyretis.engines.openmm.simulation_step_size(simulation, source='the OpenMM simulation')¶
Return the time step of an OpenMM simulation, in ps.
The time step of the OpenMM engine is the step size of the integrator of its simulation. A simulation that steps with a variable step is refused first (
refuse_variable_step_integrator()). Every integrator aCompoundIntegratorholds counts, the current one or not, those of aCompoundIntegratorit holds included: their step sizes must agree within the tolerance ofpyretis.core.engine_time.timesteps_agree(), and the time step is then the step size of the compound integrator, the one of the integrator it steps with.The engine takes its time step from this function when it is built (
OpenMMEngine), and a run reads it before any engine is built (OpenMMEngine.read_input_temperatures_and_timestep()) and records it as thetimestepof the engine section.- Parameters:
simulation (object like
openmm.app.Simulation) – The OpenMM simulation, with its integrator.source (string, optional) – The module the simulation comes from, as the message names it.
- Returns:
out (float) – The step size of the integrator, in ps.
- Raises:
RuntimeError – If OpenMM is not installed.
ValueError – If the simulation steps with a variable step (
refuse_variable_step_integrator()), or if the integrators itsCompoundIntegratorholds have different step sizes; the message names each integrator, its step size in ps and the integrator the compound steps with.
- pyretis.engines.openmm.thermal_energy_temperature(thermal_energy)¶
Return the temperature, in K, of a thermal energy in kJ/mol.
The temperature is the thermal energy divided by the molar gas constant of OpenMM (
MOLAR_GAS_CONSTANT_R,molar_gas_constant()). A thermal energy computed as the gas constant times a temperatureTdivides back toTwithin a few units in the last place of a double, the differencespyretis.inout.engine_temperature.same_temperature()accepts between two temperatures.- Parameters:
thermal_energy (float) – The thermal energy, in kJ/mol.
- Returns:
out (float) – The temperature, in K.
pyretis.engines.ams module¶
A AMS external MD integrator interface.
This module defines a class for using AMS as an external engine.
Important classes defined here¶
- AMSEngine (
AMSEngine) A class responsible for interfacing AMS.
- class pyretis.engines.ams.AMSEngine(input_path, timestep, subcycles)¶
Bases:
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: the key
'input'names the AMS input,ams.inp.
- __init__(input_path, timestep, subcycles)¶
Set up the AMS engine.
- Parameters:
input_path (string) – The absolute path to where the input files are stored.
timestep (float) – The time step used in the AMS MD simulation.
subcycles (integer) – The number of steps each AMS MD run is composed of.
- _copyfile(source, dest)¶
Copy a file from source to destination and updates the state.
This method first calls the superclass’s _copyfile method to perform the actual file copy. If the destination file is already in the states, it deletes the existing state. Finally, it copies the state from the source to the destination.
- Parameters:
source (str) – The path to the source file.
dest (str) – The path to the destination file.
- _deletestate(filename)¶
Delete the state associated with the given filename.
This method distinguishes between trajectory and snapshot files based on the presence of the substring “traj” in the filename. For trajectory files, it deletes multiple states indexed by appending an underscore and an index to the filename. For snapshot files, it deletes the state directly.
- Parameters:
filename (str) – The name of the file whose state is to be deleted.
- Raises:
KeyError – If the filename is not found in the states dictionary.
- _extract_frame(traj_file, idx, out_file)¶
Extract a frame from a trajectory file.
- Parameters:
traj_file (string) – The AMS file to open.
idx (integer) – The frame number we look for.
out_file (string) – The file to dump to.
Note
This will only properly work if the frames in the input trajectory are uniformly spaced in time.
- _extract_frame_from_disk(traj_file, idx, out_file)¶
Extract a frame from a trajectory file from disk.
- Parameters:
traj_file (string) – The AMS file to open.
idx (integer) – The frame number we look for.
out_file (string) – The file to dump to.
Note
This will only properly work if the frames in the input trajectory are uniformly spaced in time.
- _movefile(source, dest)¶
Move a file from source to destination and update internal states.
This method moves a file from the specified source path to the destination path using the superclass’s _movefile method. Additionally, it updates the internal states if the source path is present in the states.
- Parameters:
source (str) – The path of the file to be moved.
dest (str) – The destination path where the file should be moved.
- _propagate_from(name: str, path: InfPath, system: System, ens_set: dict, msg_file: FileIO, reverse: bool = False) tuple[bool, str]¶
Propagate with AMS from the current system configuration.
Here, we assume that this method is called after the propagate() has been called in the parent. The parent is then responsible for reversing the velocities and also for setting the initial state of the system.
- Parameters:
name (string) – A name to use for the trajectory we are generating.
path (object like
pyretis.core.path.PathBase) – This is the path we use to fill in phase-space points.system (object like
System) – The system object gives the initial state for the integration. The order function is injected on the engine (self.order_function).ens_set (dict) – Ensemble settings. It contains:
interfaces : list of floats These interfaces define the stopping criterion.
msg_file (object like
FileIO) – An object we use for writing out messages that are useful for inspecting the status of the current propagation.reverse (boolean, optional) – If True, the system will be propagated backward in time.
- Returns:
success (boolean) – This is True if we generated an acceptable path.
status (string) – A text description of the current status of the propagation.
- _read_configuration(filename, idx=-1)¶
Read output from AMS snapshot/trajectory.
- Parameters:
filename (string) – The file to read the configuration from.
idx (integer) – Optional, frame index in trajectory
- Returns:
xyz (numpy.array) – The positions.
vel (numpy.array) – The velocities.
box (list of floats) – The box dimensions;
inffor each of the three lengths when the state has no lattice vectors.names (None) – No atom names are read.
- _removefile(filename, disk_only=False)¶
Remove a file from the system and optionally from the internal state.
This method removes a file by calling the superclass’s _removefile method. It can also remove the file from the internal state if it represents a molecular dynamics (MD) state.
- Parameters:
filename (str) – The name of the file to be removed.
disk_only (bool, optional) – If True, only remove the file from the disk and not from the internal state. Defaults to False.
- Returns:
None
- _reverse_velocities(filename, outfile)¶
Reverse velocity in a given snapshot.
- Parameters:
filename (string) – The configuration to reverse velocities in.
outfile (string) – The output file for storing the configuration with reversed velocities.
- calculate_order(system, xyz=None, vel=None, box=None)¶
Calculate the order parameter from a configuration.
The AMS
_read_configurationreturns(xyz, vel, box, names)with the box as the THIRD element, so this override unpacks the configuration accordingly (ExternalMDEngine.calculate_order()reads the box first).- Parameters:
system (object like
System) – The system that contains the particles we are investigating.xyz (numpy.array, optional) – The positions to use, in case we have already read them.
vel (numpy.array, optional) – The velocities to use, in case we have already read them.
box (numpy.array, optional) – The current box vectors, in case we have already read them.
- Returns:
out (list of floats) – The calculated order parameter(s).
- dump_phasepoint(phasepoint, deffnm='conf')¶
Dump the configuration of a phase point to a file.
This override points the phase point at frame index
0of the dumped file,(pos_file, 0); theExternalMDEnginebase stores(pos_file, None).- Parameters:
phasepoint (object like
System) – The phase point whose configuration we dump to file.deffnm (string, optional) – The default file name for the dumped configuration.
- engine_type = 'internal'¶
- modify_velocities(system: System, vel_settings: dict[str, Any], rgen) tuple[float, float]¶
Draw new velocities for the current state with AMS.
AMS draws the velocities (
GenerateVelocities) for the statesystempoints at, and PyRETIS uses them as drawn. The draws withRandomVelocitiesMethod = Gromacs, for which the SCM manual states the removal of the net linear momentum, and withExact, the default (AMS2023.1 or later), have zero net linear momentum; forBoltzmannthis is not checked.- Parameters:
system (object like
System) – The state whose velocities are drawn anew; it is pointed at the new AMS state.vel_settings (dict) – The velocity settings: the dictionary of
make_velocity_settings()ormake_kick_velocity_settings(). It contains:sigma_v: float or numpy.array, optional Negative values select aimless shooting, the draw AMS makes; zero or positive values select soft velocity perturbations. A missing key means aimless (
is_aimless_velocity_setting()).zero_momentum: boolean, optional Selects the reset of the linear momentum after the draw. The AMS draws with
GromacsandExacthave zero net linear momentum (see above), so the AMS engine requires True; a missing key means False, the[tis]default, which is refused.rescale: float, optional The energy to re-scale the drawn velocities to, the
[tis]rescale_energy. AMS does not re-scale, so a positive value is refused (refuse_energy_rescale()).
rgen (object like
RandomGenerator) – The velocity random generator of themodify_velocitiessignature; AMS draws from its own generator.
- Returns:
dek (float) – The change in the kinetic energy.
kin_new (float) – The new kinetic energy.
- Raises:
NotImplementedError – If
zero_momentumis False, ifrescaleis positive, or ifsigma_vselects soft velocity perturbations.
- needs_order = False¶
- classmethod read_input_temperatures(engine_settings)¶
Read the temperatures of the AMS input of an engine section.
The input is the one the engine reads when it is created:
ams.inpininput_path.- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (object like
EngineTemperatures) – The temperaturesread_ams_temperatures()reads.
- set_mdrun(md_items)¶
Set up the molecular dynamics run with the given parameters.
- Parameters:
md_items (dict) – A dictionary with the keys used here:
exe_dir(str), the directory where the executable is located, andens(dict), the ensemble information carryingens_name(str), the ensemble name.
Notes
Sets the executable directory and ensemble name, logs the executable directory, deletes the states left from earlier cycles, and updates the list of old states to the current states.
- step(system, name, set_trajfile=True, set_step_to_zero=False)¶
Perform a single step with AMS.
- Parameters:
system (object like
System) – The system we are integrating.name (string) – To name the output files from the AMS step.
set_trajfile (logical) – Optional, True if new output file should be opened
set_step_to_zero (logical) – Optional, True if new MD step should start from number zero
- Returns:
out (string) – The name of the output configuration, obtained after completing the step.
- temperature_keys = 'MolecularDynamics%InitialVelocities%Temperature and the Temperature of each Thermostat of ams.inp'¶
- temperature_source = 'input'¶
pyretis.engines.ase module¶
An ASE integrator interface.
- class pyretis.engines.ase.ASEEngine(timestep: float, temperature: float, subcycles: int, input_path: str, integrator: str, calculator_settings: dict, langevin_friction: float = -1.0, langevin_fixcm: float = -1.0, exe_path: str | Path = PosixPath('/home/enrico/cache/twoway-retis/wt2/docs'))¶
Bases:
ExternalMDEngineAn ASE engine class.
The random numbers of the engine come from the random generators of PyRETIS (
ase_random_generator()): each leg of MD with the Langevin integrator draws its noise from a generator seeded fromself.rgen, the random generator of the move, and each velocity draw (modify_velocities()) from a generator seeded from thergenit is given. The velocity Verlet integrator draws no random numbers and takes nothing fromself.rgen.The calculator, and every calculator it holds, that has a
directorycomputes in that directory below the engine’sexe_dir, set again each timeexe_diris set (place_calculators()): the files of a file-based calculator are those of the move that runs, in the directory the move holds.- __init__(timestep: float, temperature: float, subcycles: int, input_path: str, integrator: str, calculator_settings: dict, langevin_friction: float = -1.0, langevin_fixcm: float = -1.0, exe_path: str | Path = PosixPath('/home/enrico/cache/twoway-retis/wt2/docs'))¶
Initialize the ase engine.
- temperature: the temperature (K) of the Langevin integrator and of
the velocity draws,
[system] temperature, which the engine factory gives the constructor (pyretis.engines.run_temperature.engine_constructor_settings()).- langevin_fixcm: removes center of mass motion. Should not be used for
low dimensional systems like double well.
- _make_integrator(atoms)¶
Return the ASE integrator of one leg of MD.
The Langevin integrator draws its noise from a generator seeded with one number of
self.rgen, the random generator of the move, which the scheduler sets for each move (run_md()), and the kick initiation, sequential or parallel, for each ensemble (initiate_path_ensemble_kick()). The velocity Verlet integrator takes no generator.- Parameters:
atoms (object like
ase.Atoms) – The atoms the integrator moves.- Returns:
out (object like
ase.md.md.MolecularDynamics) – The integrator of the leg.
- _recompute_partial_orders(partial_traj, reverse)¶
Order parameters per frame of a partial ASE
.trajdump.The frames are read with ASE’s
Trajectory, which exposes only complete frames, so a final frame left half-written by an interruption is excluded and the surviving frames are kept (“use the last good frame” recovery, as for the other engines).
- property beta¶
Return the inverse temperature of the runs, in 1/eV.
The engine runs at
[system] temperature, in kelvin, andbeta = 1 / (k_B * temperature)with the k_B of ASE in eV/K, the unit of the potential energies the calculator reports.
- calculate_order(system, xyz=None, vel=None, box=None)¶
Calculate the order parameter.
The engine’s
_read_configurationreturns the box as the third element (positions, velocities, box, names), so this override reads them in that order;ExternalMDEngine.calculate_order()reads the box first.
- default_temperature = None¶
- default_units = 'ase'¶
- dump_phasepoint(phasepoint, deffnm='conf')¶
Dump a phase point to a file and point it at frame 0 there.
- engine_type = 'internal'¶
- property exe_dir¶
Return the directory the engine runs in.
- modify_velocities(system: System, vel_settings: dict, rgen) tuple[float, float]¶
Modify the velocities.
The Langevin
fixcmoption (set at construction) and thezero_momentumsetting here are independent mechanisms acting at different times:fixcmremoves the centre-of-mass motion every integrator step, whereaszero_momentumzeroes the COM momentum once, after the velocities are drawn. Each is set by the user on its own.- Parameters:
system (object like
System) – The system whose particle velocities are to be modified.vel_settings (dict) – A dict;
zero_momentum(bool) resets the linear momentum to zero after the velocities are drawn. A missing key means False, the[tis]default. The engine draws the velocities of aimless shooting and leaves their energy as drawn, so a soft perturbation (asigma_vthat is not negative) and a positiverescaleare refused before the draw.rgen (object like
RandomGenerator) – The random generator of the velocity draw. ASE draws the velocities from a generator seeded with one number of it (ase_random_generator()).
- Returns:
dek (float) – The change in kinetic energy from the velocity modification.
kin_new (float) – The kinetic energy of the velocities written out, after the momentum reset when one is requested.
- Raises:
NotImplementedError – If
vel_settingsselect a soft perturbation (refuse_soft_perturbation()) or an energy re-scale (refuse_energy_rescale()).ValueError – If
rgenis None.
- needs_order = False¶
- place_calculators()¶
Point the calculators’ directories into
exe_dir.Each calculator of
ase_calculator_directories()gets its directory joined toself.exe_dir:exe_diritself for a calculator with the directory".". A move runs in a directory no other move uses while it runs, so a file-based calculator of one worker never reads the input or the output of another worker’s calculation.
- step(system, name)¶
Raise NotImplementedError: the ASE engine runs no single step.
A kick of this engine runs through
ExternalMDEngine.propagate()(supports_step_kick = False);stepexists only so the class can be instantiated as a concrete subclass of the abstractExternalMDEnginebase.
- supports_step_kick = False¶
- system_temperature_unit = 'kelvin'¶
- pyretis.engines.ase.SEED_RANGE = (1, 2147483646)¶
The range, both ends included, of the seeds the engine draws for the numpy random generators that ASE draws from: the positive values of a signed 32-bit integer below 2**31 - 1.
- pyretis.engines.ase._ase_box_cell(atoms)¶
Return the ASE cell as a PyRETIS box-cell list, keeping angles.
ASE stores the cell as a 3x3 lattice-vector matrix; PyRETIS’ box helpers take the flattened
xx, yy, zz, xy, xz, ...form.pyretis.core.box.box_matrix_to_list()collapses an orthorhombic cell to its three lengths (the diagonal of the matrix) and keeps the off-diagonal terms for a triclinic cell, so every box vector reaches the caller.- Parameters:
atoms (object like
ase.Atoms) – The ASE atoms object whose cell is converted.- Returns:
list of float – The cell in PyRETIS’ flattened ordering (3 items for an orthorhombic cell, otherwise the full set).
- pyretis.engines.ase._searched_for_calculators(item)¶
Return True if the attributes of
itemmay hold calculators.- Parameters:
item (object) – An object a calculator holds.
- Returns:
bool – True for an object with attributes other than an
ase.Atoms, a numpy array, a module, a class or a function.
- pyretis.engines.ase.ase_calculator_directories(calc)¶
Return the calculators that have a directory, with that directory.
A calculator that writes files (an ASE
FileIOCalculator, as the calculators of DFT programs) writes them in itsdirectory. The engine places this directory in the directory of each move (ASEEngine.place_calculators()), so the directory a calculator is given must be relative and stay below the directory it is placed in.- Parameters:
calc (object like
ase.calculators.calculator.BaseCalculator) – The calculator of the engine.- Returns:
list of tuple –
(calculator, directory)forcalcand each calculator it holds (ase_calculators()) that has adirectory.- Raises:
ValueError – If a directory is absolute or leaves the directory it is placed in: the calculations of all moves would share its files.
- pyretis.engines.ase.ase_calculators(calc)¶
Return an ASE calculator and every ASE calculator it holds.
A calculator can combine others (a sum, a mixing or a QM/MM calculator of ASE, or a class of a user module), directly or through an object of its own, as the mixer of an ASE sum calculator. They are found among the attributes of the calculator and of the objects it holds, alone or in a list, tuple, set or dict, at any depth; an
ase.Atoms, a numpy array, a module and a class are not searched.- Parameters:
calc (object like
ase.calculators.calculator.BaseCalculator) – The calculator of the engine.- Returns:
list of object –
calcfirst, then the ASE calculators it holds, each once.
- pyretis.engines.ase.ase_random_generator(rgen, what)¶
Return a numpy random generator seeded from
rgen.ASE draws the random numbers of its Langevin integrator and of
ase.md.velocitydistribution.MaxwellBoltzmannDistribution()from the generator passed asrng. The engine passes anumpy.random.default_rng()(PCG64) generator whose seed is one integer drawn fromrgeninSEED_RANGE, so each leg and each velocity draw takes one number ofrgen.- Parameters:
rgen (object like
RandomGeneratoror numpy.random.Generator) – The random generator the seed is drawn from.what (string) – The part that draws the random numbers, for the error message.
- Returns:
out (object like
numpy.random.Generator) – The generator ASE draws from.- Raises:
ValueError – If
rgenis None.
- pyretis.engines.ase.set_ase_box(system, box)¶
Set the box of a System from the cell of an ASE frame.
A cell with three positive lengths is a periodic cell. It becomes a Box (RectangularBox or TriclinicBox), whose
length,lowandpbc_dist_coordinatethe periodic order parameters use. Any other cell, as the all-zero cell of a gas-phase ASE system, is stored as the list itself: such a system has no periodic cell, and its order parameters are the non-periodic ones.- Parameters:
system (object like
System) – The system whose box is set.box (list of float) – The cell of the frame, as
_ase_box_cell()returns it.
pyretis.engines.factory module¶
Engine factory for keyed scheduler engine creation.
This module supplements pyretis.engines with the keyed-creation
helpers used by the path-sampling scheduler. Unlike
pyretis.engines.engine_factory() and
pyretis.setup.common.create_engine(), which expect the engine
settings to sit at the top-level "engine" key, create_inf_engine
takes an explicit eng_key so multiple named engines (engine,
engine2, etc.) can coexist in one config.
Both creation routes resolve the same canonical engine classes:
from pyretis.setup.common import create_engine– canonical single-engine creation, resolved through the untouchedpyretis.engines.ENGINE_MAP.from pyretis.engines.factory import create_inf_engine– keyed scheduler creation, resolved throughbuild_engine_map().ENGINE_MAPis never mutated.
- pyretis.engines.factory.assign_engines(engine_occ: dict[str, list], eng_names, pin) dict[Any, int]¶
Assign free engine instances to worker
pin.Releases any engines currently held by
pin, then claims one free instance of each engine type ineng_namesfor that worker. Returns{name: index}mapping each requested engine name to the index insideengine_occ[name]thatpinholds when the function returns.- Raises:
ValueError – If no free engine is available for one of the requested names (this should never happen with a correctly sized pool).
- pyretis.engines.factory.build_engine_map() dict[str, dict[str, Any]]¶
Return a copy of ENGINE_MAP with the optional-dependency engines.
The ase, ams and turtlemd engines are registered on the copy when their modules import, as
pyretis.enginesregisters them inENGINE_MAPitself; missing optional dependencies (e.g.scm.plamsfor AMS,turtlemd) just lead to that entry being skipped.
- pyretis.engines.factory.check_engine(settings: dict[str, Any], eng_key: str = 'engine') bool¶
Light-touch validation of an engine settings block.
Ensures the section exists and that file-format-bearing engines specify their format (resolving cp2k’s and gmx’s via the shared
resolve_engine_format(), neither of which can fail).
- pyretis.engines.factory.constructor_settings(engine_settings: dict[str, Any], cls: type) dict[str, Any]¶
Return the settings of an engine section its constructor is offered.
An internal integrator reads the
STREAMING_SETTINGSfrom its section itself, so its constructor is offered the other settings of the section; the constructor of every other engine is offered the whole section. The check of the settings a constructor does not take (pyretis.core.common.initiate_instance()) then warns about the keys no part of the engine reads.- Parameters:
engine_settings (dict) – The settings of the engine section.
cls (type) – The engine class of the section, from the engine map or from the module the section names.
- Returns:
dict – The settings the constructor is offered:
engine_settingsitself for an engine that is not an internal integrator, and a copy without theSTREAMING_SETTINGSfor an internal integrator.
- pyretis.engines.factory.create_engines(config: dict[str, Any]) tuple[dict[Any, Any], dict[Any, list]]¶
Build the engine pool for a multi-worker parallel run.
For each unique engine name referenced in
config["simulation"]["ensemble_engines"], instantiatemin(occurrences, n_workers)copies and pair them with a per-instance occupancy slot initialised to-1(free).Returns
(engines, engine_occ)where:engines[name]is the list of instantiated engines.engine_occ[name][i]is the worker pin currently usingengines[name][i], or-1when free.
- Raises:
ValueError – As
create_inf_engine()raises it. The input of every section of the pool whose classengine_section_class()resolves is checked (refuse_path_sampling_input()) before the first engine is built, so the refusal of an integrator comes before a message about the temperature of another section.
- pyretis.engines.factory.create_inf_engine(settings: dict[str, Any], eng_key: str = 'engine') Any | None¶
Create a keyed scheduler engine from a settings section.
Counterpart to
pyretis.setup.common.create_engine()for the scheduler: takes an expliciteng_keyso multiple named engines (engine,engine2, …) can coexist in one config, and resolves engine classes throughbuild_engine_map()without mutating the canonical engine map.- Parameters:
settings (dict) – Full simulation settings. The engine settings live under
settings[eng_key].eng_key (str) – Which engine section to instantiate (
"engine","engine2", …).
- Returns:
EngineBase | None – The created engine, or the result of
pyretis.setup.common.create_external()if the engine class is not in the extended engine map. An internal integrator (pyretis.engines.internal.MDEngine) holdseng_keyin itssectionattribute, the section it streams thesubcyclesof.- Raises:
ValueError – If the engine integrates with an integrator a path-sampling run cannot use (
refuse_path_sampling_engine()): the scheduler runs path sampling only. The message names the section,[eng_key]. The input of a section whose classengine_section_class()resolves is checked before the engine is built, which reads its temperature (refuse_path_sampling_input()). This refusal comes before the temperature comparison.ValueError – If the
temperatureof the engine section, or[system] temperature, differs from the temperature the engine runs at (engine_settings_offered()for an engine that runs at[system] temperature,pyretis.engines.run_temperature.check_engine_temperature()for an engine that reads its temperature from its input).
- pyretis.engines.factory.engine_section_class(settings: dict[str, Any], eng_key: str = 'engine') type | None¶
Return the class an engine section builds, without building it.
The class is resolved as
create_inf_engine()resolves it: aclassof the engine map (build_engine_map()) gives its class; any otherclassis imported from the section’smodule, looked up as a file and, failing that, relative tosettings['simulation']['exe_path'].- Parameters:
settings (dict) – Full simulation settings, with the engine section at
settings[eng_key].eng_key (str, optional) – The engine section,
"engine","engine1", …
- Returns:
type or None – The class; None when the section is missing, gives no
class, or gives aclassoutside the engine map without amodule.- Raises:
ValueError – If the module of the section cannot be found or imported, or does not define the class.
- pyretis.engines.factory.engine_settings_offered(settings: dict[str, Any], eng_key: str, cls: type, engine_settings: dict[str, Any]) dict[str, Any]¶
Return the settings the constructor of an engine is offered.
These are the settings
constructor_settings()gives, with the temperature of the engine from the source of its class (pyretis.engines.run_temperature.engine_constructor_settings()): atemperatureof the section is left out, and compared with[system] temperaturefor an engine that runs at it, and an engine that takes[system] temperaturein its constructor is given it.- Parameters:
settings (dict) – The settings of the run.
eng_key (str) – The engine section, e.g.
"engine".cls (type) – The engine class of the section.
engine_settings (dict) – The settings of the section.
- Returns:
dict – The settings the constructor is offered.
- pyretis.engines.factory.import_external(settings: dict[str, Any], key: str, required_methods: list[str] | None = None) Any¶
Import and instantiate a class described by
settings.The
settingsdict must hold"class"and"module"keys; the module is looked up relative to the current directory and, failing that,settings["simulation"]["exe_path"].This complements
pyretis.setup.common.create_external(), which requires afactory(engine map) argument.- Parameters:
settings (dict) – Settings describing the object to load.
key (str) – Label used in error messages.
required_methods (list of str, optional) – Method names that the imported class must expose.
- pyretis.engines.factory.is_internal_integrator(klass: Any) bool | None¶
Return whether the engine of a class is an internal integrator.
An internal integrator (
pyretis.engines.internal.MDEngine) streams with thesubcyclesof the engine section it is built from (pyretis.engines.internal.MDEngine.setup_streaming()); every other engine of the map takessubcyclesthrough its constructor.- Parameters:
klass (object) – The
classof an engine section, looked up inbuild_engine_map()in lower case, ascreate_inf_engine()looks it up.- Returns:
bool or None – True for a class of the map whose engine is an internal integrator, False for another class of the map, and None for a class the map does not hold: an engine imported from a module, whose class is known once the run imports it.
pyretis.engines.process_sessions module¶
Track and terminate external-engine process sessions.
Streaming external engines run MPI launchers in fresh POSIX sessions. The session keeps an interrupted engine isolated from the PyRETIS process group, but it also means that cancelling a running process-pool future cannot stop the launcher. This module gives every scheduler worker one shared registry slot so the parent process can terminate active sessions during forced shutdown.
- pyretis.engines.process_sessions._proc_session_members(session_id: int) list[int] | None¶
Return Linux procfs members of
session_id, orNoneelsewhere.
- pyretis.engines.process_sessions._registered_sessions(slots: Any) set[int]¶
Return a stable snapshot of non-empty shared registry slots.
- pyretis.engines.process_sessions._session_is_alive(session_id: int) bool¶
Return whether any process still belongs to
session_id.
- pyretis.engines.process_sessions._signal_session(session_id: int, signum: int) None¶
Signal every visible member of an external-engine session.
Open MPI ranks may create process groups distinct from the launcher’s group. On Linux, enumerate the whole session through procfs so those ranks receive the signal directly. Other POSIX systems fall back to the launcher’s process group; MPI launchers normally forward that signal to their ranks.
- pyretis.engines.process_sessions._terminate_sessions(sessions: set[int], term_timeout: float, kill_timeout: float) set[int]¶
Terminate
sessionswith a bounded TERM-then-KILL sequence.
- pyretis.engines.process_sessions.configure_process_session_registry(slots: Any | None, worker_id: int | None, shutdown_event: Any | None = None) None¶
Configure the shared active-session slot for this worker process.
- pyretis.engines.process_sessions.register_process_session(session_id: int) None¶
Record the session leader PID of a running external engine.
- pyretis.engines.process_sessions.terminate_registered_process_sessions(slots: Any, term_timeout: float = 5.0, kill_timeout: float = 2.0) set[int]¶
Terminate and reap all active external sessions in
slots.SIGTERM is sent first so MPI can clean up its ranks. Sessions still alive after
term_timeoutreceive SIGKILL. The return value contains any session IDs that remain visible after both phases.
- pyretis.engines.process_sessions.unregister_process_session(session_id: int) None¶
Clear this worker’s slot if it still identifies
session_id.
pyretis.engines.run_temperature module¶
The temperature of a run and of each of its engines.
Every engine runs at the temperature of one place, its source
(pyretis.engines.engine.EngineBase.temperature_source):
The internal integrators, TurtleMD, ASE and an engine of a module on
pyretis.engines.engine.EngineBaserun at[system] temperature. The internal integrators run at 1 when the input sets none; they are the only engines with a default. The input of any other engine that runs at[system] temperaturemust set it, and so must the input of anumbrellawindowrun, whose Monte Carlo moves run at it: a run whose input sets none is refused before any engine runs.GROMACS, LAMMPS, CP2K, OpenMM and AMS run at the temperature their own input states (
pyretis.inout.engine_temperature), which the engine reads when it is created. A[system] temperatureis then optional, and when the input sets it, it must equal the temperature of every such engine of the run.
The temperature of an engine section ([engine], [engine0] and
the numbered sections of a pool) is optional. When the input gives it,
it is compared with the temperature the engine of the section runs at,
in the units of that engine (compare_engine_temperature()), and
a run whose engine section gives another temperature is refused before
any engine runs. The engine runs at the temperature of its source.
Wherever a temperature is compared with another one, it must equal it
within the relative tolerance ENGINE_TEMPERATURE_RTOL
(temperatures_agree()).
Important functions defined here¶
- temperatures_agree (
temperatures_agree()) Return whether a temperature equals another within the tolerance.
- compare_engine_temperature (
compare_engine_temperature()) Refuse the temperature of an engine section that differs from the temperature the engine of the section runs at.
- set_default_temperature (
set_default_temperature()) Give
[system] temperatureits default when every engine of the run takes it.- refuse_path_sampling_inputs (
refuse_path_sampling_inputs()) Refuse, before a temperature is read, the engine inputs whose integrator a path-sampling run cannot use.
- resolve_run_temperature (
resolve_run_temperature()) Set the temperature a run records from the sources of its engines, and compare the temperatures the settings state with them; set the time step of each OpenMM engine section from the integrator of its simulation.
- resolve_resumed_temperature (
resolve_resumed_temperature()) Resolve the temperatures of the run file a run resumes.
- read_analysed_temperatures (
read_analysed_temperatures()) Read the temperatures of the run file of a run the analysis reads.
- compare_analysed_engine_inputs (
compare_analysed_engine_inputs()) Compare the temperature the analysis reads from a file without a state with the inputs of its engines.
- refuse_temperatures_not_numbers (
refuse_temperatures_not_numbers()) Refuse a temperature of settings that is not a finite, positive number.
- read_earlier_engine_temperatures (
read_earlier_engine_temperatures()) Give
[system] temperaturethe temperature a TurtleMD or ASE engine section of an earlier schema ran its engine at.- engine_constructor_settings (
engine_constructor_settings()) Return the settings the constructor of an engine is offered.
- check_engine_temperature (
check_engine_temperature()) Compare the temperature an engine read from its input with the settings of the run.
- pyretis.engines.run_temperature.ENGINE_TEMPERATURE_RTOL = 1e-09¶
The relative tolerance of every comparison of two temperatures (
temperatures_agree()): the temperature of an engine section, and[system] temperature, must lie within this fraction of the temperature they are compared with.
- class pyretis.engines.run_temperature.EarlierTemperatures(run: float | None = None, system_sections: dict = <factory>, inputs: dict = <factory>, no_effect: dict = <factory>, unknown: list = <factory>, recorded: float | None = None, partly_recorded: dict = <factory>)¶
Bases:
objectThe temperatures the engines of an earlier run ran at.
A run file or restart file without the
temperature_rulemark ofpyretis.core.provenance, and an input of the legacy-runner schema, were written for a PyRETIS that ran each engine (earlier_engine_temperatures()):an internal integrator at
[system] temperature, 1 when the file sets none; thetemperatureof its engine section took no effect on it;any other engine that takes
[system] temperatureand whose constructor takes notemperature(an engine of a module onEngineBase) at[system] temperature; a file that sets none does not tell the temperature it ran at, since this PyRETIS gives such an engine no default;an engine whose constructor takes a
temperature(TurtleMD, ASE) at thetemperatureof its engine section;an engine that reads its temperature from its input at the temperature of that input. The file records that temperature as the
temperatureof the engine section of an engine withEngineBase.unmarked_section_temperature, and as[system] temperaturefor the engine of[engine]withEngineBase.unmarked_system_temperature; thetemperatureof the section of any other such engine took no effect on it. An engine that used thetemperatureof its section for a part of its run only, and its input of that run for the rest (EngineBase.unmarked_unrecorded_use(), LAMMPS), ran at a temperature the file does not record in full.
- Variables:
run (float or None) – The one temperature the engines that take
[system] temperatureran at; None for a run without such an engine.system_sections (dict of tuple) – For each engine section of an engine that takes
[system] temperatureand whose temperature the file records, the temperature it ran at and the setting that records it, as(value, place).inputs (dict) – For each engine section of an engine that reads its temperature from its input, the temperature it ran at and the setting that records it, as
(value, place); None for an engine whose temperature the file does not record.no_effect (dict of float) – The
temperatureof each engine section on whose engine it took no effect, keyed by the section.unknown (list of strings) – The engine sections whose temperature the file gives no way to know: a section whose engine class is not known, the section of an engine whose constructor takes a
temperaturethat gives none, and the section of an engine without a default (EngineBase.default_temperature) in a file that records no[system] temperature.recorded (float or None) – The
[system] temperaturethe file records, or None.partly_recorded (dict of strings) – For each engine section of
inputswhose engine used the temperature the file records for a part of its run only: what the engine took from it, and what it did at the temperature of its input of that run, which the file does not record (EngineBase.unmarked_unrecorded_use()), as a warning states it.
- inputs: dict¶
- names_no_engine()¶
Return whether the settings name no engine section with a class.
- Returns:
out (boolean) – True when no engine section of the settings names a class, so that nothing tells how an engine of the run ran.
- no_effect: dict¶
- partly_recorded: dict¶
- recorded: float | None = None¶
- run: float | None = None¶
- system_sections: dict¶
- unknown: list¶
- pyretis.engines.run_temperature.NO_DEFAULT_TEMPERATURE_TASKS = frozenset({'umbrellawindow'})¶
The tasks that run no engine and make their moves at
[system] temperature: the input of a new run of one must set it (_default_temperature()); the continuation of a restart file runs at the temperature of the run it continues (resolve_restart_temperature()).
- pyretis.engines.run_temperature.PATH_ENSEMBLE_TASKS = frozenset({'biretis', 'explore', 'make-tis-files', 'pptis', 'repptis', 'retis', 'tis'})¶
the path-sampling tasks and
make-tis-files. Such a run refuses an engine whose integrator a path-sampling run cannot use (pyretis.engines.engine.refuse_path_sampling_engine()).- Type:
The tasks whose runs build path ensembles
- pyretis.engines.run_temperature.RESTART_FILE_TASKS = frozenset({'md', 'md-flux', 'md-nve', 'umbrellawindow'})¶
The tasks that run in process and continue the run of the restart file that
[simulation] restartnames (pyretis.inout.settings.settings_from_restart()).
- pyretis.engines.run_temperature.check_engine_temperature(engine, settings, section)¶
Compare the temperature an engine read from its input with the run.
- Parameters:
engine (object like
EngineBase) – An engine just created from an engine section.settings (dict) – The settings of the run.
section (string) – The engine section, as the messages name it.
- Raises:
ValueError – If the engine reads its temperature from its input, and it read none, or the input states a unit system other than
[system] units(check_engine_units()), or thetemperatureof the engine section differs from the temperature of the input (compare_engine_temperature()), or[system] temperaturediffers from it by more than the tolerance (temperatures_agree()). The message of a difference ends with how the input gives the temperature (reading_advice()).
- pyretis.engines.run_temperature.check_engine_units(temperatures, settings, section)¶
Refuse an engine input in another unit system than
[system].- Parameters:
temperatures (object like
EngineTemperatures) – The temperatures read from the input of the engine; itsengine_unitsis the unit system the input declares (the LAMMPSunitscommand), or None.settings (dict) – The settings of the run.
section (string) – The engine section, as the message names it.
- Raises:
ValueError – If the input declares a unit system and
[system] unitsnames another one.
- pyretis.engines.run_temperature.compare_analysed_engine_inputs(settings, name)¶
Compare the temperature of a file without a state with engine inputs.
A file without a
[current]state (an input, or the settings an in-process task of an earlier PyRETIS stored,out.toml, without the mark ofpyretis.core.provenance.has_stored_temperature_rule()) is no record of the temperature its engines ran at: the analysis compares the[system] temperatureit reads from the file with the input file of each engine that reads its temperature from its own input, as a run of the file compares them, the input read where the file names it (_analysed_input_conflict()). A file with a state is the record of its run, and is not compared. A difference, or an engine input that cannot be read, leaves the file without[system] temperature, with a warning that names both values or the input: the analysis refuses no file for its temperatures, and reads no temperature the run may not have run at. The analysis does not read the temperature of an engine from a Python module: a file with a module engine, or with an engine whose input is a Python module (OpenMM), and a[system] temperatureis left without[system] temperature, with a warning that the temperature of that engine is read only by a run (_analysed_module_engine()); such a file without[system] temperaturegives no warning. A read of the file again (pyretis.inout.checker.rereading()) logs no warning.- Parameters:
settings (dict) – The settings the analysis reads from a file without a state;
[system] temperatureof the settings and of each ensemble is removed in place for a difference.name (string) – The file, as the warning names it.
- Returns:
out (string or None) – What the file and the engine input state, or why the analysis does not read the temperature of an engine, as the warning states it, when the analysis reads no
[system] temperaturefor that reason; None otherwise.
- pyretis.engines.run_temperature.compare_engine_temperature(given, temperature, section, engine, place, *, run_file=None, reading='')¶
Refuse an engine-section temperature unlike the one the engine runs at.
The
temperatureof an engine section sets no temperature: the engine runs at the temperature of its source (the settings of its input, or[system] temperature). A section that gives one is compared with it, in the units of the engine, within the relative toleranceENGINE_TEMPERATURE_RTOL.- Parameters:
given (object) – The
temperatureof the engine section, or None when the section gives none.temperature (float) – The temperature the engine of the section runs at.
section (string) – The engine section, as the message names it, e.g.
engine1.engine (string) – The engine class of the section, as the message names it.
place (string) – Where the engine takes its temperature from, as the message names it: the settings of its input and the input (
input_temperature_place()), or[system] temperature(system_temperature_place()).run_file (string, optional) – The run file a resume reads the section from. The message then says how the run it records continues.
reading (string, optional) – Said at the end of the message of a difference: how the engine reads
temperaturefrom the setting it comes from (reading_advice()), starting with a space; empty for none.
- Raises:
ValueError – If
givenis not a temperature, a finite, positive number (_temperature_problem()), or differs fromtemperatureby more thanENGINE_TEMPERATURE_RTOLtimestemperature. The message names the two values, the section and the place, followed byreading.
- pyretis.engines.run_temperature.continues_earlier_run(settings)¶
Return whether the settings of a path-sampling run continue a run.
- Parameters:
settings (dict) – The settings of a path-sampling run: an input, the document of a run file or a state file, or their parsed settings.
- Returns:
out (boolean) – True for settings with
[initial-path] method = "restart", and for a document with the[current]state of an earlier run (the resume of a run file or a state file).
- pyretis.engines.run_temperature.continues_restart_file(settings)¶
Return whether settings continue a run from its restart file.
- Parameters:
settings (dict) – The settings of a run.
- Returns:
out (boolean) – True for a task of
RESTART_FILE_TASKSwith[simulation] restart: the run continues the run its restart file records, at the temperature of that run (resolve_restart_temperature()).
- pyretis.engines.run_temperature.earlier_engine_temperatures(settings, classes, name, *, reader)¶
Return the temperatures the engines of an earlier run ran at.
The settings are read as
EarlierTemperaturesdescribes (_collect_earlier_temperatures()). The engines that take[system] temperaturerun at one temperature,[system] temperature, so they must have run at one temperature, within the tolerance (temperatures_agree()).- Parameters:
settings (dict) – The sections of an input, of a run file or of the settings of a restart file, or a scheduler configuration.
classes (dict) – The engine class of each engine section of the run, keyed by the section; None for a section whose class is not known.
name (string) – The file the settings are read from, as the message names it.
reader (string) – Who reads the file:
'input'for the input of a new run,'resume'for a run file a run resumes; it selects the advice of the refusal (_EARLIER_ADVICE).
- Returns:
out (object like
EarlierTemperatures) – The temperatures the engines ran at.- Raises:
ValueError – If the engines that take
[system] temperatureran at different temperatures (_earlier_system_temperature()).
- pyretis.engines.run_temperature.earlier_input_evidence(settings, velocity)¶
Return what a file without a state records that only earlier runs ran.
A file without a
[current]state and without the[provenance] temperature_rulemark that this PyRETIS writes into the settings an in-process run stores (pyretis.core.provenance.has_stored_temperature_rule()) is an input, or theout.tomlof a run of an earlier PyRETIS. A setting that this PyRETIS refuses in the input of a run for its temperature, and that the file shows by itself, was run by an earlier PyRETIS only: a[particles.velocity] temperature(refuse_velocity_temperature()), a TurtleMD integratorbeta, thetemperatureof a TurtleMD or ASE section without[system] temperature, and thetemperatureof an engine section unlike the[system] temperaturethe file states, by more than the tolerance (compare_engine_temperature()andresolve_run_temperature()refuse it). The analysis reads a file that records one as the record of a run of an earlier PyRETIS (read_analysed_temperatures()).- Parameters:
settings (dict) – The sections of the file, before the settings parse.
velocity (object or None) – The
[particles.velocity] temperaturethe file records, which was left out of the sections (pop_velocity_temperature()), or None.
- Returns:
out (list of strings) – Each such setting and its value, as a warning names it; empty for a file that records none.
- Raises:
ValueError – If
[system] temperature, thetemperatureof an engine section (refuse_temperatures_not_numbers()) orvelocity(_refuse_velocity_not_number()) is not a temperature, a finite, positive number: such a value is an invalid input, and no evidence.
- pyretis.engines.run_temperature.engine_class(settings, section)¶
Return the class of the engine an engine section creates.
- Parameters:
settings (dict) – The settings of a run.
section (string) – The engine section, e.g.
engine.
- Returns:
out (type) – The class the section names: a class of the engine map (
pyretis.engines.factory.build_engine_map()), or the class of the module the section names (_module_path()).- Raises:
ValueError – If the section names a class without a module that is not a class of the engine map, or a module that cannot be imported.
- pyretis.engines.run_temperature.engine_constructor_settings(settings, section, cls, section_settings)¶
Return the settings an engine constructor is offered.
The
temperatureof the engine section is no setting of the engine: it is left out of the settings offered. For an engine that takes[system] temperatureit is compared with[system] temperaturehere (compare_engine_temperature()), and the constructor of such an engine with an argumenttemperature(TurtleMD, ASE) is given[system] temperaturethere. The temperature of an engine that reads its own from its input is compared once the engine has read it (check_engine_temperature()).- Parameters:
settings (dict) – The settings of the run.
section (string) – The engine section the engine is created from.
cls (type) – The engine class of the section.
section_settings (dict) – The settings of the section the constructor is offered.
- Returns:
out (dict) – A copy of
section_settingswithouttemperature, withtemperatureset to[system] temperature(_system_temperature()) for a constructor that takes it.- Raises:
ValueError – As
compare_engine_temperature()and_system_temperature()raise it.
- pyretis.engines.run_temperature.engine_sections(settings)¶
Return the engine sections of settings that name an engine class.
- Parameters:
settings (dict) – The settings of a run.
- Returns:
out (list of strings) –
engine,engine0and the numbered sections of a pool (pyretis.inout.settings.is_pool_engine_section()), in this order, for each one that the settings hold with aclass.
- pyretis.engines.run_temperature.input_temperature_place(temperatures)¶
Return how a message names where an engine input states its temperature.
- Parameters:
temperatures (object like
EngineTemperatures) – The temperatures read from the input of an engine.- Returns:
out (string) – The settings of the input that hold the temperature, the input and the unit, e.g.
gen-temp, ref-t[System] of grompp.mdp, in kelvin.
- pyretis.engines.run_temperature.known_engine_class(settings, section)¶
Return the class of an engine section, or None for an unknown one.
The settings parse gives
[system] temperatureits default before the files of a run are staged, so the class of an engine whose module is not on disk yet is not known there. The resume lock reads the class of an engine section of a recorded configuration, which can name a module the working directory does not hold.- Parameters:
settings (dict) – The settings of a run.
section (string) – The engine section.
- Returns:
out (type or None) – The class
engine_class()returns, or None for a section that names no class, a class without a module that is not a class of the engine map, and a module that is not a file (_module_path()).
- pyretis.engines.run_temperature.pop_velocity_temperature(document)¶
Remove the
[particles.velocity] temperatureof a file.A
[particles.velocity]table that holds nothing else is removed with it: the input of the run gave no other setting of the velocities.- Parameters:
document (dict) – The canonical sections of a run file, or the scheduler configuration of a state file; changed in place.
- Returns:
out (object or None) – The value removed; None when the file records none.
- pyretis.engines.run_temperature.read_analysed_temperatures(settings, state, name, velocity=None)¶
Read the temperatures of the run file of a run the analysis reads.
The analysis reads the temperature of a run from its run file, not from the inputs or the modules of its engines (
pyretis.inout.run_record.read_settings()), and refuses no run for its temperatures. A run file with thetemperature_rulemark ofpyretis.core.provenancerecords the temperature each engine of its run ran at, and is read as it is; a[particles.velocity] temperatureit records is read as for a run file without the mark, with its[system] temperature(_read_marked_velocity()). One without the mark was written by an earlier PyRETIS, as is a file without a state that records a setting only an earlier PyRETIS ran (earlier_input_evidence()), and its temperatures are read as that PyRETIS ran its engines (_read_analysed_run()):[system] temperatureis the one temperature the engines that take it ran at, thetemperatureof a TurtleMD or ASE section among them. A run whose engines all read their temperature from their own input is read at the temperatures the run file records for them (_read_analysed_inputs()): one temperature is[system] temperature, and different ones leave it out. A run with an engine the analysis does not know keeps the[system] temperaturethe file records. A run whose record gives no one temperature (_analysed_conflict(): engines that take[system] temperatureat different temperatures, a TurtleMD integratorbetaof another temperature, an engine at its input at another temperature than those, an engine the analysis does not know with a recorded input temperature that differs from the recorded[system] temperature, a[particles.velocity] temperaturethat differs from the temperature of the run) is read without[system] temperature, with a warning, and an analysis that needs it stops as for a run that states none. When the run file does not record in full the temperature an engine ran at, a warning says that the[system] temperaturethe analysis reads is not verified for that engine. The settings of each ensemble are read in the same way. A read of the file again (pyretis.inout.checker.rereading()) logs no warning: the analysis has read the file once.- Parameters:
settings (dict) – The parsed settings of the run file, or the scheduler configuration of a state file, or the sections of a file without a state; changed in place.
state (dict or None) – The
[current]state of the run file, or, for the settings an in-process task of this PyRETIS stored (out.toml), theprovenancethat carries their mark (pyretis.inout.run_record.read_settings()); None for a file without a state, which is read as a run file without the mark.name (string) – The run file, as the messages name it.
velocity (object, optional) – The
[particles.velocity] temperaturethe file records, which was left out of the settings before they were parsed (pop_velocity_temperature()); None (the default) for a file that records none.
- Returns:
out (string or None) – Why the record gives no one temperature, as the warning states it (the file and what it records), when the analysis reads no
[system] temperaturefor that reason; None otherwise.- Raises:
ValueError – If
[system] temperature, thetemperatureof an engine section (refuse_temperatures_not_numbers()) orvelocity(_refuse_velocity_not_number()) is not a temperature, a finite, positive number: the file is an invalid input, and is refused as one.
- pyretis.engines.run_temperature.read_earlier_engine_temperatures(document, name)¶
Read the temperature of a TurtleMD or ASE section as
[system].The legacy-runner schema ran an engine that takes
[system] temperaturethrough its constructor (TurtleMD, ASE) at thetemperatureof its engine section, and the Langevin integrator of TurtleMD at thebetaof its settings, and an internal integrator at[system] temperature(earlier_engine_temperatures()). Their one temperature is the temperature of the run here (_read_section_temperatures()).- Parameters:
document (dict) – The sections of an input; changed in place.
name (string) – The file the document is read from, as the messages name it.
- Returns:
out (string or None) – What was read in another place, and the
[system] temperatureit replaces, as a warning states it; None when the document has no TurtleMD or ASE engine section with atemperature.- Raises:
ValueError – If these engines ran at different temperatures (
earlier_engine_temperatures()), or a TurtleMD integratorbetadiffers from the inverse temperature the engine derives (_derived_beta()).
- pyretis.engines.run_temperature.read_earlier_velocity_temperature(document, name)¶
Leave out the
[particles.velocity] temperatureof a run file.A run file a run resumes without the
temperature_rulemark ofpyretis.core.provenancerecords the[particles.velocity] temperatureof the input of its run. The velocities are drawn at[system] temperature(refuse_velocity_temperature()), the temperature of the run, which the resume reads as the temperature the engines of the earlier run ran at (_earlier_run_temperature()), so a value equal to that one, within the tolerance (temperatures_agree()), is left out. The analysis reads the value with the temperatures of the run (read_analysed_temperatures()).- Parameters:
document (dict) – The canonical sections of the run file, or the scheduler configuration of a state file; changed in place.
name (string) – The run file, as the messages name it.
- Returns:
out (string or None) – The value left out, as a warning states it; None for a run file without a
[particles.velocity] temperature.- Raises:
ValueError – If the run file records a
[particles.velocity] temperaturethat is not a temperature, with the message of the analysis (_refuse_velocity_not_number()), or that differs from the temperature the engines of the run ran at, or records no temperature they ran at; and as_earlier_run_temperature()raises it.
- pyretis.engines.run_temperature.reading_advice(temperatures)¶
Return how an engine input gives the temperature the engine runs at.
The temperature an engine runs at is the first setting of its input (
EngineTemperatures.agreed()). When that setting gives the temperature through another quantity (thekTof an OpenMMCustomIntegrator, a thermal energy), a temperature unlike it can come from that quantity, and the message of the difference says how PyRETIS reads it.- Parameters:
temperatures (object like
EngineTemperatures) – The temperatures the input of the engine states.- Returns:
out (string) –
EngineTemperatures.advicewhen the first key ofvaluesis a key ofEngineTemperatures.advised, else an empty string.
- pyretis.engines.run_temperature.refuse_path_sampling_inputs(settings, sections=None)¶
Refuse the engine inputs a path-sampling run cannot use.
The input of each engine section is read as the class of the section reads it (
engine_class()), without building the engine and without reading a temperature, and is refused when its integrator, or then its thermostat or barostat, is one a path-sampling run cannot use (pyretis.engines.engine.refuse_path_sampling_input()). Each route of a path-sampling run calls this function before it reads a temperature (resolve_run_temperature(),resolve_resumed_temperature(), and the default ofset_default_temperature()), so the refusal of the integrator comes before a message about a temperature of the same input. An input is read once.- Parameters:
settings (dict) – The settings of a path-sampling run.
sections (list of strings, optional) – The engine sections of the run. The default is every engine section of the settings (
engine_sections()) and of each of their ensembles (settings['ensemble']), the sectionsresolve_run_temperature()reads.
- Raises:
ValueError – If the input of an engine section integrates with an integrator, a thermostat or a barostat a path-sampling run cannot use, with a message that starts with the section,
[engine1]; the sections are checked in turn, each integrator first. For settings that continue an earlier run (continues_earlier_run()), the message ends withpyretis.engines.engine.CONTINUATION_REFUSAL.
- pyretis.engines.run_temperature.refuse_path_sampling_task_inputs(settings)¶
Refuse the engine inputs a path-sampling task cannot use.
The settings parse calls this function before it refuses a temperature of the input: a
[system] temperaturethat is not a temperature (refuse_system_temperature_not_number()), also whenset_default_temperature()checks it again in the[system] unitsthe parse has given their default, a[particles.velocity] temperature(refuse_velocity_temperature()), and a[system] temperatureunlike the temperature of the CP2K input of[engine], or a CP2K input whose temperature reader refuses it (pyretis.inout.formats.cp2k.cp2k_settings()), so the refusal of an integrator, a thermostat or a barostat a path-sampling run cannot use comes first. The settings of a task ofPATH_ENSEMBLE_TASKSare checked (refuse_path_sampling_inputs()); the settings of another task, and the settings the analysis reads (pyretis.inout.settings.run_file_reader()gives one ofpyretis.inout.settings.ANALYSIS_READERS), are not.- Parameters:
settings (dict) – The settings of a run.
- Raises:
ValueError – As
refuse_path_sampling_inputs()raises it.
- pyretis.engines.run_temperature.refuse_system_temperature_not_number(settings)¶
Refuse a
[system] temperaturethat is not a temperature.[system] temperatureis the temperature of the run, a finite, positive number whose inverse temperature is finite. A value that is not one (a string, a boolean, a list, a table,nan,inf, zero or a negative number:_temperature_problem(); a number so small thatbetaoverflows:_system_temperature_problem()) is refused as an invalid input, by every reader of the settings, before it is compared with any temperature or read as one: a boolean is not read as the temperature 1 or 0.- Parameters:
settings (dict) – The sections of an input or of a run file, or the scheduler configuration of a state file.
[system]and the[system]of each ensemble (settings['ensemble']) are checked.- Raises:
ValueError – If
[system] temperature, of the settings or of an ensemble, is given and is not a temperature (_system_temperature_problem()).
- pyretis.engines.run_temperature.refuse_temperatures_not_numbers(settings)¶
Refuse the temperatures of settings that are not temperatures.
[system] temperature(refuse_system_temperature_not_number()) and thetemperatureof each engine section (_refuse_section_not_number()) are checked before a reader of an earlier run counts them as the evidence of that run, compares them or reads them as the temperature of the run.- Parameters:
settings (dict) – The sections of an input or of a run file, or the scheduler configuration of a state file.
- Raises:
ValueError – If
[system] temperatureor thetemperatureof an engine section is given and is not a temperature, a finite, positive number (_temperature_problem()).
- pyretis.engines.run_temperature.refuse_velocity_temperature(settings)¶
Refuse a
temperaturein[particles.velocity].The velocities of the system are drawn at the temperature of the system,
[system] temperature.- Parameters:
settings (dict) – The settings of a run.
- Raises:
ValueError – If
[particles.velocity]setstemperature(velocity_temperature_given()).
- pyretis.engines.run_temperature.resolve_restart_temperature(settings, restart, name)¶
Resolve the temperature of the continuation of a restart file.
The continuation (
continues_restart_file()) runs at the temperature of the run its restart file records (_restart_file_temperature()). Settings without[system] temperature, the settings of an input that sets none for an engine that takes it, are given that temperature. A[system] temperaturethe settings hold, the input’s or the one the input of an engine states (resolve_run_temperature()), must equal it within the tolerance (temperatures_agree()), and is then replaced by it, so that the settings the run stores record the temperature the continuation runs at. A restart file without thetemperature_rulemark that does not record the temperature its engine ran at, an engine that reads its temperature from its input, gives way to the temperature of that input, with a warning that the temperature of the continuation is not verified. One that records the temperature an engine used for a part of its run only (LAMMPS) is compared on it, and the continuation is warned of as not verified, also when the two are equal. Thetemperatureof the engine section of an engine that takes[system] temperatureis compared with the temperature of the continuation (compare_engine_temperature()).- Parameters:
settings (dict) – The settings of the continuation;
[system] temperatureis set in place to the temperature of the continuation when they hold none or another value within the tolerance.restart (dict) – The restart file, as
pyretis.inout.restart.read_restart_file()reads it. The temperature of its system and of its settings is set to the temperature of the continuation where it holds another one (_set_restart_temperature()).name (string) – The restart file, as the messages name it.
- Raises:
ValueError – If
[system] temperatureof the settings differs from the temperature the restart file records by more than the tolerance, or neither holds a temperature, or as_restart_file_temperature()andcompare_engine_temperature()raise it.
- pyretis.engines.run_temperature.resolve_resumed_temperature(settings, state, name)¶
Resolve the temperatures of the run file a run resumes.
A
[system] temperaturethat is not a finite, positive number is refused first, with or without the mark (refuse_system_temperature_not_number()). A run file whose[current] provenanceholdspyretis.core.provenance.TEMPERATURE_RULE_KEYrecords the temperature each engine of its run runs at, and is refused when it records none for an engine (_refuse_unrecorded_run_file()). One without it was written by an earlier PyRETIS, and its temperatures are read as that PyRETIS ran them (_read_earlier_run_file()), with a warning for each engine whose temperature it does not record, or records in part (_warn_partly_recorded_temperatures()). The settings are then resolved as the settings of a new run (resolve_run_temperature()): the temperatures the run file records are compared with the sources of the engines, so a resume whose engine input states another temperature is refused before any engine runs.- Parameters:
settings (dict) – The parsed settings of the run file, or the scheduler configuration of a state file; changed in place.
state (dict or None) – The
[current]state of the run file.name (string) – The run file, as the messages name it.
- Raises:
ValueError – As
refuse_system_temperature_not_number(),_refuse_unrecorded_run_file(),_read_earlier_run_file()andresolve_run_temperature()raise it.
- pyretis.engines.run_temperature.resolve_run_temperature(settings, run_file=None)¶
Set the temperatures a run records from the sources of its engines.
Each engine of the run that reads its temperature from its input (GROMACS, LAMMPS, CP2K, OpenMM, AMS) has that input read, with the reader the engine itself calls when it is created (
read_input_temperaturesof the engine class), and every temperature the input states must agree. Then:a run whose engines all take
[system] temperatureis given its default when the settings hold none (_default_temperature()), as the settings parse gives it (set_default_temperature()) when the classes of the engines are known there; the continuation of a restart file (continues_restart_file()) is given the temperature of the run it continues when the restart file is read (resolve_restart_temperature());a
[system] temperaturethe input sets must equal the temperature of each engine that reads its own;otherwise, when the inputs of those engines state one temperature (the lowest and the highest agree to the round-off,
same_temperature()),[system] temperatureis set to the temperature of the first of their engine sections, which the run record then holds;otherwise each engine runs at the temperature of its own input, which its engine section records when it gives none, and
[system] temperaturestays unset, unless an engine of the run takes[system] temperature, which is refused.
The
temperatureof each engine section that gives one is compared with the temperature the engine of the section runs at (compare_engine_temperature()): the temperature of its input, or[system] temperature. An input that declares a unit system (the LAMMPSunitscommand) must declare the one of[system] units(check_engine_units()).The time step of an OpenMM engine is the step size of the integrator of its simulation (
pyretis.engines.openmm.simulation_step_size()), which the same read of the module gives (EngineBase.records_input_timestep), so the module runs once. It is set as thetimestepof each OpenMM engine section that states none, which the run record then holds, and a section that states one must equal it (_resolve_input_timestep()). The run then has the time step of each OpenMM section before any engine is built: the record holds it, a resume compares it, the sections of a pool are compared for one time per step (pyretis.core.engine_time.one_time_per_step_problem()) and the analysis reads it from the run file. OpenMM runs in nm and ps: a run with an OpenMM engine section and a[system] unitswhose time unit differs from the ps is refused (_refuse_input_time_unit()).The settings of each ensemble (
settings['ensemble']), which the settings parse copies from the general sections, are resolved in the same way.- Parameters:
settings (dict) – The parsed settings of a run.
[system] temperature, thetemperatureof the engine sections of a run whose engines run at different temperatures, and thetimestepof the OpenMM engine sections, are set in place, in the general sections and in each ensemble.run_file (string, optional) – The run file a resume reads the settings from (
resolve_resumed_temperature()). A refusal then says how the run it records continues.
- Raises:
ValueError – If the
temperatureof an engine section differs from the temperature its engine runs at, an engine input states no temperature, several different ones or a unit system other than[system] units,[system] temperaturediffers from the temperature of an engine input, or the engine inputs state different temperatures and an engine of the run takes[system] temperature; aspyretis.engines.openmm.simulation_step_size()raises it for the simulation of an OpenMM engine section; if thetimestepof an OpenMM engine section differs from the step size of its integrator, or[system] unitshas a time unit other than the ps (_resolve_input_timestep()).
- pyretis.engines.run_temperature.runs_at_constructor_temperature(cls)¶
Return whether an engine takes
[system] temperatureas an argument.- Parameters:
cls (type) – An engine class.
- Returns:
out (boolean) – True for an engine that runs at
[system] temperatureand has an argumenttemperaturein its constructor, which the engine factory gives it (TurtleMD, ASE).
- pyretis.engines.run_temperature.set_default_temperature(settings)¶
Give
[system] temperatureits default.When the input sets no
[system] temperatureand every engine of the run takes it, the run runs at theEngineBase.default_temperatureof its engines, 1 (_default_temperature()), when they are internal integrators; an input with any other engine that takes it (TurtleMD, ASE, an engine of a module onEngineBase), which has no default, is refused, and so is the input of a newumbrellawindowrun (NO_DEFAULT_TEMPERATURE_TASKS). A run with an engine that reads its temperature from its input is given the temperature of that input when the run is set up (resolve_run_temperature()), and gets no default here; nor does a run with an engine whose class is not known when the settings are read (known_engine_class()), which the run set-up gives its default, nor the continuation of a restart file (continues_restart_file()), which runs at the temperature of the run it continues; the continuation of an input with an engine without a default that sets no[system] temperatureis refused as well. Other settings without an engine class, which run no engine, are given 1. The settings of a run file the analysis reads (pyretis.inout.settings.reading_run_file()with the reader'analysis') get no default and are not refused: the run file records the temperature of its run, or the analysis reads it as an earlier PyRETIS ran its engines (read_analysed_temperatures()), and a run file that records none is analysed without one. The settings of a run file whose state carries thetemperature_rulemark, which a run resumes or continues (the reader'marked-resume'), get no default either: the run file records the temperature of its run, and the resume refuses one that records none (resolve_resumed_temperature(), and the resume lock of a continuation,pyretis.bin.pyretisrun._check_resume_compatibility()); an engine without a default and without[system] temperatureis refused there as in an input. A file without a state that the analysis reads as an input (the reader'input-analysis') is given the defaults of an input, with the classes of its engine sections read without importing a module (_recorded_engine_class()): an engine section that names a module gives no default temperature (compare_analysed_engine_inputs()says why). The default of[system] unitsimports such a module (pyretis.inout.settings._set_default_units_from_engine()).- Parameters:
settings (dict) – The parsed settings.
[system] temperatureis set in place.- Raises:
ValueError – If
[system] temperatureis not a temperature in[system] units(refuse_system_temperature_not_number()), or the input sets no[system] temperatureand an engine of the run takes it with no default (TurtleMD, ASE, an engine of a module onEngineBase), or the input is the one of a newumbrellawindowrun, outside the analysis of a run file (_default_temperature()); first, for a task ofPATH_ENSEMBLE_TASKSoutside the analysis, if the input of an engine of the run integrates with an integrator a path-sampling run cannot use (refuse_path_sampling_inputs()), and for anmd,md-nveormd-fluxtask outside the analysis, if the class of[engine]cannot run the task (pyretis.setup.md_task_refusal.refuse_md_task_input()).
- pyretis.engines.run_temperature.system_resume_advice(run_file, recorded, value)¶
Return the advice of a resume refused on
[system] temperature.- Parameters:
run_file (string) – The run file the resume reads.
recorded (float) – The
[system] temperaturethe run file records.value (float) – The temperature the input of an engine states.
- Returns:
out (string) – The advice: the run file records
recordedfor the run it resumes, which the input of the engine must state again, within a relativeENGINE_TEMPERATURE_RTOL, to continue that run.
- pyretis.engines.run_temperature.system_temperature_not_number(settings)¶
Return why a
[system] temperatureis not a temperature.- Parameters:
settings (dict) – The sections of an input or of a run file, or the scheduler configuration of a state file.
[system]and the[system]of each ensemble (settings['ensemble']) are read, in this order.- Returns:
out (string or None) – The refusal of the first
[system] temperaturegiven that is not a temperature in the[system] unitsof its[system](_system_temperature_problem()), asrefuse_system_temperature_not_number()states it, or None when each one given is a temperature.
- pyretis.engines.run_temperature.system_temperature_place(cls)¶
Return how a message names the temperature of an engine at
[system].- Parameters:
cls (type) – An engine class that runs at
[system] temperature.- Returns:
out (string) –
[system] temperature, with the temperature the engine runs at when the input sets none (EngineBase.default_temperature), or with the statement that the input must set it.
- pyretis.engines.run_temperature.temperatures_agree(value, reference)¶
Return whether a temperature equals another within the tolerance.
- Parameters:
value (float) – The temperature compared.
reference (float) – The temperature it is compared with.
- Returns:
out (boolean) – True when
valuediffers fromreferenceby no more thanENGINE_TEMPERATURE_RTOLtimesreference.
- pyretis.engines.run_temperature.velocity_temperature_given(settings)¶
Return whether
[particles.velocity]setstemperature.- Parameters:
settings (dict) – The settings of a run.
- Returns:
out (boolean) – True when
[particles.velocity]is a table with the keytemperature, whichrefuse_velocity_temperature()refuses.
pyretis.engines.turtlemd module¶
A TurtleMD integrator interface.
This module defines a class for using the TurtleMD.
- pyretis.engines.turtlemd.ENGINE_INTEGRATOR_PARAMETERS = ('timestep', 'beta', 'seed', 'rgen')¶
The parameters of a TurtleMD integrator that the engine gives it, and that its settings do not set: the time step, the inverse temperature (
TurtleMDEngine._integrator_settings()), the seed of a seeded integrator and its random generator.
- pyretis.engines.turtlemd.SEEDED_INTEGRATORS = (<class 'turtlemd.integrators.LangevinInertia'>,)¶
The TurtleMD integrators that the engine seeds. Each leg seeds its integrator with a seed drawn from the random generator of the move; the other integrators take the time step and their settings only.
- class pyretis.engines.turtlemd.TurtleMDEngine(timestep: float, subcycles: int, temperature: float, boltzmann: float, integrator: dict[str, Any], potential: dict[str, Any], particles: dict[str, Any], box: dict[str, Any])¶
Bases:
ExternalMDEngineInterface the TurtleMD engine.
- To do:
Add support for multiple potentials?
Velocity generation needs to account for the dimensionality of the system
- __init__(timestep: float, subcycles: int, temperature: float, boltzmann: float, integrator: dict[str, Any], potential: dict[str, Any], particles: dict[str, Any], box: dict[str, Any])¶
Initialize the TurtleMD engine.
- Parameters:
timestep (float) – The simulation timestep.
subcycles (int) – The number of subcycles to execute per path-sampling step.
temperature (float) – The temperature of the simulation,
[system] temperature, which the engine factory gives the constructor (pyretis.engines.run_temperature.engine_constructor_settings()).boltzmann (float) – The value of Boltzmann’s constant (kB).
integrator (dict) – The name of the integrator to use for TurtleMD,
class, and itssettings. A Langevin integrator is given the inverse temperaturebetaof the engine (_integrator_settings()), and its settings must not set it.potential (dict) – The name of the potential to use for TurtleMD.
particles (dict) – The mass and name of the particles in the system.
box (dict) – Definition of the simulation box.
- _extract_frame(traj_file: str, idx: int, out_file: str) None¶
Extract a frame from a trajectory file.
This method is used by self.dump_config when we are dumping from a trajectory file. It is not used if we are dumping from a single config file.
- Parameters:
traj_file (str) – The trajectory file to dump from.
idx (int) – The frame number we look for.
out_file (str) – The file to dump to.
- static _integrator_problem(integrator)¶
Return why a path-sampling run cannot use a TurtleMD integrator.
- Parameters:
integrator (type) – A TurtleMD integrator class, a value of
INTEGRATOR_MAPS.- Returns:
out (string or None) – The reason
path_sampling_problem()gives, or None.
- _integrator_settings(integrator)¶
Return the settings the TurtleMD integrator is created with.
An integrator that takes the inverse temperature
beta(the Langevin integrators) is given thebetaof the engine,1 / (boltzmann * temperature), from[engine] boltzmannand[system] temperature, so the dynamics and the velocity draws run at one temperature.- Parameters:
integrator (dict) – The
integratorsetting of the engine: itsclassand itssettings.- Returns:
out (dict) – A copy of the
settings(empty for an integrator given none), withbetafor an integrator that takes it.- Raises:
ValueError – If the
settingssetbeta.
- _leg_integrator()¶
Return the TurtleMD integrator of one leg.
An integrator of
SEEDED_INTEGRATORStakes a seed drawn fromrgen, the random generator of the move; the other integrators take the time step and their settings.- Returns:
out (object like
turtlemd.integrators.MDIntegrator) – The integrator.- Raises:
ValueError – If a seeded integrator finds no random generator.
- _persist_force_evals()¶
Write this engine’s running force-eval total, when opted in.
Persistence is OFF by default (no stray files in normal runs or the test suite). The validation driver sets
PYRETIS_FORCE_EVAL_DIRto a run directory; each propagating engine then keeps a small per-process fileforce_evals_<pid>.txtthere holding its current cumulative count. The driver sums every such file in the run directory, so the total is correct across the worker pool and across a restart-continued run (a fresh process starts a new file).
- _propagate_from(name: str, path: Path, system: System, ens_set: dict[str, Any], msg_file: FileIO, reverse: bool = False) tuple[bool, str]¶
Propagate the equations of motion from the given system.
- We assume the following:
Box does not change (constant volume simulation)
Box is orthogonal
- static _read_configuration(filename: str) tuple[ndarray, ndarray, ndarray | None, list[str]]¶
Read TurtleMD output configuration.
This method reads the specified TurtleMD output configuration and extracts the configuration which includes the positions, velocities, box dimensions and particle names. It is used when calculating the order parameter from a TurtleMD simulation.
- Parameters:
filename (str) – The path to the file to read the configuration from.
- Returns:
tuple –
A tuple containing:
xyz: An array of atomic positions.
vel: An array of atomic velocities.
box: An array of box dimensions or None if not available.
names: A list of atom names found in the file.
- _refuse_unbound_settings(name, settings)¶
Refuse integrator settings the integrator does not take.
Each leg creates the integrator (
_leg_integrator()) with the time step of the engine, the settings, and a seed for an integrator ofSEEDED_INTEGRATORS. The settings are checked against the parameters of the integrator when the engine is created, so a setting the integrator does not take, or a parameter it needs that the settings do not give, stops the run before a file is written. An integrator that a path-sampling run cannot use is refused by its own message (path_sampling_problem()) and is not checked here.- Parameters:
name (string) – The
classof the integrator, as the input gives it.settings (dict) – The settings the integrator is created with (
_integrator_settings()),betaincluded for an integrator that takes it.
- Raises:
ValueError – If the settings give a parameter the integrator does not take, a parameter the engine gives (
timestep, andseedfor a seeded integrator), or leave out a parameter without a default that the engine does not give. The message names the settings and the ones the integrator takes (integrator_settings_text()).
- _reverse_velocities(filename: str, outfile: str) None¶
Reverse velocities in the given snapshot.
- Parameters:
filename (str) – The path to the file containing the configuration to reverse the velocities of.
outfile (str) – The path to the output file for storing the configuration with reversed velocities.
- static _update_phase_point_box(system, box)¶
Give the phase point the size of the box TurtleMD integrates in.
A phase point without a box gets one of that size. A phase point that holds the box of the settings takes the size when the box has as many dimensions as TurtleMD’s box. A non-periodic box of another dimension is left as it is: no length of it enters a distance.
- Parameters:
system (object like
System) – The phase point.box (numpy.array) – The box lengths of the configuration TurtleMD read.
- Raises:
ValueError – If the phase point holds a periodic box with another number of dimensions than TurtleMD’s box.
- property beta¶
The inverse temperature
1 / (boltzmann * temperature).
- calculate_order(system, xyz=None, vel=None, box=None)¶
Calculate the order parameter of the current system.
- default_temperature = None¶
- default_units = 'reduced'¶
- draw_maxwellian_velocities(vel, mass, beta, rgen, sigma_v=None)¶
Draw velocities from a Gaussian distribution.
- dump_phasepoint(phasepoint, deffnm='conf')¶
Dump the current configuration from a system object to a file.
- engine_type = 'internal'¶
- classmethod get_default_units(settings=None)¶
Return the default unit system for TurtleMD.
TurtleMD examples are dimensionless (
boltzmann = 1.0, unscaled lengths/energies), and the general-purpose “reduced” unit system (pyretis.core.units.UNIT_SYSTEMS, length scale 1) matches them.- Parameters:
settings (dict, optional) – Full simulation settings or engine settings. This argument is ignored for the TurtleMD engine.
- Returns:
out (string) – The default unit system for TurtleMD,
"reduced".
- classmethod input_path_sampling_problem(engine_settings)¶
Return why a path-sampling run cannot use a section’s integrator.
The integrator is the class
[engine.integrator] classnames inINTEGRATOR_MAPS, as the engine takes it when it is created, and is checked aspath_sampling_problem()checks it.- Parameters:
engine_settings (dict) – The settings of the engine section.
- Returns:
out (string or None) – The reason for the
Verletand theLangevinOverdampedintegrators; None for the other integrators, and for a section that names no integrator ofINTEGRATOR_MAPS, which the engine refuses when it is created.
- modify_velocities(system: System, vel_settings: dict[str, Any], rgen) tuple[float, float]¶
Modify the velocities of all particles.
- Parameters:
system (object like
System) – The system whose particle velocities are to be modified.vel_settings (dict) – A dict;
zero_momentum(bool) resets the linear momentum to zero after generating velocities internally. A missing key means False, the[tis]default. The engine draws the velocities of aimless shooting and leaves their energy as drawn, so a soft perturbation (asigma_vthat is not negative) and a positiverescaleare refused before the draw.
- Returns:
dek (float) – The change in kinetic energy from the velocity modification.
kin_new (float) – The new kinetic energy of the system.
- Raises:
NotImplementedError – If
vel_settingsselect a soft perturbation (refuse_soft_perturbation()) or an energy re-scale (refuse_energy_rescale()).
- needs_order = False¶
- path_sampling_problem()¶
Return why a path-sampling run cannot use this engine.
The TurtleMD
Verletintegrator stores, with the positions of a step, the velocity of the step before (the central difference of the positions around it), and starts each leg from the positions one step back that it derives from the first velocity.LangevinOverdampedintegrates Brownian dynamics, without velocities; PyRETIS runs Brownian dynamics in path sampling with the internalLangevinengine, whosehigh_frictionintegrator the method validation covers.VelocityVerletandLangevinInertiastore the velocities at the time of the positions.- Returns:
out (string or None) – The reason for the
Verletand theLangevinOverdampedintegrators, or None.
- step(system, name)¶
Perform a single step with the engine.
This engine integrates whole segments (
_propagate_from()), so a singlestep()is not supported. The method exists only so the class can be instantiated (theExternalMDEnginebase declares it as an abstract method).supports_step_kick = Falserouteskick_across_middleto thepropagate()-based_kick_across_middle_propagate, so this method is never called.
- supports_step_kick = False¶
- system_temperature_unit = 'the temperature unit of [engine] boltzmann'¶
- pyretis.engines.turtlemd.VELOCITY_FREE_INTEGRATORS = (<class 'turtlemd.integrators.LangevinOverdamped'>,)¶
The TurtleMD integrators that integrate without velocities (Brownian dynamics).
- pyretis.engines.turtlemd._ADVISED_INTEGRATOR_SETTINGS = ' "velocityverlet" takes no settings, and "langevininertia" takes the setting gamma.'¶
The settings of the integrators the refusal of a TurtleMD integrator advises (
TurtleMDEngine._integrator_problem()).
- pyretis.engines.turtlemd.integrator_settings_text(integrator)¶
Return the settings a TurtleMD integrator takes, as a message says.
- Parameters:
integrator (type) – A TurtleMD integrator class, a value of
INTEGRATOR_MAPS.- Returns:
out (string) –
takes no settings, ortakes the setting(the settings) and the names of its parameters other thanENGINE_INTEGRATOR_PARAMETERS.