This package defines the core PyRETIS tools.
The core tools are intended to define classes which are used in simulations.
pyretis.core.box
)pyretis.core.common
)pyretis.core.montecarlo
)pyretis.core.particlefunctions
)pyretis.core.particles
)pyretis.core.pathensemble
)pyretis.core.path
)pyretis.core.properties
)pyretis.core.random_gen
)pyretis.core.retis
)pyretis.core.system
)pyretis.core.tis
)pyretis.core.units
)BoxBase
)System
)Particles
)Path
)PathEnsemble
)PathEnsembleExt
)RandomGenerator
)Definition of a class for a simulation box.
The simulation box handles the periodic boundaries if needed.
It is typically referenced via the System
class,
i.e. as System.box
.
BoxBase
)RectangularBox
)TriclinicBox
)Examples
>>> from pyretis.core.box import create_box
>>> box = create_box(cell=[10, 10, 10], periodic=[True, False, True])
pyretis.core.box.
create_box
(low=None, high=None, cell=None, periodic=None)[source]¶Set up and create a box.
Parameters: 


Returns:  out (object like 
Definition of some common methods that might be useful.
inspect_function()
)initiate_instance()
)generic_factory()
)pyretis.core.common.
inspect_function
(function)[source]¶Return arguments/kwargs of a given function.
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:

pyretis.core.common.
initiate_instance
(klass, settings)[source]¶Initialise a class with optional arguments.
Parameters: 


Returns:  out (instance of klass) – Here, we just return the initiated instance of the given class. 
pyretis.core.common.
generic_factory
(settings, object_map, name='generic')[source]¶Create instances of classes based on settings.
This method is intended as a semigeneric 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: 


Returns:  out (instance of a class) – The created object, in case we were successful. Otherwise we return none. 
Module for Monte Carlo Algorithms and other “random” functions.
In this module, Monte Carlo Algorithms are defined. Note that some derived or “random” functions are also defined in the TIS module.
metropolis_accept_reject()
)max_displace_step()
)pyretis.core.montecarlo.
metropolis_accept_reject
(rgen, system, deltae)[source]¶Accept/reject a energy change according to the metropolis rule.
FIXME: Check if metropolis really is a good name here.
Parameters: 


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.
pyretis.core.montecarlo.
max_displace_step
(rgen, system, maxdx=0.1, idx=None)[source]¶Monte Carlo routine for displacing particles.
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: 


Returns:  out (boolean) – The outcome of applying the function accept_reject to the system and trial position. 
This file contains functions that act on (a selection of) particles.
These functions are intended for calculating particle properties as the kinetic temperature, pressure etc.
atomic_kinetic_energy_tensor()
)calculate_kinetic_energy()
)calculate_kinetic_energy_tensor()
)calculate_kinetic_temperature()
)calculate_linear_momentum()
)calculate_pressure_from_temp()
)calculate_pressure_tensor()
)calculate_scalar_pressure()
)calculate_thermo()
)calculate_thermo_path()
)kinetic_energy()
)kinetic_temperature()
)reset_momentum()
)pyretis.core.particlefunctions.
atomic_kinetic_energy_tensor
(particles, selection=None)[source]¶Return kinetic energy tensors for a particle selection.
Parameters: 


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. 
pyretis.core.particlefunctions.
calculate_kinetic_energy
(particles, selection=None, kin_tensor=None)[source]¶Return the kinetic energy of a collection of particles.
Parameters: 


Returns: 

pyretis.core.particlefunctions.
calculate_kinetic_energy_tensor
(particles, selection=None)[source]¶Return the kinetic energy tensor for a selection of particles.
The tensor is formed as the outer product of the velocities.
Parameters: 


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. 
pyretis.core.particlefunctions.
calculate_kinetic_temperature
(particles, boltzmann, dof=None, selection=None, kin_tensor=None)[source]¶Return the kinetic temperature of a collection of particles.
Parameters: 


Returns: 

pyretis.core.particlefunctions.
calculate_linear_momentum
(particles, selection=None)[source]¶Calculate the linear momentum for a collection of particles.
Parameters: 


Returns:  out (numpy.array) – The array contains the linear momentum for each dimension. 
pyretis.core.particlefunctions.
calculate_pressure_from_temp
(particles, dim, boltzmann, volume, dof=None)[source]¶Evaluate the scalar pressure.
The scalar pressure is here calculated using the temperature and the degrees of freedom.
Parameters: 


Returns: 

Note
This function may possibly be removed  it does not appear to be very useful right now.
pyretis.core.particlefunctions.
calculate_pressure_tensor
(particles, volume, kin_tensor=None)[source]¶Calculate the pressure tensor.
The pressure tensor is obtained from the virial the kinetic energy tensor.
Parameters: 


Returns:  out (numpy.array) – The symmetric pressure tensor, dimensions (dim, dim), where dim = the number of dimensions considered in the simulation. 
pyretis.core.particlefunctions.
calculate_scalar_pressure
(particles, volume, dim, press_tensor=None, kin_tensor=None)[source]¶Evaluate the scalar pressure using the pressure tensor.
Parameters: 


