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.
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.
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:
Determine the shooting ensemble during a RETIS simulation.
Here we check whether to do priority shooting or not. If True,
we either shoot from the ensemble with the fewest paths or
ensemble [0^-] if all ensembles have the same no. of paths.
Parameters:
ensembles (list of dictionaries of objects) – Lit of dict of ensembles we are using in a path method.
settings (dict) – This dict contains the settings for the RETIS method.
Returns:
out[0] (list) – Returns a list of boolean dictating whether certain
ensembles are to be skipped or not.
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.
Resolve the engine time step for the flux and rate analysis.
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] settings when present, otherwise from the engine’s own
input file – as PyRETIS does when it builds the engine.
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.
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).
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.
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.
Right now, this is just 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.
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.
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 already preserves vpot/ekin (they are in
_numpy_attr); it does not carry the derived etot/temp,
which would otherwise be lost and written as nan in the path
energy file. We carry them here (copy-only) rather than via
_copy_attr/_numpy_attr so the restart serialisation – and
the backward compatibility of existing restart files, whose
load_restart_info requires every listed attribute – is
untouched.
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.
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 (legacy pyretis-native shape);
inf-flavour callers pass one in explicitly (see A3.1a
alignment).
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 native 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.
Return the per-ensemble High-Acceptance weight vector.
Used by the native Stage-C output route under the "analysis"ha_weight_mode: the wf compute_weight crossing count,
applied as the per-ensemble crossing-probability weight while the
infinite-swap occupancy is driven by membership (weights).
Defaults to weights when it was never set explicitly, so
the "swap" convention and non-wf paths are unaffected.
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. Kept as a
scalar property so the legacy pyretis-native callers
(path.weight) keep working unchanged; the canonical
storage is the weights tuple (see A3.1a alignment).
Mirrors the infretis-flavour shape so RETIS swap moves that
carry a tuple of per-ensemble weights can store them on a
native Path during the A3.1a alignment period. Single-
ensemble (pyretis-native) callers can keep using
weight, which is the scalar projection of this tuple.
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 are used to 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.
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).
Load infinite-swapping paths from disk into Path objects.
These loaders were historically part of the inf-flavour Path module
(pyretis.core._path_inf). After the A3.1b Path collapse there is a
single pyretis.core.path.Path, so the loaders live here, free of
the now-deleted _path_inf module. They build native Path objects
whose phasepoints are file-backed snapshot System objects (the
external-engine representation), exactly as the infinite-swapping
scheduler expects.
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.
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. This
corresponds to [0^-], [0^+], [1^+], etc.
ensemble_name (string) – A string which can be used for printing the ensemble name.
This is of form [0^-], [0^+], [1^+], etc.
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 used to identify the ensemble.
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.
Append data from the given path to self.path_data.
This will add the data from a given` path` to the list path data
for this ensemble. If 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
py:class:.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.
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) – Used to set 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 most of the random number procedures from RandomState in
numpy.random and defines a class which used RandomState 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).
This is the canonical post-merge generator (see MERGE_TODO A3.4):
PCG64 is the modern numpy bit generator and the one the
infinite-swapping sampler already uses, so a native run configured
with rgen="pcg64" draws the same byte stream as the
infinite-swapping code from the same seed.
It is opt-in only: create_random_generator() still defaults
to the legacy MT19937 RandomGenerator (rgen="rgen"), so
every committed reference under examples/tests/ is byte-identical
until the (supervised, reference-regenerating) A3.4 campaign flips the
default. The state dict produced by get_state() carries the
PCG64 bit_generator.state dict rather than the legacy MT19937
tuple, and is tagged rgen="pcg64".
pyretis.core._compat.SharedRNG is the test-scoped sibling
that additionally bridges the inf-style Generator surface; it
subclasses this class so there is a single PCG64 implementation.
Variables:
seed (int) – The seed used to create 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.
Inf 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 native 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 the native semantics 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. Can be
used to only apply it to a selection of particles.
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.
The canonical System type for PyRETIS lives at
pyretis.core.system_core after A3.2c (the snapshot/harness
unification). This module re-exports it under the legacy import
path so existing call sites that frompyretis.core.systemimportSystem keep working.
The unified System class. Construct with the harness 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 legacy method shape (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, but the same class
also serves as the canonical live System (post A3.2c) – it
accepts the harness-style construction kwargs and carries the
particles / forcefield / post_setup attributes the
factory layer needs.
Mirrors the harness System.__eq__: 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 for harness compatibility;
dof and beta are initialised to None.
box (object, optional) – Either a pyretis.core.box.Box instance (harness
shape) or a 3x3 np.ndarray (snapshot shape). When
None the legacy snapshot 3x3 zeros default is used.
post_setup (list of (str, tuple), optional) – Deferred-setup callback list. Defaults to [].
Walk the box’s periodic attribute and subtract dofs.
Subtracts one dof per periodic dimension (harness Box only).
Snapshot ndarray boxes have no periodic – silently
no-ops via the AttributeError fallback.
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 harness-compat fields
(units/temperature/particles/post_setup). forcefield is
shared by reference – matches the harness System.copy()
contract: 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; system.particles.pos is
no longer supported on these phasepoints.
Mirrors the harness System’s reverse_velocities():
when particles is attached (harness flavour) delegate
through it (handles ParticlesExt.vel_rev flag toggle vs
regular Particles.vel flip). Otherwise (pure snapshot,
external-engine restart-on-disk style) toggle vel_rev.
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 used to define 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 is not yet implemented, but a
choice is here to include 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 currently 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.
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, all system of units expect an input temperature in Kelvin
(K) and 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.
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 harness-specific
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 both the harness
System and the snapshot System.
The corresponding harness System methods delegate to these
helpers; new code should call the free functions directly, since
the harness methods go away in A3.2c.
Re-scale system.vel so total energy matches target_energy.
Free-function form of the soon-to-go
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; used to recompute
system.vpot before the rescale. Ignored when external
is True (the existing system.vpot is used).
external (bool, optional) – Mirrors the external flag of the legacy method. When
True, use the cached system.vpot; when False, recompute
it via the forcefield first.
Collects enough metadata to detect “same directory, different
code/settings” mistakes in production runs. Not a full environment
capture — just the fields that matter for scientific auditing.
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.
Canonical flat-snapshot System (the inf-flavour shape).
This module is the public landing for the snapshot System
type chosen by the A3.2 decision
(see docs/decisions/system_canonical_form.md). Post-A3.2c,
pyretis.core.system ALSO re-exports the same class – the
snapshot vs system import paths are aliases for one
canonical type.
This module remains as the public name for new consumers who
specifically want to communicate “this is a phasepoint-storage
snapshot” rather than “this is the live System.”
Pure-lookup helpers that work on both the harness System and the
snapshot System. They cover the small bag of legacy
system.method() calls (dimensionality, Boltzmann lookup, box
update) that aren’t worth attaching to either System class – the
free-function form means we don’t have to grow the snapshot’s API
just to satisfy A3.2c’s “delete the harness” goal.
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.
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.
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.
This module holds the engine-agnostic MC move primitives that several
parts of PyRETIS need without pulling in the whole native TIS/RETIS
loop: the shooting move and its helpers, and the time-reversal move.
They were factored out of the native loop so that consumers which only
need the primitives – notably the initial-path kick machinery
(pyretis.initiation.initiate_kick, used by both the native
loop and the scheduler’s native-route input shim) – do not depend on
the full loop module. The native loop
(pyretis’s native move suite) re-imports these names.
Important
The move bodies are kept byte-for-byte identical to their previous
tis.py definitions: the random-number draw order, acceptance criteria
and sub-path construction are unchanged, so results are reproducible
across the move.
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.
Multiresolution Wire Fencing (mwf) move for the infinite-swapping route.
Ported from the upstream infretis classes/multires_wf.py (branch
multires_wf). 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 pyretis’s own
infinite-swapping move helpers in pyretis.core.moves (the
faithful port of infretis.core.tis), so this is a near-verbatim port;
the only adaptations are the lower-level kick calls in
_generate_segment_using_shoot() (pyretis’s modify_velocities
takes the random generator explicitly and check_kick takes the TIS
settings).
New [tis] keys: 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.
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.tis.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. See docs/decisions/biased_shooting_acceptance.md and the user
documentation (docs/user/section/tis.rst) for the full derivation.
The module is intentionally free of any machine-learning or heavy
dependency: it only uses numpy. A learned (committor) selector
can later 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 instead of being silently clamped – 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 native uniform rnd move. It is not wired as
the default shooting move – the uniform rnd path is left untouched.
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.tis.shoot_bias()). It is a tiny, side-effect-free
function – shared by the native and infinite-swapping flows – so the
exact arithmetic, in particular the orientation W_old/W_new and
not its inverse, 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.
Originally ported from infretis.classes.system as a lightweight
value type for phasepoint storage; A3.2c (2026-05-27) absorbed the
former pyretis-native “harness” System into this class so PyRETIS
has a single, unified type.
Both pyretis.core.system and pyretis.core.snapshot
re-export the class defined here, which carries the canonical,
unified implementation (it is no longer “internal” or “inf-flavour”;
the module was renamed from the historical _system_inf in the
de-brand pass).
pos / vel / vpot / ekin / mass / imass /
force / virial / config / vel_rev route through
self.particles when attached (harness-style behaviour for 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.
Ported from infretis.core.tis (provenance). PyRETIS already ships its
own native TIS/RETIS move suite in pyretis’s native move suite
with a broader move set (PPTIS / REPPTIS / stone_skipping / web_throwing /
target_swap / …). Phase 4 reconciles the two: the scheduler calls into
pyretis’s moves, and the genuinely-new pieces (quantis_swap_zero, the
extender maxlen fix, etc.) get folded back into
the native move suite.
Until then this module preserves the infinite-swapping move suite
verbatim so the scheduler / repex code keeps the behaviour it was tested
against.