pyretis.simulation package

pyretis.simulation package

This package defines different simulations for use with PyRETIS.

The different simulations are defined as objects which inherit from the base Simulation object defined in simulation.py. The simulation object defines as simulation as a series of tasks to be executed, typically at each step of the simulation. These tasks may produce results which can be outputted to the user in some way.

Package structure

Modules

md_simulation.py (pyretis.simulation.md_simulation)
Defines simulation classes for molecular dynamics simulations.
mc_simulation.py (pyretis.simulation.mc_simulation)
Define simulation classes for Monte Carlo simulations.
path_simulation.py (pyretis.simulation.path_simulation)
Defines simulation classes for path simulations.
simulation.py (pyretis.simulation.simulation)
Defines the Simulation class which is the base class for simulations.
simulation_task.py (pyretis.simulation.simulation_task)
Defines classes for the handling of simulation tasks.

Important classes defined in this package

Simulation (Simulation)
The base class for simulations.
SimulationTask (SimulationTask)
A class for creating tasks for simulations.
SimulationSingleTIS (SimulationSingleTIS)
A class for running a TIS simulation for a single ensemble.
SimulationPPTIS (SimulationPPTIS)
A class for running a PPTIS simulation for a single ensemble.
SimulationRETIS (SimulationRETIS)
A class for running a RETIS simulation for a set of ensembles.
SimulationPPRETIS (SimulationPPRETIS)
A class for running a REPPTIS simulation for a set of ensembles.

pyretis.simulation.async_runner module

asyncio-based task runner for the infinite-swapping scheduler.

The runner drives the worker pool that executes the per-cycle run_md calls produced by pyretis.simulation.scheduler.

exception pyretis.simulation.async_runner.RunnerError[source]

Bases: Exception

Exception class for the runner.

class pyretis.simulation.async_runner._ShutdownNoiseFilter(name='')[source]

Bases: Filter

Drop the expected BrokenProcessPool teardown noise.

When the worker pool is force-released on an interrupt / SIGTERM (a tutorial smoke run killed by its timeout, an HPC walltime kill, a user Ctrl-C), an in-flight run_in_executor future can finish with a concurrent.futures.BrokenExecutor after its wrapper task was already cancelled. asyncio then reports it – usually during interpreter shutdown – as “Future exception was never retrieved” at ERROR level with a full traceback. That is expected teardown noise, not a real failure (a genuine pool failure mid-run is retrieved onto the work future via future.set_exception and never reaches this “never retrieved” path), so it is dropped. Everything else passes through untouched.

filter(record: LogRecord) bool[source]

Return False only for the unretrieved-BrokenExecutor record.

pyretis.simulation.async_runner._install_shutdown_noise_filter() None[source]

Attach _ShutdownNoiseFilter to the asyncio logger once.

asyncio’s default exception handler logs through the asyncio logger, so the filter is installed there (a logger-level filter drops the record before it propagates to the root handlers). Idempotent: a second runner does not stack a duplicate filter.

class pyretis.simulation.async_runner.aiorunner(config: Dict, n_workers: int = 1)[source]

Bases: object

A light asynchronuous runner based on asyncio.

The runner manage an asyncio.queue with a pool of workers. Upon instanciation, a dedicated event loop is launched in a separate thread. The user can then attach a worker function to the runner and start multiple instances of that function in the background. As work is submitted to the runner, it is picked up by workers on-the-fly.

__init__(config: Dict, n_workers: int = 1) None[source]

Init function of runner.

Parameters:
  • config – The simulation configuration dictionary. It is forwarded unchanged to every worker process via the pool initializer (worker_initializer()) and must therefore be picklable (the pool uses the spawn start method). When config contains a "simulation" section the initializer builds that worker’s engine pool and order parameters from it (via pyretis.engines.factory.create_engines() and create_orderparameters()) and installs the engines as process-local state with set_worker_engines(); the engines are intentionally not part of the per-task work units, so they never cross the process boundary.
  • n_workers – Number of worker processes in the pool.
async _add_work_to_queue(work_unit: Dict[str, Any]) Future[source]

Async function adding work to queue, returns a future.

Args
work_unit: a unit of work encapsulated in a dict
Returns:A future wih the results of the work
async _cancel_pending_tasks() None[source]

Cancel the worker-wrapper tasks and await their completion.

_start_event_loop() None[source]

Start the event loop in a separate thread.

async _start_tasks() None[source]

Launch the background tasks.

async _task_wrapper(stop_event: Event, queue: Queue, executor: Executor, taskID: int) None[source]

Wrap the sync task.

To enable running the sync task_f from a dynamic list of tasks.

Parameters:
  • stop_event – a asyncio event to stop the worker
  • queue – an asyncio queue to get work from
  • executor – an executor
  • taskID – an ID for the long running task