Returns:  out (float) – The scalar pressure averaged over the diagonal components of the pressure tensor. 
pyretis.core.particlefunctions.
calculate_thermo
(system, dof=None, dim=None, volume=None, vpot=None)[source]¶Calculate and return several thermodynamic properties.
The calculated properties are the potential, kinetic and total energies per particle, the temperature, the pressure and the momentum.
Parameters: 


Returns:  out (dict) – This dict contains the float that is calculated in this routine. 
pyretis.core.particlefunctions.
calculate_thermo_path
(system)[source]¶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. 
pyretis.core.particlefunctions.
kinetic_energy
(vel, mass)[source]¶Obtain the kinetic energy for given velocities and masses.
Parameters: 


Returns: 

pyretis.core.particlefunctions.
kinetic_temperature
(vel, mass, boltzmann, dof=None, kin_tensor=None)[source]¶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: 


Returns: 

pyretis.core.particlefunctions.
reset_momentum
(particles, selection=None, dim=None)[source]¶Set the linear momentum of a selection of particles to zero.
Parameters: 


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.
Particles
)ParticlesExt
)pyretis.core.particles.
Particles
(dim=1)[source]¶Bases: object
Base class for a collection of particles.
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 allpairs list.
npart
¶Number of particles.
Type:  integer 

pos
¶Positions of the particles.
Type:  numpy.array 

vel
¶Velocities of the particles.
Type:  numpy.array 

force
¶Forces on the particles.
Type:  numpy.array 

virial
¶The current virial for the particles.
Type:  numpy.array 

mass
¶Masses of the particles.
Type:  numpy.array 

imass
¶Inverse masses, 1.0 / self.mass.
Type:  numpy.array 

name
¶A name for the particle. This may be used as short text describing the particle.
Type:  list of strings 

ptype
¶A type for the particle. Particles with identical ptype are of the same kind.
Type:  numpy.array of integers 

dim
¶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.
Type:  int 

vpot
¶The potential energy of the particles.
Type:  float 

ekin
¶The kinetic energy of the particles.
Type:  float 

__init__
(dim=1)[source]¶Initialise the Particle list.
Here we just create an empty particle list.
Parameters:  dim (integer, optional) – The number of dimensions we are considering for positions, velocities and forces. 

__iter__
()[source]¶Iterate over the particles.
This function will yield the properties of the different particles.
Yields:  out (dict) – The information in self.pos, self.vel, … etc. 

_copy_attribute
(attr, copy_function)[source]¶Copy an attribute.
Parameters: 


Returns:  out (object) – A copy of the selected attribute. 
add_particle
(pos, vel, force, mass=1.0, name='?', ptype=0)[source]¶Add a particle to the system.
Parameters: 


copy
()[source]¶Return a copy of the particle state.
Returns:  out (object like Particles ) – A copy of the current state of the particles. 

empty_list
()[source]¶Reset the particle list.
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.
get_selection
(properties, selection=None)[source]¶Return selected properties for a selection of particles.
Parameters: 


Returns:  out (list) – A list with the properties in the order they were asked for
in the 
load_restart_info
(info)[source]¶Load restart information.
Parameters:  info (dict) – Dictionary with the settings to load. 

pairs
()[source]¶Iterate over all pairs of particles.
Yields: 


particle_type
= 'internal'¶set_force
(force)[source]¶Set the forces for the particles.
Parameters:  force (numpy.array) – The forces to set. 

pyretis.core.particles.
ParticlesExt
(dim=1)[source]¶Bases: pyretis.core.particles.Particles
A particle list, when positions and velocities are stored in files.
config
¶The file name and index in this file for the configuration the particle list is representing.
Type:  tuple 

vel_rev
¶If this is True, the velocities in the file represeting the configuration will have to be reversed before they are used.
Type:  boolean 

top
¶The location of the file with the topology information for external tools (e.g. mdtraj).
Type:  string 

__init__
(dim=1)[source]¶Create an empty ParticleExt list.
Parameters:  dim (integer, optional) – The number of dimensions we are considering for positions, velocities and forces. 

add_particle
(pos, vel, force, mass=1.0, name='?', ptype=0)[source]¶Add a particle to the system.
Parameters: 


particle_type
= 'external'¶set_pos
(pos)[source]¶Set positions for the particles.
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. 

Classes and functions for paths.
The classes and functions defined in this module are useful for representing paths.
pyretis.core.path.
PathBase
(rgen=None, maxlen=None, time_origin=0)[source]¶Bases: object
Base class for representation of paths.
This class represents a path. A path consists of a series of consecutive snapshots (the trajectory) with the corresponding order parameter.
generated
¶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.
Type:  tuple 

maxlen
¶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.
Type:  int 

ordermax
¶This is the (current) maximum order parameter for the path. ordermax[0] is the value, ordermax[1] is the index in self.path.
Type:  tuple 

