This package defines the core PyRETIS tools.
The core tools are intended to set up simulations and run them.
pyretis.core.box
)pyretis.core.common
)pyretis.core.initiation
)pyretis.core.montecarlo
)pyretis.core.particlefunctions
)pyretis.core.particles
)pyretis.core.path
)pyretis.core.pathensemble
)pyretis.core.properties
)pyretis.core.random_gen
)pyretis.core.retis
)pyretis.core.system
)pyretis.core.tis
)pyretis.core.units
)BoxBase
)System
)Particles
)Path
)PathExt
)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(length=[10, 10, 10], periodic=[True, False, True])
pyretis.core.box.
create_box
(low=None, high=None, length=None, periodic=None)[source]¶Set up and create a box.
Parameters: 


Returns:  out – The object representing the simulation box. 
Return type:  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 usage where we are checking that we can call 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 analyse. 

Returns:  out – A dict with the arguments, the following keys are defined:

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


Returns:  out – Here, we just return the initiated instance of the given class. 
Return type:  instance of klass 
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 defines what classes should be created and the object_map defines a mapping between settings and the class.
Parameters: 


Returns:  out – The created object, in case we were successful. Otherwise we return none. 
Return type:  instance of a class 
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 – True if the move is accepted, False otherwise. 
Return type:  boolean 
Notes
A overflow is possible when using numpy.exp() here. This can for instance happen in a 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 return. 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 – The outcome of applying the function accept_reject to the system and trial position. 
Return type:  boolean 
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 – 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 type:  numpy.array 
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 – The kinetic energy tensor. Dimensionality equal to (dim, dim) where dim is the number of dimensions used in the velocities. The trace gives the kinetic energy. 
Return type:  numpy.array 
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 – The array contains the linear momentum for each dimension. 
Return type:  numpy.array 
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 – The symmetric pressure tensor, dimensions (dim, dim), where dim = the number of dimensions considered in the simulation. 
Return type:  numpy.array 
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 – The scalar pressure, averaged over the diagonal components of the pressure tensor. 
Return type:  float 
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 – This dict contains the float that is calculated in this routine. 
Return type:  dict 
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.
Parameters:  system (object like System ) – This object is used to access the particles and the box. 

Returns:  out – This dict contains the float that is calculated in this routine. 
Return type:  dict 
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 – Returns None and modifies velocities of the selected particles. 
Return type:  None 
This file contain a class to represent 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. In general the particle lists are intended to define neighbour lists etc. This class will just define an allpairs list.
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.
mass
¶numpy.array – Masses of the particles.
imass
¶numpy.array – Inverse masses, 1.0 / self.mass.
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.
__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. 

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


Returns:  out – This method does not return anything, but increments self.npart and updates self.particles. 
Return type:  None 
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_particle_state
()[source]¶Return a copy of the current phase point.
The phase point includes self.pos and self.vel. In addition it returns the accompanying forces from self.force.
Returns:  out – Dictionary with the positions, velocity and forces. 

Return type:  dict 
get_selection
(properties, selection=None)[source]¶Return selected properties for a selection of particles.
Parameters: 


Returns: 

pairs
()[source]¶Iterate over all pairs of particles.
For more sophisticated particle lists this can/should be an implementation of a ‘smart’ neighbour list.
Yields: 


set_force
(force)[source]¶Set the forces for the particles.
This will copy the input forces.
Parameters:  force (numpy.array) – The forces to set. 

set_particle_state
(phasepoint)[source]¶Set the position, velocities (and forces) for the particles.
The function is included here for convenience  it can be used together with self.get_particle_state() for easy change of the particle state.
Parameters:  phasepoint (dict) – This dict contains the phase point we wish to set. It contains the positions in the key ‘pos’ and the velocities in the key ‘vel’. It may optionally include the forces in the key ‘forces’. 

Returns:  out – Returns None and updates self.pos, self.vel and self.force (if given). 
Return type:  None 
pyretis.core.particles.
ParticlesExt
(dim=1)[source]¶Bases: pyretis.core.particles.Particles
Particles, when positions and velocities are stored in files.
This represents a particle list for the case where the positions and velocities might be stored in files.
config
¶tuple of (string, int) – The location of the file with positions and the index for locating a frame.
vel_rev
¶boolean – True if velocities should be reversed before using the phase point.
get_particle_state
()[source]¶Return a copy of the current phase point.
The phase point includes self.pos and self.vel. In addition it returns the accompanying forces from self.force.
Returns:  out – Dictionary with the positions, velocity and forces. 

Return type:  dict 
set_particle_state
(phasepoint)[source]¶Update the state of particles to the given phase point.
The function is included here for convenience  it can be used together with self.get_particle_state() for easy change of the particle state.
Parameters:  phasepoint (dict) – This dict contains the phase point we wish to set. It contains the positions in the key ‘pos’ and the velocities in the key ‘vel’. 