close() None[source]

Force-release runner resources without draining the queue.

Safe to call from an error/interrupt path (unlike stop(), which waits for the work queue to empty): it cancels the pending worker tasks, stops the event loop and shuts the pool down so it is never orphaned.

n_workers() int[source]

Return runner number of workers.

set_task(task_f: Callable) None[source]

Attach the task function to the runner.

Parameters:task_f – a callable function
start() None[source]

Launch background tasks.

stop() None[source]

Terminate the runner and release the worker pool.

submit_work(work_unit: Dict[str, Any]) Future[source]

Submit work to the runner.

Parameters:task – a unit of work encapsulated in a dict
Returns:A future wih the results of the work
async wait_for_tasks_to_end() None[source]

Async function waiting for tasks to end.

class pyretis.simulation.async_runner.future_list[source]

Bases: object

A managed list of future.

__init__() None[source]

Initialize future list.

add(future: Future) None[source]

Add a future to list.

as_completed() Optional[Future][source]

Get future as they are done.

Returns:return a future from the list, whenever it is done or return None when the list is empty.
pyretis.simulation.async_runner.get_worker_engines() Dict[str, Any][source]

Return the engine pool created for the current worker process.

pyretis.simulation.async_runner.prepare_streaming_engines(engines, config)[source]

Give the internal integrators their file-backed streaming setup.

The coordinator hands every engine file-backed phase points (a snapshot System whose config points at a trajectory file). The external engines read that file natively; the internal integrators (langevin / velocityverlet / verlet / randomwalk) integrate from in-memory particles instead, so they need a streaming template – their own box / particles / masses / force field – built from the carried-through native [system] / [box] / [particles] / [potential] / [forcefield] sections. This mirrors how TurtleMDEngine builds its own box / particles / potential in __init__. Engines without a setup_streaming method (the external engines) are skipped.

Parameters:
  • engines (dict of lists) – The per-worker engine pool, keyed by engine name.
  • config (dict) – The coordinator configuration dictionary.
pyretis.simulation.async_runner.set_worker_engines(engines: Dict[str, Any]) None[source]

Install the engine pool for the current worker process.

pyretis.simulation.async_runner.worker_initializer(counter, config)[source]

Initialize function for each worker process.

pyretis.simulation.mc_simulation module

Definition of simulation objects for Monte Carlo simulations.

This module defines some classes and functions for performing Monte Carlo simulations.

Important classes defined here

UmbrellaWindowSimulation (UmbrellaWindowSimulation)
Defines a simulation for performing umbrella window simulations. Several umbrella window simulations can be joined to perform a umbrella simulation.
class pyretis.simulation.mc_simulation.UmbrellaWindowSimulation(ensemble, settings, controls=None)[source]

Bases: Simulation

This class defines an Umbrella simulation.

The Umbrella simulation is a special case of the simulation class with settings to simplify the execution of the umbrella simulation.

Variables:
  • ensemble (dict) –

    It contains the simulation info:

    • system : object like System The system to act on.
    • rgen : object like RandomGenerator Object to use for random number generation.
  • umbrella (list, [float, float]) – The umbrella window to consider.
  • overlap (float) – The position we have to cross before the simulation ends.
  • maxdx (float) – Defines the maximum movement allowed in the Monte Carlo
  • steps (int, optional) – The number of simulation steps to perform.
  • startcycle (int, optional) – The cycle we start the simulation on, can be useful if restarting.
__init__(ensemble, settings, controls=None)[source]

Initialise the umbrella simulation simulation.

Parameters:
  • ensemble (dict) – It contains the simulation info:
    • system : object like System The system to act on.
    • rgen : object like RandomGenerator Object to use for random number generation.
  • settings (dict) – Contains all the simulation settings.
  • controls (dict of parameters to control the simulations. Optional) – It can contain:
    • mincycle : int, optional The MINIMUM number of cycles to perform. Note that in base Simulation class this is the MAXIMUM number of cycles to perform. The meaning is redefined in this class by overriding self.simulation_finished.
    • startcycle : int, optional The current simulation cycle, i.e. where we start.
__str__()[source]

Return some info about the simulation as a string.

is_finished()[source]

Check if the simulation is done.

In the umbrella simulation, the simulation is finished when we cycle is larger than maxcycle and all particles have crossed self.overlap.

Returns:out (boolean) – True if the simulation is finished, False otherwise.
load_restart_info(info)[source]

Load the restart information.

restart_info()[source]

Return information which can be used to restart the simulation.

Returns:info (dict,) – Contains all the updated simulation settings and counters.
simulation_type = 'umbrella-window'

pyretis.simulation.md_simulation module

Definitions of simulation objects for molecular dynamics simulations.