ordermin
¶This is the (current) minimum order parameter for the path. ordermin[0] is the value, ordermin[1] is the index in self.path.
Type:  tuple 

rgen
¶This is the random generator that will be used for the paths that required random numbers.
Type:  object like RandomGenerator 

time_origin
¶This is the location of the phase point path[0] relative to its parent. This might be useful for plotting.
Type:  int 

status
¶The status of the path. The possibilities are defined in the variable _STATUS.
Type:  str or None 

__iadd__
(other)[source]¶Add path data to a path from another path, i.e. self += other
.
This will simply append the phase points from other.
Parameters:  other (object of type Path) – The object to add path data from. 

Returns:  self (object of type Path) – The updated path object. 
__init__
(rgen=None, maxlen=None, time_origin=0)[source]¶Initialise the PathBase object.
Parameters: 


append
(phasepoint)[source]¶Append a new phase point to the path.
Parameters:  out (object like System ) – The system information we add to the path. 

check_interfaces
(interfaces)[source]¶Check current status of the path.
Get the current status of the path with respect to the interfaces. This is intended to determine if we have crossed certain interfaces or not.
Parameters:  interfaces (list of floats) – This list is assumed to contain the three interface values left, middle and right. 

Returns: 

delete
(idx)[source]¶Remove a phase point from the path.
Parameters:  idx (integer) – The index of the frame to remove. 

empty_path
(**kwargs)[source]¶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.
Returns:  out (object like PathBase ) – A new empty path. 

get_end_point
(left, right)[source]¶Return the end point of the path as a string.
The end point is either to the left of the left interface or to the right of the right interface, or somewhere in between.
Parameters: 


Returns:  out (string) – A string representing where the end point is (‘L’  left, ‘R’  right or None). 
get_path_data
(status, interfaces)[source]¶Return information about the path.
This information can be stored in a object like
PathEnsemble
.
Parameters: 


get_shooting_point
()[source]¶Return a shooting point from the path.
Returns: 


get_start_point
(left, right)[source]¶Return the start point of the path as a string.
The start point is either to the left of the left interface or to the right of the right interface.
Parameters: 


Returns:  out (string) – A string representing where the start point is (‘L’  left, ‘R’  right or None). 
length
¶Compute the length of the path.
ordermax
Compute the maximum order parameter of the path.
ordermin
Compute the minimum order parameter of the path.
reverse
(order_function)[source]¶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.
Returns: 


set_move
(move)[source]¶Update the path move.
The path move is a short string that represents how the path was generated. It should preferably match one of the moves defined in _GENERATED.
Parameters:  move (string) – A short description of the move. 

sorting
(key, reverse=False)[source]¶Reorder the phase points according to the given key.
Parameters: 


Yields:  out (object like 
success
(detect)[source]¶Check if the path is successful.
The check is based on the maximum order parameter and the value of detect. It is successful if the maximum order parameter is greater than detect.
Parameters:  detect (float) – The value for which the path is successful, i.e. the “detect” interface. 

update_energies
(ekin, vpot)[source]¶Update the energies for the phase points.
This method is useful in cases where the energies are read from external engines and returned as a list of floats.
Parameters: 


pyretis.core.path.
Path
(rgen=None, maxlen=None, time_origin=0)[source]¶Bases: pyretis.core.path.PathBase
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.
empty_path
(**kwargs)[source]¶Return an empty path of same class as the current one.
Returns:  out (object like PathBase ) – A new empty path. 

get_shooting_point
()[source]¶Return a shooting point from the path.
This will simply draw a shooting point from the path at random. All points can be selected with equal probability with the exception of the end points which are not considered.
Returns: 


pyretis.core.path.
paste_paths
(path_back, path_forw, overlap=True, maxlen=None)[source]¶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:
Parameters: 


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).
Classes and functions for path ensembles.
The classes and functions defined in this module are useful for representing path ensembles.
PathEnsemble
)PathEnsembleExt
)pyretis.core.pathensemble.
PathEnsemble
(ensemble_number, interfaces, detect=None, maxpath=10000, exe_dir=None)[source]¶Bases: object
Representation of a path ensemble.
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.
ensemble_number
¶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.
Type:  integer 

ensemble_name
¶A string which can be used for printing the ensemble name.
This is of form [0^]
, [0^+]
, [1^+]
, etc.
Type:  string 

ensemble_name_simple
¶A string with a simpler representation of the ensemble name, can be used for creating output files etc.
Type:  string 

interfaces
¶Interfaces, specified with the values for the order parameters: [left, middle, right].
Type:  list of floats 

detect
¶Interface to use for analysis.
Type:  float 

paths
¶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.
Type:  list 

nstats
¶This dict store some statistics for the path ensemble. The keys are:
Type:  dict of ints 

maxpath
¶The maximum number of paths to store.
Type:  int 

__init__
(ensemble_number, interfaces, detect=None, maxpath=10000, exe_dir=None)[source]¶Initialise the PathEnsemble object.
Parameters: 


add_path_data
(path, status, cycle=0)[source]¶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: 


