"platforms/common/src/CommonCalcNonbondedForce.cpp" did not exist on "a056d5a3754e193105409afa12c9f0c9a2d972a2"
TestSimulation.py 12.8 KB
Newer Older
1
2
import unittest
import tempfile
peastman's avatar
peastman committed
3
from datetime import datetime, timedelta
4
from io import BytesIO, StringIO
5
6
7
from openmm import *
from openmm.app import *
from openmm.unit import *
8
9
10
11
12
13
14
15
16
17
18
19
20

class TestSimulation(unittest.TestCase):
    """Test the Simulation class"""

    def testCheckpointing(self):
        """Test that checkpointing works correctly."""
        pdb = PDBFile('systems/alanine-dipeptide-implicit.pdb')
        ff = ForceField('amber99sb.xml', 'tip3p.xml')
        system = ff.createSystem(pdb.topology)
        integrator = VerletIntegrator(0.001*picoseconds)

        # Create a Simulation.

Peter Eastman's avatar
Peter Eastman committed
21
        simulation = Simulation(pdb.topology, system, integrator, Platform.getPlatform('Reference'))
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
        simulation.context.setPositions(pdb.positions)
        simulation.context.setVelocitiesToTemperature(300*kelvin)
        initialState = simulation.context.getState(getPositions=True, getVelocities=True)

        # Create a checkpoint.

        filename = tempfile.mktemp()
        simulation.saveCheckpoint(filename)

        # Take a few steps so the positions and velocities will be different.

        simulation.step(2)
        state = simulation.context.getState(getPositions=True, getVelocities=True)
        self.assertNotEqual(initialState.getPositions(), state.getPositions())
        self.assertNotEqual(initialState.getVelocities(), state.getVelocities())

        # Reload the checkpoint and see if it resets them correctly.

        simulation.loadCheckpoint(filename)
        state = simulation.context.getState(getPositions=True, getVelocities=True)
        self.assertEqual(initialState.getPositions(), state.getPositions())
        self.assertEqual(initialState.getVelocities(), state.getVelocities())


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
    def testLoadFromXML(self):
        """ Test creating a Simulation from XML files """
        pdb = PDBFile('systems/alanine-dipeptide-implicit.pdb')
        ff = ForceField('amber99sb.xml', 'tip3p.xml')
        system = ff.createSystem(pdb.topology)
        integrator = VerletIntegrator(0.001*picoseconds)
        context = Context(system, integrator)
        context.setPositions(pdb.positions)
        state = context.getState(getPositions=True, getForces=True,
                                 getVelocities=True, getEnergy=True)
        systemfn = tempfile.mktemp()
        integratorfn = tempfile.mktemp()
        statefn = tempfile.mktemp()
        with open(systemfn, 'w') as f:
            f.write(XmlSerializer.serialize(system))
        with open(integratorfn, 'w') as f:
            f.write(XmlSerializer.serialize(integrator))
        with open(statefn, 'w') as f:
            f.write(XmlSerializer.serialize(state))

        # Now create a Simulation
67
        sim = Simulation(pdb.topology, systemfn, integratorfn, state=statefn)
68

69
70
71
72
73
74
75
76
77
    def testSaveState(self):
        """Test that saving States works correctly."""
        pdb = PDBFile('systems/alanine-dipeptide-implicit.pdb')
        ff = ForceField('amber99sb.xml', 'tip3p.xml')
        system = ff.createSystem(pdb.topology)
        integrator = VerletIntegrator(0.001*picoseconds)

        # Create a Simulation.

