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_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()
Example #3
0
    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)
Example #4
0
    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)
Example #5
0
    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 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()])
Example #7
0
    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)
Example #8
0
    def redraw_states(self, nstates_event):
        self.nstates = nstates_event["new"]

        # Plotting stuff

        for line in self.ax.lines:
            if (line != self.eds_line):
                self.ax.lines.remove(line)
            del line

        self.positions_state = np.arange(-4, 4 * self.nstates, 0.5)
        self.positions = [[x] for x in self.positions_state]

        V_is = [
            pot.harmonicOscillatorPotential(x_shift=state * 4, k=10)
            for state in range(self.nstates)
        ]
        for state_e in [V.ene(self.positions_state) for V in V_is]:
            self.ax.plot(self.positions_state, state_e, alpha=0.8, lw=5)
        self.ax.set_xlim([-4, (4 * self.nstates)])

        # pot
        self.Eoffs = self.eds_pot.Eoff
        if (len(self.Eoffs) < self.nstates):
            for x in range(len(self.Eoffs), self.nstates):
                self.Eoffs.append(0)
        elif (len(self.Eoffs) > self.nstates):
            self.Eoffs = self.Eoffs[:self.nstates]

        self.eoff_sliders_box.children = self.make_eoff_sliders(self.nstates)

        self.eds_pot = pot.envelopedPotential(V_is=V_is,
                                              s=np.log10(1 +
                                                         (self.s**1.5 / 1000)),
                                              eoff=self.Eoffs)
        eds_enes = self.eds_pot.ene(self.positions)
        self.eds_line.set_data(self.positions, eds_enes)
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
Example #9
0
    def __init__(self, nstates=2, s=100, Eoff=None, figsize=[12, 6]):
        self.nstates = nstates
        self.s = s
        plt.ion()
        if (isinstance(Eoff, type(None))):
            self.Eoffs = [0 for state in range(self.nstates)]
        else:
            self.Eoffs = Eoff

        self.V_is = [
            pot.harmonicOscillatorPotential(x_shift=state * 4, k=10)
            for state in range(self.nstates)
        ]
        self.eds_pot = pot.envelopedPotential(V_is=self.V_is,
                                              s=self.s,
                                              eoff=self.Eoffs)

        ##Parameters
        self.positions_state = np.arange(-4, 4 * self.nstates, 0.5)
        self.positions = np.arange(-4, 4 * self.nstates,
                                   0.5)  # [x for x in  self.positions_state]

        energies = [V.ene(self.positions_state) for V in self.V_is]
        eds_enes = self.eds_pot.ene(self.positions)

        # plot
        if (figsize is None):
            self.fig = plt.figure()  # dpi=300)
        else:
            self.fig = plt.figure(figsize=figsize)
        ax = self.fig.add_subplot()
        ax.set_ylim([-50, 50])
        ax.set_xlim([-4, (4 * self.nstates)])
        ax.set_xlabel("x")
        ax.set_ylabel("V")

        ##init plots
        ax.plot(self.positions, energies[0], "C1", alpha=0.8, lw=5)
        ax.plot(self.positions, energies[1], "C2", alpha=0.8, lw=5)
        self.eds_line = ax.plot(self.positions,
                                eds_enes,
                                "C3",
                                lw=2,
                                zorder=100)[0]

        self.ax = ax

        # sliders
        ##states
        state_label = ipywidgets.Label("Number of States")
        state_slider = ipywidgets.IntSlider(value=2,
                                            min=2,
                                            max=10,
                                            step=1,
                                            orientation='horizontal')
        state_slider.observe(self.redraw_states, names="value")

        ##svals

        s_slider = ipywidgets.FloatSlider(value=100,
                                          min=0.1,
                                          max=101,
                                          step=1,
                                          orientation='horizontal',
                                          continous_update=True)
        self.s_label = ipywidgets.Label(
            "smoothing Parameter:  " +
            str(np.log10(1 + (s_slider.value**1.5 / 1000))))
        s_slider.observe(self.redraw_s, names="value")

        player = ipywidgets.Play(value=100,
                                 min=0.1,
                                 max=100,
                                 step=1,
                                 description="s_values")

        ipywidgets.jslink((s_slider, 'value'), (player, 'value'))

        ##eoffs
        eoff_sliders = self.make_eoff_sliders(self.nstates)

        # listeners

        # layout
        state_slider = ipywidgets.HBox([state_label, state_slider])
        s_box = ipywidgets.HBox([self.s_label, player, s_slider])
        self.eoff_sliders_box = ipywidgets.HBox(eoff_sliders)

        controls = ipywidgets.VBox(
            [state_slider, s_box, self.eoff_sliders_box])
        self.redraw_s({"new": 100})

        display(controls)
        self.fig.show()
Example #10
0
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!")

    """