get_acceptance_rate
()[source]¶Return acceptance rate for the path ensemble.
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.
Returns:  out (float) – The acceptance rate. 

get_accepted
()[source]¶Yield accepted paths from the path ensemble.
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.
get_paths
()[source]¶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. 

load_restart_info
(path, info, cycle=0)[source]¶Load restart information.
Parameters: 


reset_data
()[source]¶Erase the stored data in the path ensemble.
It can be used in combination with flushing the data to a file in order to periodically write and empty the amount of data stored in memory.
Notes
We do not reset self.last_path as this might be used in the RETIS function.
pyretis.core.pathensemble.
PathEnsembleExt
(ensemble_number, interfaces, detect=None, maxpath=10000, exe_dir=None)[source]¶Bases: pyretis.core.pathensemble.PathEnsemble
Representation of a path ensemble.
This class is similar to PathEnsemble
but it is made
to work with external paths. That is, some extra file handling is
done when accepting a path.
_copy_path
(path, target_dir, prefix=None)[source]¶Copy a path to a given target directory.
Parameters: 


Returns:  out (object like py:class:.PathBase) – A copy of the input path. 
_move_path
(path, target_dir, prefix=None)[source]¶Move a path to a given target directory.
Parameters: 


This file contains a class for a generic property.
pyretis.core.properties.
Property
(desc='')[source]¶Bases: object
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)
desc
¶Description of the property.
Type:  string 

nval
¶Number values stored.
Type:  integer 

mean
¶The current mean.
Type:  float 

delta2
¶Helper variable used for calculating the variance.
Type:  float 

variance
¶The current variance
Type:  float 

val
¶Store all values.
Type:  list 

Parameters:  desc (string, optional) – Used to set the attribute desc. 

Examples
>>> from pyretis.core.properties import Property
>>> ener = Property(desc='Energy of the particle(s)')
>>> ener.add(42.0)
>>> ener.add(12.220)
>>> ener.add(99.22)
>>> ener.mean
__init__
(desc='')[source]¶Initialise the property.
Parameters:  desc (string, optional) – Description of the object. 

add
(val)[source]¶Add a value to the property & update the mean and variance.
Parameters:  val (float or another type (list, numpy.array)) – The value to add. 

Returns:  out (None) – Returns None but updates the mean and variance. 
dump_to_file
(filename)[source]¶Dump the contents in self.val to a file.
Parameters:  filename (string) – Name/path of file to write. 

Note
Consider if this should be moved/deleted and just replaced with a function from a more general inputoutput module
update_mean_and_variance
()[source]¶Calculate the mean and variance on the fly.
Source: http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
Returns:  out (None) – Returns None but updates the mean and variance. 

Note
Consider if this should be moved/deleted and just replaced with a function from the analysis package.
This module handles random number generation.
It derives most of the random number procedures from RandomState in numpy.random and defines a class which used RandomState to generate pseudorandom numbers.
RandomGeneratorBase
)RandomGenerator
)ReservoirSampler
)MockRandomGenerator
)pyretis.core.random_gen.
RandomGeneratorBase
(seed=0)[source]¶Bases: object
A base class for random number generators.
This is a base class for random number generators. It does not actually implement a generator.
seed
¶A seed for the generator
Type:  int 

__init__
(seed=0)[source]¶Initialise the random number generator.
Parameters:  seed (int, optional) – An integer used for seeding the generator if needed. 

draw_maxwellian_velocities
(system, sigma_v=None)[source]¶Draw numbers from a Gaussian distribution.
Parameters: 


generate_maxwellian_velocities
(particles, boltzmann, temperature, dof, selection=None, momentum=True)[source]¶Generate velocities from a Maxwell distribution.
The velocities are drawn to match a given temperature and this function can be applied to a subset of the particles.
The generation is done in three steps:
1.0/sqrt(mass_i)
and reset the momentum.Parameters: 


Returns:  out (None) – Returns None but modifies velocities of the selected particles. 
multivariate_normal
(mean, cov, cho=None, size=1)[source]¶Draw numbers from a multivariate distribution.
Parameters: 


Returns:  out (float or numpy.array of floats size) – The random numbers that are drawn here. 
normal
(loc=0.0, scale=1.0, size=None)[source]¶Return values from a normal distribution.
Parameters: 


Returns:  out (float, numpy.array of floats) – The random numbers generated. 
rand
(shape=1)[source]¶Draw random numbers in [0, 1).
Parameters:  shape (int, optional) – The number of numbers to draw 

Returns:  out (float) – Pseudorandom number in [0, 1) 
pyretis.core.random_gen.
RandomGenerator
(seed=0)[source]¶Bases: pyretis.core.random_gen.RandomGeneratorBase
A random number generator from numpy.
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].
seed
¶A seed for the pseudorandom generator.
Type:  int 

rgen
¶This is a container for the Mersenne Twister pseudorandom number generator as implemented in numpy [13].
Type:  object like numpy.random.RandomState 