This module contains definitions of classes for performing molecular dynamics simulations.

Important classes defined here

SimulationNVE (SimulationNVE)
Definition of a simple NVE simulation. The engine used for this simulation must have dynamics equal to NVE.
SimulationMD (SimulationMD)
Definition of a simulation for running somply MD.
SimulationMDFlux (SimulationMDFlux)
Definition of a simulation for determining the initial flux. This is used for calculating rates in TIS simulations.
class pyretis.simulation.md_simulation.SimulationMD(ensemble, settings=None, controls=None)[source]

Bases: Simulation

A generic MD simulation.

This class is used to define a MD simulation without whistles and bells.

__init__(ensemble, settings=None, controls=None)[source]

Only add variable.

Parameters:
  • ensemble (dict) – It contains the simulations info
    • system : object like System This is the system we are investigating.
    • engine : object like EngineBase This is the integrator that is used to propagate the system in time.
    • order_function : object like OrderParameter, optional. A class that can be used to calculate an order parameter, if needed.
  • settings (dict, optional) – This dictionary contains the settings for the simulation.
  • controls (dict of parameters, optional) – It contains:
    • steps : int, optional The number of simulation steps to perform.
    • startcycle : int, optional The cycle we start the simulation on, can be useful if restarting.
__str__()[source]

Return a string with info about the simulation.

run()[source]

Run the MD simulation.

Yields:results (dict) – The results from a single step in the simulation.
simulation_output = [{'type': 'energy', 'name': 'md-energy-file'}, {'type': 'thermo-file', 'name': 'md-thermo-file'}, {'type': 'traj-xyz', 'name': 'md-traj-file'}, {'type': 'thermo-screen', 'name': 'md-thermo-screen'}, {'type': 'order', 'name': 'md-order-file'}]
simulation_type = 'md'
class pyretis.simulation.md_simulation.SimulationMDFlux(ensemble, settings=None, controls=None)[source]

Bases: SimulationMD

A simulation for obtaining the initial flux for TIS.

This class is used to define a MD simulation where the goal is to calculate crossings in order to obtain the initial flux for a TIS calculation.

__init__(ensemble, settings=None, controls=None)[source]

Initialise the MD-Flux simulation object.

Parameters:
  • ensemble (dict) – It contains the simulations info
    • system : object like System The system to act on.
    • engine : object like EngineBase This is the integrator that is used to propagate the system in time.
    • order_function : object like OrderParameter The class used for calculating the order parameters.
  • settings (dict, optional) – This dictionary contains the settings for the simulation.
  • controls (dict of parameters, optional) – It contains:
    • steps : int, optional The number of simulation steps to perform.
    • startcycle : int, optional The cycle we start the simulation on, can be useful if restarting.
__str__()[source]

Return a string with info about the simulation.

load_restart_info(info)[source]

Load the restart information.

restart_info()[source]

Return information which can be used to restart the simulation.

Returns:info (dict) – Contains all the updated simulation settings and counters.
run()[source]

Run the MD simulation.

Yields:results (dict) – The results from a single step in the simulation.
simulation_output = [{'type': 'energy', 'name': 'flux-energy-file'}, {'type': 'traj-xyz', 'name': 'flux-traj-file'}, {'type': 'thermo-screen', 'name': 'flux-thermo-screen'}, {'type': 'order', 'name': 'flux-order-file'}, {'type': 'cross', 'name': 'flux-cross-file'}]
simulation_type = 'md-flux'
class pyretis.simulation.md_simulation.SimulationNVE(ensemble, settings=None, controls=None)[source]

Bases: SimulationMD

A MD NVE simulation class.

This class is used to define a NVE simulation. Compared with the SimulationMD we here require that the engine supports NVE dynamics.

__init__(ensemble, settings=None, controls=None)[source]

Initialise the NVE simulation object.

Here we will set up the tasks that are to be performed in the simulation, such as the integration and thermodynamics calculation(s).

Parameters:
  • ensemble (dict) – It contains the simulations info
    • system : object like System This is the system we are investigating.
    • engine : object like EngineBase This is the integrator that is used to propagate the system in time.
    • order_function : object like OrderParameter, opt A class that can be used to calculate an order parameter, if needed.
  • settings (dict, optional) – This dictionary contains the settings for the simulation.
  • controls (dict of parameters, optional) – It contains:
    • steps : int, optional The number of simulation steps to perform.
    • startcycle : int, optional The cycle we start the simulation on.
__str__()[source]

Return a string with info about the simulation.

load_restart_info(info)[source]

Load the restart information.

restart_info()[source]

Return information which can be used to restart the simulation.

