### Initialize Test System Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.multistate.ReplicaExchangeSampler.html Setup the alanine dipeptide test system and necessary imports. ```python >>> import math >>> from openmm import unit >>> from openmmtools import testsystems, states, mcmc >>> testsystem = testsystems.AlanineDipeptideImplicit() >>> import os >>> import tempfile ``` -------------------------------- ### Instantiate MolecularIdealGas and Get System/Positions Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.MolecularIdealGas.html This snippet demonstrates how to create an instance of MolecularIdealGas and access its system and positions attributes. No specific setup or imports are required beyond having openmmtools installed. ```python >>> methanol_box = MolecularIdealGas() >>> system, positions = methanol_box.system, methanol_box.positions ``` -------------------------------- ### Instantiate MethanolBox and get system/positions Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.MethanolBox.html Instantiate the MethanolBox test system and retrieve its system and positions. This is a common starting point for simulations using this test system. ```python methanol_box = MethanolBox() system, positions = methanol_box.system, methanol_box.positions ``` -------------------------------- ### IdealGas Examples Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.IdealGas.html Provides example code snippets demonstrating how to create and use the IdealGas test system. ```APIDOC ## IdealGas Examples ### Description Example usage of the IdealGas class. ### Examples #### Create an ideal gas system. ```python gas = IdealGas() system, positions = gas.system, gas.positions ``` #### Create a smaller ideal gas system containing 64 particles. ```python gas = IdealGas(nparticles=64) system, positions = gas.system, gas.positions ``` ``` -------------------------------- ### Initialize MCMC Sampler and States Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/mcmc.html Setup the thermodynamic and sampler states for an alanine dipeptide system. ```python from openmm import unit from openmmtools import testsystems, cache from openmmtools.states import ThermodynamicState, SamplerState test = testsystems.AlanineDipeptideVacuum() thermodynamic_state = ThermodynamicState(system=test.system, temperature=298*unit.kelvin) sampler_state = SamplerState(positions=test.positions) ``` -------------------------------- ### Create a DiatomicFluid test system Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.DiatomicFluid.html Examples showing how to initialize the DiatomicFluid class with different configurations. ```python >>> diatom = DiatomicFluid() >>> system, positions = diatom.system, diatom.positions ``` ```python >>> diatom = DiatomicFluid(charge=1.0*unit.elementary_charge) >>> system, positions = diatom.system, diatom.positions ``` ```python >>> diatom = DiatomicFluid(constraint=True) >>> system, positions = diatom.system, diatom.positions ``` ```python >>> diatom = DiatomicFluid(constraint=True, nmolecules=200) >>> system, positions = diatom.system, diatom.positions ``` -------------------------------- ### Initialize HostGuestImplicit system Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.HostGuestImplicit.html Examples showing how to instantiate the HostGuestImplicit test system with default or custom parameters. ```python >>> testsystem = HostGuestImplicit() >>> (system, positions) = testsystem.system, testsystem.positions ``` ```python >>> testsystem = HostGuestImplicit(implicitSolvent=app.GBn) ``` -------------------------------- ### Setup Alchemical Nonequilibrium Integrator Test Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/integrators.html Example setup for testing the AlchemicalNonequilibriumLangevinIntegrator with a harmonic oscillator. ```python >>> # Create harmonic oscillator testsystem >>> from openmmtools import testsystems >>> import openmm >>> from openmm import unit >>> testsystem = testsystems.HarmonicOscillator() ``` -------------------------------- ### SamplerState Initialization and Usage Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.states.SamplerState.html Demonstrates how to initialize and use the SamplerState class, including setting initial positions and applying the state to a context. ```APIDOC ## SamplerState Initialization and Usage ### Description This section covers the initialization of the `SamplerState` class and its basic usage, including setting initial positions and applying the state to an OpenMM context. ### Method `__init__` ### Endpoint `openmmtools.states.SamplerState(_positions_, _velocities_=None, _box_vectors_=None)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **positions** (openmm.unit.Quantity) - Required - Position vectors for N particles (length units). - **velocities** (openmm.unit.Quantity, optional) - Velocity vectors for N particles (velocity units). - **box_vectors** (openmm.unit.Quantity, optional) - Current box vectors (length units). ### Request Example ```python from openmmtools import testsystems from openmmtools import states from openmm import unit toluene_test = testsystems.TolueneVacuum() sampler_state = states.SamplerState(toluene_test.positions) # Example of applying to a context temperature = 300.0*unit.kelvin thermodynamic_state = states.ThermodynamicState(toluene_test.system, temperature) integrator = openmm.VerletIntegrator(1.0*unit.femtosecond) context = thermodynamic_state.create_context(integrator) sampler_state.apply_to_context(context) ``` ### Response #### Success Response (200) N/A (This is a class constructor and methods, not an API endpoint returning data). #### Response Example N/A ``` -------------------------------- ### Get Thermal Energy (kT) in OpenMM Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/integrators.html Retrieves the thermal energy (kT) from OpenMM global variables. Requires OpenMM to be installed and configured. ```python def kT(self): """The thermal energy in openmm.Quantity""" return self.getGlobalVariableByName("kT") * _OPENMM_ENERGY_UNIT ``` -------------------------------- ### Initialize IdealGas System Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/testsystems.html Examples showing how to instantiate the IdealGas class with default or custom particle counts. ```python >>> gas = IdealGas() >>> system, positions = gas.system, gas.positions ``` ```python >>> gas = IdealGas(nparticles=64) >>> system, positions = gas.system, gas.positions ``` -------------------------------- ### Initialize an OpenMM System with CustomBondForce Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.states.GlobalParameterState.html Setup a system with a CustomBondForce containing global parameters lambda_bonds and gamma. ```python >>> import openmm >>> from openmm import unit >>> # Define a diatomic molecule. >>> system = openmm.System() >>> particle_idx = system.addParticle(40.0*unit.amu) >>> particle_idx = system.addParticle(40.0*unit.amu) >>> custom_force = openmm.CustomBondForce('lambda_bonds^gamma*60000*(r-0.15)^2;') >>> parameter_idx = custom_force.addGlobalParameter('lambda_bonds', 1.0) # Default value is 1.0. >>> parameter_idx = custom_force.addGlobalParameter('gamma', 1.0) # Default value is 1.0. >>> bond_idx = custom_force.addBond(0, 1, []) >>> force_index = system.addForce(custom_force) >>> # Create a thermodynamic state object controlling the temperature of the system. >>> thermodynamic_state = ThermodynamicState(system, temperature=300.0*unit.kelvin) ``` -------------------------------- ### Instantiate SrcImplicit and get system/positions Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.SrcImplicit.html Instantiate the SrcImplicit test system and retrieve its OpenMM System and particle positions. This is a common starting point for simulations. ```python >>> src = SrcImplicit() >>> system, positions = src.system, src.positions ``` -------------------------------- ### Instantiate AlanineDipeptideExplicit and get System/Positions Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.AlanineDipeptideExplicit.html Instantiates the AlanineDipeptideExplicit test system and retrieves its OpenMM System and positions. This is a common starting point for setting up simulations. ```python >>> alanine = AlanineDipeptideExplicit() >>> (system, positions) = alanine.system, alanine.positions ``` -------------------------------- ### Initialize DoubleWellDimer_WCAFluid Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/testsystems.html Examples of initializing the system with default settings, custom dimer counts, and particle counts. ```python >>> dw_dimer = DoubleWellDimer_WCAFluid() >>> system, positions = dw_dimer.system, dw_dimer.positions ``` ```python >>> dw_dimer = DoubleWellDimer_WCAFluid(ndimers=2, nparticles=400) >>> system, positions = dw_dimer.system, dw_dimer.positions ``` -------------------------------- ### Instantiate AMOEBAProteinBox and Get System and Positions Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.AMOEBAProteinBox.html Instantiate the AMOEBAProteinBox test system and retrieve its OpenMM System and particle positions. This is a common starting point for setting up simulations. ```python >>> testsystem = AMOEBAProteinBox() >>> system, positions = testsystem.system, testsystem.positions ``` -------------------------------- ### Initialize SAMS Stage and Pre-write Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/multistate/sams.html Handles the initial stage setup and pre-write creation logic for the sampler. ```python def _initialize_stage(self): self._t0 = 0 # reference iteration to subtract if self.update_stages == 'one-stage': self._stage = 1 # start with asymptotically-optimal stage elif self.update_stages == 'two-stage': self._stage = 0 # start with rapid heuristic adaptation initial stage def _pre_write_create(self, thermodynamic_states: list, sampler_states: list, storage, **kwargs): """Initialize SAMS sampler. Parameters ---------- thermodynamic_states : list of openmmtools.states.ThermodynamicState Thermodynamic states to simulate, where one replica is allocated per state. ``` -------------------------------- ### Initialize and Use ContextCache Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.cache.ContextCache.html Demonstrates initializing ContextCache and retrieving contexts for compatible thermodynamic states. Compatible states result in a single cached context. ```python >>> from openmm import unit >>> from openmmtools import testsystems >>> from openmmtools.states import ThermodynamicState >>> alanine = testsystems.AlanineDipeptideExplicit() >>> thermodynamic_state = ThermodynamicState(alanine.system, 310*unit.kelvin) >>> time_step = 1.0*unit.femtosecond >>> context_cache = ContextCache() >>> context1, integrator1 = context_cache.get_context(thermodynamic_state, ... openmm.VerletIntegrator(time_step)) >>> thermodynamic_state.temperature = 300*unit.kelvin >>> time_step2 = 2.0*unit.femtosecond >>> context2, integrator2 = context_cache.get_context(thermodynamic_state, ... openmm.VerletIntegrator(time_step2)) >>> id(context1) == id(context2) True >>> len(context_cache) 1 ``` -------------------------------- ### Instantiate AMOEBAIonBox and Get System and Positions Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.AMOEBAIonBox.html Instantiate the AMOEBAIonBox test system and retrieve its associated OpenMM System and particle positions. This is a common starting point for setting up simulations with this test system. ```python >>> testsystem = AMOEBAIonBox() >>> system, positions = testsystem.system, testsystem.positions ``` -------------------------------- ### Setup for GHMC Move Examples Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.mcmc.GHMCMove.html Initializes the necessary components for demonstrating GHMC moves, including creating a test system, sampler state, and thermodynamic state. Requires imports from openmm, openmmtools.testsytems, and openmmtools.states. ```python from openmm import unit from openmmtools import testsystems from openmmtools.states import ThermodynamicState, SamplerState test = testsystems.AlanineDipeptideVacuum() sampler_state = SamplerState(positions=test.positions) thermodynamic_state = ThermodynamicState(system=test.system, temperature=298*unit.kelvin) ``` -------------------------------- ### Initialize ThermodynamicState for NVT and NPT Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/testsystems.html Examples showing how to define NVT and NPT states for a system using temperature and pressure units. ```python >>> from openmmtools import testsystems >>> system_container = testsystems.WaterBox() >>> (system, positions) = system_container.system, system_container.positions >>> state = ThermodynamicState(system=system, temperature=298.0*unit.kelvin) ``` ```python >>> state = ThermodynamicState(system=system, temperature=298.0*unit.kelvin, pressure=1.0*unit.atmospheres) ``` -------------------------------- ### Timer Class for Stopwatch-Style Timing Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/utils/utils.html The `Timer` class provides stopwatch-style timing functions. Use `start` to begin timing a benchmark, `stop` to end it and get the elapsed time, and `report_timing` to log all completed timings. ```python import time import logging logger = logging.getLogger(__name__) class Timer: """A class with stopwatch-style timing functions. Examples -------- >>> timer = Timer() >>> timer.start('my benchmark') >>> for i in range(10): ... pass >>> elapsed_time = timer.stop('my benchmark') >>> timer.start('second benchmark') >>> for i in range(10): ... for j in range(10): ... pass >>> elsapsed_time = timer.stop('second benchmark') >>> timer.report_timing() """ def __init__(self): self.reset_timing_statistics() def reset_timing_statistics(self, benchmark_id=None): """Reset the timing statistics. Parameters ---------- benchmark_id : str, optional If specified, only the timings associated to this benchmark id will be reset, otherwise all timing information are. """ if benchmark_id is None: self._t0 = {} self._t1 = {} self._completed = {} else: self._t0.pop(benchmark_id, None) self._t1.pop(benchmark_id, None) self._completed.pop(benchmark_id, None) def start(self, benchmark_id): """Start a timer with given benchmark_id.""" self._t0[benchmark_id] = time.time() def stop(self, benchmark_id): try: t0 = self._t0[benchmark_id] except KeyError: logger.warning(f"Can't stop timing for {benchmark_id}") else: self._t1[benchmark_id] = time.time() elapsed_time = self._t1[benchmark_id] - t0 self._completed[benchmark_id] = elapsed_time return elapsed_time def partial(self, benchmark_id): """Return the elapsed time of the given benchmark so far.""" try: t0 = self._t0[benchmark_id] except KeyError: logger.warning(f"Couldn't return partial timing for {benchmark_id}") else: return time.time() - t0 def report_timing(self, clear=True): """Log all the timings at the debug level. Parameters ---------- clear : bool If True, the stored timings are deleted after being reported. Returns ------- elapsed_times : dict The dictionary benchmark_id : elapsed time for all benchmarks. """ for benchmark_id, elapsed_time in self._completed.items(): logger.debug(f'{benchmark_id} took {elapsed_time:8.3f}s') if clear is True: self.reset_timing_statistics() ``` -------------------------------- ### Initialize HostGuestVacuum system Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.HostGuestVacuum.html Create a host-guest system instance and retrieve its OpenMM system and positions. ```python testsystem = HostGuestVacuum() >>> (system, positions) = testsystem.system, testsystem.positions ``` -------------------------------- ### Initialize and Run ReplicaExchangeSampler Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/multistate/replicaexchange.html Demonstrates setting up a parallel tempering simulation with exponentially-spaced temperatures and running it using a GHMC move. ```python import math from openmm import unit from openmmtools import testsystems, states, mcmc testsystem = testsystems.AlanineDipeptideImplicit() import os import tempfile ``` ```python n_replicas = 3 # Number of temperature replicas. T_min = 298.0 * unit.kelvin # Minimum temperature. T_max = 600.0 * unit.kelvin # Maximum temperature. temperatures = [T_min + (T_max - T_min) * (math.exp(float(i) / float(n_replicas-1)) - 1.0) / (math.e - 1.0) for i in range(n_replicas)] thermodynamic_states = [states.ThermodynamicState(system=testsystem.system, temperature=T) for T in temperatures] ``` ```python move = mcmc.GHMCMove(timestep=2.0*unit.femtoseconds, n_steps=50) simulation = ReplicaExchangeSampler(mcmc_moves=move, number_of_iterations=2) ``` ```python storage_path = tempfile.NamedTemporaryFile(delete=False).name + '.nc' reporter = multistate.MultiStateReporter(storage_path, checkpoint_interval=1) simulation.create(thermodynamic_states=thermodynamic_states, sampler_states=states.SamplerState(testsystem.positions), storage=reporter) ``` -------------------------------- ### SequenceMove Example Usage Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.mcmc.SequenceMove.html Example demonstrating the creation and use of SequenceMove for an NPT ensemble simulation. ```APIDOC ### Example: NPT ensemble simulation with SequenceMove ```python >>> import numpy as np >>> from openmm import unit >>> from openmmtools import testsystems >>> from openmmtools.states import ThermodynamicState, SamplerState >>> from openmmtools.mcmc import SequenceMove, GHMCMove, MonteCarloBarostatMove, MCMCSampler >>> >>> test = testsystems.LennardJonesFluid(nparticles=200) >>> thermodynamic_state = ThermodynamicState(system=test.system, temperature=298*unit.kelvin, ... pressure=1*unit.atmospheres) >>> sampler_state = SamplerState(positions=test.positions) >>> >>> # Create a move set that includes a Monte Carlo barostat move. >>> move = SequenceMove([GHMCMove(n_steps=50), MonteCarloBarostatMove(n_attempts=5)]) >>> >>> # Create an MCMC sampler instance and run 5 iterations of the simulation. >>> sampler = MCMCSampler(thermodynamic_state, sampler_state, move=move) >>> sampler.run(n_iterations=2) >>> np.allclose(sampler.sampler_state.positions, test.positions) False ``` ``` -------------------------------- ### Initialize and Configure ThermodynamicState Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.states.ThermodynamicState.html Demonstrates how to define thermodynamic states by adding thermostats and barostats to an OpenMM system. ```python >>> thermostat = openmm.AndersenThermostat(200.0*unit.kelvin, 1.0/unit.picosecond) >>> force_id = waterbox.addForce(thermostat) >>> state = ThermodynamicState(system=waterbox) >>> state.pressure is None True >>> state.temperature Quantity(value=200.0, unit=kelvin) >>> barostat = openmm.MonteCarloBarostat(1.0*unit.atmosphere, 200.0*unit.kelvin) >>> force_id = waterbox.addForce(barostat) >>> state = ThermodynamicState(system=waterbox) >>> state.pressure Quantity(value=1.01325, unit=bar) >>> state.temperature Quantity(value=200.0, unit=kelvin) ``` -------------------------------- ### Initialize Thermodynamic and Sampler States Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/mcmc.html Setup the system, sampler state, and thermodynamic state for an alanine dipeptide system in vacuum. ```python from openmm import unit from openmmtools import testsystems from openmmtools.states import SamplerState, ThermodynamicState test = testsystems.AlanineDipeptideVacuum() sampler_state = SamplerState(positions=test.positions) thermodynamic_state = ThermodynamicState(system=test.system, temperature=298*unit.kelvin) ``` -------------------------------- ### Install Miniconda on Linux Source: https://openmmtools.readthedocs.io/en/stable/_sources/installation.rst.txt Downloads and installs the latest Miniconda Python 3 distribution for Linux systems. ```bash $ wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh $ bash ./Miniconda3-latest-Linux-x86_64.sh -b -p $HOME/miniconda3 $ export PATH="$HOME/miniconda3/bin:$PATH" ``` -------------------------------- ### Install Development Build Source: https://openmmtools.readthedocs.io/en/stable/_sources/installation.rst.txt Configures the necessary conda channels and installs the latest unstable development version of openmmtools. ```bash $ conda config --add channels omnia --add channels conda-forge $ conda install openmmtools-dev ``` -------------------------------- ### Initialize HostGuestImplicit system Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/testsystems.html Creates a host-guest system in implicit solvent, allowing for custom solvent model specifications. ```python >>> testsystem = HostGuestImplicit() >>> (system, positions) = testsystem.system, testsystem.positions Create host-guest system with a specified implicit solvent model >>> testsystem = HostGuestImplicit(implicitSolvent=app.GBn) ``` -------------------------------- ### Install Stable Release Build Source: https://openmmtools.readthedocs.io/en/stable/_sources/installation.rst.txt Configures the necessary conda channels and installs the latest stable version of openmmtools. ```none $ conda config --add channels omnia --add channels conda-forge $ conda install openmmtools ``` -------------------------------- ### Particle and Topology Setup Loop Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/testsystems.html This snippet demonstrates the logic for adding particles to a system and building the corresponding topology, often used within initialization methods. ```python for atom_index in range(nparticles): system.addParticle(mass) if (atom_index < ncustom): cnb.addParticle([charge, sigma, epsilon]) nb.addParticle(0.0 * charge, sigma, 0.0 * epsilon) else: cnb.addParticle([0.0 * charge, sigma, 0.0 * epsilon]) nb.addParticle(charge, sigma, epsilon) # Create initial coordinates using subrandom positions. positions = subrandom_particle_positions(nparticles, system.getDefaultPeriodicBoxVectors()) # Create topology. topology = app.Topology() element = app.Element.getBySymbol('Ar') chain = topology.addChain() for particle in range(system.getNumParticles()): residue = topology.addResidue('Ar', chain) topology.addAtom('Ar', element, residue) self.topology = topology self.system, self.positions = system, positions ``` -------------------------------- ### Initialize OpenMM System with Global Parameters Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/states.html Sets up an OpenMM System with a CustomBondForce that uses global parameters 'lambda_bonds' and 'gamma'. It then creates a ThermodynamicState object controlling the system's temperature. ```python import openmm from openmm import unit system = openmm.System() particle_idx = system.addParticle(40.0*unit.amu) particle_idx = system.addParticle(40.0*unit.amu) custom_force = openmm.CustomBondForce('lambda_bonds^gamma*60000*(r-0.15)^2;') parameter_idx = custom_force.addGlobalParameter('lambda_bonds', 1.0) parameter_idx = custom_force.addGlobalParameter('gamma', 1.0) bond_idx = custom_force.addBond(0, 1, []) force_index = system.addForce(custom_force) thermodynamic_state = ThermodynamicState(system, temperature=300.0*unit.kelvin) ``` -------------------------------- ### Install Miniconda on OS X Source: https://openmmtools.readthedocs.io/en/stable/_sources/installation.rst.txt Downloads and installs the latest Miniconda Python distribution for OS X systems. ```bash $ wget https://repo.continuum.io/miniconda/Miniconda2-latest-MacOSX-x86_64.sh $ bash ./Miniconda3-latest-Linux-x86_64.sh -b -p $HOME/miniconda3 $ export PATH="$HOME/miniconda3/bin:$PATH" ``` -------------------------------- ### Initialize and Interact with TestSystem Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/testsystems.html Demonstrates basic instantiation and property retrieval for a TestSystem object. ```python >>> testsystem = TestSystem() ``` ```python >>> system = testsystem.system ``` ```python >>> positions = testsystem.positions ``` ```python >>> topology = testsystem.topology ``` ```python >>> (system_xml, positions_xml) = testsystem.serialize() ``` -------------------------------- ### Get Current Class Options Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/multistate/multistatesampler.html Retrieves a dictionary of the current class options by inspecting the __init__ methods and getting attribute values. Excludes 'mcmc_moves'. ```python options_to_report = dict() for cls in inspect.getmro(type(self)): parameter_names, _, _, defaults, _, _, _ = inspect.getfullargspec(cls.__init__) if defaults: class_options = {parameter_name: getattr(self, '_' + parameter_name) for parameter_name in parameter_names[-len(defaults):]} options_to_report.update(class_options) options_to_report.pop('mcmc_moves') return options_to_report ``` -------------------------------- ### GET /testsystems/FlexibleDischargedWaterBox/serialize Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.FlexibleDischargedWaterBox.html Serializes the system and positions into XML format. ```APIDOC ## GET /testsystems/FlexibleDischargedWaterBox/serialize ### Description Returns the System and positions of the test system in serialized XML form. ### Response #### Success Response (200) - **xml_data** (string) - The serialized XML representation of the system and positions. ``` -------------------------------- ### Initialize HostGuestVacuum system Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/testsystems.html Creates a host-guest system in vacuum with default bond constraints. ```python >>> testsystem = HostGuestVacuum() >>> (system, positions) = testsystem.system, testsystem.positions ``` -------------------------------- ### GET /VVVRIntegrator/heat Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.integrators.VVVRIntegrator.html Retrieves the current accumulated heat from the integrator. ```APIDOC ## GET /VVVRIntegrator/heat ### Description Get the current accumulated heat during integration. ### Method GET ### Endpoint /VVVRIntegrator/heat ### Parameters #### Query Parameters - **dimensionless** (boolean) - Optional - Whether to return the heat as a dimensionless value. ### Response #### Success Response (200) - **heat** (float) - The current accumulated heat value. ``` -------------------------------- ### Create and Run SAMS Simulation with Storage Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.multistate.SAMSSampler.html Bind the simulation to a storage file using MultiStateReporter and initialize the sampler. ```python >>> storage_path = tempfile.NamedTemporaryFile(delete=False).name + '.nc' >>> reporter = multistate.MultiStateReporter(storage_path, checkpoint_interval=1) >>> simulation.create(thermodynamic_states=thermodynamic_states, ... sampler_states=[states.SamplerState(testsystem.positions)], ... storage=reporter) ``` -------------------------------- ### GET /integrator/per-dof-variable Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.integrators.BAOABIntegrator.html Methods to retrieve per-DOF variable information. ```APIDOC ## GET /integrator/per-dof-variable ### Description Retrieves values or names of per-DOF variables associated with the integrator. ### Parameters #### Query Parameters - **name** (string) - Required - The name of the per-DOF variable to retrieve. - **index** (integer) - Required - The index of the per-DOF variable to retrieve. ``` -------------------------------- ### Initialize context caches Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/multistate/multistatesampler.html Sets up default context cache instances for energy and sampling, defaulting to the global cache. ```python def _initialize_context_caches(self): """Handle energy and propagation context cache default behavior. Centralized API point where to initialize the context cache instance attributes. .. note:: As of 03-Feb-22 default behavior is to use the global cache. """ # Default is using global context cache self.energy_context_cache = cache.global_context_cache self.sampler_context_cache = cache.global_context_cache ``` -------------------------------- ### GET /read_logZ Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/multistate/multistateanalyzer.html Extracts logZ estimates from the NetCDF file. ```APIDOC ## GET /read_logZ ### Description Extracts logZ estimates from the ncfile, if present. Returns a ValueError if not present. ### Parameters #### Query Parameters - **iteration** (int or slice) - Optional - Iteration or slice of iterations to extract. ### Response #### Success Response (200) - **logZ** (np.ndarray) - Array of shape [n_states, n_iterations] representing the online logZ estimate for state l at iteration n. ``` -------------------------------- ### Internal Initialization and Reporting Methods Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/multistate/sams.html These methods handle the setup of thermodynamic and sampler states, restoration of simulation progress from storage, and the logging of iteration-specific metadata. ```APIDOC ## Internal Methods for Replica Exchange ### Description These methods manage the internal state of a replica-exchange simulation, including the initialization of thermodynamic states, restoration from reporter files, and reporting of dynamic data like logZ and state histograms. ### Methods - `_pre_write_create`: Initializes the replica-exchange simulation parameters. - `_restore_sampler_from_reporter`: Restores simulation state from a reporter file. - `_report_iteration_items`: Writes iteration-specific data to the reporter. ### Parameters #### _pre_write_create - **thermodynamic_states** (list) - Required - List of thermodynamic states. - **sampler_states** (list) - Required - List of openmmtools.states.SamplerState objects. - **storage** (str or Reporter) - Required - Path to storage file or Reporter instance. - **initial_thermodynamic_states** (list/array) - Optional - Initial thermodynamic state index for each sampler state. - **metadata** (dict) - Optional - Simulation metadata to be stored. #### _restore_sampler_from_reporter - **reporter** (Reporter) - Required - The reporter instance to restore from. ### Response #### _report_iteration_items - **logZ** (array) - LogZ estimates for each state. - **stage** (int) - Current weight update stage. - **t0** (int) - Current t0 value. ``` -------------------------------- ### Initialize and use ExternalPerturbationLangevinIntegrator Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/integrators.html Demonstrates creating a test system, initializing the integrator, performing a perturbation, and retrieving the accumulated protocol work. ```python >>> # Create harmonic oscillator testsystem >>> from openmmtools import testsystems >>> import openmm >>> from openmm import unit >>> testsystem = testsystems.HarmonicOscillator() >>> # Create an external perturbation integrator >>> integrator = ExternalPerturbationLangevinIntegrator(temperature=300*unit.kelvin, collision_rate=1.0/unit.picoseconds, timestep=1.0*unit.femtoseconds) >>> context = openmm.Context(testsystem.system, integrator) >>> context.setPositions(testsystem.positions) >>> # Take a step >>> integrator.step(1) >>> # Perturb the system >>> context.setParameter('testsystems_HarmonicOscillator_x0', 0.1) >>> # Take another step, integrating work >>> integrator.step(1) >>> # Retrieve the work >>> protocol_work = integrator.protocol_work ``` -------------------------------- ### GET /get_protocol_work Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/integrators.html Retrieves the current accumulated protocol work. ```APIDOC ## GET /get_protocol_work ### Description Get the current accumulated protocol work. ### Method GET ### Parameters #### Query Parameters - **dimensionless** (bool) - Optional - If specified as True, the work is returned in reduced (kT) units as a float. Otherwise, returns unit-bearing energy. ### Response #### Success Response (200) - **work** (unit.Quantity or float) - The protocol work. ``` -------------------------------- ### Raise SamplerStateError Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/states.html Example of raising a SamplerStateError when velocities are inconsistent with positions. ```python >>> raise SamplerStateError(SamplerStateError.INCONSISTENT_VELOCITIES) Traceback (most recent call last): ... openmmtools.states.SamplerStateError: Velocities have different length than positions. ``` -------------------------------- ### Initialize Alanine Dipeptide Test System Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.multistate.SAMSSampler.html Setup the test system and necessary imports for the SAMS simulation. ```python >>> import math >>> from openmm import unit >>> from openmmtools import testsystems, states, mcmc >>> testsystem = testsystems.AlanineDipeptideVacuum() >>> import os >>> import tempfile ``` -------------------------------- ### Create Dipolar Fluid Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/testsystems.html Example usage for creating a dipolar fluid. ```python >>> test = DipolarFluid() >>> system, positions = test.system, test.positions ``` -------------------------------- ### Initialize TolueneImplicit Test System Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/testsystems.html Examples of creating the TolueneImplicit test system with different implicit solvent models and constraints. ```python >>> testsystem = TolueneImplicit() >>> [system, positions, topology] = [testsystem.system, testsystem.positions, testsystem.topology] ``` ```python >>> testsystem = TolueneImplicit(implicitSolvent=app.HCT) ``` ```python >>> testsystem = TolueneImplicit(implicitSolvent=app.OBC2) ``` ```python >>> testsystems = { name : TolueneImplicit(implicitSolvent=getattr(openmm.app, name)) for name in ['HCT', 'OBC1', 'OBC2', 'GBn', 'GBn2'] } ``` -------------------------------- ### GET /sampler_state/state Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/states.html Retrieves a dictionary representation of the current sampler state. ```APIDOC ## GET /sampler_state/state ### Description Returns a dictionary representation of the state, including positions, velocities, box vectors, and energy values. ### Method GET ### Parameters #### Query Parameters - **ignore_velocities** (bool) - Optional - If True, velocities are not included in the serialized output. ### Response #### Success Response (200) - **positions** (array) - Particle positions - **velocities** (array) - Particle velocities - **box_vectors** (array) - Simulation box vectors - **potential_energy** (float) - Potential energy of the state - **kinetic_energy** (float) - Kinetic energy of the state - **collective_variables** (dict) - Current collective variables ``` -------------------------------- ### MultiStateSampler Initialization and Creation Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.multistate.MultiStateSampler.html Demonstrates how to initialize and create a MultiStateSampler simulation, including setting up thermodynamic states and MCMC moves. ```APIDOC ## MultiStateSampler Initialization and Creation ### Description This section covers the initialization of `MultiStateSampler` and its associated components, such as `ThermodynamicState` and `SamplerState`, and the creation of a new simulation using the `create` method. ### Methods #### `__init__` Initializes the `MultiStateSampler` with specified MCMC moves, number of iterations, and online analysis options. - **mcmc_moves** (MCMCMoves) - The MCMC moves to be used for propagation. - **number_of_iterations** (int) - The total number of iterations to run. - **online_analysis_interval** (int) - The interval for performing online analysis. - **online_analysis_target_error** (float) - The target error for online analysis. - **online_analysis_minimum_iterations** (int) - The minimum number of iterations before online analysis is performed. - **locality** (Locality) - Specifies the locality for the simulation. #### `create` Creates a new multistate sampler simulation. - **thermodynamic_states** (list[ThermodynamicState]) - A list of thermodynamic states for the simulation. - **sampler_states** (SamplerState) - The initial sampler states. - **storage** (Reporter) - The storage object to save simulation data. ### Request Example ```python from openmm import unit from openmmtools import testsystems, states, mcmc from openmmtools.multistate import MultiStateSampler, MultiStateReporter import tempfile import math testsystem = testsystems.AlanineDipeptideImplicit() n_replicas = 3 T_min = 298.0 * unit.kelvin T_max = 600.0 * unit.kelvin temperatures = [T_min + (T_max - T_min) * (math.exp(float(i) / float(n_replicas-1)) - 1.0) / (math.e - 1.0) for i in range(n_replicas)] thermodynamic_states = [states.ThermodynamicState(system=testsystem.system, temperature=T) for T in temperatures] move = mcmc.GHMCMove(timestep=2.0*unit.femtoseconds, n_steps=50) simulation = MultiStateSampler(mcmc_moves=move, number_of_iterations=2) storage_path = tempfile.NamedTemporaryFile(delete=False).name + '.nc' reporter = MultiStateReporter(storage_path, checkpoint_interval=1) simulation.create(thermodynamic_states=thermodynamic_states, sampler_states=states.SamplerState(testsystem.positions), storage=reporter) ``` ### Attributes - **is_completed** (bool) - Check if simulation has reached stop target criteria. - **is_periodic** (bool or None) - Returns True if system is periodic, False if not, and None if not initialized. - **iteration** (int) - The current iteration of the simulation. - **mcmc_moves** (list[MCMCMoves]) - A copy of the MCMCMoves list used for propagation. - **metadata** (dict) - A copy of the metadata dictionary passed on creation. - **n_replicas** (int) - The number of replicas. - **n_states** (int) - The number of thermodynamic states. - **online_analysis_interval** (int) - Interval for online analysis. - **options** (dict) - Dictionary of all class options. - **sampler_states** (list[SamplerState]) - A copy of the sampler states at the current iteration. ``` -------------------------------- ### GET /get_volume Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/states.html Retrieves the volume of the periodic box for the thermodynamic state. ```APIDOC ## GET /get_volume ### Description Returns the volume of the periodic box. If the system is not periodic or if the volume is allowed to fluctuate (and ignore_ensemble is False), it returns None. ### Method GET ### Endpoint /get_volume ### Parameters #### Query Parameters - **ignore_ensemble** (bool) - Optional - If True, the volume of the periodic box vectors is returned even if the volume fluctuates. ### Response #### Success Response (200) - **volume** (openmm.unit.Quantity) - The volume of the periodic box (units of length^3) or None. ``` -------------------------------- ### Initialize WaterBox Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.WaterBox.html Create a default water box test system. ```python >>> waterbox = WaterBox() ``` ```python >>> waterbox = WaterBox() >>> [system, positions] = [waterbox.system, waterbox.positions] ``` -------------------------------- ### GET /read_mcmc_moves Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/multistate/multistatereporter.html Returns the MCMCMoves used in the simulation from the checkpoint file. ```APIDOC ## GET /read_mcmc_moves ### Description Return the MCMCMoves of the MultiStateSampler simulation on the checkpoint. ### Method GET ### Response #### Success Response (200) - **mcmc_moves** (list of MCMCMove) - The MCMCMoves used to propagate the simulation. ``` -------------------------------- ### Initialize States for Langevin Dynamics Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.mcmc.LangevinDynamicsMove.html Setup the thermodynamic and sampler states for an alanine dipeptide system in vacuum. ```python >>> from openmm import unit >>> from openmmtools import testsystems >>> from openmmtools.states import SamplerState, ThermodynamicState >>> test = testsystems.AlanineDipeptideVacuum() >>> sampler_state = SamplerState(positions=test.positions) >>> thermodynamic_state = ThermodynamicState(system=test.system, temperature=298*unit.kelvin) ``` -------------------------------- ### GET /read_replica_thermodynamic_states Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/multistate/multistatereporter.html Retrieves the indices of the ThermodynamicStates for each replica from the analysis file. ```APIDOC ## GET /read_replica_thermodynamic_states ### Description Retrieve the indices of the ThermodynamicStates for each replica on the analysis file. ### Method GET ### Parameters #### Query Parameters - **iteration** (int or slice) - Optional - The iteration(s) at which to read the data. Defaults to slice(None). ### Response #### Success Response (200) - **state_indices** (np.ndarray of int) - The thermodynamic state index for each replica at the specified iteration. ``` -------------------------------- ### Initialize WCAFluid System Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/testsystems.html The constructor sets up the system, defines periodic box vectors based on density, adds particles, and configures the WCA potential using a CustomNonbondedForce. ```python class WCAFluid(TestSystem): def __init__(self, nparticles=216, density=0.96, mass=39.9 * unit.amu, epsilon=120.0 * unit.kelvin * kB, sigma=3.4 * unit.angstrom, **kwargs): """ Create a Weeks-Chandler-Andersen system. Parameters: ----------- npartocles : int, optional, default = 216 Number of particles. density : float, optional, default = 0.96 Reduced density, N sigma^3 / V. mass : openmm.unit.Quantity with units compatible with angstrom, optional, default=39.9 amu Particle mass. epsilon : openmm.unit.Quantity with units compatible with kilocalories_per_mole, optional, default=120K*kB WCA well depth. sigma : openmm.unit.Quantity WCA sigma. """ TestSystem.__init__(self, **kwargs) # Create system system = openmm.System() # Compute total system volume. volume = nparticles / density # Make system cubic in dimension. length = volume**(1.0 / 3.0) # TODO: Can we change this to use tuples or 3x3 array? a = unit.Quantity(numpy.array([1.0, 0.0, 0.0], numpy.float32), unit.nanometer) * length / unit.nanometer b = unit.Quantity(numpy.array([0.0, 1.0, 0.0], numpy.float32), unit.nanometer) * length / unit.nanometer c = unit.Quantity(numpy.array([0.0, 0.0, 1.0], numpy.float32), unit.nanometer) * length / unit.nanometer system.setDefaultPeriodicBoxVectors(a, b, c) # Add particles to system. for n in range(nparticles): system.addParticle(mass) # Create nonbonded force term implementing Kob-Andersen two-component Lennard-Jones interaction. energy_expression = '4.0*epsilon*((sigma/r)^12 - (sigma/r)^6) + epsilon;' energy_expression += 'sigma = %f;' % in_openmm_units(sigma) energy_expression += 'epsilon = %f;' % in_openmm_units(epsilon) # Create force. force = openmm.CustomNonbondedForce(energy_expression) # Add particles for n in range(nparticles): force.addParticle([]) # Set periodic boundary conditions with cutoff. force.setNonbondedMethod(openmm.CustomNonbondedForce.CutoffPeriodic) rmin = 2.**(1. / 6.) * sigma # distance of minimum energy for Lennard-Jones potential force.setCutoffDistance(rmin) # Add nonbonded force term to the system. system.addForce(force) # Create initial coordinates using subrandom positions. positions = subrandom_particle_positions(nparticles, system.getDefaultPeriodicBoxVectors()) # Create topology. topology = app.Topology() element = app.Element.getBySymbol('Ar') chain = topology.addChain() for particle in range(system.getNumParticles()): residue = topology.addResidue('Ar', chain) topology.addAtom('Ar', element, residue) self.topology = topology # Store system. self.system, self.positions = system, positions ``` -------------------------------- ### GET /CustomCentroidBondForce/getNumBonds Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.forces.FlatBottomRestraintForce.html Retrieves the total number of bonds defined in the force. ```APIDOC ## GET /CustomCentroidBondForce/getNumBonds ### Description Get the number of bonds for which force field parameters have been defined. ### Method GET ### Response #### Success Response (200) - **count** (int) - The number of bonds. ``` -------------------------------- ### Initialize System States Source: https://openmmtools.readthedocs.io/en/stable/_sources/mcmc.rst.txt Create the thermodynamic and sampler states for an alanine dipeptide system. ```python test = testsystems.AlanineDipeptideVacuum() thermodynamic_state = ThermodynamicState(system=test.system, temperature=298*unit.kelvin) sampler_state = SamplerState(positions=test.positions) ``` -------------------------------- ### Initialize FlexibleDischargedWaterBox Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.FlexibleDischargedWaterBox.html Create a default instance of the water box test system. ```python >>> waterbox = FlexibleDischargedWaterBox() >>> [system, positions] = [waterbox.system, waterbox.positions] ``` -------------------------------- ### GET /read_log_weights Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/multistate/multistateanalyzer.html Extracts log weights from the associated NetCDF file. ```APIDOC ## GET /read_log_weights ### Description Extracts log weights from the ncfile, if present. Returns a ValueError if not present. ### Response #### Success Response (200) - **log_weights** (np.ndarray) - Array of shape [n_states, n_iterations] representing log weights applied to state l during iteration n. ``` -------------------------------- ### Constructor: CustomGBForceSystem Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.testsystems.CustomGBForceSystem.html Initializes a new instance of the CustomGBForceSystem test system. ```APIDOC ## Constructor: CustomGBForceSystem ### Description Initializes a new instance of the CustomGBForceSystem class, which represents a system of particles with a CustomGBForce. ### Parameters #### Request Body - **kwargs** (dict) - Optional - Additional keyword arguments for the test system configuration. ``` -------------------------------- ### Raise ThermodynamicsError Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/states.html Example of raising a ThermodynamicsError when multiple barostats are detected in a system. ```python >>> raise ThermodynamicsError(ThermodynamicsError.MULTIPLE_BAROSTATS) Traceback (most recent call last): ... openmmtools.states.ThermodynamicsError: System has multiple barostats. ``` -------------------------------- ### GET /CompoundState/__getstate__ Source: https://openmmtools.readthedocs.io/en/stable/_modules/openmmtools/states.html Retrieves a dictionary representation of the current state for serialization purposes. ```APIDOC ## GET /CompoundState/__getstate__ ### Description Returns a dictionary containing the serialized thermodynamic state and a list of serialized composable states. ### Method GET ### Endpoint /CompoundState/__getstate__ ### Response #### Success Response (200) - **thermodynamic_state** (dict) - The serialized thermodynamic state. - **composable_states** (list) - A list of serialized composable states. ``` -------------------------------- ### Initialize State from System Source: https://openmmtools.readthedocs.io/en/stable/api/generated/openmmtools.states.GlobalParameterState.html Use the from_system constructor to read parameter values directly from an existing OpenMM system. ```python >>> my_composable_state = MyComposableState.from_system(system) >>> my_composable_state.lambda_bonds 1.0 >>> my_composable_state.gamma 1.0 ```