References
[13]  The NumPy documentation on RandomState, http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.RandomState.html 
__init__
(seed=0)[source]¶Initialise the random number generator.
If a seed is given, the random number generator will be seeded.
Parameters:  seed (int, optional) – An integer used for seeding the generator if needed. 

multivariate_normal
(mean, cov, cho=None, size=1)[source]¶Draw numbers from a multivariate distribution.
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: 


Returns:  out (float or numpy.array of floats size) – The random numbers that are drawn here. 
See also
numpy.random.multivariate_normal()
normal
(loc=0.0, scale=1.0, size=None)[source]¶Return values from a normal distribution.
Parameters: 


Returns:  out (float, numpy.array of floats) – The random numbers generated. 
rand
(shape=1)[source]¶Draw random numbers in [0, 1).
Parameters:  shape (int, optional) – The number of numbers to draw 

Returns:  out (float) – Pseudorandom number in [0, 1) 
Note
Here, we will just draw a list of numbers and not for an arbitrary shape.
random_integers
(low, high)[source]¶Draw random integers in [low, high].
Parameters: 


Returns:  out (int) – The pseudorandom integers in [low, high]. 
Note
np.random.randint(low, high) is defined as drawing from low (inclusive) to high (exclusive).
pyretis.core.random_gen.
ReservoirSampler
(seed=0, length=10, rgen=None)[source]¶Bases: object
A class representing a reservoir sampler.
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.
rgen
¶This is a container for the Mersenne Twister pseudorandom number generator as implemented in numpy, see the documentation of RandomGenerator.
Type:  object like numpy.random.RandomState 

items
¶The number of items seen so far, i.e. the current N.
Type:  integer 

reservoir
¶The items we have stored.
Type:  list 

length
¶The maximum number of items to store in the reservoir (i.e. k).
Type:  integer 

ret_idx
¶This is the index of the item to return if we are requesting items from the reservoir.
Type:  integer 

References
[14]  The Art of Computer Programming. 
__init__
(seed=0, length=10, rgen=None)[source]¶Initialise the reservoir.
Parameters: 


pyretis.core.random_gen.
MockRandomGenerator
(seed=0, norm_shift=False)[source]¶Bases: pyretis.core.random_gen.RandomGeneratorBase
A mock random generator, useful only for testing.
This class represents a random generator that can be used for testing algorithms. It will simply return numbers from a small list of pseudorandom numbers. This class is only useful for testing algorithms on different systems. It should NEVER be used for actual production runs!
__init__
(seed=0, norm_shift=False)[source]¶Initialise the mock random number generator.
Here, we set up some predefined random number which we will use as a pool for the generation.
Parameters: 


multivariate_normal
(mean, cov, cho=None, size=1)[source]¶Draw numbers from a multivariate distribution.
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: 


Returns:  out (float or numpy.array of floats size) – The random numbers that are drawn here. 
See also
numpy.random.multivariate_normal()
normal
(loc=0.0, scale=1.0, size=None)[source]¶Return values from a normal distribution.
Parameters: 


Returns:  out (float, numpy.array of floats) – The random numbers generated. 
Note
This is part of the Mockrandom number generator. Hence, it won’t provide a true normal distribution, though the mean is set to the value of loc.
rand
(shape=1)[source]¶Draw random numbers in [0, 1).
Parameters:  shape (int) – The number of numbers to draw. 

Returns:  out (float) – Pseudorandom number in [0, 1). 
This module contains functions for RETIS.
This module defines functions that are needed to perform Replica Exchange Transition Interface Sampling (RETIS). The algorithms implemented here and the description of RETIS was first described by van Erp [RETIS].
make_retis_step()
)retis_tis_moves()
)retis_moves()
)[0^] <> [0^+], [1^+] <> [2^+], ...
or
[0^+] <> [1^+], [2^+] <> [3^+], ...
.retis_swap()
)retis_swap_zero()
)[0^] <> [0^+]
swap.References
[RETIS]  Titus S. van Erp, Phys. Rev. Lett. 98, 26830 (2007), http://dx.doi.org/10.1103/PhysRevLett.98.268301 
pyretis.core.retis.
make_retis_step
(ensembles, order_function, engine, rgen, settings, cycle)[source]¶Determine and execute the appropriate RETIS move.
Here we will determine what kind of RETIS moves we should do. We have two options:
retis_moves()
.retis_tis_moves()
.This function will just determine and execute the appropriate move (1 or 2) based on the given swapping frequencies in the settings and drawing a random number from the random number generator rgen.
Parameters: 


Returns:  out (list of lists) – out[i] contains the result after performing the move for path ensemble no. i. 
pyretis.core.retis.
retis_tis_moves
(ensembles, order_function, engine, rgen, settings, cycle)[source]¶Execute the TIS steps in the RETIS method.
This function will execute the TIS steps in the RETIS method. These differ slightly from the regular TIS moves since we have two options on how to perform them. These two options are controlled by the given settings:
If relative_shoots is given in the input settings, then we will pick at random what ensemble we will perform TIS on. For all the other ensembles we again have two options based on the given settings[‘nullmoves’]:
Performing the null move in an ensemble will simply just accept the previously accepted path in that ensemble again.
If relative_shoots is not given in the input settings, then we will perform TIS moves for all path ensembles.
Parameters: 