Peter Eastman's avatar
Peter Eastman committed
78
        simulation = Simulation(pdb.topology, system, integrator, Platform.getPlatform('Reference'))
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
        simulation.context.setPositions(pdb.positions)
        simulation.context.setVelocitiesToTemperature(300*kelvin)
        initialState = simulation.context.getState(getPositions=True, getVelocities=True)

        # Create a state.

        filename = tempfile.mktemp()
        simulation.saveState(filename)

        # Take a few steps so the positions and velocities will be different.

        simulation.step(2)
        state = simulation.context.getState(getPositions=True, getVelocities=True)
        self.assertNotEqual(initialState.getPositions(), state.getPositions())
        self.assertNotEqual(initialState.getVelocities(), state.getVelocities())

        # Reload the state and see if it resets them correctly.

        simulation.loadState(filename)
        state = simulation.context.getState(getPositions=True, getVelocities=True)
        self.assertEqual(initialState.getPositions(), state.getPositions())
        self.assertEqual(initialState.getVelocities(), state.getVelocities())

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
    def testSafeSave(self):
        """Test that the safe saving feature works as expected."""
        pdb = PDBFile('systems/alanine-dipeptide-implicit.pdb')
        ff = ForceField('amber99sb.xml', 'tip3p.xml')
        system = ff.createSystem(pdb.topology)
        integrator = VerletIntegrator(0.001*picoseconds)

        # Create a Simulation.

        simulation = Simulation(pdb.topology, system, integrator, Platform.getPlatform('Reference'))
        simulation.context.setPositions(pdb.positions)
        simulation.context.setVelocitiesToTemperature(300*kelvin)

        # Get reference checkpoint and state data.

        checkpointBuffer = BytesIO()
        simulation.saveCheckpoint(checkpointBuffer)
        checkpointData = checkpointBuffer.getvalue()

        stateBuffer = StringIO()
        simulation.saveState(stateBuffer)
        stateData = stateBuffer.getvalue()

        # Try a safe save of a checkpoint.

        with tempfile.TemporaryDirectory() as directory:
            tempPath = os.path.join(directory, 'testSafeSaveCheckpoint.dat')

            # Make a file that should get overwritten by the safe save, and some that shouldn't.

            with open(tempPath, 'w') as testFile:
                testFile.write('Test')
            with open(f'{tempPath}.0.tmp', 'w') as testFile:
                testFile.write('Test0')
            with open(f'{tempPath}.1.tmp', 'w') as testFile:
                testFile.write('Test1')

            # Perform and verify the safe save and that the contents of the test files were not overwritten.

            simulation.saveCheckpoint(tempPath)
            with open(tempPath, 'rb') as checkpointFile:
                self.assertSequenceEqual(checkpointData, checkpointFile.read())
            with open(f'{tempPath}.0.tmp', 'r') as testFile:
                self.assertSequenceEqual('Test0', testFile.read())
            with open(f'{tempPath}.1.tmp', 'r') as testFile:
                self.assertSequenceEqual('Test1', testFile.read())

        # Try a safe save of a state.

        with tempfile.TemporaryDirectory() as directory:
            tempPath = os.path.join(directory, 'testSafeSaveState.dat')

            # Make a file that should get overwritten by the safe save, and some that shouldn't.

            with open(tempPath, 'w') as testFile:
                testFile.write('Test')
            with open(f'{tempPath}.0.tmp', 'w') as testFile:
                testFile.write('Test0')
            with open(f'{tempPath}.1.tmp', 'w') as testFile:
                testFile.write('Test1')

            # Perform and verify the safe save and that the contents of the test files were not overwritten.

            simulation.saveState(tempPath)
            with open(tempPath, 'r') as stateFile:
                self.assertSequenceEqual(stateData, stateFile.read())
            with open(f'{tempPath}.0.tmp', 'r') as testFile:
                self.assertSequenceEqual('Test0', testFile.read())
            with open(f'{tempPath}.1.tmp', 'r') as testFile:
                self.assertSequenceEqual('Test1', testFile.read())

peastman's avatar
peastman committed
173
174
175
176
177
178
179
180
181
    def testStep(self):
        """Test the step() method."""
        pdb = PDBFile('systems/alanine-dipeptide-implicit.pdb')
        ff = ForceField('amber99sb.xml', 'tip3p.xml')
        system = ff.createSystem(pdb.topology)
        integrator = VerletIntegrator(0.001*picoseconds)

        # Create a Simulation.

Peter Eastman's avatar
Peter Eastman committed
182
        simulation = Simulation(pdb.topology, system, integrator, Platform.getPlatform('Reference'))
peastman's avatar
peastman committed
183
184
185
186
        simulation.context.setPositions(pdb.positions)
        simulation.context.setVelocitiesToTemperature(300*kelvin)
        self.assertEqual(0, simulation.currentStep)
        self.assertEqual(0*picoseconds, simulation.context.getState().getTime())
187
188
        simulation.currentStep = 5
        self.assertEqual(5, simulation.currentStep)
peastman's avatar
peastman committed
189
190
191
192

        # Take some steps and verify the simulation has advanced by the correct amount.

        simulation.step(23)
193
        self.assertEqual(28, simulation.currentStep)
peastman's avatar
peastman committed
194
195
196
197
198
199
200
201
202
203
204
        self.assertAlmostEqual(0.023, simulation.context.getState().getTime().value_in_unit(picoseconds))

    def testRunForClockTime(self):
        """Test the runForClockTime() method."""
        pdb = PDBFile('systems/alanine-dipeptide-implicit.pdb')
        ff = ForceField('amber99sb.xml', 'tip3p.xml')
        system = ff.createSystem(pdb.topology)
        integrator = VerletIntegrator(0.001*picoseconds)

        # Create a Simulation.