Returns:info (dict,) – Contains all the updated simulation settings and counters.
simulation_output = [{'type': 'energy', 'name': 'nve-energy-file'}, {'type': 'thermo-file', 'name': 'nve-thermo-file'}, {'type': 'traj-xyz', 'name': 'nve-traj-file'}, {'type': 'thermo-screen', 'name': 'nve-thermo-screen'}, {'type': 'order', 'name': 'nve-order-file'}]
simulation_type = 'md-nve'
step()[source]

Run a single simulation step.

pyretis.simulation.path_simulation module

Definitions of simulation objects for path sampling simulations.

This module defines simulations for performing path sampling simulations.

Important classes defined here

PathSimulation (PathSimulation)
The base class for path simulations.
SimulationTIS (SimulationSingleTIS)
Definition of a TIS simulation for a single path ensemble.
SimulationRETIS (SimulationRETIS)
Definition of a RETIS simulation.
SimulationPPRETIS (SimulationPPRETIS)
Definition of a PPRETIS simulation.
class pyretis.simulation.path_simulation.PathSimulation(ensembles, settings, controls)[source]

Bases: Simulation

A base class for TIS/RETIS simulations.

Variables:
  • ensembles (list of dictionaries of objects) –

    Each contains:

    • path_ensemble: objects like PathEnsemble This is used for storing results for the different path ensembles.
    • engine: object like EngineBase This is the integrator that is used to propagate the system in time.
    • rgen: object like RandomGenerator This is a random generator used for the generation of paths.
    • system: object like System This is the system the simulation will act on.
  • settings (dict) –
    A dictionary with TIS and RETIS settings. We expect that
    we can find settings['tis'] and possibly settings['retis']. For settings['tis'] we further expect to find the keys:
    • sigma_v: The velocity width. Negative values select aimless shooting; zero or positive values select soft velocity perturbations.
    • seed: A integer seed for the random generator used for the path ensemble we are simulating here.

    Note that the pyretis.core.tis.make_tis_step_ensemble() method will make use of additional keys from settings['tis']. Please see this method for further details. For the settings['retis'] we expect to find the following keys:

    • swapfreq: The frequency for swapping moves.
    • relative_shoots: If we should do relative shooting for the path ensembles.
    • nullmoves: Should we perform null moves.
    • swapsimul: Should we just swap a single pair or several pairs.
    required_settingstuple of strings
    This is just a list of the settings that the simulation requires. Here it is used as a check to see that we have all we need to set up the simulation.
__init__(ensembles, settings, controls)[source]

Initialise the path simulation object.

Parameters:
  • ensembles (list of dicts) – Each contains:
    • path_ensemble: object like PathEnsemble This is used for storing results for the simulation. It is also used for defining the interfaces for this simulation.
    • system: object like System This is the system we are investigating.
    • order_function: object like OrderParameter The object used for calculating the order parameter.
    • engine: object like EngineBase This is the integrator that is used to propagate the system in time.
    • rgen: object like RandomGenerator This is the random generator to use in the ensemble.
  • settings (dict) – This dictionary contains the settings for the simulation.
  • controls (dict of parameters to set up and control the simulations) – It contains:
    • steps: int, optional The number of simulation steps to perform.
    • startcycle: int, optional The cycle we start the simulation on, useful for restarts.
    • rgen: object like RandomGenerator This object is the random generator to use in the simulation.
create_output_tasks(settings, progress=False)[source]

Create output tasks for the simulation.

This method will generate output tasks based on the tasks listed in simulation_output.

Parameters:
  • settings (dict) – These are the simulation settings.
  • progress (boolean) – For some simulations, the user may select to display a progress bar, we then need to disable the screen output.
initiate(settings)[source]

Initialise the path simulation.

Parameters:settings (dictionary) – The simulation settings.
load_restart_info(info)[source]

Load restart information.

Note: This method load the info for the main simulation, the actual
ensemble restart is done in initiate_restart.
Parameters:info (dict) – The dictionary with the restart information, should be similar to the dict produced by restart_info().
name = 'Generic path simulation'
required_settings = ('tis', 'retis')
restart_info()[source]

Return restart info.

The restart info for the path simulation includes the state of the random number generator(s).

Returns:info (dict,) – Contains all the updated simulation settings and counters.
run()[source]

Run a path simulation.

The intended usage is for simulations where all tasks have been defined in self.tasks.

Note

This function will just run the tasks via executing step() In general, this is probably too generic for the simulation you want, if you are creating a custom simulation. Please consider customizing the run() (or the step()) method of your simulation class.