Returns:  output (list of lists) – output[i] contains the result for ensemble i. output[i][0] gives information on what kind of move was tried. 
pyretis.core.retis.
retis_moves
(ensembles, order_function, engine, rgen, settings, cycle)[source]¶Perform RETIS moves on the given ensembles.
This function will perform RETIS moves on the given ensembles. First we have two strategies based on settings[‘retis’][‘swapsimul’]:
[0^] <> [0^+], [1^+] <> [2^+], ...
or [0^+] <> [1^+], [2^+] <> [3^+], ...
. Which one of these
two swap options we use is determined randomly and they have
equal probability.Parameters: 


Returns:  out (list of lists) – out[i] contains the results of the swapping/null move for path ensemble no. i. 
pyretis.core.retis.
retis_swap
(ensembles, idx, order_function, engine, settings, cycle)[source]¶Perform a RETIS swapping move for two ensembles.
The RETIS swapping move will attempt to swap accepted paths between two ensembles in the hope that path from [i^+] is an acceptable path for [(i+1)^+] as well. We have two cases:
Parameters: 


Returns: 

Note
Note that path.generated is NOT updated here. This is because we are just swapping references and not the paths. In case the swap is rejected updating this would invalidate the last accepted path.
pyretis.core.retis.
retis_swap_zero
(ensembles, order_function, engine, settings, cycle)[source]¶Perform the RETIS swapping for [0^] <> [0^+]
swaps.
The RETIS swapping move for ensembles [0^] and [0^+] requires some extra integration. Here we are generating new paths for [0^] and [0^+] in the following way:
A_0
and the
second last point B
, and we let A_1, A_2, ...
be the
points on the backward trajectory generated from A_0
then
the final path will be made up of the points
[..., A_2, A_1, A_0, B]
. Here, B
will be on the right
side of the interface and the first point of the path will also
be on the right side.B
(this is on the
left side of the interface), the last point A_0
and the
points generated from A_0
we denote by A_1, A_2, ...
.
Then the resulting path will be [B, A_0, A_1, A_2, ...]
.
Here, B
will be on the left side of the interface and the
last point of the path will also be on the left side of the
interface.Parameters: 


Returns:  out (string) – The result of the swapping move. 
pyretis.core.retis.
null_move
(path_ensemble, cycle)[source]¶Perform a null move for an path ensemble.
The null move simply consist of accepting the last accepted path again.
Parameters: 


Returns: 

Module defining the system class.
The system class is used to group together many important objects in PyRETIS, for instance, the particles, force field etc.
System
)pyretis.core.system.
System
(units='lj', box=None, temperature=None)[source]¶Bases: object
This class defines a generic system for simulations.
box
¶Defines the simulation box.
Type:  object like Box 

temperature
¶This dictionary contains information on the temperature. The following information is stored:
T
, (if any).1.0/(k_B*T)
.Type:  dict 

order
¶The order parameter(s) for the current state of the system (if they have been calculated).
Type:  tuple 

particles
¶Defines the particle list which represents the particles and the properties of the particles (positions, velocities, forces etc.).
Type:  object like Particles 

post_setup
¶This list contains extra functions that should be called when
preparing to run a simulation. This is typically functions that
should only be called after the system is fully set up. The
tuples should correspond to (‘function’, args) where
such that system.function(*args)
can be called.
Type:  list of tuples 

forcefield
¶Defines the force field to use and implements the actual force and potential calculation.
Type:  object like ForceField 

units
¶Units to use for the system/simulation. Should match the defined
units in pyretis.core.units
.
Type:  string 

__init__
(units='lj', box=None, temperature=None)[source]¶Initialise the system.
Parameters: 


Note
self.temperature is defined as a dictionary. This is just because it’s convenient to include information about the degrees of freedom of the system here.
_adjust_dof_according_to_box
()[source]¶Adjust the dof’s according to the box connected to the system.
For each ‘True’ in the periodic settings of the box, we subtract one degree of freedom for that dimension.
add_particle
(pos, vel=None, force=None, mass=1.0, name='?', ptype=0)[source]¶Add a particle to the system.
Parameters: 


Returns:  out (None) – Does not return anything, but updates 
adjust_dof
(dof)[source]¶Adjust the degrees of freedom to neglect in the system.
Parameters:  dof (numpy.array) – The degrees of freedom to neglect, in addition to the ones we already have neglected. 

calculate_beta
(temperature=None)[source]¶Return the socalled beta factor for the system.
Beta is defined as where is the Boltzmann constant and the temperature T is either specified in the parameters or assumed equal to the set temperature of the system.
Parameters:  temperature (float, optional) – The temperature of the system. If the temperature is not given, self.temperature will be used. 

