bdld.actions package

Submodules

bdld.actions.action module

Module containing the abstract base class for all actions

Also has helper functions used by multiple actions

class bdld.actions.action.Action

Bases: object

Abstract base class for all actions

final_run(step)

If not implemented, do nothing

Parameters:

step (int) – current simulation step

run(step)

Needs to be defined for all actions

Parameters:

step (int) – current simulation step

bdld.actions.action.get_valid_data(data, step, stride, update_stride, last_write)

Get the currently valid rows as a view of the data array

This is required to for actions storing their data continuously that also want to be able to write / reset their data array at any time

The data array is assumed to have the following properties:

  • it is filled every update_stride, the first step is 1, not 0

  • after the last element is reached the first is written again, all previously stored data is no longer valid

  • nothing influences this order, e.g. even a reset will continue writing the next element instead of starting from the beginning

This results in several assumptions on the arguments, which are not checked!

  • the write_stride must be a multiple of the update_stride

  • the last_write argument should not refer to a step before the last rewrite from the beginning

  • the stride argument must be a multiple of the update_stride

if these are not satisfied the returned data will not be correct.

The stride argument makes the function only return the data of every nth time step. It is placed here for calling this function regularly, because if the array size is not a multiple, an offset has to be taken into account from the previous times

Parameters:
  • data (ndarray) – data array whose valid rows are returned, each row represents a point in time

  • step (int) – current simulation step

  • stride (int) – Return only data points of every nth time step (not stride of data points!)

  • update_stride (int) – number of time steps between data points

  • last_write (int) – when the data was last written (needs to be less than write_stride ago)

Return type:

ndarray

bdld.actions.birth_death module

Birth death algorithm

class bdld.actions.birth_death.ApproxVariant(value)

Bases: Enum

Enum for the different approximation variants

add = 'additive'
classmethod from_str(label)

Return class instance from matching string

Return type:

ApproxVariant

mult = 'multiplicative'
orig = 'original'
class bdld.actions.birth_death.BirthDeath(particles, md_dt, stride, bw, kt, rate_fac=None, recalc_probs=False, approx_variant=None, eq_density=None, seed=None, stats_stride=None, stats_filename=None)

Bases: Action

Birth death algorithm.

This has a lot of instance attributes, containing also some statistics.

Parameters:
  • particles (List[BpldParticle]) – list of Particles shared with MD

  • stride (int) – number of MD timesteps between birth-death exectutions

  • dt – time between subsequent birth-death evaluations

  • kt (float) – thermal energy of system

  • inv_kt – inverse of kt for faster access

  • bw (Union[List[float], ndarray]) – bandwidth for gaussian kernels per direction

  • rate_fac (Optional[float]) – factor for b/d probabilities in exponential

  • approx_variant (Optional[ApproxVariant]) – type of approximation (lambda)

  • approx_grid – helper grid storing some values depending only on pi Note that this has different values depending on the variant (additive / multiplicative)

  • rng – random number generator instance for birth-death moves

  • stats – Stats class instance collecting statistics

:raises

class Stats(bd_action, filename=None)

Bases: object

Simple data class for grouping the stats

Parameters:
  • dup_count – number of accepted duplication events

  • dup_atempts – number of attempted duplication events

  • kill_count – number of accepted kill events

  • kill_atempts – number of attempted kill events

print(step, reset=False)

Print birth/death probabilities to file or screen

Return type:

None

reset()

Set all logging counters to zero

Return type:

None

calc_betas()

Calculate the birth/death rate for every particle

Return type:

ndarray

do_birth_death()

Calculate which particles to kill and duplicate and perform the task

The particles will be processed in random order By default the beta values will be evaluated only once at the beginning, set recalc_probs to change this behavior

Return event_list:

List with Tuples (dup_i, kill_i) of the accepted events

Return type:

List[Tuple[int, int]]

final_run(step)

Print out stats if they were not before

Return type:

None

perform_moves(event_list)

Execute the birth-death moves given in the event_list.

Parameters:

event_list (List[Tuple[int, int]]) – List with Tuples(i,j) of the particle numbers. Particle j will be replaced by a copy of particle i

Return type:

None

random_other(num_part, excl)

Select random particle while excluding the one given as second argument

Parameters:
  • num_part (int) – total number of particles

  • excl (int) – particle to exclude

Return num:

random particle

Return type:

int

run(step)

Perform birth-death step on particles

Parameters:

step (int) – current timestep of simulation

Return type:

None

walker_density_grid(grid, energy)

Calculate the density of walkers and bd-probabilities on a grid

This function is a relict and currently not used anywhere in the code Kept here for possible debugging at a later time

Parameters:
  • grid (ndarray) – positions to calculate the kernel values

  • energy (ndarray) – energies of the grid values

Return array:

grid rho beta

Return type:

ndarray

bdld.actions.birth_death.calc_additive_correction(eq_density, bw, conv_mode='same')

Additive correction for the probabilites due to the Gaussian Kernel

Calculates the following two terms from the Kernel K and equilibrium walker distribution pi .. :math:: -log((K(x) * pi(x)) / pi(x)) + int (log((K(x) * pi(x)) / pi(x))) pi mathrm{d}x

