def __init__(self, potential: _perturbedPotentialCls = linearCoupledPotentials(), sampler: samplerCls = metropolisMonteCarloIntegrator(), conditions: Iterable[conditionCls] = [], temperature: float = 298.0, start_position: (Iterable[Number] or float) = None, lam: float = 0.0): """ __init__ construct a eds-System that can be used to manage a simulation. Parameters ---------- potential: pot.envelopedPotential, optional potential function class to be explored by sampling sampler: sampler, optional sampling method, that allows exploring the potential function conditions: Iterable[condition], optional conditions that shall be applied to the system. temperature: float, optional The temperature of the system (default: 298K) start_position: starting position for the simulation and setup of the system. lam: Number, optional the value of the copuling lambda """ super().__init__(potential=potential, sampler=sampler, conditions=conditions, temperature=temperature, start_position=start_position) self.lam = lam self.update_current_state()
def test_twoD_simulation_ana_plot(self): # settings sim_steps = 100 pot2D = harmonicOscillatorPotential2D() sampler = metropolisMonteCarloIntegrator() sys = system(potential=pot2D, sampler=sampler, start_position=[0, 0]) # simulate cur_state = sys.simulate(sim_steps, withdraw_traj=True) plotSimulations.twoD_simulation_analysis_plot(system=sys)
def test_init(self): integrator = stochastic.metropolisMonteCarloIntegrator() potential = OneD.harmonicOscillatorPotential() sys = system.system(potential=potential, sampler=integrator) replicas = 22 nsteps = 100 T_range = range(288, 310) setattr(self, "group", None) group = replica_exchange.temperatureReplicaExchange( system=sys, temperature_range=T_range)
def testTraj(self): integrator = metropolisMonteCarloIntegrator() ha = OneD.harmonicOscillatorPotential(x_shift=-5) hb = OneD.harmonicOscillatorPotential(x_shift=5) pot = OneD.linearCoupledPotentials(Va=ha, Vb=hb) sys = perturbedSystem(temperature=300.0, potential=pot, sampler=integrator) lam = 0.5 sys.lam = lam ens = self.convBelt(0.0, 1, system=sys)
def test_simulate_good_exchange(self): integrator = stochastic.metropolisMonteCarloIntegrator() potential = OneD.harmonicOscillatorPotential() sys = system.system(potential=potential, sampler=integrator) replicas = 22 nsteps = 100 T_range = range(288, 310) group = replica_exchange.temperatureReplicaExchange( system=sys, temperature_range=T_range) ##print(group.get_Total_Energy()) group.nSteps_between_trials = nsteps group.simulate(5)
def __init__(self, capital_lambda: float, n_replicas: int, system:systemCls = perturbed_system.perturbedSystem( temperature=300.0, lam=0.0, potential=pot.OneD.linearCoupledPotentials( Va=pot.OneD.harmonicOscillatorPotential(k=1, x_shift=0), Vb=pot.OneD.harmonicOscillatorPotential(k=2, x_shift=0) ), sampler=stochastic.metropolisMonteCarloIntegrator() ), build: bool = False): """ initialize Ensemble object Parameters ---------- capital_lambda: float state of ensemble, 0 <= capital_lambda < pi n_replicas: int number of replicas system: systemCls, optional a system1D instance build:bool, optional build memory? """ assert 0.0 <= capital_lambda <= 2 * np.pi, "capital_lambda not allowed" assert n_replicas >= 1, "At least one system is needed" super().__init__() self.system = system self.capital_lambda = capital_lambda self.build = build # build self.dis = 2.0 * np.pi / n_replicas self.exchange_dimensions = { self._parameter_name: [ self.calculate_replica_lambda(self.capital_lambda, i) for i in range(n_replicas) ] } self._temperature_exchange = system.temperature self.initialise() self.system_trajs: dict = {}
def test_run_step(self): integrator = metropolisMonteCarloIntegrator() ha = OneD.harmonicOscillatorPotential(x_shift=-5) hb = OneD.harmonicOscillatorPotential(x_shift=5) pot = OneD.linearCoupledPotentials(Va=ha, Vb=hb) sys = perturbedSystem(temperature=300.0, potential=pot, sampler=integrator) ens = self.convBelt(0.0, 1, system=sys) ens.calculate_total_ensemble_energy() ens.run() ens.calculate_total_ensemble_energy() ens.get_replicas_positions()
def main(): TRE = replica_exchange.temperatureReplicaExchange integrator = stochastic.metropolisMonteCarloIntegrator() potential = OneD.harmonicOscillatorPotential() sys = system.system(potential=potential, sampler=integrator) replicas = 2 nsteps = 10 T_range = np.linspace(288, 310, num=replicas) group = replica_exchange.temperatureReplicaExchange( system=sys, temperature_range=T_range) print("TotENERGY:", group.get_replica_total_energies()) group.nSteps_between_trials = nsteps group._run_parallel(1) print("FINI: ", [traj.shape for key, traj in group.get_trajectories().items()])
def __init__(self, potential: pot.envelopedPotential = pot.envelopedPotential( V_is=[pot.harmonicOscillatorPotential(x_shift=2), pot.harmonicOscillatorPotential(x_shift=-2)], eoff=[0, 0]), sampler: samplerCls = metropolisMonteCarloIntegrator(), conditions: Iterable[conditionCls] = [], temperature: float = 298.0, start_position: Union[Number, Iterable[Number]] = None, eds_s: float = 1, eds_Eoff: Iterable[Number] = [0, 0]): """ __init__ construct a eds-System that can be used to manage a simulation. Parameters ---------- potential: pot.envelopedPotential, optional potential function class to be explored by sampling sampler: sampler, optional sampling method, that allows exploring the potential function conditions: Iterable[condition], optional conditions that shall be applied to the system. temperature: float, optional The temperature of the system (default: 298K) start_position: starting position for the simulation and setup of the system. eds_s: float, optional is the S-value of the EDS-Potential eds_Eoff: Iterable[Number], optional giving the energy offsets for the """ ################################ # Declare Attributes ################################# self._currentEdsS = eds_s self._currentEdsEoffs = eds_Eoff self.state = data.envelopedPStstate super().__init__(potential=potential, sampler=sampler, conditions=conditions, temperature=temperature, start_position=start_position) # Output self.set_s(self._currentEdsS) self.set_eoff(self._currentEdsEoffs)
def test_exchange_all(self): integrator = stochastic.metropolisMonteCarloIntegrator() potential = OneD.harmonicOscillatorPotential() sys = system.system(potential=potential, sampler=integrator) T_range = range(1, 10) nReplicas = len(T_range) positions = {x: float(1) for x in range(nReplicas)} velocities = {x: float(0) for x in range(nReplicas)} group = replica_exchange.temperatureReplicaExchange( system=sys, temperature_range=T_range) group.set_replicas_positions(positions) group.set_replicas_velocities(velocities) group._defaultRandomness = lambda x, y: False group.exchange() all_exchanges = group._current_exchanges finpositions = list(group.get_replicas_positions().values()) finvelocities = list(group.get_replicas_velocities().values()) # Checking: ##constant params? self.assertEqual(len(group.replicas), nReplicas, msg="not enough trajectories were retrieved!") self.assertListEqual( finpositions, list(positions.values()), msg="Positions should not change during exchange!") #self.assertListEqual(finvelocities, velocities, msg="Velocities should not change during exchange!") ##exchange process self.assertEqual(nReplicas // 2, len(all_exchanges), msg="length of all exchanges is not correct!") self.assertTrue(all(list(all_exchanges.values())), msg="not all exchanges are True!!") del group setattr(self, "group", None)
def __init__(self, potential: potentialCls = harmonicOscillatorPotential(), sampler: samplerCls = metropolisMonteCarloIntegrator(), conditions: Iterable[conditionCls] = None, temperature: Number = 298.0, start_position: (Iterable[Number] or Number) = None, mass: Number = 1, verbose: bool = True) -> NoReturn: """ The system class is wrapping all components needed for a simulation. It can be used as the control unit for executing a simulation (simulate) and also to manage the generated data or input data. Parameters ---------- potential : _potentialCls gives the potential function to be explored/sampled sampler : _samplerCls gives the method of choice to sample/explore the potential function conditions : Iterable[_conditionCls], optional apply the given conditions to the systems in a preset (tau) step iteration temperature : float, optional temperature of the system start_position : float, optional starting position of the system during the simulation mass : float, optional mass of the single particle verbose : bool, optional I can tell you a long iterative story... """ ################################ # Declare Attributes ################################# ##Physical parameters self.nParticles = 1 # FUTURE: adapt it to be multiple particles self._mass = mass # for one particle systems!!!! self._temperature = temperature # Output self._currentState = self.state( **{key: np.nan for key in self.state.__dict__["_fields"]}) self._trajectory = [] # tmpvars - private: self._currentTotE: (Number) = np.nan self._currentTotPot: (Number) = np.nan self._currentTotKin: (Number) = np.nan self._currentPosition: (Number or Iterable[Number]) = np.nan self._currentVelocities: (Number or Iterable[Number]) = np.nan self._currentForce: (Number or Iterable[Number]) = np.nan self._currentTemperature: (Number or Iterable[Number]) = np.nan # BUILD System ## Fundamental Parts: self._potential = potential self._integrator = sampler if (conditions is None): self._conditions = [] else: self._conditions = conditions ## set dim if (potential.constants[potential.nDimensions] > 0): self.nDimensions = potential.constants[potential.nDimensions] else: raise IOError( "Could not estimate the disered Dimensionality as potential dim was <1 and no initial position was given." ) ###is the potential a state dependent one? - needed for initial pos. if (hasattr(potential, "nStates")): self.nStates = potential.constants[potential.nStates] else: self.nstates = 1 # PREPARE THE SYSTEM # Only init velocities, if the samplers uses them if (issubclass(sampler.__class__, (newtonianSampler, langevinIntegrator))): init_velocity = True else: init_velocity = False self.initialise(withdraw_Traj=True, init_position=True, init_velocity=init_velocity, set_initial_position=start_position) ##check if system should be coupled to conditions: # update for metadynamics simulation - local elevation bias is like a condition/potential hybrid. if (isinstance(self.potential, metadynamicsPotential1D) or isinstance(self.potential, metadynamicsPotential2D)): self._conditions.append(self.potential) for condition in self._conditions: if (not hasattr(condition, "system")): condition.couple_system(self) else: # warnings.warn("Decoupling system and coupling it again!") condition.couple_system(self) if (not hasattr(condition, "dt") and hasattr(self.sampler, "dt")): condition.dt = self.sampler.dt else: condition.dt = 1 self.verbose = verbose
def test_1D_animation(self): sim = system(potential=harmonicOscillatorPotential(), sampler=metropolisMonteCarloIntegrator()) sim.simulate(100) animationSimulation.animation_trajectory(simulated_system=sim)
def test_static_sim_plots(self): sim = system(potential=harmonicOscillatorPotential(), sampler=metropolisMonteCarloIntegrator()) sim.simulate(100) plotSimulations.oneD_simulation_analysis_plot(sim)
class test_ReplicaExchangeCls(unittest.TestCase): RE = _replica_graph._replicaExchange integrator = stochastic.metropolisMonteCarloIntegrator() potential = OneD.harmonicOscillatorPotential() sys = system.system(potential=potential, sampler=integrator) def test_tearDown(self) -> None: self.RE.replicas = {} def test_init_1DREnsemble(self): exchange_dimensions = {"temperature": range(288, 310)} _replica_graph._replicaExchange( system=self.sys, exchange_dimensions=exchange_dimensions) def test_init_2DREnsemble(self): exchange_dimensions = { "temperature": range(288, 310), "mass": range(1, 10) } _replica_graph._replicaExchange( system=self.sys, exchange_dimensions=exchange_dimensions) def test_run_1DREnsemble(self): exchange_dimensions = {"temperature": range(288, 310)} group = _replica_graph._replicaExchange( system=self.sys, exchange_dimensions=exchange_dimensions) group.run() def test_getTraj_1DREnsemble(self): replicas = 22 nsteps = 100 group = None exchange_dimensions = {"temperature": range(288, 310)} group = _replica_graph._replicaExchange( system=self.sys, exchange_dimensions=exchange_dimensions) group.nSteps_between_trials = nsteps group.run() trajectories = group.get_trajectories() ##print(len(trajectories)) ##print([len(trajectories[t]) for t in trajectories]) self.assertEqual(len(trajectories), 22, msg="not enough trajectories were retrieved!") self.assertEquals([len(trajectories[t]) for t in trajectories], second=[nsteps + 1 for x in range(replicas)], msg="traj lengths are not correct!") def test_getTotPot_1DREnsemble(self): replicas = 22 nsteps = 100 exchange_dimensions = {"temperature": range(288, 310)} group = _replica_graph._replicaExchange( system=self.sys, exchange_dimensions=exchange_dimensions) group.nSteps_between_trials = nsteps group.run() totPots = group.get_replica_total_energies() ##print(len(totPots)) ##print(totPots) self.assertEqual(len(totPots), replicas, msg="not enough trajectories were retrieved!") """