Returns:  out (float) – The calculated beta factor, or None if no temperature data is available. 
calculate_temperature
()[source]¶Calculate the temperature of the system.
It is included here for convenience since the degrees of freedom are easily accessible and it’s a very common calculation to perform, even though it might be cleaner to include it as a particle function.
Returns:  out (float) – The temperature of the system. 

copy
()[source]¶Return a copy of the system.
This copy is useful for storing snapshots obtained during a simulation.
Returns:  out (object like System ) – A copy of the system. 

evaluate_force
()[source]¶Evaluate forces on the particles.
Returns: 


Note
This function will not update the forces, just calculate them. Use self.force to update the forces.
evaluate_potential
()[source]¶Evaluate the potential energy.
Returns:  out (float) – The potential energy. 

Note
This function will not update the potential, but it will just return its value for the (possibly given) configuration. The function self.potential can be used to update the potential for the particles in the system.
evaluate_potential_and_force
()[source]¶Evaluate the potential and/or the force.
Returns: 


Note
This function will not update the forces/potential energy for the particles. To update these, call self.potential_and_force.
extra_setup
()[source]¶Perform extra setup for the system.
The extra setup will typically be tasks that can only be performed after the system is fully setup, for instance after the force field is properly defined.
force
()[source]¶Update the forces and the virial.
The update is done by calling self._evaluate_potential_force.
Returns: 


generate_velocities
(rgen=None, seed=0, momentum=True, temperature=None, distribution='maxwell')[source]¶Set velocities for the particles according to a given temperature.
The temperature can be specified, or it can be taken from self.temperature[‘set’].
Parameters: 


Returns:  out (None) – Does not return anything, but updates system.particles.vel. 
get_boltzmann
()[source]¶Return the Boltzmann constant in correct units for the system.
Returns:  out (float) – The Boltzmann constant. 

get_dim
()[source]¶Return the dimensionality of the system.
The value is obtained from the box. In other words, it is the box object that defines the dimensionality of the system.
Returns:  out (integer) – The number of dimensions of the system. 

potential_and_force
()[source]¶Update the potential energy and forces.
The potential in self.particles.vpot and the forces in self.particles.force are here updated by calling forcefield.evaluate_potential_force().
Returns: 


This file contains functions used in TIS.
This module defines the functions needed to perform TIS simulations. The algorithms are implemented as described by van Erp et al. [TIS].
make_tis_step()
)make_tis_step_ensemble()
)shoot()
)time_reversal()
)References
[TIS]  Titus S. van Erp, Daniele Moroni and Peter G. Bolhuis, J. Chem. Phys. 118, 7762 (2003), https://dx.doi.org/10.1063%2F1.1562614 
pyretis.core.tis.
make_tis_step_ensemble
(path_ensemble, order_function, engine, rgen, tis_settings, cycle)[source]¶Perform a TIS step in a given path ensemble.
This function will run make_tis_step()
for the
given path ensemble and handling adding of the path to the path
ensemble.
Parameters: 


Returns: 

pyretis.core.tis.
make_tis_step
(path, order_function, interfaces, engine, rgen, tis_settings, start_cond)[source]¶Perform a TIS step and generate a new path.
The new path will be generated from the input path, either by performing a timereversal move or by a shooting move. This is determined pseudorandomly by drawing a random number from a uniform distribution using the given random generator.
Parameters: 


Returns: 

pyretis.core.tis.
shoot
(path, order_function, interfaces, engine, rgen, tis_settings, start_cond)[source]¶Perform a shootingmove.
This function will perform the shooting move from a randomly selected timeslice.
Parameters: 


Returns: 

pyretis.core.tis.
time_reversal
(path, order_function, interfaces, start_condition)[source]¶Perform a timereversal move.
Parameters: 


Returns: 

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 . An internal calculation of 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:
e
: Electron charge.C
: Coulomb.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).N
: Newton.pN
: Piconewton.dyn
: Dyne.A
: Ångström.nm
: Nanometre.bohr
: Bohr radius.m
: Meter.g/mol
: Grams per mol, numerically equal to the atomic mass unit.g
: Gram.kg
: Kilogram.Pa
: Pascal.bar
: Bar.atm
: Atmosphere.K
: Kelvin.s
: Second.ps
: Picosecond.fs
: Femtosecondns
: Nanosecond.us
: Microsecond.ms
: Millisecond.m/s
: Meter per second.nm/ps
: Nanometer per picosecond.A/fs
: Ångström per femtosecond.A/ps
: Ångström per picosecond.The following system of units are defined for PyRETIS:
lj
: A LennardJones type of units.real
: A system of units similar to the LAMMPS unit real. [8]metal
: A system of units similar to the LAMMPS unit metal. [8]au
: Atomic units. [9]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 LennardJones units (lj
) are typically
based on the LennardJones parameters for one of the components, e.g.
, 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:
System name  Energy unit  Length unit  Mass unit 