Returns:  out – Returns None and updates self.pos, self.vel 
Return type:  None 
Classes and functions for paths.
The classes and functions defined in this module are useful for representing paths.
PathBase
)Path
)PathExt
)pyretis.core.path.
PathBase
(rgen, maxlen=None, time_origin=0)[source]¶Bases: object
Base class for representation of paths.
This class represents a path. A path consist of a series of consecutive snapshots (the trajectory) with the corresponding order parameter. We are going to assume that we always store the order parameter as a function of the time. For the other properties, the different subclasses might not store all the information.
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 requires this to be set. Others don’t, which is indicated by setting maxlen equal to None.
order
¶list of floats – The order parameters as function of time.
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.
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.
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
vpot
¶list of floats – The potential energy as function of time.
ekin
¶list of floats – The kinetic energy as function of time.
__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 – The updated path object. 
Return type:  object of type Path 
append
(phasepoint)[source]¶Append a new phase point to the path.
We will here append a new phasespace point to the path. The phase point is assumed to be given by positions and velocities with a corresponding order parameter and energy.
Parameters:  phasepoint (dict) – A dictionary with the things to add to the path. We assume that it contains the following keys:


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: 

empty_path
(**kwargs)[source]¶Return an empty path of same class as the current one.
This function is intended to spawn child 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 – A new empty path. 

Return type:  object like PathBase 
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 representing where the end point is (‘L’  left, ‘R’  right or None). 
Return type:  string 
get_path_data
(status, interfaces)[source]¶Return information about the Path.
This information can (and is typically) stored in a 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 representing where the start point is (‘L’  left, ‘R’  right or None). 
Return type:  string 
length
¶Compute the legtt of the path.
ordermax
Compute the maximum order parameter of the path.
ordermin
Compute the minimum order parameter of the path.
phasepoint
(idx)[source]¶Return a specific phase point.
Parameters:  idx (int) – Index for phasespace point to return. 

Returns:  out – A phasespace point in the path. 
Return type:  tuple 
reverse_trajectory
()[source]¶Reverse a path and return the reverse path as a new path.
This will simply reverse a path and return the reversed path as a new Path object. Note that currently, recalculating order parameters have not been implemented! Typically, reversing will not change the order parameter, but it might change the velocity for the order parameter and so on.
Returns:  new_path – This is basically a copy of self, just reversed. 

Return type:  object like PathBase 
set_move
(move)[source]¶Update the path move.
The path move is a short string that represent 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. 

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. 

trajectory
(reverse=False)[source]¶Iterate over the phasespace points in the path.
Parameters:  reverse (boolean) – If this is True, we iterate in the reverse direction. 

Yields:  out (dict) – The phasespace points in the path. 
wt_segments_counter
(interface_l, interface_r)[source]¶Count the directional segment between interfaces.
Method to count the number of the directional segments of the path, along the orderp, that connect FROM interface_r TO interface_l.
Parameters: 


wt_select_and_trim_a_segment
(interface_l, interface_r, segment_to_pick=1)[source]¶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. Be carefull, it can provide multiple discontinous segments
Parameters: 


Returns:  segment – orderp is between interface_r and interface_l and the ones right after/before the interfaces 
Return type:  a path segment composed only of by the snaphots which 
pyretis.core.path.
Path
(rgen, 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 consist 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.
pos
¶list of numpy.arrays – Positions as function of time
vel
¶list of numpy.arrays – Velocities as function of time.
empty_path
(**kwargs)[source]¶Return an empty path of same class as the current one.
Returns:  out – A new empty path. 

Return type:  object like PathBase 
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.
PathExt
(rgen, maxlen=None, time_origin=0)[source]¶Bases: pyretis.core.path.Path
A path where snapshots are not stored in memory.
This class represents a path where the snapshots are stored on disk and not in memory. This is useful when we are using external engines and do not have to read entire trajectories into memory.
pos
¶list of strings – Positions as function of time. Here, the positions are actually files which contain the positions AND velocities
vel
¶list of booleans – If an item in this list is True, the the corresponding
velocities in the snapshot file in pos
should be
reversed.
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 an 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
¶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
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].
detect
¶float – Interface to use for analysis.
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:
maxpath
¶int – The maximum number of paths to store.
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 – The acceptance rate. 

Return type:  float 
get_accepted
()[source]¶Yield accepted paths from the PathEnsemble.
This function will give an iterator useful for iterating over accepted paths only. In the PathEnsemble 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 PathEnsembleFile object defined in pyretis.inout. 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.
generate_output
(cycle, path)[source]¶Output a trajectory by adding it to a tar file.
This method handles the “physical” output.
Parameters: 


Returns:  path_copy – A path like the input path, but with updated file names. 
Return type:  object like 
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
¶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
>>> 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
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 – Returns None but updates the mean and variance. 
Return type:  None 
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 – Returns None but updates the mean and variance. 

Return type:  None 
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
¶int – A seed for the generator
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 – Returns None but modifies velocities of the selected particles. 
Return type:  None 
multivariate_normal
(mean, cov, cho=None, size=1)[source]¶Draw numbers from a multivariate distribution.
Parameters: 


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


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