Yields:out (dict) – This dictionary contains the results from the simulation.
simulation_output = [{'type': 'pathensemble', 'name': 'path_ensemble', 'result': ('pathensemble-{}',)}, {'type': 'path-order', 'name': 'path_ensemble-order', 'result': ('path-{}', 'status-{}')}, {'type': 'path-traj-{}', 'name': 'path_ensemble-traj', 'result': ('path-{}', 'status-{}', 'pathensemble-{}')}, {'type': 'path-energy', 'name': 'path_ensemble-energy', 'result': ('path-{}', 'status-{}')}]
simulation_type = 'generic-path'
step()[source]

Perform a TIS/RETIS/PPRETIS simulation step.

Returns:out (dict) – This list contains the results of the defined tasks.
write_restart(now=False)[source]

Create a restart file.

Parameters:now (boolean, optional) – If True, the output file will be written irrespective of the step number.
class pyretis.simulation.path_simulation.SimulationRETIS(ensembles, settings, controls)[source]

Bases: PathSimulation

A RETIS simulation.

This class is used to define a RETIS simulation where the goal is to calculate crossing probabilities for several path ensembles.

The attributes are documented in the parent class, please see: PathSimulation.

__str__()[source]

Just a small function to return some info about the simulation.

name = 'RETIS simulation'
required_settings = ('retis',)
simulation_output = [{'type': 'pathensemble', 'name': 'path_ensemble', 'result': ('pathensemble-{}',)}, {'type': 'path-order', 'name': 'path_ensemble-order', 'result': ('path-{}', 'status-{}')}, {'type': 'path-traj-{}', 'name': 'path_ensemble-traj', 'result': ('path-{}', 'status-{}', 'pathensemble-{}')}, {'type': 'path-energy', 'name': 'path_ensemble-energy', 'result': ('path-{}', 'status-{}')}, {'type': 'pathensemble-retis-screen', 'name': 'path_ensemble-retis-screen', 'result': ('pathensemble-{}',)}]
simulation_type = 'retis'
class pyretis.simulation.path_simulation.SimulationTIS(ensembles, settings, controls)[source]

Bases: PathSimulation

A TIS simulation.

This class is used to define a TIS simulation where the goal is to calculate crossing probabilities for a single path ensemble.

__str__()[source]

Just a small function to return some info about the simulation.

name = 'TIS simulation'
required_settings = ('tis',)
simulation_output = [{'type': 'pathensemble', 'name': 'path_ensemble', 'result': ('pathensemble-{}',)}, {'type': 'path-order', 'name': 'path_ensemble-order', 'result': ('path-{}', 'status-{}')}, {'type': 'path-traj-{}', 'name': 'path_ensemble-traj', 'result': ('path-{}', 'status-{}', 'pathensemble-{}')}, {'type': 'path-energy', 'name': 'path_ensemble-energy', 'result': ('path-{}', 'status-{}')}, {'type': 'pathensemble-screen', 'name': 'path_ensemble-screen', 'result': ('pathensemble-{}',)}]
simulation_type = 'tis'

pyretis.simulation.repex module

Replica-exchange (REPEX) coordinator.

Runs the infinite-swap parallel REPEX bookkeeping for the scheduler in pyretis.simulation.scheduler. A future phase will collapse this with pyretis’s pyretis.core.retis swap moves.

class pyretis.simulation.repex.InfSwapState(config, minus=False)[source]

Bases: object

Define the infinite-swapping replica-exchange (REPEX) state object.

__init__(config, minus=False)[source]

Initiate the swap state given the config dict from a TOML file.

_apply_freq_moves(picked)[source]

Draw the per-cycle native frequency move for a single pick.

Ports the per-cycle move selection of pyretis.core.tis.make_tis_step_ensemble() onto the scheduler. For a single-ensemble (non-swap) pick the configured shooting move is replaced, with the native [tis] weights, by a time reversal (tr, weight freq), a mirror (mr, weight mirror_freq) or a target swap (ts, weight target_freq); otherwise the configured move is kept (weight max(1 - freq - mirror_freq - target_freq, 0)). Mirror and target swap are allowed only in the [0^-] ensemble – native ensemble_number == 0, which is scheduler pick key -1 – matching native’s ensemble_number != 0 gate.

The draw is taken from the ensemble’s per-cycle rgen (the same generator the move itself consumes, so the choice-then-move ordering follows native), and the result overrides mc_move on the (locked, hence worker-private for this cycle) ensemble dict. The move order in the draw matches native (tr, mirror, target swap, configured move).

Parameters:picked (dict) – The per-ensemble pick dict from pick() / pick_lock().
_native_energy_engine()[source]

Return a cached streaming engine for native energy recompute.

Built once from self.config (force field + masses, via the engine’s setup_streaming) and reused for every captured path. Returns None when the configured engine is not a streaming internal integrator that can recompute energy from stored frames (e.g. an external engine that reports energy through its own files), in which case the native energy.txt keeps the engine’s in-memory terms (nan when absent).

add_traj(ens, traj, valid, count=True, n=0)[source]