real  1 kcal/mol  1 Å  1 g/mol 
metal  1 eV  1 Å  1 g/mol 
au  1 hartree  1 bohr  9.10938291e31 kg 
electron  1 hartree  1 bohr  1 g/mol 
si  1 J  1 m  1 kg 
gromacs  1 kJ/mol  1 nm  1 g/mol 
cp2k  1 hartree  1 Å  1 g/mol 
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.
System name  Time unit 

real  48.8882129084 fs 
metal  10.1805056505 fs 
au  0.0241888423521 fs 
electron  1.03274987345 fs 
si  1.0 s 
gromacs  1.0 ps 
cp2k  0.0457102889683 fs 
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.5 fs / 48.8882129084 fs
.
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.
[1]  (1, 2) https://en.wikipedia.org/wiki/Boltzmann_constant 
[2]  https://en.wikipedia.org/wiki/Avogadro_constant 
[3]  https://en.wikipedia.org/wiki/Elementary_charge 
[4]  https://en.wikipedia.org/wiki/Speed_of_light 
[5]  https://en.wikipedia.org/wiki/Vacuum_permeability 
[6]  https://en.wikipedia.org/wiki/Vacuum_permittivity 
[7]  National Institute of Standards and Technology, http://physics.nist.gov/cuu/Constants/Table/allascii.txt 
[8]  (1, 2, 3, 4) The LAMMPS manual, http://lammps.sandia.gov/doc/units.html 
[9]  https://en.wikipedia.org/wiki/Atomic_units 
[10]  The GROMACS manual, tables 2.1 and 2.2 on page. 8, http://manual.gromacs.org/documentation/5.1.1/manual5.1.1.pdf 
[11]  Rowley et al., J. Comput. Phys., vol. 17, pp. 401414, 1975, doi: http://dx.doi.org/10.1016/00219991 
[12]  Note that ‘dimension’ here is, strictly speaking, not a true dimension, for instance, we define conversions for the dimension velocity which in reality is composed of the dimensions length and time. 
Examples
>>> from pyretis.core.units import CONVERT # doctest: +ELLIPSIS
>>> print(CONVERT['length'])
{('A', 'nm'): 0.1, ('A', 'bohr'): 1.8897261254578281, ('A', 'm'): 1e10}
>>> from pyretis.core.units import create_conversion_factors
>>> create_conversion_factors('lj', length=(3.405, 'A'), energy=(119.8, 'kB'),
... mass=(39.948, 'g/mol'), charge='e')
>>> print(CONVERT['length']['bohr', 'nm'])
0.052917721067
>>> print(CONVERT['length']['lj', 'nm'])
0.3405
>>> print(CONVERT['length']['bohr', 'lj'])
0.155411809301
>>> create_conversion_factors('cgs', length=(0.01, 'm'),
... energy=(1.0e7, 'J'),
... mass=(1.0, 'g'), charge='e')
>>> print(round(CONVERT['force']['cgs', 'dyn'], 2))
1.0
>>> print(round(CONVERT['time']['cgs', 's'], 2))
1.0
pyretis.core.units.
generate_conversion_factors
(unit, distance, energy, mass, charge='e')[source]¶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: 


pyretis.core.units.
generate_inverse
(conversions)[source]¶Generate all simple inverse conversions.
A simple inverse conversion is something we can obtain by doing
a 1 / unit
type of conversion.
Parameters:  conversions (dictionary) – The unit conversions as convert[quantity]. Note that this variable will be updated by this function. 

Returns:  out (None) – Will not return anything, but will update the given parameter conversions. 
pyretis.core.units.
bfs_convert
(conversions, unit_from, unit_to)[source]¶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 Breadthfirst search.
Parameters: 


Returns: 

pyretis.core.units.
convert_bases
(dimension)[source]¶Create all conversions between base units.
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. 

pyretis.core.units.
print_table
(unit, system=False)[source]¶Print out tables with conversion factors.
This is a table in rst format which is useful for displaying conversions.
Parameters: 


Returns:  out (None) – Does not return anything, but will print to the screen. 
pyretis.core.units.
write_conversions
(filename='units.txt')[source]¶Print out the information currently stored in CONVERT.
This function is intended for creating a big list of conversion factors that can be included in this script for defining unit conversions.
Parameters:  filename (string, optional) – The file to write units to. 

Returns:  out (None) – Will not return anything, but writes the given file. 
pyretis.core.units.
read_conversions
(filename='units.txt', select_units=None)[source]¶Load conversion factors from a file.
This will load unit conversions from a file.
Parameters: 


Returns:  out (dict) – A dictionary with the conversions. 
pyretis.core.units.
CONSTANTS
= Dictionary with natural constants¶A dict containing the natural constants. Natural constants can be accessed with CONSTANTS[‘kB’][‘eV/K’] etc.
pyretis.core.units.
CONVERT
= Dictionary with conversion factors¶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.
pyretis.core.units.
DIMENSIONS
= Dictionary with known dimensions¶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.
pyretis.core.units.
UNITS
= Dictionary with known base units¶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’}
pyretis.core.units.
UNIT_SYSTEMS
= Dictionary with definitions of systems of units¶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.