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.
List of submodules¶
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:
ExceptionException class for the runner.
-
class
pyretis.simulation.async_runner._ShutdownNoiseFilter(name='')[source]¶ Bases:
FilterDrop the expected
BrokenProcessPoolteardown 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-flightrun_in_executorfuture can finish with aconcurrent.futures.BrokenExecutorafter 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 viafuture.set_exceptionand never reaches this “never retrieved” path), so it is dropped. Everything else passes through untouched.
-
pyretis.simulation.async_runner._install_shutdown_noise_filter() None[source]¶ Attach
_ShutdownNoiseFilterto the asyncio logger once.asyncio’s default exception handler logs through the
asynciologger, 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:
objectA 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 thespawnstart method). Whenconfigcontains a"simulation"section the initializer builds that worker’s engine pool and order parameters from it (viapyretis.engines.factory.create_engines()andcreate_orderparameters()) and installs the engines as process-local state withset_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.
- config – The simulation configuration dictionary. It is
forwarded unchanged to every worker process via the
pool initializer (
-
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.
-
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.
-
set_task(task_f: Callable) None[source]¶ Attach the task function to the runner.
Parameters: task_f – a callable function
-
-
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
Systemwhoseconfigpoints 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 howTurtleMDEnginebuilds its own box / particles / potential in__init__. Engines without asetup_streamingmethod (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.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:
SimulationThis 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
SystemThe system to act on. - rgen : object like
RandomGeneratorObject to use for random number generation.
- system : object like
- 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
SystemThe system to act on. - rgen : object like
RandomGeneratorObject to use for random number generation.
- system : object like
- 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.
- ensemble (dict) – It contains the simulation info:
-
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.
-
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'¶
- ensemble (dict) –
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:
SimulationA 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
SystemThis is the system we are investigating. - engine : object like
EngineBaseThis 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.
- system : object like
- 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.
- ensemble (dict) – It contains the simulations info
-
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:
SimulationMDA 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
SystemThe system to act on. - engine : object like
EngineBaseThis is the integrator that is used to propagate the system in time. - order_function : object like
OrderParameterThe class used for calculating the order parameters.
- system : object like
- 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.
- ensemble (dict) – It contains the simulations info
-
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:
SimulationMDA MD NVE simulation class.
This class is used to define a NVE simulation. Compared with the
SimulationMDwe 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
SystemThis is the system we are investigating. - engine : object like
EngineBaseThis 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.
- system : object like
- 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.
- ensemble (dict) – It contains the simulations info
-
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'¶
-
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:
SimulationA base class for TIS/RETIS simulations.
Variables: - ensembles (list of dictionaries of objects) –
Each contains:
- path_ensemble: objects like
PathEnsembleThis is used for storing results for the different path ensembles. - engine: object like
EngineBaseThis is the integrator that is used to propagate the system in time. - rgen: object like
RandomGeneratorThis is a random generator used for the generation of paths. - system: object like
SystemThis is the system the simulation will act on.
- path_ensemble: objects like
- settings (dict) –
- A dictionary with TIS and RETIS settings. We expect that
- we can find
settings['tis']and possiblysettings['retis']. Forsettings['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 fromsettings['tis']. Please see this method for further details. For thesettings['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
PathEnsembleThis is used for storing results for the simulation. It is also used for defining the interfaces for this simulation. - system: object like
SystemThis is the system we are investigating. - order_function: object like
OrderParameterThe object used for calculating the order parameter. - engine: object like
EngineBaseThis is the integrator that is used to propagate the system in time. - rgen: object like
RandomGeneratorThis is the random generator to use in the ensemble.
- path_ensemble: object like
- 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
RandomGeneratorThis object is the random generator to use in the simulation.
- ensembles (list of dicts) – Each contains:
-
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 therun()(or thestep()) 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'¶
- ensembles (list of dictionaries of objects) –
-
class
pyretis.simulation.path_simulation.SimulationRETIS(ensembles, settings, controls)[source]¶ Bases:
PathSimulationA 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.-
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:
PathSimulationA TIS simulation.
This class is used to define a TIS simulation where the goal is to calculate crossing probabilities for a single path ensemble.
-
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:
objectDefine 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, weightfreq), a mirror (mr, weightmirror_freq) or a target swap (ts, weighttarget_freq); otherwise the configured move is kept (weightmax(1 - freq - mirror_freq - target_freq, 0)). Mirror and target swap are allowed only in the[0^-]ensemble – nativeensemble_number == 0, which is scheduler pick key-1– matching native’sensemble_number != 0gate.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 overridesmc_moveon 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’ssetup_streaming) and reused for every captured path. ReturnsNonewhen 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 (nanwhen absent).
-
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_outputto format the per-ensemblepathensemble.txtrows. Stored at path-creation time because the livePathobject (with its phase points,generatedmove tag and status) is not retained intraj_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.
-
property
interfaces¶ Retrieve interfaces from config dict.
-
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 onlyinfswap_data.txt.
-
pick_lock()[source]¶ Pick path and ens.
In case a crash, we pick lock locked from previous simulation.
-
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.
-
property
screen¶ Retrieve screen print frequency from config dict.
-
property
tsteps¶ Retrieve total steps from config dict.
-
property
workers¶ Retrieve workers from config dict.
-
write_toml()[source]¶ Write the restart state to
./restart.tomlatomically.Sequence: serialise to
restart.toml.tmpwith an explicitfsyncso the new payload is on disk; copy any existingrestart.tomltorestart.toml.prevso the previous cycle’s restart survives even if the final rename loses a race with a power loss;os.replacethe tmp file overrestart.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.scheduler module¶
Main 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:
ExceptionRaised 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 andrun_mdtakes 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.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:
objectThis 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
RandomGeneratorThe random generator that will be used for the paths that required random numbers.
settings (dict) – Contains all the simulation settings.
-
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
SimulationTaskwith 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.
- task (dict) – A dict defining the task. A task is represented by an
object of type
-
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
endproperty 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 therun()(or thestep()) 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'¶
-
step()[source]¶ Execute a simulation step.
Here, the tasks in
taskswill 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.
- cycle (dict of integers) –
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:
TaskRepresentation 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.
-
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.
-
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.