Add traj to state and calculate P matrix.

property cap

Retrieve mc moves list from config dict.

capture_native_row(pn, path, status)[source]

Store the native pathensemble.txt column data for a path.

Only used on the native-output route; the data is read back by pyretis.inout.native_output to format the per-ensemble pathensemble.txt rows. Stored at path-creation time because the live Path object (with its phase points, generated move tag and status) is not retained in traj_data.

Parameters:
  • pn (int) – The path number.
  • path (object like pyretis.core.path.Path) – The accepted path.
  • status (str) – The native path status (e.g. "ACC").
compute_swap_matrix(input_mat, locks)[source]

Permanent calculator (the infinite-swap probability matrix).

property cstep

Retrieve cstep from config dict.

cworker = None
property data_dir

Retrieve data_dir from config dict.

property data_file

Retrieve data_file from config dict.

fast_glynn_perm(M)[source]

Glynn permanent.

find_blocks(arr, offset)[source]

Find blocks in a W matrix.

initiate()[source]

Initiate loop.

initiate_ensembles()[source]

Create all the ensemble dicts from the TOML config dict.

property interfaces

Retrieve interfaces from config dict.

live_paths()[source]

Return list of live paths.

load_paths(paths)[source]

Load paths.

lock(ens)[source]

Lock ensemble.

locked_paths()[source]

Return list of locked paths.

loop()[source]

Check and iterate loop.

property maxop

Get the maximum orderparameter seen during the simulation.

property mc_moves

Retrieve mc moves list from config dict.

property native_output

Return True when native per-ensemble output is requested.

Set by the native-config input shim via [output] native_compat = true. The normal inf route never sets it, so the coordinator keeps writing only infswap_data.txt.

permanent_prob(arr)[source]

P matrix calculation for specific W matrix.

pick()[source]

Pick path and ens.

pick_lock()[source]

Pick path and ens.

In case a crash, we pick lock locked from previous simulation.

pick_traj_ens(ens)[source]

Pick traj ens.

prep_md_items(md_items)[source]

Fill md_items with picked path and ens.

print_end()[source]

Print end.

print_pick(ens_nums, pat_nums, pin)[source]

Print pick.

print_shooted(md_items, pn_news)[source]

Print shooted.

print_start()[source]

Print start.

print_state()[source]

Print state.

printing()[source]

Check if print.

property prob

Calculate the P matrix.

prune_native_rows()[source]

Drop captured native rows for paths that are no longer live.

Only live paths receive frac increments (see treat_output), so a path that has left every ensemble can never contribute another native output row. Its captured order/energy series would otherwise accumulate without bound over a long run.

quick_prob(arr)[source]

Quick P matrix calculation for specific W matrix.

random_prob(arr, n=10000)[source]

P matrix calculation for specific W matrix.

property screen

Retrieve screen print frequency from config dict.

set_rgen()[source]

Set numpy random generator state from restart.

sort_trajstate()[source]

Sort trajs and calculate P matrix.

swap(traj, ens)[source]

Swap to keep the locks symmetric.

treat_output(md_items)[source]

Treat output.

property tsteps

Retrieve total steps from config dict.

unlock(ens)[source]

Unlock ensemble.

property workers

Retrieve workers from config dict.

write_toml()[source]

Write the restart state to ./restart.toml atomically.

Sequence: serialise to restart.toml.tmp with an explicit fsync so the new payload is on disk; copy any existing restart.toml to restart.toml.prev so the previous cycle’s restart survives even if the final rename loses a race with a power loss; os.replace the tmp file over restart.toml (POSIX-atomic on the same filesystem); finally best-effort fsync the parent directory so the rename commit is past the filesystem journal.

pyretis.simulation.repex.spawn_rng(rgen)[source]

Reimplementation of np.random.Generator.spawn() for numpy <= 1.24.4.

Spawns a new random number generator (RNG) from an existing RNG.

This function creates a new instance of the same type of RNG as the input RNG, using a seed generated from the input RNG’s bit generator.

Parameters: rgen (np.random.Generator): The input random number generator.

Returns: np.random.Generator: A new random number generator instance.

pyretis.simulation.repex.write_path_ensemble_data(state, pn_archive)[source]

Write data to the path-ensemble data file (infswap_data.txt).

pyretis.simulation.scheduler module

Main infinite-swapping scheduler loop.

pyretis.simulation.scheduler.scheduler(config)[source]

Run the infinite-swapping scheduler loop.

pyretis.simulation.setup module

Setup for the infinite-swapping scheduler.

Reads the TOML config, builds the replica-exchange (REPEX) state, and hands the worker pool to pyretis.simulation.async_runner.aiorunner.

exception pyretis.simulation.setup.TOMLConfigError[source]