Parameters:
  • eq_density (Grid) – grid with equilibrium probability density of system

  • bw (ndarray) – bandwidths of the kernel (sigma)

  • conv_mode (str) – convolution mode to use. See dens_kernel_convolution() for details.

Return correction:

grid wih the correction values

Return type:

Grid

bdld.actions.birth_death.calc_kernel(dist, bw)

Return kernel values from the distances to center

Currently directly returns Gaussian kernel other kernels could later be implemented via string argument

Parameters:
  • dist (ndarray) – array of shape (n_dist, n_dim) with distances per dimensions

  • bw (ndarray) – bandwidth per dimension

Return type:

ndarray

bdld.actions.birth_death.dens_kernel_convolution(eq_density, bw, conv_mode)

Return convolution of the a probability density with the kernel

This is equivalent to doing a kernel density estimation

In practice only used to calculate K * pi, i.e. the KDE of the equilibrium density

If the “valid” conv_mode is used the returned grid is smaller than the original one. The “same” mode will return a grid with the same ranges, but might have issues due to edge effects from the convolution

Parameters:
  • eq_density (Grid) – grid with equilibrium probability density of system

  • bw (ndarray) – bandwidths of the kernel (sigma)

  • conv_mode (str) – convolution mode to use (affects output size). If ‘valid’ the resulting correction grid will have a smaller domain than the original eq_density one. If ‘same’ it will use exactly the ranges of the original grid.

Return conv:

grid holding the convolution values

Return type:

Grid

bdld.actions.birth_death.nd_trapz(data, dx)

Calculate a multidimensional integral via recursive usage of the trapezoidal rule

Uses numpy’s trapz for the 1d integrals

Parameters:
  • data (ndarray) – values to integrate

  • dx (Union[List[float], float]) – distances between datapoints per dimension

Return integral:

integral value

Return type:

float

bdld.actions.birth_death.walker_density(pos, bw)

Calculate the local density at each walker (average kernel value)

The actual calculations are done by the different _walker_density functions depending on the number of walkers

Parameters:
  • pos (numpy.ndarray) – positions of particles

  • bw (float) – bandwidth parameter of kernel

Return numpy.ndarray kernel:

kernel value matrix

Return type:

ndarray

bdld.actions.bussi_parinello_ld module

Simple Langevin Dynamics with Bussi-Parinello thermostat

This is an implementation of the algorithm introduced in https://doi.org/10.1103/PhysRevE.75.056707 see there for reasoning and further details

It works by introducing thermostat steps between the velocity Verlet ones, the algorithm is designed to yield also the correct sampling in the overdamped limit

class bdld.actions.bussi_parinello_ld.BpldParticle(*args)

Bases: Particle

Derived Particle class that additionally stores MD related variables

Parameters:
  • energy – stores last energy evaluation

  • forces – stores last force evaluation per dimension

  • c2 – constant for the MD thermostat (mass dependent)

class bdld.actions.bussi_parinello_ld.BussiParinelloLD(pot, dt, friction, kt, seed=None)

Bases: Action

Perform Langevin Dynamics with Bussi-Parinello thermostat

Can handle multiple non-interacting particles (= walkers) simultaneously

Parameters:
  • pot (Potential) – potential to perform LD on

  • dt (float) – timestep

  • friction (float) – friction parameter of langevin equation

  • kt (float) – thermal energy in units of kt

  • rng – numpy.random.Generator instance for the thermostat

  • c1 – constant for thermostat

add_particle(pos, mass=1.0, partnum=-1, overwrite=False)

Add particle to system

Parameters:
  • pos (Union[List, ndarray]) – list or numpy array with initial position of the particle per dimension

  • mass – mass of particle, defaults to 1.0

  • partnum (int) – specifies particle number (position in list). Default is -1 (at end)

  • overwrite (bool) – overwrite existing particle instead of inserting (default False)

Raises:

ValueError – when dimensions of pos and potential do not match

Return type:

None

remove_particle(partnum)

Removes particle from MD

Parameters:

partnum (int) – specifies particle number in list

Return type:

None

run(step=None)

Perform single MD step on all particles

Parameters:

step (Optional[int]) – Not used, just to have the right function signature

Return type:

None

bdld.actions.delta_f_action module

Module holding the DeltaFAction class

class bdld.actions.delta_f_action.DeltaFAction(fes_action, masks, stride=None, filename=None, write_stride=None, write_fmt=None, ref=None)

Bases: Action

Calculate Delta F from fes and print or save it to file

If no filename is specified this still calculates the values (for possible usage in other actions) but never actually writes them to file

final_run(step)

If not implemented, do nothing

Parameters:

step (int) – current simulation step

Return type:

None

run(step)

Calculate Delta F from fes and write to file

Parameters:

step (int) – current simulation step, optional

Return type:

None

write(step)

Write delta F values to file to file

Does nothing if self.filename is empty

Parameters:

step (int) – current simulation step

Return type:

None

bdld.actions.delta_f_action.calculate_delta_f(fes, kt, masks)

Calculates the free energy difference between states defined by boolean masks