Peter Eastman's avatar
Peter Eastman committed
205
        simulation = Simulation(pdb.topology, system, integrator, Platform.getPlatform('Reference'))
peastman's avatar
peastman committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
        simulation.context.setPositions(pdb.positions)
        simulation.context.setVelocitiesToTemperature(300*kelvin)
        self.assertEqual(0, simulation.currentStep)
        self.assertEqual(0*picoseconds, simulation.context.getState().getTime())

        # Run for five seconds, the save both a checkpoint and a state.

        checkpointFile = tempfile.mktemp()
        stateFile = tempfile.mktemp()
        startTime = datetime.now()
        simulation.runForClockTime(5*seconds, checkpointFile=checkpointFile, stateFile=stateFile)
        endTime = datetime.now()

        # Make sure at least five seconds have elapsed, but no more than ten.

        self.assertTrue(endTime >= startTime+timedelta(seconds=5))
        self.assertTrue(endTime < startTime+timedelta(seconds=10))
223
224
225
226
227
228
        
        # Check that the time and step count are consistent.
        
        time = simulation.context.getState().getTime().value_in_unit(picoseconds)
        expectedTime = simulation.currentStep*integrator.getStepSize().value_in_unit(picoseconds)
        self.assertAlmostEqual(expectedTime, time)
peastman's avatar
peastman committed
229
230
231
232
233
234
235
236
237
238
239

        # Load the checkpoint and state and make sure they are both correct.

        velocities = simulation.context.getState(getVelocities=True).getVelocities()
        simulation.context.setVelocitiesToTemperature(300*kelvin)
        simulation.loadCheckpoint(checkpointFile)
        self.assertEqual(velocities, simulation.context.getState(getVelocities=True).getVelocities())
        simulation.context.setVelocitiesToTemperature(300*kelvin)
        simulation.loadState(stateFile)
        self.assertEqual(velocities, simulation.context.getState(getVelocities=True).getVelocities())

240
241
242
243
244
245
246
247
248
249
250
251
252
253
    def testWrappedCoordinates(self):
        """Test generating reports with and without wrapped coordinates."""
        pdb = PDBFile('systems/alanine-dipeptide-explicit.pdb')
        ff = ForceField('amber99sb.xml', 'tip3p.xml')
        system = ff.createSystem(pdb.topology, nonbondedMethod=CutoffPeriodic, constraints=HBonds)
        integrator = LangevinIntegrator(300*kelvin, 1/picosecond, 0.002*picoseconds)

        class CompareCoordinatesReporter(object):
            def __init__(self, periodic):
                self.periodic = periodic
                self.interval = 100
                
            def describeNextReport(self, simulation):
                steps = self.interval - simulation.currentStep%self.interval
254
                return {'steps':steps, 'periodic':self.periodic, 'include':['positions']}
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
        
            def report(self, simulation, state):
                state2 = simulation.context.getState(getPositions=True, enforcePeriodicBox=self.periodic)
                assert state.getPositions() == state2.getPositions()

        # Create a Simulation.

        simulation = Simulation(pdb.topology, system, integrator)
        simulation.context.setPositions(pdb.positions)
        simulation.context.setVelocitiesToTemperature(300*kelvin)
        simulation.reporters.append(CompareCoordinatesReporter(False))
        simulation.reporters.append(CompareCoordinatesReporter(True))
        
        # Run for a little while and make sure the reporters don't find any problems.
        
        simulation.step(500)

272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
    def testMinimizationReporter(self):
        """Test invoking a reporter during minimization."""
        pdb = PDBFile('systems/alanine-dipeptide-implicit.pdb')
        ff = ForceField('amber99sb.xml', 'tip3p.xml')
        system = ff.createSystem(pdb.topology)
        integrator = LangevinIntegrator(300*kelvin, 1/picosecond, 0.002*picoseconds)
        simulation = Simulation(pdb.topology, system, integrator)
        simulation.context.setPositions(pdb.positions)

        class Reporter(MinimizationReporter):
            lastIteration = -1
            error = False

            def report(self, iteration, x, grad, args):
                if iteration != self.lastIteration+1:
                    self.error = True
                self.lastIteration = iteration
                if iteration == 10:
                    return True
                if iteration > 10:
                    self.error = True
                return False

        reporter = Reporter()
        simulation.minimizeEnergy(reporter=reporter)
        assert not reporter.error

299
300
301

if __name__ == '__main__':
    unittest.main()