Returns:  out – Pseudo random number in [0, 1) 
Return type:  float 
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
¶int – A seed for the pseudorandom generator.
rgen
¶object like numpy.random.RandomState
– This is a container for the Mersenne Twister pseudorandom
number generator as implemented in numpy [13].
References
[13]  The NumPy documentation on RandomState, http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.RandomState.html 
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 a 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 – The random numbers drawn. 
Return type:  float or numpy.array of floats size 
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 – The random numbers generated. 
Return type:  float, numpy.array of floats 
rand
(shape=1)[source]¶Draw random numbers in [0, 1).
Parameters:  shape (int) – Number of numbers to draw 

Returns:  out – Pseudo random number in [0, 1) 
Return type:  float 
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 – The pseudo random integers in [low, high]. 
Return type:  int 
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 maintains 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
¶object like numpy.random.RandomState
– This is a container for the Mersenne Twister pseudorandom
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.
References
[14]  The Art of Computer Programming. 
pyretis.core.random_gen.
MockRandomGenerator
(seed=0)[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!
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 a 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 – The random numbers drawn. 
Return type:  float or numpy.array of floats size 
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 – The random numbers generated. 
Return type:  float, numpy.array of floats 
rand
(shape=1)[source]¶Draw random numbers in [0, 1).
Parameters:  shape (int) – Number of numbers to draw 

Returns:  out – Pseudo random number in [0, 1). 
Return type:  float 
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, system, 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:
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 – out[i] contains the result after performing the move for path ensemble no. i. 
Return type:  list of lists 
pyretis.core.retis.
retis_tis_moves
(ensembles, system, 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 – output[i] contains the result for ensemble i. output[i][0] gives information on what kind of move was tried. 
Return type:  list of lists 
pyretis.core.retis.
retis_moves
(ensembles, system, 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 – out[i] contains the results of the swapping/nullmove for path ensemble no. i. 
Return type:  list of lists 
pyretis.core.retis.
retis_swap
(ensembles, idx, system, 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, system, 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 – The result of the swapping move. 
Return type:  string 
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
¶object like Box
– Defines the simulation box.
temperature
¶dict – This dictionary contains information on the temperature. The following information is stored:
T
, (if any).1.0/(k_B*T)
.particles
¶object like Particles
– Defines the particle list which represents the particles and the
properties of the particles (positions, velocities, forces etc.)
post_setup
¶list of tuples – This list contain 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.
forcefield
¶object like ForceField
– Defines the force field to use and implements the actual force
and potential calculation.
units
¶string – Units to use for the system/simulation. Should match the defined
units in pyretis.core.units
.
add_particle
(pos, vel=None, force=None, mass=1.0, name='?', ptype=0)[source]¶Add a particle to the system.
Parameters: 


Returns:  out – Does not return anything, but updates system.particles. 
Return type:  None 
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 – The calculated beta factor, or None if no temperature data is available. 
Return type:  float 
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 – The temperature of the system. 

Return type:  float 
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 – The potential energy. 

Return type:  float 
Note
This function will not update the potential, but it will just return it’s 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 – Does not return anything, but updates system.particles.vel. 
Return type:  None 
get_boltzmann
()[source]¶Return the Boltzmann constant in correct units for the system.
Returns:  out – The Boltzmann constant. 

Return type:  float 
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 – The number of dimensions of the system. 

Return type:  integer 
potential
()[source]¶Update the potential energy.
Returns:  out – The potential energy. 

Return type:  float 
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, system, order_function, engine, rgen, tis_settings, cycle)[source]¶Perform a TIS step for a given path ensemble.
This function will run make_tis_step for the given path_ensemble.
It will handle adding of the path. This function is intended for
convenience when working with path ensembles. If we are using the
path ensemble [0^]
then the start condition should be ‘R’ for
right.
Parameters: 


Returns: 

pyretis.core.tis.
make_tis_step
(path, system, order_function, interfaces, engine, rgen, tis_settings, start_cond)[source]¶Perform a TIS step and generate a new path/trajectory.
The new path will be generated from an existing one, either by performing a timereversal move or by shooting. T(h)is is determined randomly by drawing a random number from a uniform distribution.
Parameters: 


Returns: 

pyretis.core.tis.
shoot
(path, system, 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, 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 defines the time unit.
Further, all system of units expect an input temperature in Kelvin
(K
) and all systems, with the exception of si
, expects a
charge in units of electron charges. The si
system uses here
Coulomb as it’s unit for 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
>>> 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, assumed to be of type convert[quantity]. Note that this variable will be updated by this function. 

Returns:  out – Will not return anything, but will update the given parameter conversions. 
Return type:  None 
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 – Does not return anything, but will print to the screen. 
Return type:  None 
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 – Will not return anything, but writes the given file. 
Return type:  None 
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 – A dictionary with the conversions. 
Return type:  dict 
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 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.