If more than two are specified, this returns the difference to the first state for all others

Parameters:
  • fes (ndarray) – free energy surface to examine

  • kt (float) – energy in units of kT

  • masks (List[ndarray]) – a list of boolean numpy arrays resembling the states

Return delta_F:

a list of doubles containing the free energy difference to the first state

Raises:

IndexError – if the dimensions of the FES and any of the masks do not match

bdld.actions.delta_f_action.check_mask_shapes(masks, fes)

Check if the shape of all masks is equal to the shape of the FES

Return type:

None

bdld.actions.fes_action module

Module holding the FesAction class

Also holds functions for calculating and plotting the FES

class bdld.actions.fes_action.FesAction(histo_action, stride=None, filename=None, write_stride=None, write_fmt=None, plot_stride=None, plot_filename=None, plot_domain=None, plot_title=None, ref=None)

Bases: Action

Calculate fes from histogram and save to file

The actual FES is not a data member of this class but rather a member of the Histogram instance of the passed histo_action. This is mostly for historical reasons, as the Histogram class existed before the code was restructured into actions

Parameters:
  • fes – Grid instance hosting the FES

  • kt – thermal energy in units of kT

final_run(step)

Same as run() but without stride checks and passing the step number

Return type:

None

plot(step=None)

Plot fes with reference and optionally save to file

If a step is specified it will be appended to the filename, i.e. it is written to a new file. It will also be used for the plot title

Parameters:

step (Optional[int]) – current simulation step, optional

Return type:

None

run(step)

Calculate fes from histogram, write to file and plot if matching strides

Parameters:

step (int) – current simulation step, optional

Return type:

None

write(step=None)

Write fes to file

If a step is specified it will be appended to the filename, i.e. it is written to a new file. If no filename is set, this will do nothing.

Parameters:

step (Optional[int]) – current simulation step, optional

Return type:

None

bdld.actions.fes_action.calculate_fes(histo, kt, mintozero=True)

Calculate free energy surface from histogram

Parameters:
  • histo (Histogram) – Histogram instance to calculate FES from

  • kt (float) – thermal energy of the system

  • mintozero (bool) – shift FES to have minimum at zero

Return fes:

Grid with the fes values as data

Return type:

Grid

bdld.actions.fes_action.plot_fes(fes, axes, ref=None, plot_domain=None, filename=None, title=None)

Show fes with matplotlib

Does work with 1D and 2D fes, higher dimensions will be ignored without error

Parameters:
  • fes (ndarray) – the fes to plot

  • axes (List[ndarray]) – axes of plot

  • ref (Optional[ndarray]) – optional reference FES to plot (makes only sense for 1d fes)

  • plot_domain (Optional[Tuple[float, float]]) – optional Tuple with minimum and maximum value to show

  • filename (Optional[str]) – optional filename to save figure to

  • title (Optional[str]) – optional title for the legend

Return type:

None

bdld.actions.fes_action.save_fig_interactive(fig)

Ask for filename to save file to

bdld.actions.histogram_action module

Module holding the HistogramAction class

class bdld.actions.histogram_action.HistogramAction(traj_action, n_bins, ranges, stride=None, reset=None, filename=None, write_stride=None, write_fmt=None)

Bases: Action

Action collecting trajectory data into a histogram

The Histogram data member is periodically enhanced with the new data from the trajectories.

Parameters:
  • histo – Histogram data

  • update_stride – add trajectory data every n time steps

final_run(step)

Same as run without stride checks

Parameters:

step (int) – current simulation step

get_traj_data(step)

Get the right data from the trajectory array

Parameters:

step (int) – current simulation step

Return type:

ndarray

run(step)

Add trajectory data to histogram and write to file if strides are matched

Parameters:

step (int) – current simulation step

write(step=None)

Write histogram to file

If a step is specified it will be appended to the filename, i.e. it is written to a new file If no filename is set, this will do nothing.

Parameters:

step (Optional[int]) – current simulation step, optional

bdld.actions.trajectory_action module

Module holding the TrajectoryAction class

class bdld.actions.trajectory_action.TrajectoryAction(ld, stride=None, filename=None, momentum=None, write_stride=None, write_fmt=None)

Bases: Action

Class that stories trajectories and writes them to file

The write_stride parameter determines how many trajectory points are being held in memory even if they are never written. This allow other actions to use them.

Parameters:

traj – fixed size numpy array holding the time and positions it is written row-wise (i.e. every row represents a time) and overwritten after being saved to file

final_run(step)

Write rest of trajectories to files

Return type:

None

run(step)

Store positions in traj array and write to file if write_stride is matched

The stride parameters is ignored here and all times are temporarily stored This is because a HistogramAction using the data might have a different stride

Parameters:

step (int) – current simulation step

Return type:

None

write(step)

Write currently stored trajectory data to file

This can also be called between regular saves (e.g. at the end of the simulation) and will not result in missing or duplicate data Because the trajectories are stored in the array independently from the writes the function needs to do some arithmetics to find out what to write

If no filenames were set this function will do nothing but not raise an exception

Parameters:

step (int) – current simulation step

Return type:

None

Module contents

Import all submodules when importing the actions module