This module re-exports the system class (defined in
pyretis.core.system_core) which connects different
parts (for instance box, forcefield and particles) into a single
structure.
A class which defines the system we are working with. This
class contain a lot of information and is used to group the
information into a structure which the simulations will make use
of. Typically the system will contain a reference to a box,
a list of particles and also a force field.
This method ensures correct ordering of the elements for PyRETIS:
xx,yy,zz,xy,xz,yx,yz,zx,zy.
Parameters:
matrix (numpy.array) – A matrix (2D) representing the box.
full (boolean, optional) – Return a full set of parameters (9) if set to True. If False,
and we need 3 or fewer parameters (i.e. the other 6 are zero)
we will only return the 3 non-zero ones.
low (numpy.array, optional) – 1D array containing the lower bounds of the cell.
high (numpy.array, optional) – 1D array containing the higher bounds of the cell.
cell (numpy.array, optional) – 1D array, a flattened version of the simulation box matrix.
This array is expected to contain 1, 2, 3, 6 or 9 items.
These are the xx, yy, zz, xy, xz, yx, yz, zx, zy elements,
respectively.
periodic (list of boolean, optional) – If periodic[i] then we should apply periodic boundaries
to dimension i.
Returns:
out (object like BoxBase) – The object representing the simulation box.
The ensemble layout of a bidirectional RETIS (biretis) run.
A biretis run samples the transitions A -> B and B -> A in one run.
It has two families of ensembles, which share the paths that connect
the two states:
the A family: the [0^-] of state A and the ladder of ensembles
whose paths start in A and cross an A interface going up;
the B family: the [0^-] of state B and the ladder of ensembles
whose paths start in B and cross a B interface going down;
k shared ensembles, each one holding the paths that start in A
and cross its A interface, and the paths that start in B and cross its
B interface.
A path keeps the orientation it was generated in, and its family is the
state it starts in. A reactive path is held in its A orientation by the
A family and in its B orientation by the B family; a time reversal in a
shared ensemble turns the one into the other.
The interfaces are given as two RETIS interface lists: the A list
ascending from lambda_A to lambda_B and the B list descending from
lambda_B to lambda_A. The last shared interior interfaces of the two
lists are paired in order into the shared ensembles.
The ensembles are laid out in this slot order: the [0^-] of A, the
[0^-] of B, the A ladder (its [0^+] first), the B ladder (its
[0^+] first), and the shared ensembles.
Return the input keys of a biretis run that it cannot run with.
A biretis run shoots every ensemble with sh, swaps paths only
by the two zero swaps and the infinite-swapping occupancy, runs
every ensemble with [engine], and has a [0^-] of state A
with no left boundary: its flux is the one of
pyretis.analysis.biretis_analysis. [tis]shooting_moves and [simulation]ensemble_engines give one entry
per interface, and a biretis run has more ensembles than interfaces,
so it takes neither. It runs with one worker: its rates with several
workers are not validated in this version. It starts from kicked
paths, or continues with [initial-path]method="restart"; it
does not load paths.
Parameters:
quantis (boolean or None) – [tis]quantis.
permeability (boolean or None) – [simulation]permeability.
mirror_freq (float or None) – [tis]mirror_freq.
target_freq (float or None) – [tis]target_freq.
zero_left (float, boolean or None) – [simulation]zero_left; None and False mean that it is not
set.
moves (list of strings) – The shooting moves the run is given: [tis]shooting_move and
[tis]move of the input, or the move of each ensemble of the
scheduler configuration.
per_interface (list of strings) – The keys of the input with one entry per interface that the input
gives, of "[tis]shooting_moves" and "[simulation]ensemble_engines".
initial_method (string or None, optional) – [initial-path]method, None when it is not given.
workers (integer or None, optional) – The worker count of the run, None when it is not given.
workers_source (string or None, optional) – Where the worker count comes from: the environment variable that
sets it ("PYRETIS_WORKERS" or "PYRETIS_NATIVE_WORKERS"),
or None or "runner.workers" for [runner]workers
(pyretis.inout.key_table.workers_source()).
Returns:
out (list of strings) – The keys the run cannot take, empty when it takes them all.
Return the weights of a positive path in the ensembles of a run.
A path weighs 1 in an ensemble it belongs to and 0 in the others:
in an A-family ensemble with middle interface m when it starts
in A and its largest order reaches m;
in a B-family ensemble with middle interface m when it starts
in B and its smallest order is below m;
in a shared ensemble when it does one of the two for the A and the
B interface of the ensemble.
A path that starts in A has its smallest order below every A
interface and one that starts in B its largest above every B
interface, so these are the crossing tests of the moves
(ordermin<m<=ordermax of
pyretis.core.path.Path.check_interfaces()).
windows (list of dict) – The ensembles of the run (biretis_windows()).
Returns:
out (tuple of floats) – One weight per positive ensemble, in slot order from the first
one after the minus ensembles, followed by a 0 for the trailing
slot of the scheduler.
Return the ensembles of a biretis run, in slot order.
Parameters:
interfaces (list of floats) – The A list, ascending from lambda_A to lambda_B.
interfaces_b (list of floats) – The B list, descending from lambda_B to lambda_A.
shared (integer) – The number of shared ensembles.
lambda_minus_one (float or False, optional) – The interface that bounds the [0^-] of A on the left.
Returns:
out (list of dict) – One dict per ensemble with interfaces ((left,middle,right) in the order parameter), start_cond, role
("minus", "zero-plus", "body" or "shared"),
family ("A", "B" or "S"), ens_name and, for a
shared ensemble, middle_b, the B interface it pairs.
Return the side the kick of an ensemble starts its path from.
A shared ensemble holds the paths that start in A and the paths that
start in B. Its kick starts from A: it then gives a path that starts
in A and crosses the A interface of the ensemble, which the ensemble
holds. Every other ensemble is kicked from the side its paths start
from. The start condition is a string, as the kick’s amendment of a
path by TIS moves reads it.
This method will compare two PyRETIS objects by checking
the equality of the attributes. Some of these attributes
might be numpy arrays in which case we use the
numpy_allclose() defined in this module.
Parameters:
obj1 (object) – The first object for the comparison.
obj2 (object) – The second object for the comparison.
attrs (iterable of strings) – The attributes to check.
numpy_attrs (iterable of strings, optional) – The subset of attributes which are numpy arrays.
Returns:
out (boolean) – True if the objects are equal, False otherwise.
Compute the High Acceptance path weight after a MC move.
This function computes the weights that will be used in the
computation of the P cross. This trick allows the use of
the High Acceptance version of Stone Skipping or Wire Fencing,
allowing the acceptance of B to A paths.
The drawback is that swapping moves needs
to account also for this different weights.
The weight 1 will be returned for a path not generated by SS or WF.
Parameters:
path (object like PathBase) – This is the input path which will be checked.
interfaces (list/tuple of floats) – These are the interface positions of the form
[left,middle,right].
move (string, optional) – The MC move to compute the weights for.
Method to select the crosses of a path over an interface.
Parameters:
path (object like PathBase) – Input path which will be trimmed.
interface (float) – Interface position.
last_frame (boolean, optional) – Determines if the last crossing will be selected or not.
rgen (object like RandomGenerator, optional) – The generator the random crossing is drawn from: a
RandomGenerator or a numpy.random.Generator
(draw_integer_inclusive()). A Monte Carlo move passes
its own stream. When it is omitted, the path’s own rgen is
used. A number is drawn only when last_frame is False and the
path crosses the interface more than once.
Returns:
ph1, ph2 (snapshots) – Define the randomly picked crossing,
one right before and one right after the interface.
This method is intended as a semi-generic factory for creating
instances of different objects based on simulation input settings.
The input settings define what classes should be created and
the object_map defines a mapping between settings and the
class.
Parameters:
settings (dict) – This defines how we set up and select the order parameter.
object_map (dict) – Definitions on how to initiate the different classes.
name (string, optional) – Short name for the object type. Only used for error messages.
Returns:
out (instance of a class) – The created object, in case we were successful. Otherwise, we
return none.
This method will dynamically import a specified method/object
from a module and return it. If the module can not be imported or
if we can’t find the method/class in the module we will raise
exceptions.
Parameters:
module_path (string) – The path/filename to load from.
function_name (string) – The name of the method/class to load.
This method is intended for use where we are checking that we can
call a certain function. This method will return arguments and
keyword arguments a function expects. This method may be fragile -
we assume here that we are not really interested in args and
kwargs and we do not look for more information about these here.
Parameters:
function (callable) – The function to inspect.
Returns:
out (dict) – A dict with the arguments, the following keys are defined:
Randomly select the ensemble for ‘relative’ shooting moves.
Here we select the ensemble to do the shooting in based on relative
probabilities. We draw a random number between 0 and 1 which is used to
select the ensemble.
Parameters:
ensembles (list of objects like PathEnsemble) – This is a list of the ensembles we are using in the RETIS method.
rgen (object like RandomGenerator) – This is a random generator. Here we assume that we can call
rgen.rand() to draw random uniform numbers.
relative (list of floats) – These are the relative probabilities for the ensembles. We
assume here that these numbers are normalised.
Returns:
out[0] (integer) – The index of the path ensemble to shoot in.
out[1] (object like PathEnsemble) – The selected path ensemble for shooting.
Cut a directional segment from interface_l to interface_r.
It keeps what is within the range [interface_l interface_r)
AND the snapshots just after/before the interface.
Parameters:
path (object like PathBase) – This is the input path which will be trimmed.
interface_r (float) – This is the position of the RIGHT interface.
interface_l (float) – This is the position of the LEFT interface.
segment_to_pick (integer (n.b. it starts from 0)) – This is the segment to be selected, None = random
Returns:
segment (object like PathBase) – a path segment composed only the snapshots for which
orderp is between interface_r and interface_l and the
ones right after/before the interfaces.
The method cut a path and keeps only what is within the range
(interface_l interface_r).
-Be careful, it can provide multiple discontinuous segments-
=Be carefull2 consider if you need to make this check left inclusive
(as the ensemble should be left inclusive)
Parameters:
path (object like PathBase) – This is the input path which will be trimmed.
interface_r (float) – This is the position of the RIGHT interface.
interface_l (float) – This is the position of the LEFT interface.
Returns:
new_path (object like PathBase) – This is the output trimmed path.
Return the index of the scheduler worker this process is.
Returns:
out (integer or None) – The index set_worker_index() recorded in this process,
or None in a process that is no worker of a pool, the main
process of a run.
Resolve the engine time per step of a run and of its engine sections.
The simulation time per PyRETIS step (timestep*subcycles) is the
single factor that turns path lengths, counted in integration steps,
into times when computing fluxes and rates. The time step belongs to the
engine, so this module resolves it the same way for every engine: from
the engine section when present, otherwise from the engine’s own input
file – as PyRETIS does when it builds the engine.
A path-sampling run has one time per step: every engine section of the
run gives the same timestep*subcycles
(one_time_per_step_problem()). Under infinite swapping a path
held by one ensemble can have been generated by the engine of another
ensemble, and a zero swap builds a path from segments of two engines, so
the path lengths, counted in steps, convert to time with one time per
step only. The analysis converts with the time per step of [engine]
(engine_time_per_step()), which is then the time per step of
every engine section of the run.
The relative tolerance within which two time steps are one time step
(timesteps_agree()): a time step an engine section states and
the time step the engine takes from its own input, or the step sizes
of the integrators an OpenMM CompoundIntegrator holds.
The relative tolerance within which two times per step are one time
per step. A time step and a subcycle count whose products are equal
in exact arithmetic can give floats that differ in their last bits.
Return the simulation time per PyRETIS step from settings.
This is the engine timestep multiplied by its subcycles
(defaulting to 1) – the physical time between two recorded path
points, in the engine’s own time unit. It is the single factor used
to turn path lengths (counted in steps) into times when computing
fluxes and rates, so every analysis routine derives it the same way.
The time step belongs to the engine. When it is not present in the
[engine] settings (e.g. LAMMPS, which keeps it in the LAMMPS
input file), it is recovered from the engine’s own input file – as
PyRETIS does when it builds the engine – before giving up.
The value is the time per step of the [engine] section
(section_time_per_step()). A path-sampling run is refused
when two of its engine sections have different times per step
(one_time_per_step_problem()), and [engine] is one of
them, so for such a run the value is the time per step of every
engine section.
Parameters:
settings (dict) – The simulation settings, or a loaded run configuration. The
engine information is read from the engine section.
Returns:
float or None – timestep*subcycles, or None if the time step cannot be
determined from the settings or the engine input (so each caller
can decide whether that is an error or a reason to fall back to a
per-step quantity).
Return the refusal of an analysis whose [engine] has no time step.
The flux per unit time needs the time per step of [engine]
(engine_time_per_step()). The message says what the
analysed file lacks and how to give it. The analysis reads the
settings only: it imports no module of the run. For an OpenMM
[engine], the time step is the step size of the integrator of
the simulation, which the output.toml of a run records as
[engine]timestep
(pyretis.engines.run_temperature.resolve_run_temperature()).
Parameters:
settings (dict) – The settings the analysis reads.
Describe the engine sections of a run whose times per step differ.
Every engine section of a path-sampling run has one time per step,
timestep*subcycles (section_time_per_step()). Under
infinite swapping a path held by one ensemble can have been generated
by the engine of another ensemble, and a zero swap builds a path from
segments of two engines, so the path lengths, counted in steps,
convert to time with one time per step only. The engines may differ
in every other setting.
The time per step of a section is compared when it can be read: from
the timestep of the section, or from the input file of its engine
(LAMMPS lammps.in). Two times per step are one time per step when
they are equal within TIME_PER_STEP_RTOL. A section whose
time per step cannot be read takes no part in the comparison; when no
section’s time per step can be read, there is nothing to compare.
Parameters:
settings (dict) – The simulation settings, or a scheduler configuration, with the
engine sections.
sections (list of strings) – The engine sections of the run.
Returns:
string or None – The reason of the refusal, naming each section and its time per
step, when two sections have different times per step; None
when the sections whose time per step can be read have one.
Return the simulation time per PyRETIS step of an engine section.
This is the time step of the section (section_timestep())
multiplied by its subcycles, 1 when the section leaves it out:
the default the internal integrators and OpenMM run with. The other
engines of PyRETIS are built only from a section that states
subcycles.
Parameters:
settings (dict) – The simulation settings, or a scheduler configuration, with the
engine section.
section (string) – The engine section, e.g. "engine", "engine0" or
"engine1".
Returns:
float or None – timestep*subcycles, or None if the time step of the
section cannot be read.
Return the time step of an engine section, and where it is read.
The time step is the timestep of the section. For a section that
leaves it out, it is the time step of the engine’s own input file,
for the engines whose input file holds it (LAMMPS,
_engine_timestep_from_input()).
Parameters:
settings (dict) – The simulation settings, or a scheduler configuration, with the
engine section.
section (string) – The engine section.
Returns:
out[0] (float or None) – The time step, or None when the section states none and no
input file of its engine holds one.
out[1] (string or None) – Where the time step is read: "timestep" for the key of the
section, the path of the engine’s input file for a time step
read from it, and None when no time step is read.
Check a supplied time step against the engine’s own time step.
External engines own their time step in their own input file or
integrator, so an [engine]timestep is optional for them. When
one is supplied it must agree with the value the engine actually
uses – otherwise the simulation and the analysis would silently run
with different time steps. This fails loud on a mismatch and does
nothing when no time step is supplied.
Parameters:
given (float or None) – The time step from the [engine] settings, or None when it
was not supplied.
actual (float) – The time step the engine itself uses (read from its input file or
integrator).
engine_name (string) – Name of the engine, used in the error message.
Raises:
ValueError – If given is supplied and differs from actual
(timesteps_agree()).
It selects and displaces one particle randomly.
If the move is accepted, the new positions and energy are
returned. Otherwise, the move is rejected and the old positions
and potential energy is returned.
The function accept_reject is used to accept/reject the move.
Parameters:
rgen (object like RandomGenerator) – The random number generator.
system (object like System) – The system object to operate on
maxdx (float, optional) – The maximum displacement (default is 0.1).
idx (int, optional) – Index of the particle to displace. If idx is not given, the
particle is chosen randomly.
Returns:
out (boolean) – The outcome of applying the function accept_reject to the
system and trial position.
Accept/reject a energy change according to the metropolis rule.
FIXME: Check if metropolis really is a good name here.
Parameters:
rgen (object like RandomGenerator) – The random number generator.
system (object like System) – The system object we are investigating. This is used
to access the beta factor.
deltae (float) – The change in energy.
Returns:
out (boolean) – True if the move is accepted, False otherwise.
Notes
An overflow is possible when using numpy.exp() here.
This can, for instance, happen in an umbrella simulation
where the bias potential is infinite or very large.
This is ignored.
Calculate and return several “thermodynamic” properties as the
potential, kinetic and total energies per particle, the temperature,
the pressure and the momentum.
Calculate and return some thermodynamic properties. This method
is similar to the calculate_thermo, however, it is simpler and
calculates fewer quantities.
Return kinetic energy tensors for a particle selection.
Parameters:
particles (object like Particles) – This object represents the particles.
selection (list of integers, optional) – A list with indices of particles to use in the calculation.
Returns:
kin (numpy.array) – A numpy array with dimensionality equal to
(len(selection), dim, dim) where dim is the number of
dimensions used in the velocities. kin[i] contains the kinetic
energy tensor formed by the outer product of mol[selection][i]
and vel[selection][i]. The sum of the tensor should equal the
output from calculate_kinetic_energy_tensor.
Return the kinetic energy tensor for a selection of particles.
The tensor is formed as the outer product of the velocities.
Parameters:
particles (object like Particles) – This object represents the particles.
selection (list of integers, optional) – A list with indices of particles to use in the calculation.
Returns:
out (numpy.array) – The kinetic energy tensor. Dimensionality is equal to (dim, dim)
where dim is the number of dimensions used in the velocities.
The trace gives the kinetic energy.
Calculate and return several thermodynamic properties.
The calculated properties are the potential, kinetic and total
energies for the system and the current temperature. The name here
calculate_thermo_path just indicates that this function is
useful in connection with path sampling simulations, i.e. it
just calculates a few energy terms.
Parameters:
system (object like System) – This object is used to access the particles and the box.
Returns:
out (dict) – This dict contains the float that is calculated in this routine.
Return the kinetic temperature given velocities and masses.
This method does not work on a particle object, but rather with
numpy arrays. That is, it is intended for use when we can’t rely
on the particle object.
Parameters:
vel (numpy.array) – The velocities
mass (numpy.array) – The masses. This is assumed to be a column vector.
boltzmann (float) – This is the Boltzmann factor/constant in correct units.
dof (list of floats, optional) – The degrees of freedom to subtract. Its shape should
be equal to the number of dimensions.
kin_tensor (numpy.array optional) – The kinetic energy tensor. If the kinetic energy tensor is not
given, it will be recalculated here.
Returns:
out[0] (numpy.array) – It contains the temperature in each spatial dimension.
Array with the same size as the kinetic energy.
out[1] (float) – The temperature averaged over all dimensions.
Set the linear momentum of a selection of particles to zero.
Parameters:
particles (object like Particles) – This object represents the particles.
selection (list of integers, optional) – A list with indices of particles to use in the calculation.
dim (list or None, optional) – If dim is None, the momentum will be reset for ALL
dimensions. Otherwise, it will only be applied to the
dimensions where dim is True.
Returns:
out (None) – Returns None and modifies velocities of the selected
particles.
This module defines a class, representing a collection of particles.
The class for particles is, in reality, a simplistic particle list which
stores positions, velocities, masses etc. and is used for representing
the particles in the simulations.
This is a simple particle list. It stores the positions,
velocities, forces, masses (and inverse masses) and type
information for a set of particles. This class also defines a
method for iterating over pairs of particles, which could be
useful for implementing neighbour lists. In this particular
class, this method will just define an all-pairs list.
Variables:
npart (integer) – Number of particles.
pos (numpy.array) – Positions of the particles.
vel (numpy.array) – Velocities of the particles.
force (numpy.array) – Forces on the particles.
virial (numpy.array) – The current virial for the particles.
name (list of strings) – A name for the particle. This may be used as short text
describing the particle.
ptype (numpy.array of integers) – A type for the particle. Particles with identical ptype are
of the same kind.
dim (int) – This variable is the dimensionality of the particle list. This
should be derived from the box. For some functions, it is
convenient to be able to access the dimensionality directly
from the particle list. It is therefore set as an attribute
here.
vpot (float) – The potential energy of the particles.
ekin (float) – The kinetic energy of the particles.
A bolted-on config (a (filename,index) tuple) and its
velocity flag vel_rev are carried across the copy when
present. A plain internal Particles has neither. The
particles of a TurtleMD system
(pyretis.setup.createsystem) name the frame of a file
by config, which TurtleMDEngine.calculate_order reads,
and the velocities of the phase point are those of the frame,
negated when vel_rev is True
(pyretis.core.system_core.System.vel_rev puts the flag
on the particles). The copy is the same phase point, so it names
the same frame with the same flag. Both are carried copy-only,
like ParticlesExt.copy’s etot/temp, and are not in
_copy_attr, which with _numpy_attr lists the attributes a
restart file holds: load_restart_info requires each of them,
so an internal restart file without a config or a vel_rev
loads.
Returns:
out (object like Particles) – A copy of the current state of the particles.
This will delete all particles in the list and set other
variables to None.
Note
This is almost self.__init__ repeated. The reason for this is
simply that we want to define all attributes in self.__init__
and not get any ‘surprise attributes’ defined elsewhere.
Also, note that the dimensionality (self.dim) is not changed
in this method.
Particles that name the frame of a file by a bolted-on
config with a file name, as the particles of a TurtleMD
system do (see copy()), give the velocities of that
frame, negated when vel_rev is True. Their reversal toggles
vel_rev, so the frame and the flag give the reversed
velocities, and negates the velocities they hold in memory, if
any.
Return a copy of the particle state, including etot/temp.
The engine reports all four energy terms (vpot/ekin/
etot/temp) for every frame it actually propagates. Moves
that do NOT re-run the engine – time reversal and swaps – reuse
those frames, so the copy must carry the energies forward. The
base copy preserves vpot/ekin (they are in
_numpy_attr) but not the derived etot/temp, which
would otherwise be lost and written as nan in the path
energy file. They are carried here (copy-only) and are not in
_copy_attr/_numpy_attr, the attributes a restart file
holds: load_restart_info requires each of those, so a
restart file without etot/temp loads.
Returns:
out (object like ParticlesExt) – A copy of the current state, carrying etot/temp when
the engine has set them.
This will copy the input positions, for this class, the
input positions are assumed to be a file name with a
corresponding integer which determines the index for the
positions in the file for cases where the file contains
several snapshots.
Parameters:
pos (tuple of (string, int)) – The positions to set, this represents the file name and the
index for the frame in this file.
The fewest phase points a path needs to be usable by interior-frame
shooting. get_shooting_point draws from [1,length-2], so a
shorter path has no frame that can be selected: the range is empty and
numpy raises. Three is VALID – it has exactly one interior frame.
A path where the full trajectory is stored in memory.
This class represents a path. A path consists of a series of
consecutive snapshots (the trajectory) with the corresponding
order parameter. Here we store all information for all phase points
on the path.
This will simply draw a shooting point from the path at
random. All points can be selected with equal probability,
except the end points which are not considered.
Parameters:
criteria (string, optional) – The criteria to select the shooting point:
‘rnd’: random, except the first and last point, standard sh.
‘exp’: selection towards low density region.
interfaces (list/tuple of floats, optional) – These are the interface positions of the form
[left,middle,right].
rgen (object like RandomGenerator, optional) – Random generator to draw from. When omitted the path’s
own self.rgen is used; the moves pass one in
explicitly.
Returns:
out[0] (object like System) – The phase point we selected.
info (dict) – The dictionary with the restart information, similar to the
dict produced by restart_info().
forcefield (object like ForceField, optional) – Force field to attach to each restored phasepoint. The
force field is not serialised as part of the restart info,
so it must be supplied by the caller (typically taken from
the owning ensemble’s system).
This class represents a path. A path consists of a series of
consecutive snapshots (the trajectory) with the corresponding order
parameter.
Variables:
generated (tuple) – This contains information on how the path was generated.
generated[0] : string, as defined in the variable _GENERATED
generated[1:] : additional information:
For generated[0]=='sh' the additional information is the
index of the shooting point on the old path, the new path and
the corresponding order parameter.
maxlen (int) – This is the maximum path length. Some algorithms require this
to be set. Others don’t, which is indicated by setting maxlen
equal to None.
ordermax (tuple) – This is the (current) maximum order parameter for the path.
ordermax[0] is the value, ordermax[1] is the index in
self.path.
ordermin (tuple) – This is the (current) minimum order parameter for the path.
ordermin[0] is the value, ordermin[1] is the index in
self.path.
phasepoints (list of objects like System) – The phase points the path is made up of.
rgen (object like RandomGenerator) – This is the random generator that will be used for the
paths that required random numbers.
time_origin (int) – This is the location of the phase point path[0] relative to
its parent. This might be useful for plotting.
status (str or None) – The status of the path. The possibilities are defined
in the variable _STATUS.
weight (real) – The statistical weight of the path.
Return the external-configuration addresses on the path.
Collects the file address (config[0]) of every phasepoint
that carries a real external configuration. Phasepoints with no
external config – internal-engine paths where config is
None or the empty default ('',-1) – are skipped, so
this never raises on an in-memory path. Used by the
infinite-swapping scheduler for trajectory-file housekeeping
(it drives os.remove in repex); it is never part of
any numeric or bit-level output.
Return an empty path of same class as the current one.
This function is intended to spawn sibling paths that share some
properties and also some characteristics of the current path.
The idea here is that a path of a certain class should only be
able to create paths of the same class.
Frames the move that produced this path obtained by fresh
integration. A product that integrated nothing keeps its
source’s move code, so an initialisation path stays one.
Return the per-ensemble High-Acceptance weight vector.
The per-ensemble output divides the occupancy of a path by it,
the WHAM Cxy/HA unweighting
(pyretis.inout.pathensemble_output). Defaults to
weights when it was never set explicitly: the cv vector of
pyretis.core.moves.calc_cv_vector(), which holds the
compute_weight crossing count of a wf or mwf ensemble, and of
an ss ensemble with [tis]high_accept.
The state the order function measured this path with – for a
permeability order parameter, the molecule it tracks and
whether its coordinate is mirrored – as the order function’s
restart_info() gives it. A target swap or a mirror changes
that state, so it belongs to the path and travels with it
between ensembles. None means the order function’s
configured (home) state.
Reverse a path and return the reverse path as a new path.
This will reverse a path and return the reversed path as
a new object like PathBase object.
Parameters:
order_function (object like OrderParameter, optional) – The method to use to re-calculate the order parameter,
if it is velocity dependent.
rev_v (boolean, optional) – If True, also the velocities are reversed, if False, the velocities
for each frame are not altered.
engine (object like EngineBase, optional) – The engine to evaluate a velocity-dependent order parameter
through. Required whenever the phase points are file-backed
(see evaluate_order()); harmless otherwise.
Returns:
new_path (object like PathBase) – The time reversed path.
The check is based on the maximum order parameter and the value
of target_interface. It is successful if the maximum order parameter
is greater than target_interface.
Parameters:
target_interface (float) – The value for which the path is successful, i.e. the
“target_interface” interface.
Returns the first element of weights, or 1.0 when
weights is empty. The scalar property serves callers
that read path.weight; the weights are stored in the
weights tuple.
The infinite-swapping scheduler stores a tuple of per-ensemble
weights here (pyretis.core.moves.calc_cv_vector()).
Single-ensemble callers can use weight, which is the
scalar projection of this tuple.
Raised when a path with no interior frame reaches the sampler.
Carries, besides the message, the evidence needed to explain the
failure afterwards: the offending path, where it came from, and the
ensemble it was being used in.
Variables:
path (object like PathBase) – The offending path, kept intact.
ens_name (string) – The ensemble the path was being used in.
interfaces (tuple of floats) – The ensemble’s interfaces.
origin (string) – Where the path came from: ‘loaded’, ‘occupant’ or ‘generated’.
shooting_point (object like System or None) – The phase point the trial was shot from, when there was one. Only
an origin of 'generated' has one: the ‘loaded’ and
‘occupant’ stops happen BEFORE any point is drawn, and reporting a
point there would be inventing evidence.
shooting_index (integer or None) – The index that point was drawn from in the parent path, same
condition. Together with the parent’s length it says whether the
draw was in the interior at all.
engine_name (string or None) – The engine’s description. The identity is stored as text, not
as the engine, because this error is raised inside a worker and
has to survive being sent back across the process boundary.
scratch_dir (string or None) – The engine’s working directory at the moment of the stop – where
the trial’s own trajectories and the post-kick state are. It is
SCRATCH: the next run of the same ensemble overwrites it, so the
report of the stop renames the directory to keep it.
rng_state (dict or None) – The ensemble generator’s bit-generator state at the stop, so the
draw can be replayed. Captured as a plain dict because this
error crosses the worker process boundary.
parent_length (integer or None) – The length of the path the shooting point was drawn FROM. On its
own shooting_index cannot say whether the draw was interior;
with this it can.
point_in_window (boolean or None) – Whether the shooting point was inside the ensemble window when
the stop happened, or None when there was no point to test. This
is the single most diagnostic fact about a short success: a leg
returns one frame precisely when its starting point is already
outside, so False here names the cause outright.
Check if we have crossed an interface during the last step.
This function is useful for checking if an interface was crossed
from the previous step till the current one. This is for instance
used in the MD simulations for the initial flux.
It will use a variable to store the previous positions with respect
to the interfaces and check if interfaces were crossed here.
Parameters:
cycle (int) – This is the current simulation cycle number.
orderp (float) – The current order parameter.
interfaces (list of floats) – These are the interfaces to check.
leftside_prev (list of booleans or None) – These store the previous positions with respect
to the interfaces.
Returns:
leftside_curr (list of booleans) – These are the updated positions with respect to the interfaces.
cross (list of tuples) – If a certain interface is crossed, a tuple will be added to this
list. The tuple is of form
(cycle number, interface number, direction)
where the direction is ‘-’ for a crossing in the negative
direction and ‘+’ for a crossing in the positive direction.
Return True if a path an ensemble holds is an initialisation path.
A path is an initialisation path when its move is one of
INITIAL_MOVES. In a run that does not record each
attempt’s MD, an MD-free move of a held initialisation path is that
path too: such a run writes a time reversal of a kicked path as
tr and a null move of it as 00, although no dynamics were run
and the frames are the kicked ones. A run that records its MD needs
no such inference, because its writer keeps the source’s code on a
product that integrated nothing. The crossing analysis
(pyretis.analysis.path_analysis) and the path-data matrix
of the WHAM analysis
(pyretis.inout.pathensemble_output.reconstruct_path_data_matrix())
leave out the rows of the initialisation paths by this rule.
Parameters:
move (string) – The move that generated the path.
held_initial (boolean) – Whether the path the ensemble held before this one is an
initialisation path.
labels_recorded (boolean) – Whether the run records each attempt’s MD in moves.txt, and
so labels every product by what its move integrated.
Returns:
out (boolean) – True when the path is an initialisation path.
A phase point comes in two flavours. An in-memory one carries its
own particles, so the order function reads the positions and
velocities straight off it. A file-backed one
(_is_file_backed()) – what the infinite-swapping scheduler
works with, and what an external engine builds in the in-process
initiation – names its frame by config, the trajectory file
and frame index, and the coordinates only exist on disk. Handing
such a phase point to an order function that touches system.pos
or system.vel yields a bare TypeError on None.
Reading the frame back takes one of two routes, and which one is
correct depends on the engine.
A streaming internal engine (it has _materialize_system) owns
what the stored frame does not carry – the box, the masses, the
force field – so only it can rebuild a usable system from its own
frames, and its calculate_order honours the frame index and the
vel_rev flag. Every other engine’s calculate_order reads the
FIRST snapshot of config[0] and ignores the frame index (see
pyretis.engines.external), which for a phase point inside a
multi-frame trajectory is the wrong frame – so those are read BY
FORMAT through pyretis.tools.recalculate_order(), which
understands frame indices and velocity flipping for every trajectory
format the engines write. The frame index of a frame of a LAMMPS dump
is its time step
(pyretis.tools.recalculate_order.lammpstrj_timesteps()).
Parameters:
order_function (object like OrderParameter) – The order parameter to evaluate.
phasepoint (object like System) – The phase point to evaluate it on.
engine (object like EngineBase, optional) – Reads the frame back for a file-backed phase point.
Returns:
out (list of floats) – The order parameter value(s) for this phase point.
Raises:
ValueError – If the phase point is file-backed and no engine is given, if it
names no file, or if its file holds no frame at its index.
out (boolean) – True when the path has at least one interior frame.
Note
This is a question about the SAMPLER, not about the ensemble. A path can
satisfy its ensemble’s interface conditions and still have no interior
frame, in which case no shooting move can proceed from it.
Merge a backward with a forward path into a new path.
The resulting path is equal to the two paths stacked, in correct
time. Note that the ordering is important here so that:
paste_paths(path1,path2)!=paste_paths(path2,path1).
There are two things we need to take care of here:
path_back must be iterated in reverse (it is assumed to be a
backward trajectory).
we may have to remove one point in path2 (if the paths overlap).
Parameters:
path_back (object like PathBase) – This is the backward trajectory.
path_forw (object like PathBase) – This is the forward trajectory.
overlap (boolean, optional) – If True, path_back and path_forw have a common
starting-point, that is, the first point in path_forw is
identical to the first point in path_back. In time-space, this
means that the first point in path_forw is identical to the
last point in path_back (the backward and forward path
started at the same location in space).
maxlen (float, optional) – This is the maximum length for the new path. If it’s not given,
it will just be set to the largest of the maxlen of the two
given paths.
Note
Some information about the path will not be set here. This must be
set elsewhere. This includes how the path was generated
(path.generated) and the status of the path (path.status).
Return the human-readable description of a path status code.
The status codes name the path property that broke (wrong end
interface, too long, no crossing with the middle interface, …);
the run log decodes them through this helper so a rejection is
readable without the status-code table at hand.
Parameters:
status (string) – A path status code (a key of _STATUS, e.g. 'BTL').
Returns:
out (string) – The description, or 'Unknownstatus' for a code this
version does not know.
Load infinite-swapping paths from disk into Path objects.
The loaders build pyretis.core.path.Path objects whose
phasepoints are file-backed snapshot System objects (the
external-engine representation), exactly as the infinite-swapping
scheduler expects.
Raise when the recomputed progress coordinate has moved.
Recomputation is meant to FILL IN collective variables, leaving the
progress coordinate (order[0], the quantity the interfaces are
defined on) as sampled. If it changed, the main order parameter
itself was edited, and the loaded paths belong to different
ensembles from the ones this run defines – continuing would
mix two different reaction coordinates in one data set.
The whole path is checked before ANY phase point is updated, so a
rejected restart leaves the loaded paths untouched.
Return the trajectory frame a configuration index names.
An engine names the frames of its trajectory files by configuration
indices (_frame_config_index, frame to index); an engine without
a rule names each frame by its frame number. The frames read back
here are numbered by frame, so the index is mapped back through the
engine’s own rule. A frame of a LAMMPS dump is named by its time
step instead, which _config_frames() reads from the dump.
Parameters:
engine (object like EngineBase) – The engine that wrote the trajectory.
config_index (integer or None) – The configuration index of a phase point (config[1]); None
names the first frame.
Returns:
out (integer) – The frame number.
Raises:
ValueError – If the index lies before the first frame or between two frames
of the engine’s rule.
Return the trajectory frame each configuration index of a file names.
A frame of a LAMMPS dump (.lammpstrj) is named by its time step,
whichever engine wrote the dump, so the frame of an index is the
frame of that time step in the dump
(pyretis.tools.recalculate_order.lammpstrj_frame_numbers()).
A frame of another format is named by the engine’s rule
(_config_frame()).
Parameters:
engine (object like EngineBase) – The engine that wrote the trajectory.
filename (string) – The trajectory file.
config_indices (list of integers or None) – The configuration index of each phase point stored in the file.
Returns:
out (list of integers) – The frame number of each configuration index.
Raises:
ValueError – If an index names no frame of the file: a time step that no
frame of the LAMMPS dump has, or an index outside the rule of
the engine.
Order-parameter values for a list of file-backed phase points.
There are two ways to read a stored frame back, and which one applies
depends on the engine.
An internal (streaming) integrator owns the information the stored
frame does NOT carry – the box, the masses, the force field – so
only it can rebuild a usable system from an .xyz whose header says
the box is zero. It provides streaming_orders, which is also the
batch route: each trajectory file is read once rather than once per
frame.
Every other engine writes a self-describing trajectory, and those are
read by format rather than by engine
(pyretis.tools.recalculate_order.recalculate_order() covers
.trr, .xtc, .xyz, .gro, .g96, .lammpstrj and
the ASE .traj).
This route is required: a GROMACS phase point points INTO a binary
.trr at a frame index, which the engine’s own single-configuration
reader cannot parse at all.
Parameters:
phasepoints (list of objects like System) – The file-backed phase points to evaluate.
order_function (object like OrderParameter) – The order parameter configured for THIS run.
engine (object like EngineBase) – The engine for reading the frames back.
Returns:
out (list of lists of floats) – One order-parameter list per phase point, in input order.
Read the frames back by trajectory format and evaluate them.
Each distinct file is read once, and once more when the order
parameter reads the velocities AND some frame of that file is stored
time-reversed (the two passes differ only in the sign of the
velocities). A phase point’s configuration index names its frame by
its time step in a LAMMPS dump and by the engine’s rule in the other
formats (_config_frames()); without an engine it is the
frame number of a frame of another format. A frame that records no
cell is evaluated in the engine’s cell
(EngineBase.frame_cell()).
Group the phase points of a path by the file that holds them.
Parameters:
phasepoints (list of objects like System) – The file-backed phase points of a path.
Returns:
out (list of tuples of (string, list of integers)) – For each file, in the order the path first reaches it, its name
(config[0]) and the positions in phasepoints of the
phase points it holds, in path order.
Report interior frames lying outside the ensemble window.
A path is the segment between the two interface crossings that
bound it. The sampler builds one that way: add_to_path stops on
the frame that leaves [left,right], so only the first and last
frames sit outside and every interior frame is within. A loaded path
carrying interior frames outside the window is a longer trajectory
that was not cut at its first exit – it re-enters after leaving,
and the excursions it contains belong to neighbouring windows.
Accepting one gives the ensemble an occupant whose crossing
statistics describe a different region than the window it is filed
under.
Convert one repr-formatted move-tuple token to its scalar value.
Parameters:
token (str) – A single, already-stripped element of the move tuple, e.g.
"'sh'", "-0.2478", "2" or "nan".
Returns:
object – The string (quotes removed), float or int the token represents.
Integers keep their int type so the recovered tuple’s repr
matches the persisted one exactly.
Widen (or narrow) a loaded path’s order data to new_width.
The values already recorded are KEPT, byte for byte; only the
columns beyond them are taken from the recompute. This is what makes
adding a collective variable a pure observation.
The reason is precision. order.txt holds the values the sampler
used: the scheduler’s archive writes them at full float64 precision
(pyretis.inout.scheduler_archive.SchedulerOrderPathFormatter).
A value re-derived from the frame is computed from the coordinates
its trajectory file stores, at the precision of that format, and can
differ in its last digits – enough to flip an interface
comparison, change an acceptance, and send the continuation down a
different trajectory than an identical run without the new
collective variable. Keeping the stored column means the sampling
continues bit for bit as it would have.
Existing collective variables are matched to the new ones BY
POSITION: a run that appends collective variables gets exactly what
it asks for, while one that reorders them keeps the old values under
the new names. The main order parameter, which is the one that
matters for the sampling, is verified.
Parameters:
path (object like Path) – The loaded path whose phase points are updated in place.
order_function (object like OrderParameter) – The order parameter configured for THIS run.
new_width (int) – The number of values the order function produces.
engine (object like EngineBase) – The engine for reading the frames back.
is_restart (boolean, optional) – See align_order_width(). On a load a moved progress
coordinate is adopted rather than refused, and the recomputed
value REPLACES the stored one – keeping the stored column would
leave the path carrying a coordinate this run does not use.
Refuse a restart whose order parameter moves the stored values.
Every frame of each path is evaluated with the order parameter of
the restart, and the value of the progress coordinate each stores
(order[0]) is compared with the evaluated one, within the
tolerance of _check_main_order()
(_main_order_tolerance()), as on a restart that changes
the number of order values. Each path is evaluated in the state of
the order function it was measured with (order_state, for a
permeability order parameter the molecule it tracks and whether it
is mirrored), and the order function is given back the state it was
configured with.
A changed order parameter (another class, setting or module) that
keeps the number of order values otherwise continues on stored
values of another coordinate, also when it moves only the frames
between the ends of a path. The frames of a file that cannot be
read back (the reading errors of align_order_width()) are
not compared, with a warning that names the path, its directory and
the file; the frames of the other files of the path are compared.
Parameters:
paths (list of objects like Path) – The paths the restart reads, in the order of [current]active; None for a slot without a path.
order_function (object like OrderParameter) – The order parameter configured for the restart.
engine (object like EngineBase) – The engine for reading the frames back.
path_dirs (list of strings, optional) – The directory each path was read from, in the order of
paths, which the refusal and the warning name with the
path. None names the path by its number only.
Raises:
ValueError – If the evaluated progress coordinate of a frame of a path
differs from the stored one by more than the tolerance. The
message names the path, its directory, the frame and both
values.
Evaluate every frame of a path that a restart reads.
The path is evaluated in the state of the order function it was
measured with, which travels with it ([current]order_state); a
path without one was measured in the configured state. The order
function is given back the configured state after the path.
The frames are evaluated file by file, each file read once
(_file_frame_groups()). A file whose frames cannot be read
back (the reading errors of align_order_width()) is named
in a warning, and the frames of the other files are evaluated.
Parameters:
path (object like Path) – The path, with at least one phase point.
label (string) – The path as the warning names it (_path_label()).
order_function (object like OrderParameter) – The order parameter configured for the restart.
engine (object like EngineBase) – The engine for reading the frames back.
home (object or None) – The state the order function was configured with
(restart_info); None for an order function measured in one
state.
Returns:
out (list of (lists of floats or None)) – The order values of each frame, in the order of the phase
points; None for a frame of a file that cannot be read back.
Match the loaded order data to the configured order function.
A simulation may gain (or lose) collective variables between runs:
the order.txt of the paths being resumed then holds a different
number of columns than the configured order function produces.
The loaded paths are then re-evaluated here, so that they are written
at the configured width like every newly sampled path, and the change
is reported: the frames are on disk, and the order parameter is a
deterministic function of a frame, so the missing collective
variables are recovered exactly. Where the frames are re-evaluated,
the progress coordinate is checked against its stored value
(_check_main_order()), so adding a collective variable
keeps it where it was.
Every loaded path is compared with the configured width, so the
paths are aligned the same way whatever their order in the active
list. A RESTART whose paths all carry the configured width has
every frame of every path evaluated and its progress coordinate
compared with the stored one
(_refuse_moved_restart_orders()), so a changed order
parameter that keeps the column count is refused, and then ends the
call, which is every ordinary continuation: the order.txt of a live
path holds the values the run sampled it with, for the initial paths
of a load as well (see write_path_orders()). On a LOAD the
frames are always re-evaluated: a load may change parameters, and a
changed cutoff or formula keeps the column count, so the recomputed
values are what describe this run’s coordinate.
Parameters:
paths (list of objects like Path) – The paths just loaded from disk; updated in place.
order_function (object like OrderParameter) – The order parameter configured for THIS run, or None when the
configuration carries no [orderparameter] section because
the engine produces the order values itself.
engine (object like EngineBase) – The engine for reading the frames back.
is_restart (boolean, optional) – True when this run CONTINUES an existing one. A restart must
preserve the coordinate its paths were sampled with, so a moved
progress coordinate is fatal there. A load starts a new
calculation and may change parameters, so the recomputed value
is adopted and reported instead. Defaults to the strict
reading.
path_dirs (list of strings, optional) – The directory each path was read from, in the order of
paths, which a refusal of a restart names with the path
(_refuse_moved_restart_orders()). None names the path
by its number only.
Returns:
out (boolean) – True when the paths were recomputed.
config (dict) – The scheduler config; [current]active lists the paths.
Returns:
out (list of objects like Path) – The paths, in the order of [current]active.
Raises:
FileNotFoundError – If the load is a load of the flat store and the staged directory
of an active path is missing. The message names every missing
directory, and the check comes before the first path is read.
ValueError – If a resume of a run with an OpenMM engine reads a path in
which two phase points name one frame while their order
parameters differ (refuse_reused_frame_openmm_path()).
Refuse a resume whose stored LAMMPS order values its frames move.
PyRETIS evaluates the order parameter of a LAMMPS frame on the
unwrapped positions of its atoms from the lower bounds of its box
(pyretis.engines.lammps_steps.lammps_order_positions()). A
path stored by a run that evaluated them on other positions, as an
earlier version of PyRETIS did, holds order values of another
coordinate. Every frame of each path that the resume reads is
evaluated, and each order value it stores is compared with the value
of its frame: a resume that would sample on the stored values
against interfaces of the evaluated ones is refused.
Parameters:
paths (list of objects like Path) – The paths that the resume reads, as
load_paths_from_disk() returns them; None for an
ensemble without a path.
order_function (object like OrderParameter) – The order parameter configured for the run.
engine (object like LAMMPSEngineSteps) – The LAMMPS engine of the run, which evaluates the order parameter
of its frames (order_mode="pyretis").
Raises:
ValueError – If a frame cannot be read, or if an order value that a path
stores differs from the value of its frame by more than
LAMMPS_RESTORED_ORDER_TOLERANCE.
Refuse a stored OpenMM path in which one frame has two orders.
Each phase point of a path the OpenMM engine stores names the frame
of its own MD step (OpenMMEngine.propagate()). A frame
holds one configuration, so two rows of traj.txt that name the
same (file,index,vel_rev) name phase points of one order
parameter. Two such rows whose main order parameters in
order.txt differ name, for one of them, the frame of another
phase point: an OpenMM path stored by an earlier version of PyRETIS,
which named the frame a leg started from for every phase point of
the leg. A resume would read that frame for each of them.
Parameters:
path (object like Path) – The path, as load_path() reads it.
pdir (string) – The directory the path was read from.
Raises:
ValueError – If two phase points name one (file,index,vel_rev) and
their main order parameters differ.
Raise when a loaded path does not satisfy an ensemble window.
The start must satisfy the ensemble’s start_cond and the path
must end at an interface. The middle-interface crossing is only
required where it is an OCCUPANT invariant, as in the sampler’s own
shoot: for the single-sided positive windows (where a
non-crossing path can only mean mis-staged input) – there it catches
a path staged into the wrong ensemble that the start/end checks alone
would accept – and for the positive windows of a partial-path run,
which carry must_cross_M, unless [tis]enforce_must_cross_m
is false. It is not required for the other windows whose paths may
start at either end (start_cond covering both L and R:
the permeability [0^-] window, and the partial-path windows when
enforce_must_cross_m is false) – shoot skips the crossing
check there too (“paths that can start everywhere”), so LL/RR
occupants are legitimate. The middle of the right-starting [0^-]
window is lambda_0, which each of its paths crosses.
Write the order values of loaded paths into their order.txt.
A load evaluates the order parameter of its initial paths from their
frames (align_order_width()) and samples with those
values. The order.txt in a path’s archive directory is what a
restart reads the path’s values from
(load_paths_from_disk()), so the evaluated values are
written there in the format of the scheduler’s archive,
pyretis.inout.scheduler_archive.SchedulerOrderPathFormatter,
at full float64 round-trip precision (the {:>26.17e} format). A restart
then restores them bit for bit and applies its rules to them as to
every path the run sampled.
The archive directory of a path is <ensemble>/<load_dir>/<pn>
of its birth ensemble. A path read from a directory the user staged
flat, <load_dir>/<pn>, is first copied there
(pyretis.inout.staged_paths.archive_dirs()), and the
values are written into the copy. The flat directory keeps its
files and bytes.
Each file is swapped into place by
pyretis.inout.common.atomic_write(), so a staged
order.txt hard-linked to a copy elsewhere leaves that copy with
its content.
Parameters:
config (dict) – The scheduler config. It locates the directory each path was
read from, as in load_paths_from_disk(), and
[current]cstep is the cycle the block comment records.
paths (list of objects like Path) – The loaded paths, carrying the order values the run samples
with; None entries are skipped.
birth_ensembles (dict, optional) – The birth ensemble of each path, keyed by its path number as a
string; it names the path’s archive directory. The default is
[current]ens_save_idx.
Returns:
out (list of int) – The sorted path numbers whose order.txt was written.
Raises:
ValueError – If the birth ensemble of a path is not known: birth_ensembles
does not name the path, or, by default, [current]ens_save_idx records none for it.
FileExistsError – If a staged path has an archive directory already.
Either is raised before the first file is written.
The layout with both optional windows, the minus window and the
[0^+], as (has_minus, has_zero_plus). Every task other than
pptis builds it (pyretis.inout.checker.pptis_layout()).
This class represents a collection of paths in a path ensemble.
In general, paths may be “long and complicated” so here, we really
just store a simplified abstraction of the path, which is obtained
by the Path.get_path_data() function for a given Path object.
The returned dictionary is stored in the list PathEnsemble.paths.
The only full path we store is the last accepted path. This is
convenient for the RETIS method where paths may be swapped between
path ensembles.
Variables:
ensemble_number (integer) – This integer is used to represent the path ensemble, for RETIS
simulations it’s useful to identify the path ensemble. The path
ensembles are numbered sequentially 0, 1, 2, etc. In the full
layout this corresponds to [0^-], [0^+], [1^+],
etc.; a layout without the minus window or the [0^+]
numbers only the windows it holds (ensemble_label()).
ensemble_name (string) – A string which can be used for printing the ensemble name.
This is of form [0^-], [0^+], [1^+], etc., and it
names the role of the ensemble in its layout
(ensemble_label()).
ensemble_name_simple (string) – A string with a simpler representation of the ensemble name,
can be used for creating output files etc.
interfaces (list of floats) – Interfaces, specified with the values for the
order parameters: [left, middle, right].
paths (list) – This list contains the stored information for the paths. Here
we only store the data returned by calling the get_path_data()
function of the Path object.
nstats (dict of ints) –
This dict store some statistics for the path ensemble. The keys
are:
npath : The number of paths stored.
nshoot : The number of accepted paths generated by shooting.
ACC, BWI, … : Number of paths with given status (from _STATUS).
maxpath (int) – The maximum number of paths to store.
last_path (object like PathBase) – This is the last accepted path.
ensemble_number (integer) – An integer for identifying the ensemble: its number in
layout.
interfaces (list of floats) – These are the interfaces specified with the values
for the order parameters: [left,middle,right].
rgen (object like RandomGenerator, optional) – The random generator that will be used for the
paths that required random numbers.
maxpath (integer, optional) – The maximum number of paths to store information for in memory.
Note, that this will not influence the analysis as long as
you are using the output files when running the analysis.
exe_dir (string, optional) – The base folder where the simulation was executed from.
This is used to set up output directories for the path
ensemble.
layout (tuple of boolean, optional) – Whether the layout that ensemble_number counts in
includes the minus window and the [0^+] window, as
pyretis.inout.checker.pptis_layout() gives them.
The layout decides the role the number names, and with it
the ensemble_name and the start_condition. The
default is the full layout, which includes both windows.
This will add the data from a given path to the list path data
for this ensemble. It will also update self.last_path if the
given path is accepted.
Parameters:
path (object like PathBase) – This is the object to store data from.
status (string) – This is the status of the path. Note that the path object
also has a status property. However, this one might not be
set, for instance when the path is just None. We therefore
use status here as a parameter.
The acceptance rate is obtained as the fraction of accepted
paths to the total number of paths in the path ensemble. This
will only consider the paths that are currently stored in
self.paths.
This function will return an iterator useful for iterating over
accepted paths only. In the path ensemble we store both accepted
and rejected paths. This function will loop over all paths
stored and yield the accepted paths the correct number of times.
Yield the different paths stored in the path ensemble.
It is included here in order to have a simple compatibility
between the PathEnsemble object and the
PathEnsembleFile object. This is useful for the
analysis.
Yields:
out (dict) – This is the dictionary representing the path data.
info (dict) – A dictionary with the restart information.
cycle (integer, optional) – The current simulation cycle.
forcefield (object like ForceField, optional) – Force field to attach to the phasepoints of the restored
path. The force field is not part of the serialised restart
info, so it must be supplied by the caller.
Return the label that names an ensemble by its role in a layout.
A layout numbers the windows it holds from 0, in the order
[0^-], [0^+], [1^+], [2^+], … The full layout
holds the minus window and the [0^+]: there number 0 is the
[0^-] and number n is the [(n-1)^+]. A pptis
layout can also hold neither of the two, or the [0^+] alone
(pyretis.inout.checker.pptis_layout()), and its numbers
count only the windows it holds. The label [i^+] names the
window whose middle interface is lambda_i.
Parameters:
ensemble_number (int) – The number of the ensemble in its layout.
has_minus (boolean) – Whether the layout includes the minus window.
has_zero_plus (boolean) – Whether the layout includes the [0^+] window.
Returns:
out (string) – The label: [0^-] for the minus window, and [i^+] for
the window whose middle interface is lambda_i.
A generic numerical value with standard deviation and average.
A generic object to store values obtained during a simulation.
It will maintain the mean and variance as values are added using
Property.add(val)
Variables:
desc (string) – Description of the property.
nval (integer) – Number values stored.
mean (float) – The current mean.
delta2 (float) – Helper variable used for calculating the variance.
variance (float) – The current variance
val (list) – Store all values.
Parameters:
desc (string, optional) – Sets the attribute desc.
Examples
>>> frompyretis.core.propertiesimportProperty>>> ener=Property(desc='Energy of the particle(s)')>>> ener.add(42.0)>>> ener.add(12.220)>>> ener.add(99.22)>>> ener.mean
It derives the random number procedures from numpy.random: it defines
a class which uses RandomState (MT19937) and a class which uses
Generator (PCG64, the default) to generate pseudo-random numbers.
This class represents a random generator that can be used for
testing algorithms. It will simply return numbers from a
small list of pseudo-random numbers. This class is only useful
for testing algorithms on different systems. It should NEVER
be used for actual production runs!
a (1-D array-like or int) – If an ndarray, a random sample is generated from its
elements. If an int, the random sample is generated as if
a were np.arange(a).
size (int or tuple of ints, optional) – Output shape. Default is None, in which case a single
value is returned.
replace (boolean, optional) – Whether the sample is with or without replacement.
p (1-D array-like, optional) – The probabilities associated with each entry in a. If not
given the sample assumes a uniform distribution over all
entries in a.
Returns:
choice (any or numpy.array) – The generated random samples.
Note
This is part of a mock generator and uses the pre-defined
sequence to make choices.
This is an attempt on speeding up the call of
RandomState.multivariate_normal if we need to call it over and
over again. Such repeated calling will do an SVD repeatedly,
which is wasteful. In this function, this transform can be
supplied and it is only estimated if it’s not explicitly given.
Parameters:
mean (numpy array (1D, 2)) – Mean of the N-dimensional array
cov (numpy array (2D, (2, 2))) – Covariance matrix of the distribution.
cho (numpy.array (2D, (2, 2)), optional) – Cholesky factorization of the covariance. If not given,
it will be calculated here.
size (int, optional) – The number of samples to do.
Returns:
out (float or numpy.array of floats size) – The random numbers that are drawn here.
loc (float, optional) – The mean of the distribution.
scale (float, optional) – The standard deviation of the distribution.
size (int or tuple of ints, optional) – Output shape. Default is None, which returns a single
value.
Returns:
out (float or numpy.array) – The generated “random” numbers.
Note
This is part of a mock generator and does NOT provide a true
normal distribution. It simply returns values from the
pre-defined sequence, shifted by loc-0.5 if
norm_shift is enabled.
shape (int, optional) – The number of numbers to draw. Default is 1.
Returns:
out (numpy.array) – The pseudo-random numbers in [0, 1).
Note
This method draws numbers from a pre-defined sequence
(starting with 0.78008018) to ensure deterministic behavior
during testing. If the end of the sequence is reached, it
wraps around to the beginning.
A random generator backed by numpy.random.Generator (PCG64).
PCG64 is the bit generator of numpy’s default_rng and the one
the infinite-swapping sampler uses, so a run configured with
rgen="pcg64" draws the same byte stream as the
infinite-swapping code from the same seed.
create_random_generator() builds this generator when the
settings name no rgen (DEFAULT_GENERATOR). The state
dict produced by get_state() carries the PCG64
bit_generator.state dict rather than the MT19937 tuple of
RandomGenerator (rgen="rgen"), and is tagged
rgen="pcg64".
pyretis.core._compat.SharedRNG is the test-scoped sibling
that tags its state rgen="shared"; it subclasses this class so
there is a single PCG64 implementation.
Variables:
seed (int) – The seed for creating the generator (bookkeeping only when an
explicit generator is injected).
rgen (numpy.random.Generator) – The underlying PCG64 generator; all draws come from it.
seed (int, optional) – Seed for a freshly created PCG64 Generator when no
generator is supplied.
generator (numpy.random.Generator, optional) – Inject a pre-constructed Generator (e.g. one obtained
from SeedSequence.spawn() for per-worker streams). When
given, seed is recorded for bookkeeping only – the
generator’s own state is the source of truth.
Return a serialisable snapshot of the generator state.
The shape mirrors RandomGenerator.get_state()
({'seed':...,'state':...,'rgen':...}) so callers that
persist the dict do not special-case this generator. state
holds the PCG64 bit_generator.state dict.
Draw samples from a multivariate normal via Cholesky.
Re-uses the trick from
RandomGenerator.multivariate_normal(): when the Cholesky
factor of cov is reused across many draws, skip the SVD that
Generator.multivariate_normal would do.
The underlying Generator, for callers of the numpy API.
Code that calls rgen.random() / rgen.integers() /
rgen.choice() or reads rgen.bit_generator.state directly
should be handed this object; it draws from the same stream as
the RandomGeneratorBase surface on self.
shape may be an int (returns a 1D array of that length) or a
tuple (returns an array of that shape); shape=1 returns a
length-one array, matching RandomGenerator.rand().
Draw a single integer in the inclusive interval [low,high].
Matches RandomGenerator.random_integers(), where the upper
bound is inclusive (legacy RandomState.randint(low,high+1));
here Generator.integers is called with endpoint=True.
Accepts either the wrapped dict (state['state']) or a raw
bit_generator.state payload, so callers that already unpacked
the dict do not trip on the extra indirection.
This class that defines a random number generator. It will use
numpy.random.RandomState for the actual generation and we refer
to the numpy documentation [1].
Variables:
seed (int) – A seed for the pseudo-random generator.
rgen (object like numpy.random.RandomState) – This is a container for the Mersenne Twister pseudo-random
number generator as implemented in numpy [13].
This is an attempt on speeding up the call of
RandomState.multivariate_normal if we need to call it over and
over again. Such repeated calling will do an SVD repeatedly,
which is wasteful. In this function, this transform can be
supplied and it is only estimated if it’s not explicitly given.
Parameters:
mean (numpy array (1D, 2)) – Mean of the N-dimensional array
cov (numpy array (2D, (2, 2))) – Covariance matrix of the distribution.
cho (numpy.array (2D, (2, 2)), optional) – Cholesky factorization of the covariance. If not given,
it will be calculated here.
size (int, optional) – The number of samples to do.
Returns:
out (float or numpy.array of floats size) – The random numbers that are drawn here.
shape (int or tuple of ints, optional) – The number of numbers to draw. Default is 1, which
returns an array of one random number.
Returns:
out (float or numpy.array) – Pseudo-random number in [0, 1). If shape is an integer,
a 1D array is returned. If shape is a tuple, an array
with the given shape is returned.
Note
This is a convenience wrapper for self.rgen.random_sample.
The velocities are drawn to match a given temperature. This
function can be applied to a subset of the particles.
The generation is performed in three steps:
Initial velocities are drawn from a standard normal
distribution (0, 1).
Velocities are scaled by 1.0/sqrt(mass) to account
for particle masses. The linear momentum is reset if
requested.
The velocities are scaled to match the target kinetic
temperature exactly.
Parameters:
particles (object) – These are the particles to set the velocity of.
boltzmann (float) – The Boltzmann factor in correct units.
temperature (float) – The desired temperature. Typically,
system.temperature['set'] will be used here.
dof (list of floats or numpy.array) – The degrees of freedom to subtract. Its shape should be
equal to the number of dimensions.
selection (list of ints, optional) – A list with indices of the particles to consider, which
applies it to that selection alone.
momentum (boolean, optional) – If True, we will reset the linear momentum of the particles
(or the selected subset) after generating the initial
velocities.
Returns:
None – The velocities of the selected particles are modified
in-place.
The reservoir sampler will maintain a list of k items drawn
randomly from a set of N > k items. The list is created and
maintained so that we only need to store k`items This is useful
when `N is very large or when storing all N items require a lot
of memory. The algorithm is described by Knuth [14] but here we do
a variation, so that each item may be picked several times.
Variables:
rgen (object like numpy.random.RandomState) – This is a container for the Mersenne Twister pseudo-random
number generator as implemented in numpy, see the documentation
of RandomGenerator.
items (integer) – The number of items seen so far, i.e. the current N.
reservoir (list) – The items we have stored.
length (integer) – The maximum number of items to store in the reservoir
(i.e. k).
ret_idx (integer) – This is the index of the item to return if we are requesting
items from the reservoir.
seed (int, optional) – An integer used for seeding the generator.
length (int, optional) – The maximum number of items to store.
rgen (object like RandomGenerator, optional) – In case we want to re-use a random generator object.
If this is specified, the parameter seed is ignored.
The items are returned in the order they were added to the
reservoir (with wrapping). If the end of the reservoir is
reached, a critical message is logged and the index is reset
to zero.
Returns:
out (any) – The next item from the reservoir. The type depends on what
was stored in the reservoir.
settings (dict, optional) – The rgen value that names the generator class
(GENERATOR_CLASSES; DEFAULT_GENERATOR when it is
absent or None), the seed (0 when it is absent), and the
state of a generator to restore.
Returns:
out (object like RandomGenerator) – The random generator created.
Raises:
ValueError – If the rgen value names no generator
(generator_class()).
Return the random generators of the kick of each ensemble of a run.
Ensemble k (its slot in the layout of the run, [0^-] first
when the run has one) takes the children 3k, 3k+1 and
3k+2 of SeedSequence(seed) (spawn_kick_generators()),
the generators the parallel kick gives it.
Parameters:
seed (int) – The seed of the random numbers of the run, [simulation]seed.
n_ensembles (int) – The number of ensembles of the run.
Returns:
list of dict – The generators of each ensemble, in the order of the slots, as
spawn_kick_generators() returns them.
Empty the shared state of the Borg random generators.
The generators that create_random_generator() builds for
rgen="rgen-borg" (RandomGeneratorBorg) and
rgen="mock-borg" (MockRandomGeneratorBorg) share
one state per class: the first one constructed is seeded from its
own seed, and every later one of the same class draws from that
shared state. After this call, the next generator constructed of
each class starts a new shared state from its own seed. Generators
constructed before the call keep sharing the state they hold.
Spawn the random generators of the kick of one ensemble.
The kick initiation of an ensemble draws from three generators, the
next three children of the seed sequence of rgen, spawned in
turn. The parallel kick
(pyretis.simulation.setup._build_kick_items()) and the
sequential kick (kick_generators()) both spawn them here,
so ensemble k of a run draws the same numbers on both routes.
Parameters:
rgen (numpy.random.Generator) – The root generator of the kick, built on
SeedSequence([simulation]seed); the call spawns its next
three children.
Returns:
dict – engine_rgen, the generator of the engine (the integration
noise and the seeds of the runs of an external engine);
kick_rgen, the generator of the velocity draws of the kick
and of the shots of the repair; path_rgen, the generator of
the path ensemble and of its paths. Each one is a
numpy.random.Generator.
The System type for PyRETIS is defined in
pyretis.core.system_core. This module re-exports it so that
frompyretis.core.systemimportSystem resolves to the same
class.
The System class. Construct with the factory kwargs
(units, temperature, box) or no-args for the
lightweight phasepoint-storage default. Carries the bridge
surface (pos / vel / vpot / ekin / mass /
imass / force / virial / config / vel_rev /
particles / forcefield / post_setup / units /
temperature) plus the methods (update_force,
potential_and_force, rescale_velocities,
update_box, get_dim, get_boltzmann,
calculate_temperature, generate_velocities,
calculate_beta, restart_info, load_restart_info,
reverse_velocities, add_particle, extra_setup,
particle_type, npart).
The system is intended for sharing the current configuration (of a
frame in a path) between different methods, and the same class
also serves as the live System – it accepts the construction
kwargs units / temperature / box / post_setup and
carries the particles / forcefield / post_setup
attributes the factory layer needs.
Ignores the order parameter (depends on the order-function
choice), compares units / post_setup / box / particles /
forcefield, and the set / beta / dof keys of the
temperature dict.
temperature (float, optional) – Target temperature, stored under the
temperature['set'] key. temperature['beta'] is
calculated from it (None without a temperature);
temperature['dof'] is None unless the box has
periodic dimensions (see adjust_dof()).
box (object, optional) – Either a pyretis.core.box.Box instance or a 3x3
np.ndarray (snapshot shape). None (the default)
leaves the system without a box.
post_setup (list of (str, tuple), optional) – Deferred-setup callback list. Defaults to [].
When self.particles is a ParticlesExt, routes
through its config attribute. For pure phasepoints (no
particles) the backing self._config tuple is used.
Deep-copies the phasepoint-storage state (pos/vel/box/order/
energies/etc.) and the per-instance live-System fields
(units/temperature/particles/post_setup). forcefield is
shared by reference: if the force field changes, every system
copy must see the change.
In-memory particles, or a guard sentinel for pure snapshots.
Returns the attached particles object when present. For a
file-backed / scheduler phasepoint (no in-memory particles) returns
NO_PARTICLES, whose attribute access raises a clear error
pointing callers at the system.pos / system.vel bridge.
Read positions through system.pos, which is the
supported accessor on these phasepoints.
When particles is attached, delegate through it (handles
ParticlesExt.vel_rev flag toggle vs regular
Particles.vel flip).
A phase point without particles names its stored frame by
config; its velocities are the velocities of that frame,
negated when vel_rev is True. Such a phase point can also
hold these velocities in memory (vel), as an OpenMM phase
point of the infinite-swapping scheduler does, and the engine
then integrates from them. The reversal toggles vel_rev and
negates the velocities held in memory, so both give the
reversed velocities.
This module defines natural constants and unit conversions.
This module defines some natural constants and conversions between units
which can be used by the PyRETIS program.
The natural constants are mainly used for
conversions but it is also for defining the Boltzmann constant for
internal use in PyRETIS. The unit conversions
are mainly useful for input/output.
All numerical values are from the National Institute of Standards and
Technology and can be accessed through a web interface
http://physics.nist.gov/constants or in plain text. [7]
Internally, all computations are carried out in units which are defined
by a length scale, an energy scale and a mass scale. The time scale
is defined by these choices.
Charges are typically given (in the input) in units of the electron
charge. The internal unit for charge includes the
factor \(\frac{1}{\sqrt{4\pi\varepsilon_0}}\). An internal
calculation of \(q_1 q_2\) will then include coulombs constant in
the correct units.
The different sets of unit systems are described below in
the section on unit systems.
The keys for CONSTANTS defines the natural constant and its units,
for instance CONSTANTS['kB']['J/K'] is the Boltzmann constants in
units of Joule per Kelvin. The defined natural constants are:
For defining the different unit conversions a simple set of base
conversions are defined. These represent some common units that are
convenient for input and output. For each dimension [12] we define some
units and the conversion between these. The base units are:
Charge:
e: Electron charge.
C: Coulomb.
Energy:
kcal: Kilocalorie.
kcal/mol: Kilocalorie per mol.
J: Joule.
J/mol: Joule per mol.
kJ/mol: Kilojoule per mol.
eV: Electronvolt.
hartree: Hartree (atomic unit of energy).
Force:
N: Newton.
pN: Piconewton.
dyn: Dyne.
Length:
A: Ångström.
nm: Nanometre.
bohr: Bohr radius.
m: Meter.
Mass:
g/mol: Grams per mol, numerically equal to the atomic mass unit.
electron: A system of units similar to the LAMMPS unit
electron. [8]
si: A system of units similar to the LAMMPS unit si. [8]
gromacs: A system of units similar to the units used
by GROMACS. [10]
reduced: A reduced system of units.
cp2k: A system of units consistent with CP2K.
ase: The energy and length units of ASE, eV and Å, and the
femtosecond, the unit of the time step of the ASE engine, as the time
unit.
The defining units for the Lennard-Jones units (lj) are typically
based on the Lennard-Jones parameters for one of the components, e.g.
\(\varepsilon\), \(\sigma\) and the atomic mass
of argon (119.8 kB, 3.405 Å, 39.948 g/mol). [11] The defining
units for the other systems are given in the table below:
These units are also used for the input and define the time unit.
Further, the systems of units expect an input temperature in Kelvin
(K), except two: in lj the temperature is in reduced units,
\(k_B T / \varepsilon\), and in au it is in hartree,
\(k_B T\) (temperature=1.0 is 315775 K). All systems, with
the exception of si, expect a charge in units of electron charges.
The si system uses here Coulomb as its unit of charge. The time
units for the different energy systems are given in the table below.
The interpretation here is that if you are for instance using the system
real and would like to have a time step equal to 0.5 fs, then the
input time step to PyRETIS should be 0.5fs/48.8882129084fs.
NOTE: When using external engines, PyRETIS will not do any assumptions
on the input time/length etc and simply assume that the input values
are given in correct units for the external engine. In this case, the
only time PyRETIS will make use of the unit system is when the
Boltzmann constant is used together with energies. That is, the
Boltzmann constant must be in units consistent with the energy output
from the external engine.
Generate unit conversion between the provided units.
The unit conversion can be obtained given that a “path” between
these units exist. This path is obtained by a Breadth-first search.
Parameters:
conversions (dictionary) – The unit conversion as convert[quantity].
unit_from (string) – Starting unit.
unit_to (string) – Target unit.
Returns:
out[0] (tuple) – A tuple containing the two units: (unit_from, unit_to).
out[1] (float) – The conversion factor.
out[2] (list of tuples) – The ‘path’ between the units, i.e. the traversal from
unit_from to unit_to. out[2][i] gives the
(unit_from, unit_to) tuple for step i in the conversion.
This function will generate all conversions between base units
defined in a UNITS[dimension] dictionary. It assumes that one of
the bases have been used to defined conversions to all other bases.
Parameters:
dimension (string) – The dimension to convert for.
length (tuple, optional) – This is the length unit given as (float, string) where the
float is the numerical value and the string the unit,
e.g. (1.0, nm).
energy (tuple, optional) – This is the energy unit given as (float, string) where the
float is the numerical value and the string the unit,
e.g. (1.0, eV).
mass (tuple, optional) – This is the mass unit given as (float, string) where the
float is the numerical value and the string the unit,
e.g. (1.0, g/mol).
charge (string, optional) – This is the unit of charge given as a string, e.g. ‘e’ or ‘C’.
Returns:
None but will update CONVERT so that the conversion factors are
Create conversions for a system of units from fundamental units.
This will create a system of units from the three fundamental units
distance, energy and mass.
Parameters:
unit (string) – This is a label for the unit
distance (tuple) – This is the distance unit. The form is assumed to be
(value, unit) where the unit is one of the known distance
units, ‘nm’, ‘A’, ‘m’.
energy (tuple) – This is the energy unit. The form is assumed to be
(value, unit) where unit is one of the known energy
units, ‘J’, ‘kcal’, ‘kcal/mol’, ‘kb’.
mass (tuple) – This is the mass unit. The form is assumed to be (value, unit)
where unit is one of the known mass units, ‘g/mol’, ‘kg’, ‘g’.
charge (string, optional) – This selects the base charge. It can be ‘C’ or ‘e’ for Coulomb
or the electron charge. This will determine how we treat
Coulomb’s constant.
filename (string, optional) – The file to load units from.
select_units (string, optional) – If select_units is different from None, it can be used to
pick out only conversions for a specific system of units,
e.g. ‘real’ or ‘gromacs’, … etc.
Return the unit system of settings and its time unit in ps.
The unit system is the one units_from_settings() sets up:
[system]units, else the name of [unit-system], else the
default of the engine of the settings. Its conversion factors are
created as units_from_settings() creates them, from the
definitions of [unit-system] when it names the unit system; the
settings are left as they are.
Parameters:
settings (dict) – The settings of a run.
Returns:
out[0] (string) – The name of the unit system.
out[1] (float) – Its time unit, in ps: 1 for "openmm" and "gromacs",
within the round-off of the conversion.
settings (dict) – A dict defining the units. The unit system is taken from
system.units when explicitly given. Otherwise, the selected
engine must define default units.
Returns:
msg (string) – Just a string with some information about the units
created. This can be used for printing out some info to
the user.
Raises:
KeyError – If the system section is missing, or if no unit system can
be determined.
ValueError – If the provided unit-system settings are inconsistent.
A dictionary with conversion factors. It is used to convert between
different units, e.g. CONVERT[‘length’][‘bohr’, ‘nm] will convert
from the length unit bohr to the length unit nm.
A dictionary with the known dimensions. Note that not all of these
are true dimensions, for instance, we are using velocity as a dimension
here. This is just because it is convenient to use this to get
conversion factors for velocities.
A dictionary of sets. Each set defines the known base unit for a
dimension, i.e. UNITS[‘length’] is the set with known base units for
the length: UNITS[‘length’] = {‘A’, ‘nm’, ‘bohr’, ‘m’}
A dictionary containing basic information about the different
unit systems. E.g. UNIT_SYSTEMS[‘lj’][‘length’] contains the length
unit for the ‘lj’ unit system.
These free functions let callers compute / update the potential and
forces of a System without going through the
system.potential_and_force() style methods. The functions operate
purely through the System bridge surface (system.vpot / system.force
/ system.virial), so they work transparently on a System with
particles attached and on a phase-point snapshot without them.
The corresponding System methods delegate to these helpers; new
code should call the free functions directly.
Re-scale system.vel so total energy matches target_energy.
Free-function form of the
System.rescale_velocities(energy,external=...) method.
Parameters:
system (object like System) – The system whose velocities should be rescaled in place via
the bridge surface (system.vel / system.mass /
system.vpot).
target_energy (float) – Desired total energy (kinetic + potential).
forcefield (object like ForceField, optional) – Required when external is False; for recomputing
system.vpot before the rescale. Ignored when external
is True (the existing system.vpot is used).
external (bool, optional) – When True, use the cached system.vpot; when False,
recompute it via the forcefield first.
Collects the fields that matter for scientific auditing: enough
metadata to detect “same directory, different code/settings” mistakes
in production runs.
The key of a state file’s [current]provenance record that marks a
run whose internal integrators stream with the subcycles of the
engine section each of them is built from
(pyretis.engines.internal.MDEngine.setup_streaming()). In a
run without the key, every internal integrator streamed with the
subcycles of [engine].
The key of a state file’s [current]provenance record that marks a
run whose run file records the temperature each of its engines runs
at: [system]temperature, the temperature of the inputs of the
engines that read their own when they agree, and else the
temperature of each engine section
(pyretis.engines.run_temperature.resolve_run_temperature()).
In a run file without the key, [system]temperature is the
temperature of the internal integrators only, and TurtleMD and ASE ran
at the temperature of their engine section
(pyretis.engines.run_temperature.resolve_resumed_temperature()).
input_file (str or path-like, optional) – Path to the TOML/rst input file. Its SHA-256 hash is recorded
so a restart can detect if the settings changed underneath.
Returns:
info (dict) – Keys: pyretis_version, python_version,
numpy_version, git_commit (or "unknown"),
input_hash (when input_file is given and can be read),
pyretis.core.velocity_draws.VELOCITY_RULE_KEY, the rule
by which the shooting draws of the run apply the [tis]
settings the state file records,
SUBCYCLES_RULE_KEY, the rule by which the internal
integrators of the run take subcycles, and
TEMPERATURE_RULE_KEY, the rule by which the run file
records the temperatures of the engines.
Return whether stored settings carry the record of the temperatures.
Parameters:
document (dict) – The TOML document of a settings file, as tomllib reads
it.
name (string) – The file, as the message names it.
Returns:
out (boolean) – True when the document holds the table
STORED_SETTINGS_PROVENANCE
(stored_settings_provenance()): it holds the settings an
in-process task of this PyRETIS stored, which record the
temperature its run ran at. False when it holds no such table.
Return whether a state marks the streaming rule of subcycles.
Parameters:
state (dict) – The [current] section of a state file.
Returns:
out (boolean) – True when the provenance of state carries
SUBCYCLES_RULE_KEY: every internal integrator of the
run that wrote it streamed with the subcycles of its own
engine section. False when it lacks the key: every internal
integrator of that run streamed with [engine]subcycles.
Return whether a state marks the record of the engine temperatures.
Parameters:
state (dict) – The [current] section of a state file.
Returns:
out (boolean) – True when the provenance of state carries
TEMPERATURE_RULE_KEY: the run file of the run that
wrote it records the temperature each of its engines runs at.
False when it lacks the key.
Free functions for the dimensionality, the Boltzmann lookup, the box
update, the velocity generation and the temperature of a
System; the corresponding System methods delegate to
them. The box helpers accept both a Box and the 3x3
np.ndarray box of a phase-point snapshot.
The single user-facing selector for shooting style is the sign of
sigma_v:
negative values (the default -1) select aimless shooting;
zero or positive values select soft velocity perturbations whose
per-particle width is sigma_v (a scalar or a per-particle array).
The legacy aimless boolean is stripped from parsed settings (see
pyretis.inout.settings._remove_legacy_tis_settings()); helpers
in this module therefore only look at sigma_v.
The linear-momentum reset after a draw is selected by the one key
zero_momentum, the [tis] keyword of the same name. The velocity
settings every engine’s modify_velocities receives carry it under
that name, and a missing key means False, the [tis] default.
The total energy the drawn velocities are re-scaled to is the key
rescale of the velocity settings, the [tis]rescale_energy
(make_velocity_settings()). An engine that does not re-scale
stops before its draw when a re-scale is requested
(refuse_energy_rescale()), and an engine that draws the
velocities of aimless shooting only stops before a soft perturbation
(refuse_soft_perturbation()).
Return True when velocity settings select aimless shooting.
Parameters:
settings (dict) – Mapping containing a sigma_v key. A missing key is treated
as the default -1 (aimless), matching the input-file
default in pyretis.inout.settings.SECTIONS.
Return True when velocity settings request an energy re-scale.
Parameters:
settings (dict) – The velocity settings handed to modify_velocities. The key
rescale holds the total energy the drawn velocities are
re-scaled to; None, False and a number that is not positive
request no re-scale.
Returns:
out (bool) – True if rescale is a positive number.
Raises:
TypeError – If rescale is True. A boolean names no energy, and the
number True compares as 1.
Return True when velocity settings request a zero linear momentum.
Parameters:
settings (dict) – The velocity settings handed to modify_velocities, or the
[tis] settings themselves. The key zero_momentum selects
the reset; a missing key is treated as the default False,
matching the input-file default in
pyretis.inout.settings.SECTIONS.
Returns:
out (bool) – True if the total linear momentum is to be set to zero after
the velocities are drawn.
Raises:
ValueError – If settings carries the key momentum. The key
zero_momentum alone selects the reset.
TypeError – If zero_momentum is not a boolean. The truth value of a
string such as "false" is True, so a boolean is the one type
that selects the reset unambiguously.
Build the velocity settings of one kick of a crossing search.
A kick of a middle-interface crossing search
(kick_across_middle) is an aimless draw (sigma_v=-1),
whatever sigma_v the [tis] settings select for shooting. It
follows the [tis]zero_momentum setting.
Parameters:
tis_settings (dict) – The [tis] settings of the search.
rescale (float or bool, optional) – The energy the kicked velocities are re-scaled to, as the
rescale entry of the velocity settings. None, and a value
that requests no re-scale (is_energy_rescale_setting()),
leave the drawn velocities unscaled.
Returns:
out (dict) – The velocity settings: sigma_v, zero_momentum and
rescale, which is False for a value other than None that
requests no re-scale.
If tis_settings carries a pre-computed imass-scaled width
(_sigma_v_scaled, populated by
PathSimulation.__init__()), that array is forwarded;
otherwise the raw sigma_v is used.
Parameters:
tis_settings (dict) – The [tis] settings, or the tis_set of a scheduler
ensemble.
Returns:
out (dict) – The velocity settings: sigma_v, zero_momentum and
rescale, the [tis]rescale_energy when it requests a
re-scale (is_energy_rescale_setting()) and False
otherwise.
The shooting draws of a scheduler run, and their record in a state file.
A shooting move of the scheduler draws new velocities for its shooting
point. Two [tis] settings select the distribution of the draw:
zero_momentum, whether the total linear momentum is set to zero after
the draw, and rescale_energy, the total energy the drawn velocities
are re-scaled to. Every engine applies the two as the tis_set of the
run records them, or stops with an error before its first draw
(pyretis.core.velocity.make_velocity_settings()). A state file
written by such a run carries VELOCITY_RULE_KEY in its
[current]provenance
(pyretis.core.provenance.collect_provenance()), and
recorded_draws() gives its draws.
A state file without the key records the shooting draws of
unmarked_draws(), per engine class and velocity_generation:
the internal integrators, OpenMM and cp2k_steps reset the momentum
for a tis_set key momentum only; the streaming cp2k engine
resets it for a missing zero_momentum; GROMACS gen_vel, LAMMPS
velocitycreate without a mom keyword (whose default is yes)
and AMS GenerateVelocities (RandomVelocitiesMethodGromacs and
Exact, the AMS default; Boltzmann is not checked) draw with zero
total momentum; and no engine re-scales with rescale_energy. The
momentum reset of a module engine is UNKNOWN, and so is its
re-scale for a positive rescale_energy.
The paths the ensembles of a state file hold were shot with its draws, so
a run that continues it has to draw the same way:
refuse_changed_draws() stops one that does not.
How the engine of one [engine] section draws the shooting velocities.
zero_momentum is True when every draw has zero total linear
momentum, False when a draw keeps the momentum it is drawn with, and
UNKNOWN when the record does not decide it. rescale is
the [tis]rescale_energy the drawn velocities are re-scaled with,
None when their energy is left as drawn, and UNKNOWN when the
record does not decide it. momentum_source and rescale_source
say what selects the two.
The engine classes that re-scale the energy of a shooting draw; the
other classes of KNOWN_ENGINES refuse a positive
rescale_energy. lammps_steps re-scales with
velocity_generation="engine" only.
Return what selects the momentum reset of a run with the rule.
GROMACS with velocity_generation="engine" and AMS
(RandomVelocitiesMethodGromacs and Exact; Boltzmann
is not checked) draw with zero total momentum, so they refuse
zero_momentum=false before their first draw.
Parameters:
config (dict) – A scheduler configuration.
key (string) – The engine section.
zero_momentum (boolean) – The zero_momentum of its tis_set.
Returns:
out (string) – The setting, and the refusal of an engine that refuses it.
Return the settings that draw as the run that wrote a state did.
Parameters:
before (dict of Draw) – The draws of the run that wrote the state.
config_before (dict) – Its scheduler configuration.
config_after (dict) – The scheduler configuration of the run that continues it.
section (string) – Where the settings are set, as the hint names it.
Returns:
out (string) – The zero_momentum and rescale_energy of the previous run,
when every section of it drew the same way, the record decides
both, and the two runs have the same engine sections; otherwise
an empty string.
Return the energy re-scale of one engine section of an unmarked run.
The shooting moves handed the engine the tis_set, whose
rescale_energy the engines of the engine map do not re-scale
with; the AMS engine stopped before its draw for a positive value.
How a module engine read it is not known.
Parameters:
config (dict) – The scheduler configuration of a state file without
VELOCITY_RULE_KEY.
key (string) – The engine section.
Returns:
out (tuple) – The rescale and the rescale_source of the draw.
The draws are compared section by section, on the engine sections
both runs have. A section whose draw either run leaves
UNKNOWN is reported as unknown, and the other sections
are still compared, so an unknown section never hides a known change.
When the two runs have different engine sections, the known values
the sections of each run take are also compared as sets.
Parameters:
before (dict of Draw) – The draws of the run that wrote the state.
after (dict of Draw) – The draws of the run that continues it.
Returns:
changed (list of tuples) – The entries of DRAW_SETTINGS on which the two runs
differ.
unknown (list of tuples) – The entries of DRAW_SETTINGS that a run leaves
UNKNOWN.
This module holds engine-agnostic MC move primitives: the shooting move
and its helpers, and the time-reversal move. The initial-path kick
machinery (pyretis.initiation.initiate_kick) uses them.
allowmaxlength: boolean, should paths be allowed to reach
maximum length?
maxlength: integer, maximum allowed length of paths.
start_cond (string or tuple of strings) – The starting condition for the current ensemble, ‘L’eft or
‘R’ight. (‘L’, ‘R’), the default option, implies no directional
difference.
shooting_point (object like System, optional) – If given, it is the shooting point from which the path is generated.
Returns:
out[0] (boolean) – True if the path can be accepted.
out[1] (object like PathBase) – Returns the generated path.
out[2] (string) – Status of the path, this is one of the strings defined in
path._STATUS.
path (object like PathBase) – This is the input path which will be used for generating a
new path.
order_function (object like OrderParameter) – The class used for obtaining the order parameter(s).
interfaces (list/tuple of floats) – These are the interface positions of the form
[left,middle,right].
start_condition (string) – The starting condition, ‘L’eft or ‘R’ight.
engine (object like EngineBase, optional) – Needed to re-read file-backed frames when the order parameter
is velocity dependent (external engines store the path as file
references, not in-memory coordinates).
Returns:
out[0] (boolean) – True if the path can be accepted.
out[1] (object like PathBase) – The time reversed path.
out[2] (string) – Status of the path, this is one of the strings defined in
.path._STATUS.
Multiresolution Wire Fencing (mwf) move for the infinite-swapping route.
Multiresolution wire fencing generates the wire-fencing
sub-paths at TWO engine resolutions: the intermediate sub-paths are shot
with a small number of subcycles (cheap, “high resolution” in the number
of shooting attempts) and only the final sub-path of each set is shot with
the engine’s full subcycle count, before the surviving sub-path is extended
to a full path and accepted with the usual sub-trajectory acceptance.
The high-level helpers (wirefence_weight_and_pick / shoot /
extender / subt_acceptance / check_kick) are the
infinite-swapping move helpers in pyretis.core.moves;
_generate_segment_using_shoot() kicks the shooting point the move
chose (modify_velocities and check_kick) before it hands the
point to shoot.
The [tis] keys of the move: mwf_subcycle_small (and the
per-ensemble mwf_subcycle_small_by_ensemble dict) and
mwf_nsubpath; the number of sets reuses the wire-fencing n_jumps.
Shoot a sub-path from si.phasepoints[idx] (MWF-chosen point).
The MWF caller owns the shooting-point policy, so we build the explicit
shooting point and pass it to pyretis.core.moves.shoot(),
performing the velocity kick (modify_velocities + check_kick)
here to preserve standard MC kick semantics.
pyretis.core.multires_wf._no_progress_error(mwf, i, picked, current, fallback)¶
Describe a sub-path set whose advance has stalled.
The inner loop of multires_wire_fencing() leaves its sub-path
counter unchanged when the shooting index is not an interior frame of
the current sub-path; a shot and an empty high-resolution queue
advance it. A failed sub-path makes the loop roll back to the last
accepted sub-path and retry, unless the counter is 1 or nsubpath.
The rollback restores exactly the state the failing iteration started
from, so if the counter did not advance the retry repeats the same
rejected choice, and the loop cannot terminate.
Parameters:
mwf (object like _MWFSettings) – The resolved multiresolution settings; used for nsubpath.
i (integer) – The sub-path counter, which the failing iteration left unchanged.
picked (tuple) – The rejected choice as (index,status,queue), where queue
is the high-resolution shooting queue at the point of failure.
current (object like PathBase) – The sub-path the shooting index was drawn from.
fallback (tuple) – The rollback target as (path,queue).
Returns:
out (string) – A message naming the state, for a RuntimeError.
Strategy objects for biased shooting-point selection.
This module defines a small, dependency-free strategy abstraction used by
the biased shooting move (shooting_move="bias"). A selector assigns
a strictly positive weight w(x) to every interior frame of a path
(the two end points are excluded, exactly as the uniform rnd move
excludes them). The shooting point is then drawn with probability
w_i/W where W=sum_jw_j is the selection partition function,
and detailed balance is restored by the Metropolis acceptance factor
min(1,W_old/W_new) applied in pyretis.core.moves.shoot_bias().
The weight w_i of the chosen frame cancels in the acceptance ratio
because the shooting point is the same physical frame shared by the old
and the new path; only the two partition functions W_old and W_new
survive: this is the acceptance of Jung et al., Nat. Comput. Sci. 3, 334
(2023). The user documentation (docs/user/section/tis.rst) states the
rule and its restrictions.
The module is intentionally free of any machine-learning or heavy
dependency: it only uses numpy. A learned (committor) selector
can be added as one more ShootingPointSelector subclass whose
weights() queries a model.
Important
Every random draw must use the per-ensemble random generator that is
passed in to select(), never a path’s own
rgen (which can be aliased across ensembles and would break
continue-vs-restart equivalence). select() draws exactly one
uniform number, so the random stream advances deterministically.
Weights must be strictly positive and finite. Non-positive or non-finite
weights raise: a wrong selection weight silently biases the sampled
rate, which is the worst possible failure mode for this code.
where \(\\lambda(x)\) is the index-th order-parameter component
of a frame. This concentrates the shooting points near
\(\\lambda_0\) (for example a barrier-top / transition-state value),
which is where re-shooting is most informative. It is a cheap, analytic,
machine-learning-free bias and the reference selector for the
statistical-equivalence test of the biased move.
Parameters:
alpha (float) – Inverse-width of the Gaussian; must be strictly positive. Larger
values concentrate the selection more tightly around lambda0.
Very large values can make distant frames underflow to zero weight,
which select() reports as an error – reduce alpha then.
lambda0 (float) – The order-parameter value the selection is biased toward.
index (int, optional) – Which order-parameter component to read (default 0, the progress
coordinate).
Strategy for choosing a shooting point and its acceptance weight.
A selector defines a strictly positive per-frame weight w(x) over a
path’s interior frames (the end points are excluded). The shooting
point is drawn with probability w_i/W (W=sum_jw_j) and the
biased shooting move is made detailed-balance correct by the Metropolis
factor min(1,W_old/W_new).
Subclasses only need to implement weights(); the selection and
the partition-function bookkeeping are provided here so every selector
shares the exact same, reproducible draw.
Return the interior weights after checking the contract.
Raises:
ValueError – If the path has no interior frame, or if any weight is
non-finite or not strictly positive. Failing loud here keeps a
broken weight from silently biasing the sampled rate.
Draw an interior frame with probability proportional to w_i.
Exactly one uniform random number is drawn from rgen and mapped
to a frame through the inverse cumulative weight distribution, so
the draw is deterministic given the random stream and independent of
the concrete generator implementation.
Parameters:
path (object like PathBase) – The path to select a shooting point from.
rgen (object like RandomGenerator) – The per-ensemble random generator. A path’s own rgen
must not be used (see the module docstring).
Returns:
out[0] (int) – The index of the selected frame in path.phasepoints. It lies
in [1,path.length-2] (an interior frame).
out[1] (float) – The weight w_i of the selected frame.
out[2] (float) – The selection partition function W of path.
Selector with constant weights (every interior frame equally likely).
With w==1 the partition function is W=L-2 (the number of
interior frames) and the biased-move acceptance reduces to the standard
flexible-length two-way-shooting factor min(1,(L_o-2)/(L_n-2)).
This selector is the correctness anchor of the biased move: running
shooting_move="bias" with UniformSelector must reproduce
the statistics of the uniform rnd move.
Apply the selection-bias Metropolis test min(1,W_o/W_n).
This is the sole acceptance correction for the aimless biased shooting
move (the dynamics and the shooting-point weight cancel; see
pyretis.core.moves.shoot_bias()). It is a tiny, side-effect-free
function, so the exact arithmetic, in particular the orientation
W_old/W_new, can be unit-tested without an engine.
Parameters:
rgen (object) – The per-ensemble random generator; one uniform number is drawn
(via draw_uniform(), so either generator flavour works).
sum_weight_old (float) – W_o, the selection partition function of the current path.
sum_weight_new (float) – W_n, the selection partition function of the trial path.
Must be strictly positive.
Returns:
out (bool) – True if the trial path is accepted by the selection-bias test.
The class stores the state of a phase point (a frame of a path) and
also serves as the live system of a simulation, with its units,
temperature, box, particles and force field.
pos / vel / vpot / ekin / mass / imass /
force / virial / config / vel_rev route through
self.particles when attached (the factory-built case) and
through per-instance backing storage when no particles are attached
(pure-snapshot use as path phasepoints).
TIS / RETIS move suite for the infinite-swapping scheduler.
The module defines the Monte Carlo moves the scheduler runs: the
shooting moves (shoot, shoot_bias), wire fencing, stone
skipping, web throwing, time reversal, target swap and mirror, which
select_shoot() dispatches together with the multiresolution
wire fencing of pyretis.core.multires_wf, and the swap moves
(retis_swap_zero, ppretis_swap, quantis_swap_zero), with
their acceptance helpers and the path weights (compute_weight,
calc_cv_vector).