TestExpandedEnsembleSampler.py 8.32 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
from openmm import *
from openmm.app import *
from openmm.unit import *
import numpy as np
import os
import tempfile
import unittest

class TestExpandedEnsembleSampler(unittest.TestCase):
    def testTemperature(self):
        """Test a set of states that differ in temperature."""
        system = System()
        system.addParticle(1.0)
        force = CustomExternalForce('x*x+y*y+z*z')
        force.addParticle(0)
        system.addForce(force)
        states = [{'temperature':t*kelvin} for t in np.geomspace(300.0, 600.0, 5)]
        for reinitialize in [False, True]:
            integrator = LangevinIntegrator(300*kelvin, 10/picosecond, 0.01*picosecond)
            simulation = Simulation(Topology(), system, integrator, Platform.getPlatform('Reference'))
            simulation.context.setPositions([Vec3(0, 0, 0)])
            sampler = ExpandedEnsembleSampler(states, simulation, 10, reinitialize)

            # Run for a little while to let the weights stabilize.

            sampler.step(10000)

            # Run for a while and record the states and energies.

            energies = [[] for _ in range(len(states))]
            iterations = 20000
            for i in range(iterations):
                sampler.step(10)
                energies[sampler.currentStateIndex].append(simulation.context.getState(energy=True).getPotentialEnergy())

            # Check that it spent roughly equal time in each state, and that the energies are correct.

            for energy, state in zip(energies, states):
                n = len(energy)
                assert iterations/10 < n < iterations/2
                average = sum(energy)/n
                expected = 1.5*(state['temperature']*MOLAR_GAS_CONSTANT_R)
                self.assertTrue(0.7 < average/expected < 1.3)

    def testParameter(self):
        """Test a set of states that differ in a force parameter."""
        system = System()
        system.addParticle(1.0)
        force = CustomExternalForce('0.5*k*x*x')
        force.addGlobalParameter('k', 1.0)
        force.addParticle(0)
        system.addForce(force)
        states = [{'k':k*kilojoules_per_mole/(nanometer**2)} for k in np.geomspace(10.0, 100.0, 5)]
        for reinitialize in [False, True]:
            integrator = LangevinIntegrator(300*kelvin, 10/picosecond, 0.01*picosecond)
            simulation = Simulation(Topology(), system, integrator, Platform.getPlatform('Reference'))
            simulation.context.setPositions([Vec3(0, 0, 0)])
            sampler = ExpandedEnsembleSampler(states, simulation, 10, reinitialize)

            # Run for a little while to let the weights stabilize.

            sampler.step(10000)

            # Run for a while and record the states and displacements.

            r2 = [[] for _ in range(len(states))]
            iterations = 20000
            for i in range(iterations):
                sampler.step(10)
                x = simulation.context.getState(positions=True).getPositions()[0][0]
                r2[sampler.currentStateIndex].append(x*x)

            # Check that it spent roughly equal time in each state, and that the energies are correct.

            expected = 0.5*integrator.getTemperature()*MOLAR_GAS_CONSTANT_R
            for i in range(len(r2)):
                n = len(r2[i])
                assert iterations/10 < n < iterations/2
                average = 0.5*states[i]['k']*sum(r2[i])/n
                self.assertTrue(0.7 < average/expected < 1.3)

    def testReporter(self):
        """Test reporting output from an expanded ensemble simulation."""
        system = System()
        force = CustomExternalForce('0.5*k*(x*x+y*y+z*z)')
        force.addGlobalParameter('k', 1.0)
        system.addForce(force)
        for i in range(3):
            system.addParticle(1.0)
            force.addParticle(0)
        states = [{'k':k} for k in (200.0, 300.0, 400.0)]
        with tempfile.NamedTemporaryFile(mode='w', delete=False) as logFile:
            with tempfile.NamedTemporaryFile(mode='w', delete=False) as energyFile:
                with tempfile.NamedTemporaryFile(mode='w', delete=False) as checkpointFile:
                    integrator = LangevinIntegrator(300*kelvin, 1/picosecond, 0.001*picosecond)
                    simulation = Simulation(Topology(), system, integrator, Platform.getPlatform('Reference'))
                    simulation.context.setPositions([Vec3(0, 0, 0)]*3)
                    sampler = ExpandedEnsembleSampler(states, simulation, 5, reportInterval=5, logFile=logFile.name,
                                                      energyFile=energyFile.name, checkpointFile=checkpointFile.name)

                    # Run a simulation.

                    step = []
                    iteration = []
                    stateIndex = []
                    weights = []
                    energies = []

                    def runIteration():
                        simulation.step(5)
                        step.append(simulation.currentStep)
                        iteration.append(sampler.currentIteration)
                        stateIndex.append(sampler.currentStateIndex)
                        weights.append(sampler.weights)
                        kT = MOLAR_GAS_CONSTANT_R*simulation.integrator.getTemperature()
                        energies.append(sampler._sampler.computeAllEnergies()/kT)
                        sampler._sampler.applyState(sampler.currentStateIndex)

                    try:
                        for _ in range(4):
                            runIteration()
                    except PermissionError:
                        # tempfile is kind of broken on Windows.  Just skip the test.
                        return
                    state1 = simulation.context.getState(positions=True, velocities=True, parameters=True)

                    # Delete all objects from the simulation and create a new one, telling it to resume from the files.

                    del sampler
                    del simulation
                    del integrator
                    integrator = LangevinIntegrator(300*kelvin, 1/picosecond, 0.001*picosecond)
                    simulation = Simulation(Topology(), system, integrator, Platform.getPlatform('Reference'))
                    sampler = ExpandedEnsembleSampler(states, simulation, 5, reportInterval=5, logFile=logFile.name,
                                                      energyFile=energyFile.name, checkpointFile=checkpointFile.name,
                                                      resume=True)

                    # Make sure everything was loaded correctly.

                    state2 = simulation.context.getState(positions=True, velocities=True, parameters=True)
                    self.assertEqual(XmlSerializer.serialize(state1), XmlSerializer.serialize(state2))
                    self.assertEqual(step[-1], simulation.currentStep)
                    self.assertEqual(iteration[-1], sampler.currentIteration)
                    self.assertEqual(stateIndex[-1], sampler.currentStateIndex)
                    self.assertEqual(weights[-1], sampler.weights)

                    # Generate some more output.

                    for _ in range(4):
                        runIteration()

                    # Check the log file.

                    logFile.close()
                    with open(logFile.name) as input:
                        lines = input.readlines()[1:]
                    os.remove(logFile.name)
                    self.assertEqual(8, len(lines))
                    for i, line in enumerate(lines):
                        fields = line.split(',')
                        self.assertEqual(int(fields[0]), step[i])
                        self.assertEqual(int(fields[1]), iteration[i])
                        self.assertEqual(int(fields[2]), stateIndex[i])
                        self.assertTrue(np.allclose([float(x) for x in fields[3:]], weights[i]))

                    # Check the energy file.

                    energyFile.close()
                    with open(energyFile.name) as input:
                        lines = input.readlines()[1:]
                    os.remove(energyFile.name)
                    self.assertEqual(8, len(lines))
                    for i, line in enumerate(lines):
                        fields = line.split(',')
                        self.assertEqual(int(fields[0]), step[i])
                        self.assertTrue(np.allclose([float(x) for x in fields[1:]], energies[i]))