Bases: Exception

Raised when there is an error in the .toml configuration.

pyretis.simulation.setup._run_md_task(md_items: dict) dict[source]

Worker-side entry point for the runner.

Runs in the worker process and injects that worker’s process-local engine pool into pyretis.core._tis_inf.run_md(), so the runner stays engine-agnostic and run_md takes its engines explicitly rather than reading a module global.

pyretis.simulation.setup.check_config(config: dict) None[source]

Perform some checks on the settings from the .toml file.

Args
config: the configuration dictionary
pyretis.simulation.setup.setup_config(inp: str = 'infswap.toml', re_inp: str = 'restart.toml') Optional[dict][source]

Set dict from a TOML file up.

Arg
inp: a string specifying the input file (def: infswap.toml) re_inp: a string specifying the restart file (def: restart.toml)
Return
A dictionary containing the configuration parameters or None
pyretis.simulation.setup.setup_internal(config: dict) Tuple[dict, InfSwapState][source]

Run the various setup functions.

Args
config: the configuration dictionary
Returns:A blank md_items dict An initialized REPEX state
pyretis.simulation.setup.setup_logger(inp: str = 'sim.log') None[source]

Set main logger.

Args
inp: a string specifying the main log file
pyretis.simulation.setup.setup_runner(state: InfSwapState) Tuple[aiorunner, future_list][source]

Set the task runner class up.

Parameters:state – A REPEX state from which to get the config dict
pyretis.simulation.setup.write_header(config: dict) None[source]

Write infswap_data.txt header.

Args
config: the configuration dictionary

pyretis.simulation.simulation module

Definitions of generic simulation objects.

This module defines the generic simulation object. This is the base class for all other simulations.

Important classes defined here

Simulation (Simulation)
A class defining a generic simulation.
class pyretis.simulation.simulation.Simulation(settings, controls)[source]

Bases: object

This class defines a generic simulation.

Variables:
  • cycle (dict of integers) –

    This dictionary stores information about the number of cycles. The keywords are:

    • step: The current cycle number.
    • startcycle: The cycle number we started at.
    • endcycle: Represents the cycle number where the simulation should end.
    • stepno: The number of cycles we have performed to arrive at
      cycle number given by cycle[‘step’]. Note that cycle[‘stepno’] might be different from cycle[‘step’] since cycle[‘startcycle’] might be != 0.
  • exe_dir (string) – The path we are running the simulation from.
  • restart_freq (integer) – The frequency for creating restart files.
  • first_step (boolean) – True if the first step has not been executed yet.
  • system (object like System) – This is the system the simulation will act on.
  • simulation_output (list of dicts) – This list defines the output tasks associated with the simulation.
  • simulation_type (string) – An identifier for the simulation.
  • tasks (list of objects like SimulationTask) – This is the list of simulation tasks to execute.
__init__(settings, controls)[source]

Initialise the simulation object.

Parameters:
  • controls (dict of parameters to set up and control the simulations.) –

    It contains:

    • steps: int, optional The number of simulation steps to perform.
    • startcycle: int, optional The cycle we start the simulation on, useful for restarts.
    • endcycle: int, optional The cycle we end the simulation to, useful in restarts.
    • rgen: object like RandomGenerator The random generator that will be used for the paths that required random numbers.
  • settings (dict) – Contains all the simulation settings.

__str__()[source]

Just a small function to return some info about the simulation.

add_task(task, position=None)[source]

Add a new simulation task.

A task can still be added manually by simply appending to py:attr:.tasks. This function will, however, do some checks so that the task added can be executed.

Parameters:
  • task (dict) – A dict defining the task. A task is represented by an object of type SimulationTask with some additional settings on how to store the output and when to execute the task. The keywords in the dict defining the task are:
    • func: Callable, this is a function to execute in the task.
    • args: List, with arguments for the function.
    • kwargs: Dict, with the keyword arguments for the function.
    • when: Dict, which defines when the task should be executed.
    • first: Boolean, determines if the task should be executed on the initial step, i.e. before the full simulation starts.
    • result: String, used to label the result.
  • position (int, optional) – Can be used to give the tasks a specific position in the task list.
create_output_tasks(settings, progress=False)[source]

Create output tasks for the simulation.

This method will generate output tasks based on the tasks listed in simulation_output.

Parameters:
  • settings (dict) – These are the simulation settings.
  • progress (boolean) – For some simulations, the user may select to display a progress bar, we then need to disable the screen output.
execute_tasks()[source]

Execute all the tasks in sequential order.

Returns:results (dict) – The results from the different tasks (if any).
extend_cycles(steps)[source]

Extend a simulation with the given number of steps.

Parameters:steps (int) – The number of steps to extend the simulation with.
Returns:out (None) – Returns None but modifies self.cycle.
is_finished()[source]

Determine if the simulation is finished.

In this object, the simulation is done if the current step number is larger than the end cycle. Note that the number of steps performed is dependent on the value of self.cycle[‘startcycle’].

Returns:out (boolean) – True if the simulation is finished, False otherwise.
load_restart_info(info)[source]

Load restart information.

Note, we do not change the end property here as we probably are extending a simulation.

Parameters:info (dict) – The dictionary with the restart information.
restart_info()[source]

Return information which can be used to restart the simulation.

Returns:info (dict,) – Contains all the updated simulation settings and counters.
run()[source]

Run a simulation.

The intended usage is for simulations where all tasks have been defined in self.tasks.

Note

This function will just run the tasks via executing step() In general, this is probably too generic for the simulation you want, if you are creating a custom simulation. Please consider customizing the run() (or the step()) method of your simulation class.

Yields:out (dict) – This dictionary contains the results from the simulation.
set_up_output(settings, progress=False)[source]

Set up output from the simulation.

This includes the predefined output tasks, but also output related to the restart file(s).

Parameters:
  • settings (dict) – These are the simulation settings.
  • progress (boolean) – For some simulations, the user may select to display a progress bar, we then need to disable the screen output.
simulation_output = []
simulation_type = 'generic'
soft_exit()[source]

Force simulation to stop at the current step.

step()[source]

Execute a simulation step.

Here, the tasks in tasks will be executed sequentially.

Returns:out (dict) – This dictionary contains the results of the defined tasks.

Note

This function will have ‘side effects’ and update/change the state of other attached variables such as the system or other variables that are not explicitly shown. This is intended and the behavior is defined by the tasks in tasks.

write_restart(now=False)[source]

Create a restart file.

Parameters:now (boolean, optional) – If True, the output file will be written irrespective of the step number.

pyretis.simulation.simulation_task module

Definition of a class for simulation tasks.

Important classes defined here

SimulationTask (SimulationTask)
A class representing a simulation task.
SimulationTaskList (SimulationTaskList)
A class for representing a list of simulation tasks. This class defines functionality for adding tasks from a dictionary description.
class pyretis.simulation.simulation_task.SimulationTask(function, args=None, kwargs=None, when=None, result=None, first=False)[source]

Bases: Task

Representation of simulation tasks.

This class defines a task object. A task is executed at specific points, at regular intervals etc. in a simulation. A task will typically provide a result, but it does not need to. It can simply just alter the state of the passed argument(s).

Variables:
  • function (function) – The function to execute.
  • when (dict) – Determines when the task should be executed.
  • args (list) – List of arguments to the function.
  • kwargs (dict) – The keyword arguments to the function.
  • first (boolean) – True if this task should be executed before the first step of the simulation.
  • result (string) – This is a label for the result created by the task.
__call__(step)[source]

Execute the task.

Parameters:

step (dict of ints) – The keys are:

  • ‘step’: the current cycle number.
  • ‘startcycle’: the cycle number at the start.
  • ‘stepno’: the number of cycles we have performed so far.
Returns:

out (unknown type) – The result of self.execute(step).

__init__(function, args=None, kwargs=None, when=None, result=None, first=False)[source]

Initialise the task.

Parameters:
  • function (callable) – The function to execute.
  • args (list, optional) – List of arguments to the function.
  • kwargs (dict, optional) – The keyword arguments to the function.
  • when (dict, optional) – Determines if the task should be executed.
  • result (string, optional) – This is a label for the result created by the task.
  • first (boolean, optional) – True if this task should be executed before the first step of the simulation.
__str__()[source]

Output info about the task.

execute(step)[source]

Execute the task.

Parameters:

step (dict of ints) – The keys are:

  • ‘step’: the current cycle number.
  • ‘startcycle’: the cycle number at the start.
  • ‘stepno’: the number of cycles we have performed so far.
Returns:

out (unknown type) – The result of running self.function.

property result

Return the result label.

run_first()[source]

Return True if task should be executed before first step.

task_dict()[source]

Return a dict representing the task.

pyretis.simulation.simulation_task._check_args(function, given_args=None, given_kwargs=None)[source]

Check consistency for function and the given (keyword) arguments.

Here we assume that the arguments are given in a list and that the keyword arguments are given as a dictionary. The function inspect.getargspec is used to check the input function.

Parameters:
  • function (callable) – The function we will inspect.
  • given_args (list, optional) – A list of the arguments to pass to the function. ‘self’ will not be considered here since it passed implicitly.
  • given_kwargs (dict, optional) – A dictionary with keyword arguments.
Returns:

out (boolean) – False if there is some inconsistencies, i.e. when the calling of the given function will probably fail. True otherwise.