TestForceField.py 105 KB
Newer Older
1
2
import unittest
from validateConstraints import *
3
4
5
6
7
from openmm.app import *
from openmm import *
from openmm.unit import *
import openmm.app.element as elem
import openmm.app.forcefield as forcefield
8
import math
9
10
import shutil
import tempfile
11
import textwrap
12
13
14
15
try:
    from cStringIO import StringIO
except ImportError:
    from io import StringIO
16
import os
ChayaSt's avatar
ChayaSt committed
17
import warnings
18
19
20

class TestForceField(unittest.TestCase):
    """Test the ForceField.createSystem() method."""
21

22
    def setUp(self):
23
        """Set up the tests by loading the input pdb files and force field
24
25
26
27
28
29
30
31
        xml files.

        """
        # alanine dipeptide with explicit water
        self.pdb1 = PDBFile('systems/alanine-dipeptide-explicit.pdb')
        self.forcefield1 = ForceField('amber99sb.xml', 'tip3p.xml')
        self.topology1 = self.pdb1.topology
        self.topology1.setUnitCellDimensions(Vec3(2, 2, 2))
32

33
        # alanine dipeptide with implicit water
34
35
36
37
38
        self.pdb2 = PDBFile('systems/alanine-dipeptide-implicit.pdb')
        self.forcefield2 = ForceField('amber99sb.xml', 'amber99_obc.xml')


    def test_NonbondedMethod(self):
Peter Eastman's avatar
Peter Eastman committed
39
        """Test all six options for the nonbondedMethod parameter."""
40

41
42
43
        methodMap = {NoCutoff:NonbondedForce.NoCutoff,
                     CutoffNonPeriodic:NonbondedForce.CutoffNonPeriodic,
                     CutoffPeriodic:NonbondedForce.CutoffPeriodic,
Peter Eastman's avatar
Peter Eastman committed
44
45
46
                     Ewald:NonbondedForce.Ewald,
                     PME:NonbondedForce.PME,
                     LJPME:NonbondedForce.LJPME}
47
48
49
50
        for method in methodMap:
            system = self.forcefield1.createSystem(self.pdb1.topology,
                                                  nonbondedMethod=method)
            forces = system.getForces()
51
52
            self.assertTrue(any(isinstance(f, NonbondedForce) and
                                f.getNonbondedMethod()==methodMap[method]
53
54
                                for f in forces))

55
    def test_DispersionCorrection(self):
56
57
58
        """Test to make sure that the dispersion/long-range correction is set properly."""
        top = Topology()
        chain = top.addChain()
59

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
        for lrc in (True, False):
            xml = textwrap.dedent(
                """
                <ForceField>
                 <LennardJonesForce lj14scale="0.3" useDispersionCorrection="{lrc}">
                  <Atom type="A" sigma="1" epsilon="0.1"/>
                  <Atom type="B" sigma="2" epsilon="0.2"/>
                  <NBFixPair type1="A" type2="B" sigma="2.5" epsilon="1.1"/>
                 </LennardJonesForce>
                 <NonbondedForce coulomb14scale="0.833333" lj14scale="0.5" useDispersionCorrection="{lrc2}">
                  <Atom type="A" sigma="0.315" epsilon="0.635"/>
                 </NonbondedForce>
                </ForceField>
                """
            )
            ff = ForceField(StringIO(xml.format(lrc=lrc, lrc2=lrc)))
            system = ff.createSystem(top)
            checked_nonbonded = False
            checked_custom = False
79
80
            for force in system.getForces():
                if isinstance(force, NonbondedForce):
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
                    self.assertEqual(force.getUseDispersionCorrection(), lrc)
                    checked_nonbonded = True
                elif isinstance(force, CustomNonbondedForce):
                    self.assertEqual(force.getUseLongRangeCorrection(), lrc)
                    checked_custom = True
            self.assertTrue(checked_nonbonded and checked_custom)

            # check that the keyword argument overwrites xml input
            lrc_kwarg = not lrc
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter("always")
                system2 = ff.createSystem(top, useDispersionCorrection=lrc_kwarg)
                self.assertTrue(len(w) == 2)
                assert "conflict" in str(w[-1].message).lower()
            checked_nonbonded = False
            checked_custom = False
            for force in system2.getForces():
                if isinstance(force, NonbondedForce):
                    self.assertEqual(force.getUseDispersionCorrection(), lrc_kwarg)
                    checked_nonbonded = True
                elif isinstance(force, CustomNonbondedForce):
                    self.assertEqual(force.getUseLongRangeCorrection(), lrc_kwarg)
                    checked_custom = True
            self.assertTrue(checked_nonbonded and checked_custom)

            # check that no warning is generated when useDispersionCorrection is not in the xml file
            xml = textwrap.dedent(
                """
                <ForceField>
                 <LennardJonesForce lj14scale="0.3">
                  <Atom type="A" sigma="1" epsilon="0.1"/>
                  <Atom type="B" sigma="2" epsilon="0.2"/>
                  <NBFixPair type1="A" type2="B" sigma="2.5" epsilon="1.1"/>
                 </LennardJonesForce>
                 <NonbondedForce coulomb14scale="0.833333" lj14scale="0.5">
                  <Atom type="A" sigma="0.315" epsilon="0.635"/>
                 </NonbondedForce>
                </ForceField>
                """
            )
            ff = ForceField(StringIO(xml))
            system = ff.createSystem(top)
            for lrc_kwarg in [True, False]:
                with warnings.catch_warnings():
                    warnings.simplefilter("error")
                    system2 = ff.createSystem(top, useDispersionCorrection=lrc_kwarg)
127

128
129
130
    def test_Cutoff(self):
        """Test to make sure the nonbondedCutoff parameter is passed correctly."""

Peter Eastman's avatar
Peter Eastman committed
131
        for method in [CutoffNonPeriodic, CutoffPeriodic, Ewald, PME, LJPME]:
132
            system = self.forcefield1.createSystem(self.pdb1.topology,
133
134
                                                   nonbondedMethod=method,
                                                   nonbondedCutoff=2*nanometer,
135
136
137
138
139
140
141
142
                                                   constraints=HBonds)
            cutoff_distance = 0.0*nanometer
            cutoff_check = 2.0*nanometer
            for force in system.getForces():
                if isinstance(force, NonbondedForce):
                    cutoff_distance = force.getCutoffDistance()
            self.assertEqual(cutoff_distance, cutoff_check)

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
    def test_SwitchingDistance(self):
        """Test that the switchDistance parameter is processed correctly."""

        for switchDistance in [None, 0.9*nanometers]:
            system = self.forcefield1.createSystem(self.pdb1.topology,
                                                   nonbondedMethod=PME,
                                                   switchDistance=switchDistance)
            for force in system.getForces():
                if isinstance(force, NonbondedForce):
                    if switchDistance is None:
                        self.assertFalse(force.getUseSwitchingFunction())
                    else:
                        self.assertTrue(force.getUseSwitchingFunction())
                        self.assertEqual(switchDistance, force.getSwitchingDistance())

158
159
160
161
162
163
164
165
166
    def test_RemoveCMMotion(self):
        """Test both options (True and False) for the removeCMMotion parameter."""
        for b in [True, False]:
            system = self.forcefield1.createSystem(self.pdb1.topology,removeCMMotion=b)
            forces = system.getForces()
            self.assertEqual(any(isinstance(f, CMMotionRemover) for f in forces), b)

    def test_RigidWaterAndConstraints(self):
        """Test all eight options for the constraints and rigidWater parameters."""
167

168
169
        topology = self.pdb1.topology
        for constraints_value in [None, HBonds, AllBonds, HAngles]:
170
            for rigidWater_value in [True, False, None]:
171
                system = self.forcefield1.createSystem(topology,
172
                                                       constraints=constraints_value,
173
                                                       rigidWater=rigidWater_value)
174
                validateConstraints(self, topology, system,
175
                                    constraints_value, rigidWater_value != False)
176

177
178
179
180
181
182
183
    def test_flexibleConstraints(self):
        """ Test the flexibleConstraints keyword """
        topology = self.pdb1.topology
        system1 = self.forcefield1.createSystem(topology, constraints=HAngles,
                                                rigidWater=True)
        system2 = self.forcefield1.createSystem(topology, constraints=HAngles,
                                                rigidWater=True, flexibleConstraints=True)
Jason Swails's avatar
Jason Swails committed
184
        system3 = self.forcefield1.createSystem(topology, constraints=None, rigidWater=False)
185
        validateConstraints(self, topology, system1, HAngles, True)
Jason Swails's avatar
Jason Swails committed
186
187
188
189
        # validateConstraints fails for system2 since by definition atom pairs can be in both bond
        # and constraint lists. So just check that the number of constraints is the same for both
        # system1 and system2
        self.assertEqual(system1.getNumConstraints(), system2.getNumConstraints())
190
191
192
193
194
195
196
197
198
199
        for force in system1.getForces():
            if isinstance(force, HarmonicBondForce):
                bf1 = force
            elif isinstance(force, HarmonicAngleForce):
                af1 = force
        for force in system2.getForces():
            if isinstance(force, HarmonicBondForce):
                bf2 = force
            elif isinstance(force, HarmonicAngleForce):
                af2 = force
Jason Swails's avatar
Jason Swails committed
200
201
202
203
        for force in system3.getForces():
            if isinstance(force, HarmonicAngleForce):
                af3 = force
        # Make sure we picked up extra bond terms with flexibleConstraints
204
        self.assertGreater(bf2.getNumBonds(), bf1.getNumBonds())
Jason Swails's avatar
Jason Swails committed
205
206
        # Make sure flexibleConstraints yields just as many angles as no constraints
        self.assertEqual(af2.getNumAngles(), af3.getNumAngles())
207

208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
    def testTemplateConstraints(self):
        """Test constraints defined by a residue template."""
        xml = """
<ForceField>
 <AtomTypes>
  <Type name="C" class="C" element="C" mass="12.01078"/>
  <Type name="O" class="O" element="O" mass="15.99943"/>
  <Type name="H" class="H" element="H" mass="1.007947"/>
  <Type name="Na+" class="Na+" element="Na" mass="22.99"/>
  <Type name="Cl-" class="Cl-" element="Cl" mass="35.45"/>
 </AtomTypes>
 <Residues>
  <Residue name="MEOH">
   <Atom name="CB" type="C"/>
   <Atom name="OG" type="O"/>
   <Atom name="HG" type="H"/>
   <Atom name="HB1" type="H"/>
   <Atom name="HB2" type="H"/>
   <Atom name="HB3" type="H"/>
   <Bond atomName1="CB" atomName2="OG"/>
   <Bond atomName1="CB" atomName2="HB1"/>
   <Bond atomName1="CB" atomName2="HB2"/>
   <Bond atomName1="CB" atomName2="HB3"/>
   <Bond atomName1="OG" atomName2="HG"/>
   <Constraint atomName1="CB" atomName2="OG" distance="1.987"/>
   <Constraint atomName1="OG" atomName2="HG" distance="1.123"/>
  </Residue>
  <Residue name="NA">
    <Atom name="NA" type="Na+"/>
  </Residue>
  <Residue name="CL">
    <Atom name="CL" type="Cl-"/>
  </Residue>
 </Residues>
 <HarmonicBondForce>
  <Bond class1="C" class2="O" k="100.0" length="2.0"/>
  <Bond class1="C" class2="H" k="100.0" length="1.0"/>
  <Bond class1="O" class2="H" k="100.0" length="1.1"/>
 </HarmonicBondForce>
</ForceField>"""
        ff = ForceField(StringIO(xml))
        pdb = PDBFile('systems/methanol_ions.pdb')
        expected = {None:2, HBonds:5, AllBonds:5}
        for constraints in [None, HBonds, AllBonds]:
            system = ff.createSystem(pdb.topology, constraints=constraints)
            self.assertEqual(expected[constraints], system.getNumConstraints())
            lengths = {}
            for i in range(system.getNumConstraints()):
                p1, p2, length = system.getConstraintParameters(i)
                lengths[(min(p1, p2), max(p1, p2))] = length.value_in_unit(nanometer)
            self.assertEqual(1.987, lengths[(0, 1)])
            self.assertEqual(1.123, lengths[(1, 2)])
            if constraints is not None:
                self.assertEqual(1.0, lengths[(0, 3)])
                self.assertEqual(1.0, lengths[(0, 4)])
                self.assertEqual(1.0, lengths[(0, 5)])

Peter Eastman's avatar
Peter Eastman committed
265
266
267
268
269
270
271
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
    def testTemplateConstraintsMultipleMols(self):
        """Test that constraints defined by a residue template don't leak into
        other residues.
        See https://github.com/openmm/openmm/issues/5234
        """
        MOL_A = """<ForceField>
 <AtomTypes>
  <Type name="A0" mass="12" class="A0" element="C"/>
  <Type name="A1" mass="12" class="A1" element="C"/>
 </AtomTypes>
 <HarmonicBondForce>
  <Bond class1="A0" class2="A1" length="0.15" k="200000"/>
 </HarmonicBondForce>
 <NonbondedForce coulomb14scale="1" lj14scale="1">
  <Atom class="A0" sigma="0.3" epsilon="0.1" charge="0"/>
  <Atom class="A1" sigma="0.3" epsilon="0.1" charge="0"/>
 </NonbondedForce>
 <Residues>
  <Residue name="MOLA">
   <Atom name="a0" type="A0"/><Atom name="a1" type="A1"/>
   <Bond atomName1="a0" atomName2="a1"/>
  </Residue>
 </Residues>
</ForceField>"""

        MOL_B = """<ForceField>
 <AtomTypes>
  <Type name="B0" mass="12" class="B0" element="C"/>
  <Type name="B1" mass="1" class="B1" element="H"/>
 </AtomTypes>
 <HarmonicBondForce>
  <Bond class1="B0" class2="B1" length="0.11" k="300000"/>
 </HarmonicBondForce>
 <NonbondedForce coulomb14scale="1" lj14scale="1">
  <Atom class="B0" sigma="0.3" epsilon="0.1" charge="0"/>
  <Atom class="B1" sigma="0.1" epsilon="0.01" charge="0"/>
 </NonbondedForce>
 <Residues>
  <Residue name="MOLB">
   <Atom name="b0" type="B0"/><Atom name="b1" type="B1"/>
   <Bond atomName1="b0" atomName2="b1"/>
   <Constraint atomName1="b0" atomName2="b1" distance="0.11"/>
  </Residue>
 </Residues>
</ForceField>"""

        top = Topology()
        c = top.addChain()
        C, H = Element.getBySymbol('C'), Element.getBySymbol('H')
        r1 = top.addResidue('MOLA', c)
        a0, a1 = top.addAtom('a0', C, r1), top.addAtom('a1', C, r1)
        top.addBond(a0, a1)
        r2 = top.addResidue('MOLB', c)
        b0, b1 = top.addAtom('b0', C, r2), top.addAtom('b1', H, r2)
        top.addBond(b0, b1)

        ff = ForceField()
        ff.loadFile(StringIO(MOL_A))
        ff.loadFile(StringIO(MOL_B))
        sys = ff.createSystem(top,
                              nonbondedMethod=NoCutoff,
                              constraints=None)

        self.assertEqual(sys.getNumConstraints(), 1)
        constraintParameters = sys.getConstraintParameters(0)
        self.assertEqual(constraintParameters[0], 2)
        self.assertEqual(constraintParameters[1], 3)
        self.assertEqual(constraintParameters[2], 0.11 * nanometer)

334
    def test_ImplicitSolvent(self):
335
        """Test the four types of implicit solvents using the implicitSolvent
336
337
338
        parameter.

        """
339
340

        topology = self.pdb2.topology
341
342
343
344
345
        system = self.forcefield2.createSystem(topology)
        forces = system.getForces()
        self.assertTrue(any(isinstance(f, GBSAOBCForce) for f in forces))

    def test_ImplicitSolventParameters(self):
346
        """Test that solventDielectric and soluteDielectric are passed correctly
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
        for the different types of implicit solvent.

        """

        topology = self.pdb2.topology
        system = self.forcefield2.createSystem(topology, solventDielectric=50.0,
                                               soluteDielectric=0.9)
        found_matching_solvent_dielectric=False
        found_matching_solute_dielectric=False
        for force in system.getForces():
            if isinstance(force, GBSAOBCForce):
                if force.getSolventDielectric() == 50.0:
                    found_matching_solvent_dielectric = True
                if force.getSoluteDielectric() == 0.9:
                    found_matching_solute_dielectric = True
            if isinstance(force, NonbondedForce):
                self.assertEqual(force.getReactionFieldDielectric(), 1.0)
364
        self.assertTrue(found_matching_solvent_dielectric and
365
366
                        found_matching_solute_dielectric)

Evan Pretti's avatar
Evan Pretti committed
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
    def test_LCPO(self):
        """Check LCPO parameter assignment vs. the Amber implementation."""

        prmtop = AmberPrmtopFile('systems/lcpo_test.prmtop')
        pdb = PDBFile('systems/lcpo_test.pdb')
        system1 = prmtop.createSystem(implicitSolvent=GBn2, sasaMethod='LCPO')
        system2 = ForceField('amber14-all.xml', 'implicit/gbn2.xml').createSystem(pdb.topology, sasaMethod='LCPO')
        lcpo1, = (force for force in system1.getForces() if isinstance(force, LCPOForce))
        lcpo2, = (force for force in system2.getForces() if isinstance(force, LCPOForce))
        self.assertEqual(XmlSerializer.serialize(lcpo1), XmlSerializer.serialize(lcpo2))

    def test_LCPOInvalid(self):
        """Check that LCPO parameter assignment fails instead of assigning incorrect parameters for unsupported atom types."""

        # Build a water molecule.
        topology = Topology()
        chain = topology.addChain()
        residue = topology.addResidue("HOH", chain)
        o = topology.addAtom("O", elem.oxygen, residue)
        h1 = topology.addAtom("H1", elem.hydrogen, residue)
        h2 = topology.addAtom("H2", elem.hydrogen, residue)
        topology.addBond(o, h1)
        topology.addBond(o, h2)

        # Water should be matched correctly but there are no LCPO parameters for
        # O bonded to two H atoms, so an exception should be raised.
        ff = ForceField('amber14-all.xml', 'amber14/opc3.xml', 'implicit/gbn2.xml')
        with self.assertRaisesRegex(ValueError, 'atomic number 8.+2 bonds.+0 bonds excluding H'):
            ff.createSystem(topology, sasaMethod='LCPO')

397
398
    def test_HydrogenMass(self):
        """Test that altering the mass of hydrogens works correctly."""
399

400
401
402
403
404
405
406
        topology = self.pdb1.topology
        hydrogenMass = 4*amu
        system1 = self.forcefield1.createSystem(topology)
        system2 = self.forcefield1.createSystem(topology, hydrogenMass=hydrogenMass)
        for atom in topology.atoms():
            if atom.element == elem.hydrogen:
                self.assertNotEqual(hydrogenMass, system1.getParticleMass(atom.index))
407
408
409
410
                if atom.residue.name == 'HOH':
                    self.assertEqual(system1.getParticleMass(atom.index), system2.getParticleMass(atom.index))
                else:
                    self.assertEqual(hydrogenMass, system2.getParticleMass(atom.index))
411
412
413
        totalMass1 = sum([system1.getParticleMass(i) for i in range(system1.getNumParticles())]).value_in_unit(amu)
        totalMass2 = sum([system2.getParticleMass(i) for i in range(system2.getNumParticles())]).value_in_unit(amu)
        self.assertAlmostEqual(totalMass1, totalMass2)
414

415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
    def test_DrudeMass(self):
        """Test that setting the mass of Drude particles works correctly."""

        forcefield = ForceField('charmm_polar_2013.xml')
        pdb = PDBFile('systems/ala_ala_ala.pdb')
        modeller = Modeller(pdb.topology, pdb.positions)
        modeller.addExtraParticles(forcefield)
        system = forcefield.createSystem(modeller.topology, drudeMass=0)
        trueMass = [system.getParticleMass(i) for i in range(system.getNumParticles())]
        drudeMass = 0.3*amu
        system = forcefield.createSystem(modeller.topology, drudeMass=drudeMass)
        adjustedMass = [system.getParticleMass(i) for i in range(system.getNumParticles())]
        drudeForce = [f for f in system.getForces() if isinstance(f, DrudeForce)][0]
        drudeParticles = set()
        parentParticles = set()
        for i in range(drudeForce.getNumParticles()):
            params = drudeForce.getParticleParameters(i)
            drudeParticles.add(params[0])
            parentParticles.add(params[1])
        for i in range(system.getNumParticles()):
            if i in drudeParticles:
                self.assertEqual(0*amu, trueMass[i])
                self.assertEqual(drudeMass, adjustedMass[i])
            elif i in parentParticles:
                self.assertEqual(trueMass[i]-drudeMass, adjustedMass[i])
            else:
                self.assertEqual(trueMass[i], adjustedMass[i])

443
444
445
446
447
448
449
450
    def test_UnusedArgs(self):
        """Test that specifying an argument that is never used throws an exception."""
        topology = self.pdb1.topology
        # Using the default value should not raise an exception.
        self.forcefield1.createSystem(topology, drudeMass=0.4*amu)
        # Specifying a non-default value should.
        with self.assertRaises(ValueError):
            self.forcefield1.createSystem(topology, drudeMass=0.5*amu)
451
        # Specifying a nonexistent argument should raise an exception.
452
453
454
        with self.assertRaises(ValueError):
            self.forcefield1.createSystem(topology, nonbndedCutoff=1.0*nanometer)

455
456
    def test_Forces(self):
        """Compute forces and compare them to ones generated with a previous version of OpenMM to ensure they haven't changed."""
457

458
459
460
461
462
463
        pdb = PDBFile('systems/lysozyme-implicit.pdb')
        system = self.forcefield2.createSystem(pdb.topology)
        integrator = VerletIntegrator(0.001)
        context = Context(system, integrator)
        context.setPositions(pdb.positions)
        state1 = context.getState(getForces=True)
464
465
        with open('systems/lysozyme-implicit-forces.xml') as input:
            state2 = XmlSerializer.deserialize(input.read())
466
        numDifferences = 0
467
        for f1, f2, in zip(state1.getForces().value_in_unit(kilojoules_per_mole/nanometer), state2.getForces().value_in_unit(kilojoules_per_mole/nanometer)):
468
469
470
471
            diff = norm(f1-f2)
            if diff > 0.1 and diff/norm(f1) > 1e-3:
                numDifferences += 1
        self.assertTrue(numDifferences < system.getNumParticles()/20) # Tolerate occasional differences from numerical error
472

473
474
475
476
477
478
479
480
481
482
483
    def test_ImplicitSolventForces(self):
        """Compute forces for different implicit solvent types, and compare them to ones generated with AmberPrmtopFile."""

        solventType = ['hct', 'obc1', 'obc2', 'gbn', 'gbn2']
        nonbondedMethod = [NoCutoff, CutoffNonPeriodic, CutoffNonPeriodic, NoCutoff, NoCutoff]
        kappa = [0.0, 0.0, 1.698295227342757, 1.698295227342757, 0.0]
        file = [None, 'OBC1_NonPeriodic', 'OBC2_NonPeriodic_Salt', None, 'GBn2_NoCutoff']
        for i in range(len(file)):
            forcefield = ForceField('amber96.xml', f'implicit/{solventType[i]}.xml')
            system = forcefield.createSystem(self.pdb2.topology, nonbondedMethod=nonbondedMethod[i], implicitSolventKappa=kappa[i])
            integrator = VerletIntegrator(0.001)
Peter Eastman's avatar
Peter Eastman committed
484
            context = Context(system, integrator, Platform.getPlatform("Reference"))
485
486
487
488
489
490
491
492
493
            context.setPositions(self.pdb2.positions)
            state1 = context.getState(getForces=True)
            if file[i] is not None:
                with open('systems/alanine-dipeptide-implicit-forces/'+file[i]+'.xml') as infile:
                    state2 = XmlSerializer.deserialize(infile.read())
                for f1, f2, in zip(state1.getForces().value_in_unit(kilojoules_per_mole/nanometer), state2.getForces().value_in_unit(kilojoules_per_mole/nanometer)):
                    diff = norm(f1-f2)
                    self.assertTrue(diff < 0.1 or diff/norm(f1) < 1e-4)

494
495
    def test_ProgrammaticForceField(self):
        """Test building a ForceField programmatically."""
496

497
498
        # Build the ForceField for TIP3P programmatically.
        ff = ForceField()
499
500
        ff.registerAtomType({'name':'tip3p-O', 'class':'OW', 'mass':15.99943*daltons, 'element':elem.oxygen})
        ff.registerAtomType({'name':'tip3p-H', 'class':'HW', 'mass':1.007947*daltons, 'element':elem.hydrogen})
501
502
503
504
505
506
507
508
509
510
511
512
513
        residue = ForceField._TemplateData('HOH')
        residue.atoms.append(ForceField._TemplateAtomData('O', 'tip3p-O', elem.oxygen))
        residue.atoms.append(ForceField._TemplateAtomData('H1', 'tip3p-H', elem.hydrogen))
        residue.atoms.append(ForceField._TemplateAtomData('H2', 'tip3p-H', elem.hydrogen))
        residue.addBond(0, 1)
        residue.addBond(0, 2)
        ff.registerResidueTemplate(residue)
        bonds = forcefield.HarmonicBondGenerator(ff)
        bonds.registerBond({'class1':'OW', 'class2':'HW', 'length':0.09572*nanometers, 'k':462750.4*kilojoules_per_mole/nanometer})
        ff.registerGenerator(bonds)
        angles = forcefield.HarmonicAngleGenerator(ff)
        angles.registerAngle({'class1':'HW', 'class2':'OW', 'class3':'HW', 'angle':1.82421813418*radians, 'k':836.8*kilojoules_per_mole/radian})
        ff.registerGenerator(angles)
514
        nonbonded = forcefield.NonbondedGenerator(ff, 0.833333, 0.5, True)
515
516
517
        nonbonded.registerAtom({'type':'tip3p-O', 'charge':-0.834, 'sigma':0.31507524065751241*nanometers, 'epsilon':0.635968*kilojoules_per_mole})
        nonbonded.registerAtom({'type':'tip3p-H', 'charge':0.417, 'sigma':1*nanometers, 'epsilon':0*kilojoules_per_mole})
        ff.registerGenerator(nonbonded)
518

519
520
521
        # Build a water box.
        modeller = Modeller(Topology(), [])
        modeller.addSolvent(ff, boxSize=Vec3(3, 3, 3)*nanometers)
522

523
524
525
526
527
        # Create a system using the programmatic force field as well as one from an XML file.
        system1 = ff.createSystem(modeller.topology)
        ff2 = ForceField('tip3p.xml')
        system2 = ff2.createSystem(modeller.topology)
        self.assertEqual(XmlSerializer.serialize(system1), XmlSerializer.serialize(system2))
528

529
530
531
532
533
534
535
536
537
538
    def test_PeriodicBoxVectors(self):
        """Test setting the periodic box vectors."""

        vectors = (Vec3(5, 0, 0), Vec3(-1.5, 4.5, 0), Vec3(0.4, 0.8, 7.5))*nanometers
        self.pdb1.topology.setPeriodicBoxVectors(vectors)
        self.assertEqual(Vec3(5, 4.5, 7.5)*nanometers, self.pdb1.topology.getUnitCellDimensions())
        system = self.forcefield1.createSystem(self.pdb1.topology)
        for i in range(3):
            self.assertEqual(vectors[i], self.pdb1.topology.getPeriodicBoxVectors()[i])
            self.assertEqual(vectors[i], system.getDefaultPeriodicBoxVectors()[i])
539

540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
    def test_duplicateAtomTypeAllowed(self):
        """Test that multiple registrations of the same atom type with identical definitions are allowed."""

        xml1 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test" element="H" mass="1.007947"/>
 </AtomTypes>
</ForceField>"""

        xml2 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test" element="H" mass="1.007947"/>
 </AtomTypes>
</ForceField>"""

        ff = ForceField(StringIO(xml1), StringIO(xml2))

        self.assertTrue("test-name" in ff._atomTypes)
        at = ff._atomTypes["test-name"]
        self.assertEqual(at.atomClass, "test")
        self.assertEqual(at.element, elem.hydrogen)
        self.assertEqual(at.mass, 1.007947)

    def test_duplicateAtomTypeAllowedNoElement(self):
        """Test that multiple registrations of the same atom type with identical definitions and without elements are allowed."""

        xml1 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test" mass="0.0"/>
 </AtomTypes>
</ForceField>"""

        xml2 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test" mass="0.0"/>
 </AtomTypes>
</ForceField>"""

        ff = ForceField(StringIO(xml1), StringIO(xml2))

        self.assertTrue("test-name" in ff._atomTypes)
        at = ff._atomTypes["test-name"]
        self.assertEqual(at.atomClass, "test")
        self.assertEqual(at.element, None)
        self.assertEqual(at.mass, 0.0)

    def test_duplicateAtomTypeForbiddenClass(self):
        """Test that multiple registrations of the same atom type with different classes are forbidden."""

        xml1 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test-1" element="H" mass="1.007947"/>
 </AtomTypes>
</ForceField>"""

        xml2 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test-2" element="H" mass="1.007947"/>
 </AtomTypes>
</ForceField>"""

        with self.assertRaises(ValueError):
            ff = ForceField(StringIO(xml1), StringIO(xml2))

    def test_duplicateAtomTypeForbiddenElement(self):
        """Test that multiple registrations of the same atom type with different elements are forbidden."""

        xml1 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test" element="H" mass="1.007947"/>
 </AtomTypes>
</ForceField>"""

        xml2 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test" element="C" mass="1.007947"/>
 </AtomTypes>
</ForceField>"""

        with self.assertRaises(ValueError):
            ff = ForceField(StringIO(xml1), StringIO(xml2))

    def test_duplicateAtomTypeForbiddenElementAdded(self):
        """Test that multiple registrations of the same atom type, the first without and the second with an element, are forbidden."""

        xml1 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test" mass="1.007947"/>
 </AtomTypes>
</ForceField>"""

        xml2 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test" element="H" mass="1.007947"/>
 </AtomTypes>
</ForceField>"""

        with self.assertRaises(ValueError):
            ff = ForceField(StringIO(xml1), StringIO(xml2))

    def test_duplicateAtomTypeForbiddenElementRemoved(self):
        """Test that multiple registrations of the same atom type, the first with and the second without an element, are forbidden."""

        xml1 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test" element="H" mass="1.007947"/>
 </AtomTypes>
</ForceField>"""

        xml2 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test" mass="1.007947"/>
 </AtomTypes>
</ForceField>"""

        with self.assertRaises(ValueError):
            ff = ForceField(StringIO(xml1), StringIO(xml2))

    def test_duplicateAtomTypeForbiddenMass(self):
        """Test that multiple registrations of the same atom type with different masses are forbidden."""

        xml1 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test" element="H" mass="1.007947"/>
 </AtomTypes>
</ForceField>"""

        xml2 = """
<ForceField>
 <AtomTypes>
  <Type name="test-name" class="test" element="H" mass="12.01078"/>
 </AtomTypes>
</ForceField>"""

        with self.assertRaises(ValueError):
            ff = ForceField(StringIO(xml1), StringIO(xml2))

690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
    def test_ResidueAttributes(self):
        """Test a ForceField that gets per-particle parameters from residue attributes."""

        xml = """
<ForceField>
 <AtomTypes>
  <Type name="tip3p-O" class="OW" element="O" mass="15.99943"/>
  <Type name="tip3p-H" class="HW" element="H" mass="1.007947"/>
 </AtomTypes>
 <Residues>
  <Residue name="HOH">
   <Atom name="O" type="tip3p-O" charge="-0.834"/>
   <Atom name="H1" type="tip3p-H" charge="0.417"/>
   <Atom name="H2" type="tip3p-H" charge="0.417"/>
   <Bond from="0" to="1"/>
   <Bond from="0" to="2"/>
  </Residue>
 </Residues>
 <NonbondedForce coulomb14scale="0.833333" lj14scale="0.5">
  <UseAttributeFromResidue name="charge"/>
  <Atom type="tip3p-O" sigma="0.315" epsilon="0.635"/>
  <Atom type="tip3p-H" sigma="1" epsilon="0"/>
 </NonbondedForce>
</ForceField>"""
        ff = ForceField(StringIO(xml))

        # Build a water box.
        modeller = Modeller(Topology(), [])
        modeller.addSolvent(ff, boxSize=Vec3(3, 3, 3)*nanometers)

        # Create a system and make sure all nonbonded parameters are correct.
        system = ff.createSystem(modeller.topology)
        nonbonded = [f for f in system.getForces() if isinstance(f, NonbondedForce)][0]
        atoms = list(modeller.topology.atoms())
        for i in range(len(atoms)):
            params = nonbonded.getParticleParameters(i)
            if atoms[i].element == elem.oxygen:
                self.assertEqual(params[0], -0.834*elementary_charge)
                self.assertEqual(params[1], 0.315*nanometers)
                self.assertEqual(params[2], 0.635*kilojoule_per_mole)
            else:
                self.assertEqual(params[0], 0.417*elementary_charge)
                self.assertEqual(params[1], 1.0*nanometers)
                self.assertEqual(params[2], 0.0*kilojoule_per_mole)
734

735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
    def test_residueMatcher(self):
        """Test using a custom template matcher to select templates."""
        xml = """
<ForceField>
 <AtomTypes>
  <Type name="tip3p-O" class="OW" element="O" mass="15.99943"/>
  <Type name="tip3p-H" class="HW" element="H" mass="1.007947"/>
 </AtomTypes>
 <Residues>
  <Residue name="HOH">
   <Atom name="O" type="tip3p-O" charge="-0.834"/>
   <Atom name="H1" type="tip3p-H" charge="0.417"/>
   <Atom name="H2" type="tip3p-H" charge="0.417"/>
   <Bond from="0" to="1"/>
   <Bond from="0" to="2"/>
  </Residue>
  <Residue name="HOH2">
   <Atom name="O" type="tip3p-O" charge="0.834"/>
   <Atom name="H1" type="tip3p-H" charge="-0.417"/>
   <Atom name="H2" type="tip3p-H" charge="-0.417"/>
   <Bond from="0" to="1"/>
   <Bond from="0" to="2"/>
  </Residue>
 </Residues>
 <NonbondedForce coulomb14scale="0.833333" lj14scale="0.5">
  <UseAttributeFromResidue name="charge"/>
  <Atom type="tip3p-O" sigma="0.315" epsilon="0.635"/>
  <Atom type="tip3p-H" sigma="1" epsilon="0"/>
 </NonbondedForce>
</ForceField>"""
        ff = ForceField(StringIO(xml))

        # Load a water box.
        prmtop = AmberPrmtopFile('systems/water-box-216.prmtop')
        top = prmtop.topology
        
        # Building a System should fail, because two templates match each residue.
        self.assertRaises(Exception, lambda: ff.createSystem(top))
        
        # Register a template matcher that selects a particular one.
Peter Eastman's avatar
Peter Eastman committed
775
        def matcher(ff, res, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles):
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
            return ff._templates['HOH2']
        ff.registerTemplateMatcher(matcher)
        
        # It should now succeed in building a System.
        system = ff.createSystem(top)
        
        # Make sure it used the correct parameters.
        nb = [f for f in system.getForces() if isinstance(f, NonbondedForce)][0]
        for atom in top.atoms():
            charge, sigma, epsilon = nb.getParticleParameters(atom.index)
            if atom.name == 'O':
                self.assertEqual(0.834*elementary_charge, charge)
            else:
                self.assertEqual(-0.417*elementary_charge, charge)

791
792
    def test_residueTemplateGenerator(self):
        """Test the ability to add residue template generators to parameterize unmatched residues."""
793
        def simpleTemplateGenerator(forcefield, residue):
794
795
796
797
798
799
800
            """\
            Simple residue template generator.
            This implementation uses the programmatic API to define residue templates.

            NOTE: We presume we have already loaded the force definitions into ForceField.
            """
            # Generate a unique prefix name for generating parameters.
801
802
            from uuid import uuid4
            template_name = uuid4()
803
            # Create residue template.
804
            from openmm.app.forcefield import _createResidueTemplate
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
805
            template = _createResidueTemplate(residue) # use helper function
806
            template.name = template_name # replace template name
807
            for (template_atom, residue_atom) in zip(template.atoms, residue.atoms()):
808
                template_atom.type = 'XXX' # replace atom type
809
            # Register the template.
810
            forcefield.registerResidueTemplate(template)
811
812
813
814
815
816
817

            # Signal that we have successfully parameterized the residue.
            return True

        # Define forcefield parameters used by simpleTemplateGenerator.
        # NOTE: This parameter definition file will currently only work for residues that either have
        # no external bonds or external bonds to other residues parameterized by the simpleTemplateGenerator.
818
        simple_ffxml_contents = """
819
<ForceField>
820
821
822
823
824
825
826
827
828
829
830
831
 <AtomTypes>
  <Type name="XXX" class="XXX" element="C" mass="12.0"/>
 </AtomTypes>
 <HarmonicBondForce>
  <Bond type1="XXX" type2="XXX" length="0.1409" k="392459.2"/>
 </HarmonicBondForce>
 <HarmonicAngleForce>
  <Angle type1="XXX" type2="XXX" type3="XXX" angle="2.09439510239" k="527.184"/>
 </HarmonicAngleForce>
 <NonbondedForce coulomb14scale="0.833333" lj14scale="0.5">
  <Atom type="XXX" charge="0.000" sigma="0.315" epsilon="0.635"/>
 </NonbondedForce>
832
833
834
</ForceField>"""

        #
835
        # Test where we generate parameters for only a ligand.
836
837
838
839
840
        #

        # Load the PDB file.
        pdb = PDBFile(os.path.join('systems', 'T4-lysozyme-L99A-p-xylene-implicit.pdb'))
        # Create a ForceField object.
841
        forcefield = ForceField('amber99sb.xml', 'tip3p.xml', StringIO(simple_ffxml_contents))
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
        # Add the residue template generator.
        forcefield.registerTemplateGenerator(simpleTemplateGenerator)
        # Parameterize system.
        system = forcefield.createSystem(pdb.topology, nonbondedMethod=NoCutoff)
        # TODO: Test energies are finite?

        #
        # Test for a few systems where we generate all parameters.
        #

        tests = [
            { 'pdb_filename' : 'alanine-dipeptide-implicit.pdb', 'nonbondedMethod' : NoCutoff },
            { 'pdb_filename' : 'lysozyme-implicit.pdb', 'nonbondedMethod' : NoCutoff },
            { 'pdb_filename' : 'alanine-dipeptide-explicit.pdb', 'nonbondedMethod' : CutoffPeriodic },
            ]

        # Test all systems with separate ForceField objects.
        for test in tests:
            # Load the PDB file.
            pdb = PDBFile(os.path.join('systems', test['pdb_filename']))
            # Create a ForceField object.
863
            forcefield = ForceField(StringIO(simple_ffxml_contents))
864
865
866
867
868
869
870
871
            # Add the residue template generator.
            forcefield.registerTemplateGenerator(simpleTemplateGenerator)
            # Parameterize system.
            system = forcefield.createSystem(pdb.topology, nonbondedMethod=test['nonbondedMethod'])
            # TODO: Test energies are finite?

        # Now test all systems with a single ForceField object.
        # Create a ForceField object.
872
        forcefield = ForceField(StringIO(simple_ffxml_contents))
873
874
875
876
877
878
879
880
881
        # Add the residue template generator.
        forcefield.registerTemplateGenerator(simpleTemplateGenerator)
        for test in tests:
            # Load the PDB file.
            pdb = PDBFile(os.path.join('systems', test['pdb_filename']))
            # Parameterize system.
            system = forcefield.createSystem(pdb.topology, nonbondedMethod=test['nonbondedMethod'])
            # TODO: Test energies are finite?

882
883
884
885
886
887
888
889
890
891
892
893
    def test_getUnmatchedResidues(self):
        """Test retrieval of list of residues for which no templates are available."""

        # Load the PDB file.
        pdb = PDBFile(os.path.join('systems', 'T4-lysozyme-L99A-p-xylene-implicit.pdb'))
        # Create a ForceField object.
        forcefield = ForceField('amber99sb.xml', 'tip3p.xml')
        # Get list of unmatched residues.
        unmatched_residues = forcefield.getUnmatchedResidues(pdb.topology)
        # Check results.
        self.assertEqual(len(unmatched_residues), 1)
        self.assertEqual(unmatched_residues[0].name, 'TMP')
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
894
        self.assertEqual(unmatched_residues[0].id, '163')
895
896
897
898
899
900
901
902
903
904

        # Load the PDB file.
        pdb = PDBFile(os.path.join('systems', 'ala_ala_ala.pdb'))
        # Create a ForceField object.
        forcefield = ForceField('tip3p.xml')
        # Get list of unmatched residues.
        unmatched_residues = forcefield.getUnmatchedResidues(pdb.topology)
        # Check results.
        self.assertEqual(len(unmatched_residues), 3)
        self.assertEqual(unmatched_residues[0].name, 'ALA')
jchodera's avatar
jchodera committed
905
        self.assertEqual(unmatched_residues[0].chain.id, 'X')
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
906
        self.assertEqual(unmatched_residues[0].id, '1')
907

peastman's avatar
peastman committed
908
    def test_generateTemplatesForUnmatchedResidues(self):
909
        """Test generation of blank forcefield residue templates for unmatched residues."""
910
911
912
913
914
915
916
917
918
919
        #
        # Test where we generate parameters for only a ligand.
        #

        # Load the PDB file.
        pdb = PDBFile(os.path.join('systems', 'nacl-water.pdb'))
        # Create a ForceField object.
        forcefield = ForceField('tip3p.xml')
        # Get list of unmatched residues.
        unmatched_residues = forcefield.getUnmatchedResidues(pdb.topology)
920
        [templates, residues] = forcefield.generateTemplatesForUnmatchedResidues(pdb.topology)
921
        # Check results.
922
        self.assertEqual(len(unmatched_residues), 24)
923
        self.assertEqual(len(residues), 2)
924
        self.assertEqual(len(templates), 2)
925
        unique_names = set([ residue.name for residue in residues ])
926
        self.assertTrue('HOH' not in unique_names)
927
928
        self.assertTrue('NA' in unique_names)
        self.assertTrue('CL' in unique_names)
929
930
931
932
        template_names = set([ template.name for template in templates ])
        self.assertTrue('HOH' not in template_names)
        self.assertTrue('NA' in template_names)
        self.assertTrue('CL' in template_names)
933

934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
        # Define forcefield parameters using returned templates.
        # NOTE: This parameter definition file will currently only work for residues that either have
        # no external bonds or external bonds to other residues parameterized by the simpleTemplateGenerator.
        simple_ffxml_contents = """
<ForceField>
 <AtomTypes>
  <Type name="XXX" class="XXX" element="C" mass="12.0"/>
 </AtomTypes>
 <HarmonicBondForce>
  <Bond type1="XXX" type2="XXX" length="0.1409" k="392459.2"/>
 </HarmonicBondForce>
 <HarmonicAngleForce>
  <Angle type1="XXX" type2="XXX" type3="XXX" angle="2.09439510239" k="527.184"/>
 </HarmonicAngleForce>
 <NonbondedForce coulomb14scale="0.833333" lj14scale="0.5">
  <Atom type="XXX" charge="0.000" sigma="0.315" epsilon="0.635"/>
 </NonbondedForce>
</ForceField>"""

        #
954
        # Test the pre-geenration of missing residue template for a ligand.
955
956
957
958
959
960
961
        #

        # Load the PDB file.
        pdb = PDBFile(os.path.join('systems', 'T4-lysozyme-L99A-p-xylene-implicit.pdb'))
        # Create a ForceField object.
        forcefield = ForceField('amber99sb.xml', 'tip3p.xml', StringIO(simple_ffxml_contents))
        # Get list of unique unmatched residues.
962
        [templates, residues] = forcefield.generateTemplatesForUnmatchedResidues(pdb.topology)
963
964
965
        # Make sure template atom parameter dictionaries are distinct objects.
        parameters = [atom.parameters for template in templates for atom in template.atoms]
        self.assertEqual(len(set(map(id, parameters))), len(parameters))
966
967
968
        # Add residue templates to forcefield.
        for template in templates:
            # Replace atom types.
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
969
970
            for atom in template.atoms:
                atom.type = 'XXX'
971
972
973
974
975
976
            # Register the template.
            forcefield.registerResidueTemplate(template)
        # Parameterize system.
        system = forcefield.createSystem(pdb.topology, nonbondedMethod=NoCutoff)
        # TODO: Test energies are finite?

977
978
979
980
981
982
983
984
985
986
    def test_getMatchingTemplates(self):
        """Test retrieval of list of templates that match residues in a topology."""

        # Load the PDB file.
        pdb = PDBFile(os.path.join('systems', 'ala_ala_ala.pdb'))
        # Create a ForceField object.
        forcefield = ForceField('amber99sb.xml')
        # Get list of matching residue templates.
        templates = forcefield.getMatchingTemplates(pdb.topology)
        # Check results.
jchodera's avatar
jchodera committed
987
        residues = [ residue for residue in pdb.topology.residues() ]
988
        self.assertEqual(len(templates), len(residues))
jchodera's avatar
jchodera committed
989
990
991
        self.assertEqual(templates[0].name, 'NALA')
        self.assertEqual(templates[1].name, 'ALA')
        self.assertEqual(templates[2].name, 'CALA')
992

993
994
995
996
    def test_matchErrorMessages(self):
        """Test match error detection and diagnostics"""

        # Load a force field to test with and prepare some lines with which to build topologies from PDB files.
997
        forcefield = ForceField('amber14-all.xml', 'amber14/opc.xml')
998
        pdbLines = [
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
            'ATOM      0 CH3  ACE A   1       0       0       0                           C',
            'ATOM      1 HH31 ACE A   1       0       0       0                           H',
            'ATOM      2 HH32 ACE A   1       0       0       0                           H',
            'ATOM      3 HH33 ACE A   1       0       0       0                           H',
            'ATOM      4 C    ACE A   1       0       0       0                           C',
            'ATOM      5 O    ACE A   1       0       0       0                           O',
            'ATOM      6 N    GLY A   2       0       0       0                           N',
            'ATOM      7 H    GLY A   2       0       0       0                           H',
            'ATOM      8 CA   GLY A   2       0       0       0                           C',
            'ATOM      9 HA2  GLY A   2       0       0       0                           H',
            'ATOM     10 HA3  GLY A   2       0       0       0                           H',
            'ATOM     11 C    GLY A   2       0       0       0                           C',
            'ATOM     12 O    GLY A   2       0       0       0                           O',
            'ATOM     13 N    NME A   3       0       0       0                           N',
            'ATOM     14 H    NME A   3       0       0       0                           H',
            'ATOM     15 CH3  NME A   3       0       0       0                           C',
            'ATOM     16 HH31 NME A   3       0       0       0                           H',
            'ATOM     17 HH32 NME A   3       0       0       0                           H',
            'ATOM     18 HH33 NME A   3       0       0       0                           H',
1018
1019
1020
1021
1022
1023
1024
1025
        ]

        def makeSystem(lines):
            return forcefield.createSystem(PDBFile(StringIO("\n".join(lines))).topology)

        # This should succeed and not produce any match errors.
        self.assertEqual(makeSystem(pdbLines).getNumParticles(), 19)

1026
1027
1028
1029
1030
1031
1032
1033
        # Add an He atom and B atoms atom to GLY.
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The residue contains He atoms and B atoms, which are not supported by any template in the force field'):
            makeSystem(pdbLines[:9] + [
                'ATOM     19 X1   GLY A   2       0       0       0                          He',
                'ATOM     20 X2   GLY A   2       0       0       0                           B',
                'ATOM     21 X3   GLY A   2       0       0       0                           B',
            ] + pdbLines[9:])

1034
        # Delete CA atom from GLY.
1035
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The set of atoms is similar to GLY, but is missing 1 C atom'):
1036
1037
            makeSystem(pdbLines[:8] + pdbLines[9:])

1038
1039
        # Add an F atom to GLY.
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The set of atoms is similar to GLY, but has 1 F atom too many'):
1040
            makeSystem(pdbLines[:9] + [
1041
                'ATOM     19 X1   GLY A   2       0       0       0                           F',
1042
1043
            ] + pdbLines[9:])

1044
1045
        # Delete CA atom from GLY and add an F atom.
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The set of atoms is similar to GLY, but is missing 1 C atom and has 1 F atom too many'):
1046
            makeSystem(pdbLines[:8] + [
1047
                'ATOM     19 X1   GLY A   2       0       0       0                           F',
1048
1049
            ] + pdbLines[9:])

1050
1051
        # Add 1 F atom, 2 Cl atoms, and 1 Br atom to GLY.
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The set of atoms is similar to GLY, but has 1 F atom, 2 Cl atoms, and 1 Br atom too many'):
1052
            makeSystem(pdbLines[:9] + [
1053
1054
1055
1056
                'ATOM     19 X1   GLY A   2       0       0       0                           F',
                'ATOM     20 X2   GLY A   2       0       0       0                          Cl',
                'ATOM     21 X3   GLY A   2       0       0       0                          Cl',
                'ATOM     22 X4   GLY A   2       0       0       0                          Br',
1057
1058
1059
            ] + pdbLines[9:])

        # Add a virtual site to GLY.
1060
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The set of heavy atoms matches GLY, but the residue has 1 extra site too many'):
1061
            makeSystem(pdbLines[:9] + [
1062
                'ATOM     19 X1   GLY A   2       0       0       0                          EP',
1063
1064
1065
            ] + pdbLines[9:])

        # Delete HA3 atom from GLY.
1066
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The set of heavy atoms matches GLY, but the residue is missing 1 H atom.*You may be able to add it with.*addHydrogens'):
1067
1068
            makeSystem(pdbLines[:10] + pdbLines[11:])

1069
1070
1071
1072
        # Delete HA2 and HA3 atoms from GLY.
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The set of heavy atoms matches GLY, but the residue is missing 2 H atoms.*You may be able to add them with.*addHydrogens'):
            makeSystem(pdbLines[:9] + pdbLines[11:])

1073
        # Delete HA3 atom from GLY and add a virtual site.
1074
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The set of heavy atoms matches GLY, but the residue is missing 1 H atom and has 1 extra site too many'):
1075
            makeSystem(pdbLines[:10] + [
1076
                'ATOM     19 X1   GLY A   2       0       0       0                          EP',
1077
1078
1079
            ] + pdbLines[11:])

        # Rename HA3 atom to remove the CA-HA3 bond.
1080
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The set of atoms matches GLY, but the residue is missing 1 H-C bond'):
1081
            makeSystem(pdbLines[:10] + [
1082
                'ATOM     10 X1   GLY A   2       0       0       0                           H',
1083
1084
1085
            ] + pdbLines[11:])

        # Add an extra N-O bond.
1086
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The set of atoms matches GLY, but the residue has 1 N-O bond too many'):
1087
            makeSystem(pdbLines + [
1088
                'CONECT    6   12'
1089
1090
1091
            ])

        # Remove an external bond to NME by renaming its N atom.
1092
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The atoms and bonds in the residue match GLY, but the set of externally bonded atoms is missing 1 C atom'):
1093
            makeSystem(pdbLines[:13] + [
1094
                'ATOM     13 X1   NME A   3       0       0       0                           N',
1095
1096
1097
            ] + pdbLines[14:])

        # Add an extra external bond to NME.
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The atoms and bonds in the residue match GLY, but the set of externally bonded atoms has 1 O atom too many'):
            makeSystem(pdbLines + [
                'CONECT   12   15'
            ])

        # Delete ACE so that a capping group is missing from GLY.
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The atoms and bonds in the residue match GLY, but the set of externally bonded atoms is missing 1 N atom.*Is the chain missing a terminal capping group?'):
            makeSystem(pdbLines[6:])

        # Keep the atom/bond element fingerprint the same but change the connectivity.
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*GLY.*The atoms and bonds in the residue match GLY, but the connectivity is different'):
            # Rename O to break the C=O bond, but then reattach the O to the CA.
            makeSystem(pdbLines[:12] + [
                'ATOM     12 X1   GLY A   2       0       0       0                           O',
            ] + pdbLines[13:] + [
                'CONECT    8   12'
            ])

        # Make water with incorrect atom names so bonds will be missing.
        pdbLines = [
            'ATOM      0 X1   HOH A   1       0       0       0                           O',
            'ATOM      1 X2   HOH A   1       0       0       0                           H',
            'ATOM      2 X3   HOH A   1       0       0       0                           H',
        ]

        # Check for a special message when all bonds are missing.
        forcefield = ForceField('opc3.xml')
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*HOH.*The set of atoms matches HOH, but the residue has no bonds between its atoms'):
            makeSystem(pdbLines)

        # Add a site to a residue with a force field that doesn't support sites.
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*HOH.*The residue contains extra sites, which are not supported by any template in the force field'):
1130
            makeSystem(pdbLines + [
1131
                'ATOM      3 X4   HOH A   1       0       0       0                          EP',
1132
1133
            ])

1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
        # Load a force field so that 1 site will be missing.
        forcefield = ForceField('opc.xml')
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*HOH.*The set of heavy atoms matches HOH, but the residue is missing 1 extra site.*You may be able to add it with.*addExtraParticles'):
            makeSystem(pdbLines)

        # Load a force field so that 2 sites will be missing.
        forcefield = ForceField('tip5p.xml')
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*HOH.*The set of heavy atoms matches HOH, but the residue is missing 2 extra sites.*You may be able to add them with.*addExtraParticles'):
            makeSystem(pdbLines)

        # Use an empty force field so that there are no templates.
        forcefield = ForceField()
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*HOH.*The force field contains no residue templates'):
            makeSystem(pdbLines)

1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
        # Make water with an extra site and an (invalid) bond to it.
        pdbLines = [
            'ATOM      0 O    HOH A   1       0       0       0                           O',
            'ATOM      1 H1   HOH A   1       0       0       0                           H',
            'ATOM      2 H2   HOH A   1       0       0       0                           H',
            'ATOM      3 M    HOH A   1       0       0       0                          EP',
            'CONECT    0    3'
        ]
        forcefield = ForceField('opc.xml')
        with self.assertRaisesRegex(ValueError, 'No template found for residue.*HOH.*The set of atoms matches HOH, but the residue has 1 extra site-O bond too many'):
            makeSystem(pdbLines)

1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
    def test_Wildcard(self):
        """Test that PeriodicTorsionForces using wildcard ('') for atom types / classes in the ffxml are correctly registered"""

        # Use wildcards in types
        xml = """
<ForceField>
 <AtomTypes>
  <Type name="C" class="C" element="C" mass="12.010000"/>
  <Type name="O" class="O" element="O" mass="16.000000"/>
 </AtomTypes>
 <PeriodicTorsionForce>
  <Proper type1="" type2="C" type3="C" type4="" periodicity1="2" phase1="3.141593" k1="15.167000"/>
  <Improper type1="C" type2="" type3="" type4="O" periodicity1="2" phase1="3.141593" k1="43.932000"/>
 </PeriodicTorsionForce>
</ForceField>"""

        ff = ForceField(StringIO(xml))

        self.assertEqual(len(ff._forces[0].proper), 1)
        self.assertEqual(len(ff._forces[0].improper), 1)

       # Use wildcards in classes
        xml = """
<ForceField>
 <AtomTypes>
  <Type name="C" class="C" element="C" mass="12.010000"/>
  <Type name="O" class="O" element="O" mass="16.000000"/>
 </AtomTypes>
 <PeriodicTorsionForce>
  <Proper class1="" class2="C" class3="C" class4="" periodicity1="2" phase1="3.141593" k1="15.167000"/>
  <Improper class1="C" class2="" class3="" class4="O" periodicity1="2" phase1="3.141593" k1="43.932000"/>
 </PeriodicTorsionForce>
</ForceField>"""

        ff = ForceField(StringIO(xml))

        self.assertEqual(len(ff._forces[0].proper), 1)
        self.assertEqual(len(ff._forces[0].improper), 1)

    def test_ScalingFactorCombining(self):
        """ Tests that FFs can be combined if their scaling factors are very close """
        forcefield = ForceField('amber99sb.xml', os.path.join('systems', 'test_amber_ff.xml'))
        # This would raise an exception if it didn't work

    def test_MultipleFilesandForceTags(self):
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1206
1207
1208
1209
        """Test that the order of listing of multiple ffxmls does not matter.
           Tests that one generator per force type is created and that the ffxml
           defining atom types does not have to be listed first"""

1210
        ffxml = """<ForceField>
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
 <Residues>
  <Residue name="ACE-Test">
   <Atom name="HH31" type="710"/>
   <Atom name="CH3" type="711"/>
   <Atom name="HH32" type="710"/>
   <Atom name="HH33" type="710"/>
   <Atom name="C" type="712"/>
   <Atom name="O" type="713"/>
   <Bond from="0" to="1"/>
   <Bond from="1" to="2"/>
   <Bond from="1" to="3"/>
   <Bond from="1" to="4"/>
   <Bond from="4" to="5"/>
   <ExternalBond from="4"/>
  </Residue>
 </Residues>
1227
 <PeriodicTorsionForce>
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1228
1229
  <Proper class1="C" class2="C" class3="C" class4="C" periodicity1="2" phase1="3.14159265359" k1="10.46"/>
  <Improper class1="C" class2="C" class3="C" class4="C" periodicity1="2" phase1="3.14159265359" k1="43.932"/>
1230
 </PeriodicTorsionForce>
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1231
</ForceField>"""
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241

        ff1 = ForceField(StringIO(ffxml), 'amber99sbildn.xml')
        ff2 = ForceField('amber99sbildn.xml', StringIO(ffxml))

        self.assertEqual(len(ff1._forces), 4)
        self.assertEqual(len(ff2._forces), 4)

        pertorsion1 = ff1._forces[0]
        pertorsion2 = ff2._forces[2]

Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1242
1243
1244
1245
        self.assertEqual(len(pertorsion1.proper), 110)
        self.assertEqual(len(pertorsion1.improper), 42)
        self.assertEqual(len(pertorsion2.proper), 110)
        self.assertEqual(len(pertorsion2.improper), 42)
1246

Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
    def test_ResidueTemplateUserChoice(self):
        """Test createSystem does not allow multiple matching templates, unless
           user has specified which template to use via residueTemplates arg"""
        ffxml = """<ForceField>
 <AtomTypes>
  <Type name="Fe2+" class="Fe2+" element="Fe" mass="55.85"/>
  <Type name="Fe3+" class="Fe3+" element="Fe" mass="55.85"/>
 </AtomTypes>
 <Residues>
  <Residue name="FE2">
   <Atom name="FE2" type="Fe2+" charge="2.0"/>
  </Residue>
  <Residue name="FE">
   <Atom name="FE" type="Fe3+" charge="3.0"/>
  </Residue>
 </Residues>
 <NonbondedForce coulomb14scale="0.833333333333" lj14scale="0.5">
  <UseAttributeFromResidue name="charge"/>
  <Atom type="Fe2+" sigma="0.227535532613" epsilon="0.0150312292"/>
  <Atom type="Fe3+" sigma="0.192790482606" epsilon="0.00046095128"/>
 </NonbondedForce>
</ForceField>"""

        pdb_string = "ATOM      1 FE    FE A   1      20.956  27.448 -29.067  1.00  0.00          Fe"
        ff = ForceField(StringIO(ffxml))
        pdb = PDBFile(StringIO(pdb_string))

        self.assertRaises(Exception, lambda: ff.createSystem(pdb.topology))
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1275
1276
1277
1278
1279
1280
        sys = ff.createSystem(pdb.topology, residueTemplates={list(pdb.topology.residues())[0] : 'FE2'})
        # confirm charge
        self.assertEqual(sys.getForce(0).getParticleParameters(0)[0]._value, 2.0)
        sys = ff.createSystem(pdb.topology, residueTemplates={list(pdb.topology.residues())[0] : 'FE'})
        # confirm charge
        self.assertEqual(sys.getForce(0).getParticleParameters(0)[0]._value, 3.0)
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1281

1282
1283
    def test_ResidueOverriding(self):
        """Test residue overriding via override tag in the XML"""
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319

        ffxml1 = """<ForceField>
 <AtomTypes>
  <Type name="Fe2+_tip3p_HFE" class="Fe2+_tip3p_HFE" element="Fe" mass="55.85"/>
 </AtomTypes>
 <Residues>
  <Residue name="FE2">
   <Atom name="FE2" type="Fe2+_tip3p_HFE" charge="2.0"/>
  </Residue>
 </Residues>
 <NonbondedForce coulomb14scale="0.833333333333" lj14scale="0.5">
  <UseAttributeFromResidue name="charge"/>
  <Atom type="Fe2+_tip3p_HFE" sigma="0.227535532613" epsilon="0.0150312292"/>
 </NonbondedForce>
</ForceField>"""

        ffxml2 = """<ForceField>
 <AtomTypes>
  <Type name="Fe2+_tip3p_standard" class="Fe2+_tip3p_standard" element="Fe" mass="55.85"/>
 </AtomTypes>
 <Residues>
  <Residue name="FE2">
   <Atom name="FE2" type="Fe2+_tip3p_standard" charge="2.0"/>
  </Residue>
 </Residues>
 <NonbondedForce coulomb14scale="0.833333333333" lj14scale="0.5">
  <UseAttributeFromResidue name="charge"/>
  <Atom type="Fe2+_tip3p_standard" sigma="0.241077193129" epsilon="0.03940482832"/>
 </NonbondedForce>
</ForceField>"""

        ffxml3 = """<ForceField>
 <AtomTypes>
  <Type name="Fe2+_tip3p_standard" class="Fe2+_tip3p_standard" element="Fe" mass="55.85"/>
 </AtomTypes>
 <Residues>
1320
  <Residue name="FE2" override="1">
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
   <Atom name="FE2" type="Fe2+_tip3p_standard" charge="2.0"/>
  </Residue>
 </Residues>
 <NonbondedForce coulomb14scale="0.833333333333" lj14scale="0.5">
  <UseAttributeFromResidue name="charge"/>
  <Atom type="Fe2+_tip3p_standard" sigma="0.241077193129" epsilon="0.03940482832"/>
 </NonbondedForce>
</ForceField>"""

        pdb_string = "ATOM      1 FE    FE A   1      20.956  27.448 -29.067  1.00  0.00          Fe"
        pdb = PDBFile(StringIO(pdb_string))

        self.assertRaises(Exception, lambda: ForceField(StringIO(ffxml1), StringIO(ffxml2)))
        ff = ForceField(StringIO(ffxml1), StringIO(ffxml3))
1335
        self.assertEqual(ff._templates['FE2'].atoms[0].type, 'Fe2+_tip3p_standard')
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1336
1337
        ff.createSystem(pdb.topology)

1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
    def test_CMAPTorsionGeneratorMapAssignment(self):
        """Tests assignment of the correct maps when multiple CMAPTorsionGenerators are present"""

        ffxml_1 = """
<ForceField>
    <AtomTypes>
        <Type name="A" class="A" element="C" mass="12" />
        <Type name="B" class="B" element="N" mass="14" />
    </AtomTypes>
    <Residues>
        <Residue name="X">
            <Atom name="X1" type="A" />
            <Atom name="X2" type="A" />
            <Atom name="X3" type="A" />
            <Atom name="X4" type="A" />
            <Atom name="X5" type="B" />
            <Bond atomName1="X1" atomName2="X2" />
            <Bond atomName1="X2" atomName2="X3" />
            <Bond atomName1="X3" atomName2="X4" />
            <Bond atomName1="X4" atomName2="X5" />
        </Residue>
        <Residue name="Y">
            <Atom name="Y1" type="A" />
            <Atom name="Y2" type="A" />
            <Atom name="Y3" type="A" />
            <Atom name="Y4" type="B" />
            <Atom name="Y5" type="B" />
            <Bond atomName1="Y1" atomName2="Y2" />
            <Bond atomName1="Y2" atomName2="Y3" />
            <Bond atomName1="Y3" atomName2="Y4" />
            <Bond atomName1="Y4" atomName2="Y5" />
        </Residue>
    </Residues>
    <CMAPTorsionForce>
        <Map>10 11 12 13</Map>
        <Torsion map="0" class1="A" class2="A" class3="A" class4="A" class5="B" />
    </CMAPTorsionForce>
</ForceField>
"""

        ffxml_2 = """
<ForceField>
    <CMAPTorsionForce>
        <Map>14 15 16 17</Map>
        <Torsion map="0" class1="A" class2="A" class3="A" class4="B" class5="B" />
    </CMAPTorsionForce>
</ForceField>
"""

        ff = ForceField(StringIO(ffxml_1), StringIO(ffxml_2))

        topology = Topology()

        x = topology.addResidue("X", topology.addChain())
        x1 = topology.addAtom("X1", elem.carbon, x)
        x2 = topology.addAtom("X2", elem.carbon, x)
        x3 = topology.addAtom("X3", elem.carbon, x)
        x4 = topology.addAtom("X4", elem.carbon, x)
        x5 = topology.addAtom("X5", elem.nitrogen, x)
        topology.addBond(x1, x2)
        topology.addBond(x2, x3)
        topology.addBond(x3, x4)
        topology.addBond(x4, x5)

        y = topology.addResidue("Y", topology.addChain())
        y1 = topology.addAtom("Y1", elem.carbon, y)
        y2 = topology.addAtom("Y2", elem.carbon, y)
        y3 = topology.addAtom("Y3", elem.carbon, y)
        y4 = topology.addAtom("Y4", elem.nitrogen, y)
        y5 = topology.addAtom("Y5", elem.nitrogen, y)
        topology.addBond(y1, y2)
        topology.addBond(y2, y3)
        topology.addBond(y3, y4)
        topology.addBond(y4, y5)

        system = ff.createSystem(topology)
        cmap, = (force for force in system.getForces() if isinstance(force, openmm.CMAPTorsionForce))

        torsionCount = cmap.getNumTorsions()
        assert torsionCount == 2

        for torsionIndex in range(torsionCount):
            mapIndex, *atomIndices = cmap.getTorsionParameters(torsionIndex)
            mapSize, energy = cmap.getMapParameters(mapIndex)

            if atomIndices == [0, 1, 2, 3, 1, 2, 3, 4]:
                expectedEnergy = (10.0, 11.0, 12.0, 13.0) * kilojoule_per_mole
            elif atomIndices == [5, 6, 7, 8, 6, 7, 8, 9]:
                expectedEnergy = (14.0, 15.0, 16.0, 17.0) * kilojoule_per_mole
            else:
                raise ValueError("unexpected torsion")

            assert energy == expectedEnergy

1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
    def test_LennardJonesGenerator(self):
        """ Test the LennardJones generator"""
        warnings.filterwarnings('ignore', category=CharmmPSFWarning)
        psf = CharmmPsfFile('systems/ions.psf')
        pdb = PDBFile('systems/ions.pdb')
        params = CharmmParameterSet('systems/toppar_water_ions.str'
                                    )

        # Box dimensions (found from bounding box)
        psf.setBox(12.009*angstroms,   12.338*angstroms,   11.510*angstroms)

        # Turn off charges so we only test the Lennard-Jones energies
        for a in psf.atom_list:
            a.charge = 0.0

        # Now compute the full energy
Peter Eastman's avatar
Peter Eastman committed
1448
        plat = Platform.getPlatform('Reference')
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
        system = psf.createSystem(params, nonbondedMethod=PME,
                                  nonbondedCutoff=5*angstroms)

        con = Context(system, VerletIntegrator(2*femtoseconds), plat)
        con.setPositions(pdb.positions)

        # Now set up system from ffxml.
        xml = """
<ForceField>
 <AtomTypes>
  <Type name="SOD" class="SOD" element="Na" mass="22.98977"/>
  <Type name="CLA" class="CLA" element="Cl" mass="35.45"/>
 </AtomTypes>
 <Residues>
  <Residue name="CLA">
   <Atom name="CLA" type="CLA"/>
  </Residue>
  <Residue name="SOD">
   <Atom name="SOD" type="SOD"/>
  </Residue>
 </Residues>
1470
 <LennardJonesForce lj14scale="1.0" useDispersionCorrection="False">
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
  <Atom type="CLA" sigma="0.404468018036" epsilon="0.6276"/>
  <Atom type="SOD" sigma="0.251367073323" epsilon="0.1962296"/>
  <NBFixPair type1="CLA" type2="SOD" sigma="0.33239431" epsilon="0.350933"/>
 </LennardJonesForce>
</ForceField> """
        ff = ForceField(StringIO(xml))
        system2 = ff.createSystem(pdb.topology, nonbondedMethod=PME,
                                  nonbondedCutoff=5*angstroms)
        con2 = Context(system2, VerletIntegrator(2*femtoseconds), plat)
        con2.setPositions(pdb.positions)

        state = con.getState(getEnergy=True, enforcePeriodicBox=True)
        ene = state.getPotentialEnergy().value_in_unit(kilocalories_per_mole)
        state2 = con2.getState(getEnergy=True, enforcePeriodicBox=True)
        ene2 = state2.getPotentialEnergy().value_in_unit(kilocalories_per_mole)
        self.assertAlmostEqual(ene, ene2)

1488
1489
1490
1491
        # LJPME should be forbidden with LennardJonesForce since it makes a CustomNonbondedForce to handle NBFix
        with self.assertRaisesRegex(ValueError, 'LJPME is not supported'):
            ff.createSystem(pdb.topology, nonbondedMethod=LJPME)

1492
1493
    def test_NBFix(self):
        """Test using LennardJonesGenerator to implement NBFix terms."""
1494
        # Create a chain of seven atoms.
1495

1496
1497
1498
        top = Topology()
        chain = top.addChain()
        res = top.addResidue('RES', chain)
1499
1500
1501
1502
1503
1504
1505
        top.addAtom('A', elem.carbon, res)
        top.addAtom('B', elem.nitrogen, res)
        top.addAtom('C', elem.nitrogen, res)
        top.addAtom('D', elem.oxygen, res)
        top.addAtom('E', elem.carbon, res)
        top.addAtom('F', elem.nitrogen, res)
        top.addAtom('G', elem.oxygen, res)
1506
1507
1508
1509
1510
        atoms = list(top.atoms())
        top.addBond(atoms[0], atoms[1])
        top.addBond(atoms[1], atoms[2])
        top.addBond(atoms[2], atoms[3])
        top.addBond(atoms[3], atoms[4])
1511
1512
        top.addBond(atoms[4], atoms[5])
        top.addBond(atoms[5], atoms[6])
1513

1514
        # Create the force field and system.
1515

1516
1517
1518
        xml = """
<ForceField>
 <AtomTypes>
1519
1520
1521
  <Type name="A" class="A" element="C" mass="1"/>
  <Type name="B" class="B" element="N" mass="1"/>
  <Type name="C" class="C" element="O" mass="1"/>
1522
1523
1524
1525
1526
 </AtomTypes>
 <Residues>
  <Residue name="RES">
   <Atom name="A" type="A"/>
   <Atom name="B" type="B"/>
1527
1528
1529
1530
1531
   <Atom name="C" type="B"/>
   <Atom name="D" type="C"/>
   <Atom name="E" type="A"/>
   <Atom name="F" type="B"/>
   <Atom name="G" type="C"/>
1532
1533
1534
1535
   <Bond atomName1="A" atomName2="B"/>
   <Bond atomName1="B" atomName2="C"/>
   <Bond atomName1="C" atomName2="D"/>
   <Bond atomName1="D" atomName2="E"/>
1536
1537
   <Bond atomName1="E" atomName2="F"/>
   <Bond atomName1="F" atomName2="G"/>
1538
1539
1540
  </Residue>
 </Residues>
 <LennardJonesForce lj14scale="0.3">
1541
1542
1543
1544
1545
1546
  <Atom type="A" sigma="2.1" epsilon="1.1"/>
  <Atom type="B" sigma="2.2" epsilon="1.2"/>
  <Atom type="C" sigma="2.4" epsilon="1.4"/>
  <NBFixPair type1="C" type2="C" sigma="3.1" epsilon="4.1"/>
  <NBFixPair type1="A" type2="A" sigma="3.2" epsilon="4.2"/>
  <NBFixPair type1="B" type2="A" sigma="3.4" epsilon="4.4"/>
1547
1548
1549
1550
 </LennardJonesForce>
</ForceField> """
        ff = ForceField(StringIO(xml))
        system = ff.createSystem(top)
1551

1552
        # Check that it produces the correct energy.
1553
1554
1555
1556
1557
        # The chain is A-B-B-C-A-B-C, and the pairs that are evaluated are:
        # A0-C3, A0-A4, A0-B5, A0-C6,
        # B1-A4, B1-B5, B1-C6,
        # B2-B5, B2-C6,
        # C3-C6.
1558

1559
1560
        integrator = VerletIntegrator(0.001)
        context = Context(system, integrator, Platform.getPlatform(0))
1561
        positions = [Vec3(i, 0, 0) for i in range(7)]*nanometers
1562
1563
1564
        context.setPositions(positions)
        def ljEnergy(sigma, epsilon, r):
            return 4*epsilon*((sigma/r)**12-(sigma/r)**6)
1565
1566
1567
1568
        expected = 0.3*ljEnergy(2.25, math.sqrt(1.54), 3) + ljEnergy(3.2, 4.2, 4) + ljEnergy(3.4, 4.4, 5) + ljEnergy(2.25, math.sqrt(1.54), 6) \
                 + 0.3*ljEnergy(3.4, 4.4, 3) + ljEnergy(2.2, 1.2, 4) + ljEnergy(2.3, math.sqrt(1.68), 5) \
                 + 0.3*ljEnergy(2.2, 1.2, 3) + ljEnergy(2.3, math.sqrt(1.68), 4) \
                 + 0.3*ljEnergy(3.1, 4.1, 3)
1569
1570
        self.assertAlmostEqual(expected, context.getState(getEnergy=True).getPotentialEnergy().value_in_unit(kilojoules_per_mole))

1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
    def test_IgnoreExternalBonds(self):
        """Test the ignoreExternalBonds option"""

        modeller = Modeller(self.pdb2.topology, self.pdb2.positions)
        modeller.delete([next(modeller.topology.residues())])
        self.assertRaises(Exception, lambda: self.forcefield2.createSystem(modeller.topology))
        system = self.forcefield2.createSystem(modeller.topology, ignoreExternalBonds=True)
        templates = self.forcefield2.getMatchingTemplates(modeller.topology, ignoreExternalBonds=True)
        self.assertEqual(2, len(templates))
        self.assertEqual('ALA', templates[0].name)
        self.assertEqual('NME', templates[1].name)
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1582

Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1583
1584
1585
1586
1587
1588
    def test_Includes(self):
        """Test using a ForceField that includes other files."""
        forcefield = ForceField(os.path.join('systems', 'ff_with_includes.xml'))
        self.assertTrue(len(forcefield._atomTypes) > 10)
        self.assertTrue('spce-O' in forcefield._atomTypes)
        self.assertTrue('HOH' in forcefield._templates)
1589

1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
    def test_IncludesFromDataDirectory(self):
        """Test relative include paths from subdirectories of the data directory."""

        oldDataDirs = forcefield._dataDirectories
        try:
            with tempfile.TemporaryDirectory() as tempDataDir:
                forcefield._dataDirectories = forcefield._getDataDirectories() + [tempDataDir]
                os.mkdir(os.path.join(tempDataDir, 'subdir'))
                for testFileName in ['ff_with_includes.xml', 'test_amber_ff.xml']:
                    shutil.copyfile(os.path.join('systems', testFileName), os.path.join(tempDataDir, 'subdir', testFileName))
                ff = ForceField(os.path.join('subdir', 'ff_with_includes.xml'))
                self.assertTrue(len(ff._atomTypes) > 10)
                self.assertTrue('spce-O' in ff._atomTypes)
                self.assertTrue('HOH' in ff._templates)
        finally:
            forcefield._dataDirectories = oldDataDirs

Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1607
    def test_ImpropersOrdering(self):
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1608
        """Test correctness of the ordering of atom indexes in improper torsions
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
        and the torsion.ordering parameter.
        """

        xml = """
<ForceField>
 <PeriodicTorsionForce ordering="amber">
  <Improper class1="C" class2="" class3="O2" class4="O2" periodicity1="2" phase1="3.14159265359" k1="43.932"/>
 </PeriodicTorsionForce>
</ForceField>
"""
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1619
        pdb = PDBFile('systems/impropers_ordering_tetrapeptide.pdb')
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1620
1621
1622
1623
1624
        # ff1 uses default ordering of impropers, ff2 uses "amber" for the one
        # problematic improper
        ff1 = ForceField('amber99sbildn.xml')
        ff2 = ForceField(StringIO(xml), 'amber99sbildn.xml')

Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1625
1626
        system1 = ff1.createSystem(pdb.topology)
        system2 = ff2.createSystem(pdb.topology)
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1627

1628
        imp1 = system1.getForce(1).getTorsionParameters(158)
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1629
1630
1631
1632
1633
        imp2 = system2.getForce(0).getTorsionParameters(158)

        system1_indexes = [imp1[0], imp1[1], imp1[2], imp1[3]]
        system2_indexes = [imp2[0], imp2[1], imp2[2], imp2[3]]

1634
        self.assertEqual(system1_indexes, [51, 55, 54, 56])
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1635
        self.assertEqual(system2_indexes, [51, 55, 54, 56])
1636

1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
    def test_ImpropersOrdering_smirnoff(self):
        """Test correctness of the ordering of atom indexes in improper torsions
        and the torsion.ordering parameter when using the 'smirnoff' mode.
        """

        # SMIRNOFF parameters for formaldehyde
        xml = """
<ForceField>
  <AtomTypes>
    <Type name="[H]C(=O)[H]$C1#0" element="C" mass="12.01078" class="[H]C(=O)[H]$C1#0"/>
    <Type name="[H]C(=O)[H]$O1#1" element="O" mass="15.99943" class="[H]C(=O)[H]$O1#1"/>
    <Type name="[H]C(=O)[H]$H1#2" element="H" mass="1.007947" class="[H]C(=O)[H]$H1#2"/>
    <Type name="[H]C(=O)[H]$H2#3" element="H" mass="1.007947" class="[H]C(=O)[H]$H2#3"/>
  </AtomTypes>
  <PeriodicTorsionForce ordering="smirnoff">
    <Improper class1="[H]C(=O)[H]$C1#0" class2="[H]C(=O)[H]$O1#1" class3="[H]C(=O)[H]$H1#2" class4="[H]C(=O)[H]$H2#3" periodicity1="2" phase1="3.141592653589793" k1="1.5341333333333336"/>
    <Improper class1="[H]C(=O)[H]$C1#0" class2="[H]C(=O)[H]$H1#2" class3="[H]C(=O)[H]$H2#3" class4="[H]C(=O)[H]$O1#1" periodicity1="2" phase1="3.141592653589793" k1="1.5341333333333336"/>
    <Improper class1="[H]C(=O)[H]$C1#0" class2="[H]C(=O)[H]$H2#3" class3="[H]C(=O)[H]$O1#1" class4="[H]C(=O)[H]$H1#2" periodicity1="2" phase1="3.141592653589793" k1="1.5341333333333336"/>
  </PeriodicTorsionForce>
  <Residues>
    <Residue name="[H]C(=O)[H]">
      <Atom name="C1" type="[H]C(=O)[H]$C1#0" charge="0.5632799863815308"/>
      <Atom name="O1" type="[H]C(=O)[H]$O1#1" charge="-0.514739990234375"/>
      <Atom name="H1" type="[H]C(=O)[H]$H1#2" charge="-0.02426999807357788"/>
      <Atom name="H2" type="[H]C(=O)[H]$H2#3" charge="-0.02426999807357788"/>
      <Bond atomName1="C1" atomName2="O1"/>
      <Bond atomName1="C1" atomName2="H1"/>
      <Bond atomName1="C1" atomName2="H2"/>
    </Residue>
  </Residues>
</ForceField>
"""
        pdb = PDBFile('systems/formaldehyde.pdb')
        # ff1 uses default ordering of impropers, ff2 uses "amber" for the one
        # problematic improper
        ff = ForceField(StringIO(xml))

        system = ff.createSystem(pdb.topology)

        # Check that impropers are applied in the correct three-fold trefoil pattern
        forces = { force.__class__.__name__ : force for force in system.getForces() }
        force = forces['PeriodicTorsionForce']
        created_torsions = set()
        for index in range(force.getNumTorsions()):
            i,j,k,l,_,_,_ = force.getTorsionParameters(index)
            created_torsions.add((i,j,k,l))
1683
        expected_torsions = set([(0,3,1,2), (0,1,2,3), (0,2,3,1)])
1684
1685
        self.assertEqual(expected_torsions, created_torsions)

peastman's avatar
peastman committed
1686
1687
1688
    def test_Disulfides(self):
        """Test that various force fields handle disulfides correctly."""
        pdb = PDBFile('systems/bpti.pdb')
1689
        for ff in ['amber99sb.xml', 'amber14-all.xml', 'amber19-all.xml', 'charmm36.xml', 'charmm36_2024.xml', 'amberfb15.xml', 'amoeba2013.xml']:
peastman's avatar
peastman committed
1690
1691
1692
            forcefield = ForceField(ff)
            system = forcefield.createSystem(pdb.topology)

1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
    def test_IdenticalTemplates(self):
        """Test a case where patches produce two identical templates."""
        ff = ForceField('charmm36.xml')
        pdb = PDBFile(StringIO("""
ATOM      1  N   HIS     1A   -2.670    -0.476   0.475  1.00  0.00           N
ATOM      2  HT1 HIS     1A   -2.645    -1.336   1.036  1.00  0.00           H
ATOM      3  HT2 HIS     1A   -2.859    -0.751  -0.532  1.00  0.00           H
ATOM      4  HT3 HIS     1A   -3.415     0.201   0.731  1.00  0.00           H
ATOM      5  CA  HIS     1A   -1.347     0.163   0.471  1.00  0.00           C
ATOM      6  HA  HIS     1A   -1.111     0.506   1.479  1.00  0.00           H
ATOM      7  CB  HIS     1A   -0.352    -0.857  -0.040  1.00  0.00           C
ATOM      8  HB1 HIS     1A   -0.360    -1.741   0.636  1.00  0.00           H
ATOM      9  HB2 HIS     1A   -0.640    -1.175  -1.046  1.00  0.00           H
ATOM     10  CG  HIS     1A    1.003    -0.275  -0.063  1.00  0.00           C
ATOM     11  CD2 HIS     1A    2.143    -0.931  -0.476  1.00  0.00           C
ATOM     12  HD2 HIS     1A    2.217    -1.952  -0.840  1.00  0.00           H
ATOM     13  NE2 HIS     1A    3.137    -0.024  -0.328  1.00  0.00           N
ATOM     14  HE2 HIS     1A    4.132    -0.238  -0.565  1.00  0.00           H
ATOM     15  CE1 HIS     1A    2.649     1.130   0.150  1.00  0.00           C
ATOM     16  HE1 HIS     1A    3.233     2.020   0.360  1.00  0.00           H
ATOM     17  ND1 HIS     1A    1.323     0.973   0.314  1.00  0.00           N
ATOM     18  C   HIS     1A   -1.465     1.282  -0.497  1.00  0.00           C
ATOM     19  OT1 HIS     1A   -2.108     2.309  -0.180  1.00  0.00           O
ATOM     20  OT2 HIS     1A   -0.864     1.172  -1.737  1.00  0.00           O
END"""))
        # If the check is not done correctly, this will throw an exception.
        ff.createSystem(pdb.topology)
1720
1721
1722
1723
1724
    
    def test_CharmmLoad(self):
        """Tests that the CHARMM force fields are capable of parameterizing systems."""

        charmm_models = ("charmm36", "charmm36_2024")
1725
1726
1727
        water_models_3 = ("water", "spce", "tip3p-pme-b", "tip3p-pme-f")
        water_models_4 = ("tip4p2005", "tip4pew")
        water_models_5 = ("tip5p", "tip5pew")
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756

        # Checks that the numbers of various types of terms in a system matches expected counts.
        def check_system(system, particle_count, site_count, constraint_count, bond_count, angle_count, cmap_count, exception_count, override_count, drude_count, screen_count):
            self.assertEqual(particle_count, system.getNumParticles())
            self.assertEqual(site_count, sum([1 for index in range(system.getNumParticles()) if system.isVirtualSite(index)]))
            self.assertEqual(constraint_count, system.getNumConstraints())
            self.assertEqual(bond_count, sum([force.getNumBonds() for force in system.getForces() if isinstance(force, HarmonicBondForce)]))
            self.assertEqual(angle_count, sum([force.getNumAngles() for force in system.getForces() if isinstance(force, HarmonicAngleForce)]))
            self.assertEqual(cmap_count, sum([force.getNumTorsions() for force in system.getForces() if isinstance(force, CMAPTorsionForce)]))
            self.assertEqual(exception_count, sum([force.getNumExceptions() for force in system.getForces() if isinstance(force, NonbondedForce)]))
            self.assertEqual(override_count, sum([force.getNumBonds() for force in system.getForces() if isinstance(force, CustomBondForce)]))
            self.assertEqual(drude_count, sum([force.getNumParticles() for force in system.getForces() if isinstance(force, DrudeForce)]))
            self.assertEqual(screen_count, sum([force.getNumScreenedPairs() for force in system.getForces() if isinstance(force, DrudeForce)]))

        # Standard 20 amino acids including N- and C-terminal variants.
        pdb_20aa = PDBFile("systems/test_charmm_20aa.pdb")
        for charmm_model in charmm_models:
            check_system(ForceField(f"{charmm_model}.xml").createSystem(pdb_20aa.topology), 1032, 0, 0, 1937, 1833, 20, 5390, 2527, 0, 0)

        # Standard 20 amino acids including N- and C-terminal variants (Drude).
        pdb_20aa_drude = PDBFile("systems/test_charmm_20aa_drude.pdb")
        for drude_model in ("charmm_polar_2019", "charmm_polar_2023"):
            check_system(ForceField(f"{drude_model}.xml").createSystem(pdb_20aa_drude.topology), 1794, 241, 0, 2106, 1833, 20, 18162, 7434, 521, 1203)

        # Peptide in water with ions.
        pdb_peptide_3 = PDBFile("systems/test_charmm_peptide_3.pdb")
        pdb_peptide_4 = PDBFile("systems/test_charmm_peptide_4.pdb")
        pdb_peptide_5 = PDBFile("systems/test_charmm_peptide_5.pdb")
        for charmm_model in charmm_models:
1757
            for water_model in water_models_3:
1758
                check_system(ForceField(f"{charmm_model}.xml", f"{charmm_model}/{water_model}.xml").createSystem(pdb_peptide_3.topology), 1136, 0, 984, 234, 249, 8, 1727, 353, 0, 0)
1759
            for water_model in water_models_4:
1760
                check_system(ForceField(f"{charmm_model}.xml", f"{charmm_model}/{water_model}.xml").createSystem(pdb_peptide_4.topology), 1464, 328, 984, 234, 249, 8, 2711, 353, 0, 0)
1761
            for water_model in water_models_5:
1762
                check_system(ForceField(f"{charmm_model}.xml", f"{charmm_model}/{water_model}.xml").createSystem(pdb_peptide_5.topology), 1792, 656, 984, 234, 249, 8, 4023, 353, 0, 0)
peastman's avatar
peastman committed
1763

1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
    def test_CharmmVersionMismatchCheck(self):
        """
        Tests that CHARMM force fields cannot be loaded with the wrong water model versions.
        """

        charmm_models = ("charmm36", "charmm36_2024")
        water_models = ("water", "spce", "tip3p-pme-b", "tip3p-pme-f", "tip4p2005", "tip4pew", "tip5p", "tip5pew")

        for base_charmm_model in charmm_models:
            for water_charmm_model in charmm_models:
                if base_charmm_model != water_charmm_model:
                    for water_model in water_models:
                        with self.assertRaises(Exception):
                            ForceField(f"{base_charmm_model}.xml", f"{water_charmm_model}/{water_model}.xml")
                        with self.assertRaises(Exception):
                            ForceField(f"{water_charmm_model}/{water_model}.xml", f"{base_charmm_model}.xml")

1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
    def test_CharmmPolar(self):
        """Test the CHARMM polarizable force field."""
        pdb = PDBFile('systems/ala_ala_ala_drude.pdb')
        pdb.topology.setUnitCellDimensions(Vec3(3, 3, 3))
        ff = ForceField('charmm_polar_2019.xml')
        system = ff.createSystem(pdb.topology, nonbondedMethod=PME, nonbondedCutoff=1.2*nanometers)
        for i,f in enumerate(system.getForces()):
            f.setForceGroup(i)
            if isinstance(f, NonbondedForce):
                f.setPMEParameters(3.4, 64, 64, 64)
        integrator = DrudeLangevinIntegrator(300, 1.0, 1.0, 10.0, 0.001)
Peter Eastman's avatar
Peter Eastman committed
1792
        context = Context(system, integrator, Platform.getPlatform('Reference'))
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
        context.setPositions(pdb.positions)

        # Compare the energy to values computed by CHARMM.  Here is what it outputs:

        # ENER ENR:  Eval#     ENERgy      Delta-E         GRMS
        # ENER INTERN:          BONDs       ANGLes       UREY-b    DIHEdrals    IMPRopers
        # ENER CROSS:           CMAPs        PMF1D        PMF2D        PRIMO
        # ENER EXTERN:        VDWaals         ELEC       HBONds          ASP         USER
        # ENER EWALD:          EWKSum       EWSElf       EWEXcl       EWQCor       EWUTil
        #  ----------       ---------    ---------    ---------    ---------    ---------
peastman's avatar
peastman committed
1803
        # ENER>        0    102.83992      0.00000     13.06415
1804
1805
        # ENER INTERN>       54.72574     40.21459     11.61009     26.10373      0.14113
        # ENER CROSS>        -3.37113      0.00000      0.00000      0.00000
peastman's avatar
peastman committed
1806
1807
        # ENER EXTERN>       22.74761    -24.21667      0.00000      0.00000      0.00000
        # ENER EWALD>        56.14258  -7279.07968   7197.82192      0.00000      0.00000
1808
1809
1810
1811
1812
        #  ----------       ---------    ---------    ---------    ---------    ---------

        # First check the total energy.
        
        energy = context.getState(getEnergy=True).getPotentialEnergy().value_in_unit(kilocalories_per_mole)
peastman's avatar
peastman committed
1813
        self.assertAlmostEqual(102.83992, energy, delta=energy*1e-3)
1814

peastman's avatar
peastman committed
1815
1816
1817
1818
        # Now check individual components.  CHARMM and OpenMM split them up a little differently.  I've tried to
        # match things up, but I think there's still some inconsistency in where forces related to Drude particles
        # are categorized.  That's why the Coulomb and bonds terms match less accurately than the other terms
        # (and less accurately than the total energy, which agrees well).
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842

        coulomb = 0
        vdw = 0
        bonds = 0
        angles = 0
        propers = 0
        impropers = 0
        cmap = 0
        for i,f in enumerate(system.getForces()):
            energy = context.getState(getEnergy=True, groups={i}).getPotentialEnergy().value_in_unit(kilocalories_per_mole)
            if isinstance(f, NonbondedForce):
                coulomb += energy
            elif isinstance(f, CustomNonbondedForce) or isinstance(f, CustomBondForce):
                vdw += energy
            elif isinstance(f, HarmonicBondForce) or isinstance(f, DrudeForce):
                bonds += energy
            elif isinstance(f, HarmonicAngleForce):
                angles += energy
            elif isinstance(f, PeriodicTorsionForce):
                propers += energy
            elif isinstance(f, CustomTorsionForce):
                impropers += energy
            elif isinstance(f, CMAPTorsionForce):
                cmap += energy
peastman's avatar
peastman committed
1843
1844
        self.assertAlmostEqual(-24.21667+56.14258-7279.07968+7197.82192, coulomb, delta=abs(coulomb)*5e-2) # ELEC+EWKSum+EWSElf+EWEXcl
        self.assertAlmostEqual(22.74761, vdw, delta=vdw*1e-3) # VDWaals
1845
        self.assertAlmostEqual(54.72574+11.61009, bonds, delta=bonds*2e-2) # BONDs+UREY-b
peastman's avatar
peastman committed
1846
1847
1848
        self.assertAlmostEqual(40.21459, angles, delta=angles*1e-3) # ANGLes
        self.assertAlmostEqual(26.10373, propers, delta=propers*1e-3) # DIHEdrals
        self.assertAlmostEqual(0.14113, impropers, delta=impropers*1e-3) # IMPRopers
1849

1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
    def test_InitializationScript(self):
        """Test that <InitializationScript> tags get executed."""
        xml = """
<ForceField>
  <InitializationScript>
self.scriptExecuted = True
  </InitializationScript>
</ForceField>
"""
        ff = ForceField(StringIO(xml))
        self.assertTrue(ff.scriptExecuted)
Peter Eastman's avatar
Peter Eastman committed
1861
1862
1863
1864
1865
1866
1867
1868
1869

    def test_Glycam(self):
        """Test computing energy with GLYCAM."""
        ff = ForceField('amber14/protein.ff14SB.xml', 'amber14/GLYCAM_06j-1.xml')
        pdb = PDBFile('systems/glycopeptide.pdb')
        system = ff.createSystem(pdb.topology)
        for i, f in enumerate(system.getForces()):
            f.setForceGroup(i)
        integrator = VerletIntegrator(0.001)
Peter Eastman's avatar
Peter Eastman committed
1870
        context = Context(system, integrator, Platform.getPlatform('Reference'))
Peter Eastman's avatar
Peter Eastman committed
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
        context.setPositions(pdb.positions)
        energies = {}
        for i, f in enumerate(system.getForces()):
            energy = context.getState(getEnergy=True, groups={i}).getPotentialEnergy().value_in_unit(kilojoules_per_mole)
            energies[f.getName()] = energy

        # Compare to values computed with ParmEd.

        self.assertAlmostEqual(32.14082401103625, energies['HarmonicBondForce'], 4)
        self.assertAlmostEqual(48.92017455984504, energies['HarmonicAngleForce'], 3)
        self.assertAlmostEqual(291.61241586209286, energies['PeriodicTorsionForce'], 4)
        self.assertAlmostEqual(1547.011267801862, energies['NonbondedForce'], 4)
        self.assertAlmostEqual(1919.6846822348361, sum(list(energies.values())), 3)
1884

1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
    def test_CustomNonbondedGenerator(self):
        """ Test the CustomNonbondedForce generator"""
        pdb = PDBFile('systems/ions.pdb')
        xml = """
<ForceField>
 <AtomTypes>
  <Type name="SOD" class="SOD" element="Na" mass="22.98977"/>
  <Type name="CLA" class="CLA" element="Cl" mass="35.45"/>
 </AtomTypes>
 <Residues>
  <Residue name="CLA">
   <Atom name="CLA" type="CLA"/>
  </Residue>
  <Residue name="SOD">
   <Atom name="SOD" type="SOD"/>
  </Residue>
 </Residues>
 <CustomNonbondedForce energy="scale*epsilon*((sigma/r)^12-(sigma/r)^6); sigma=halfSig1+halfSig2; epsilon=rootEps1*rootEps2" bondCutoff="3">
  <GlobalParameter name="scale" defaultValue="4"/>
  <PerParticleParameter name="sigma"/>
  <PerParticleParameter name="epsilon"/>
  <ComputedValue name="halfSig" expression="0.5*sigma"/>
  <ComputedValue name="rootEps" expression="sqrt(epsilon)"/>
  <Atom type="CLA" sigma="0.404468018036" epsilon="0.6276"/>
  <Atom type="SOD" sigma="0.251367073323" epsilon="0.1962296"/>
 </CustomNonbondedForce>
</ForceField> """
        ff = ForceField(StringIO(xml))
        system = ff.createSystem(pdb.topology)
Peter Eastman's avatar
Peter Eastman committed
1914
        context = Context(system, VerletIntegrator(2*femtoseconds), Platform.getPlatform('Reference'))
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
        context.setPositions(pdb.positions)
        energy1 = context.getState(getEnergy=True).getPotentialEnergy().value_in_unit(kilojoules_per_mole)

        # See if it matches an equivalent NonbondedForce.
        
        system = System()
        system.addParticle(1.0)
        system.addParticle(1.0)
        f = NonbondedForce()
        f.addParticle(0, 0.404468018036, 0.6276)
        f.addParticle(0, 0.251367073323, 0.1962296)
        system.addForce(f)
Peter Eastman's avatar
Peter Eastman committed
1927
        context = Context(system, VerletIntegrator(2*femtoseconds), Platform.getPlatform('Reference'))
1928
1929
1930
1931
        context.setPositions(pdb.positions)
        energy2 = context.getState(getEnergy=True).getPotentialEnergy().value_in_unit(kilojoules_per_mole)
        self.assertAlmostEqual(energy1, energy2)

Alex Izvorski's avatar
Alex Izvorski committed
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
    def test_OpcEnergy(self):
        pdb = PDBFile('systems/opcbox.pdb')
        topology, positions = pdb.topology, pdb.positions
        self.assertEqual(len(positions), 864)
        forcefield = ForceField('opc.xml')
        system = forcefield.createSystem(
            topology,
            nonbondedMethod=PME,
            nonbondedCutoff=0.7*nanometer,
            constraints=HBonds,
            rigidWater=True,
        )

        integrator = LangevinIntegrator(300*kelvin, 2.0/picoseconds, 2.0*femtoseconds)
        simulation = Simulation(topology, system, integrator)
        context = simulation.context
        context.setPositions(positions)

        # Compare to values computed with Amber (sander).
        energy_amber = -2647.6233 # kcal/mol
        energy_tolerance = 1.0

        state = context.getState(getEnergy=True)
        energy1 = state.getPotentialEnergy().value_in_unit(kilocalorie_per_mole)
        # -2647.2222697324237
        self.assertTrue(abs(energy1 - energy_amber) < energy_tolerance)

        context.applyConstraints(1e-12)
        state = context.getState(getEnergy=True)
        energy2 = state.getPotentialEnergy().value_in_unit(kilocalorie_per_mole)
        # -2647.441600693312
        self.assertTrue(abs(energy1 - energy_amber) < energy_tolerance)
        self.assertTrue(abs(energy1 - energy2) < energy_tolerance)

    def test_Opc3Energy(self):
        pdb = PDBFile('systems/opc3box.pdb')
        topology, positions = pdb.topology, pdb.positions
        self.assertEqual(len(positions), 648)
        forcefield = ForceField('opc3.xml')
        system = forcefield.createSystem(
            topology,
            nonbondedMethod=PME,
            nonbondedCutoff=0.7*nanometer,
            constraints=HBonds,
            rigidWater=True,
        )

        integrator = LangevinIntegrator(300*kelvin, 2.0/picoseconds, 2.0*femtoseconds)
        simulation = Simulation(topology, system, integrator)
        context = simulation.context
        context.setPositions(positions)

        # Compare to values computed with Amber (sander).
        energy_amber = -2532.1414 # kcal/mol
        energy_tolerance = 1.0

        state = context.getState(getEnergy=True)
        energy1 = state.getPotentialEnergy().value_in_unit(kilocalorie_per_mole)
        # -2532.4862082354407
        self.assertTrue(abs(energy1 - energy_amber) < energy_tolerance)

1993
1994
1995
1996
1997
1998
        context.applyConstraints(1e-12)
        state = context.getState(getEnergy=True)
        energy2 = state.getPotentialEnergy().value_in_unit(kilocalorie_per_mole)
        self.assertTrue(abs(energy1 - energy_amber) < energy_tolerance)
        self.assertTrue(abs(energy1 - energy2) < energy_tolerance)

1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
    def testWholeMolecule(self):
        """Test matching a template to a whole molecule."""
        xml = """
<ForceField>
  <AtomTypes>
    <Type class="C" element="C" mass="12.01" name="C" />
    <Type class="CT" element="C" mass="12.01" name="CT" />
    <Type class="CX" element="C" mass="12.01" name="CX"/>
    <Type class="H" element="H" mass="1.008" name="H"/>
    <Type class="HC" element="H" mass="1.008" name="HC" />
    <Type class="H1" element="H" mass="1.008" name="H1" />
    <Type class="N" element="N" mass="14.01" name="N" />
    <Type class="O" element="O" mass="16.0" name="O" />
  </AtomTypes>
  <Residues>
    <Residue name="Alanine-Dipeptide">
      <Atom charge="0.1123" name="ACE-H1" type="HC" />
      <Atom charge="-0.3662" name="ACE-CH3" type="CT" />
      <Atom charge="0.1123" name="ACE-H2" type="HC" />
      <Atom charge="0.1123" name="ACE-H3" type="HC" />
      <Atom charge="0.5972" name="ACE-C" type="C" />
      <Atom charge="-0.5679" name="ACE-O" type="O" />
      <Bond atomName1="ACE-H1" atomName2="ACE-CH3" />
      <Bond atomName1="ACE-CH3" atomName2="ACE-H2" />
      <Bond atomName1="ACE-CH3" atomName2="ACE-H3" />
      <Bond atomName1="ACE-CH3" atomName2="ACE-C" />
      <Bond atomName1="ACE-C" atomName2="ACE-O" />
      <Atom charge="-0.4157" name="ALA-N" type="N" />
      <Atom charge="0.2719" name="ALA-H" type="H" />
      <Atom charge="0.0337" name="ALA-CA" type="CX" />
      <Atom charge="0.0823" name="ALA-HA" type="H1" />
      <Atom charge="-0.1825" name="ALA-CB" type="CT" />
      <Atom charge="0.0603" name="ALA-HB1" type="HC" />
      <Atom charge="0.0603" name="ALA-HB2" type="HC" />
      <Atom charge="0.0603" name="ALA-HB3" type="HC" />
      <Atom charge="0.5973" name="ALA-C" type="C" />
      <Atom charge="-0.5679" name="ALA-O" type="O" />
      <Bond atomName1="ALA-N" atomName2="ALA-H" />
      <Bond atomName1="ALA-N" atomName2="ALA-CA" />
      <Bond atomName1="ALA-CA" atomName2="ALA-HA" />
      <Bond atomName1="ALA-CA" atomName2="ALA-CB" />
      <Bond atomName1="ALA-CA" atomName2="ALA-C" />
      <Bond atomName1="ALA-CB" atomName2="ALA-HB1" />
      <Bond atomName1="ALA-CB" atomName2="ALA-HB2" />
      <Bond atomName1="ALA-CB" atomName2="ALA-HB3" />
      <Bond atomName1="ALA-C" atomName2="ALA-O" />
      <Atom charge="-0.4157" name="NME-N" type="N" />
      <Atom charge="0.2719" name="NME-H" type="H" />
      <Atom charge="-0.149" name="NME-C" type="CT" />
      <Atom charge="0.0976" name="NME-H1" type="H1" />
      <Atom charge="0.0976" name="NME-H2" type="H1" />
      <Atom charge="0.0976" name="NME-H3" type="H1" />
      <Bond atomName1="NME-N" atomName2="NME-H" />
      <Bond atomName1="NME-N" atomName2="NME-C" />
      <Bond atomName1="NME-C" atomName2="NME-H1" />
      <Bond atomName1="NME-C" atomName2="NME-H2" />
      <Bond atomName1="NME-C" atomName2="NME-H3" />
      <Bond atomName1="ACE-C" atomName2="ALA-N" />
      <Bond atomName1="ALA-C" atomName2="NME-N" />
    </Residue>
    <!-- A template that matches just the ACE with different parameters -->
    <Residue name="ACE">
      <Atom charge="0.1123" name="ACE-H1" type="HC" />
      <Atom charge="-0.3662" name="ACE-CH3" type="CT" />
      <Atom charge="-10.0" name="ACE-H2" type="HC" />
      <Atom charge="0.1123" name="ACE-H3" type="HC" />
      <Atom charge="10.0" name="ACE-C" type="C" />
      <Atom charge="-0.5679" name="ACE-O" type="O" />
      <Bond atomName1="ACE-H1" atomName2="ACE-CH3" />
      <Bond atomName1="ACE-CH3" atomName2="ACE-H2" />
      <Bond atomName1="ACE-CH3" atomName2="ACE-H3" />
      <Bond atomName1="ACE-CH3" atomName2="ACE-C" />
      <Bond atomName1="ACE-C" atomName2="ACE-O" />
      <ExternalBond atomName="ACE-C" />
    </Residue>
  </Residues>
  <NonbondedForce coulomb14scale="0.8333333333333334" lj14scale="0.5">
    <UseAttributeFromResidue name="charge"/>
    <Atom epsilon="0.359824" sigma="0.3399669508423535" type="C"/>
    <Atom epsilon="0.4577296" sigma="0.3399669508423535" type="CT"/>
    <Atom epsilon="0.4577296" sigma="0.3399669508423535" type="CX"/>
    <Atom epsilon="0.06568879999999999" sigma="0.2649532787749369" type="HC"/>
    <Atom epsilon="0.06568879999999999" sigma="0.10690784617684071" type="H"/>
    <Atom epsilon="0.06568879999999999" sigma="0.2471353044121301" type="H1"/>
    <Atom epsilon="0.7112800000000001" sigma="0.3249998523775958" type="N"/>
    <Atom epsilon="0.87864" sigma="0.2959921901149463" type="O"/>
  </NonbondedForce>
</ForceField>"""
        pdb = PDBFile('systems/alanine-dipeptide-implicit.pdb')
        ff = ForceField(StringIO(xml))
        system = ff.createSystem(pdb.topology)
        nonbonded = next(f for f in system.getForces() if isinstance(f, NonbondedForce))

        def checkAtom(resName, atomName, expected):
            for atom in pdb.topology.atoms():
                if atom.name == atomName and atom.residue.name == resName:
                    params = nonbonded.getParticleParameters(atom.index)
                    self.assertEqual(expected, params)
                    return
            raise ValueError(f'{resName} {atomName} not found')

        checkAtom('ACE', 'C', [0.5972*elementary_charge, 0.3399669508423535*nanometers, 0.359824*kilojoules_per_mole])
        checkAtom('ACE', 'H2', [0.1123*elementary_charge, 0.2649532787749369*nanometers, 0.06568879999999999*kilojoules_per_mole])
        checkAtom('ALA', 'CA', [0.0337*elementary_charge, 0.3399669508423535*nanometers, 0.4577296*kilojoules_per_mole])
        checkAtom('NME', 'N', [-0.4157*elementary_charge, 0.3249998523775958*nanometers, 0.7112800000000001*kilojoules_per_mole])
2104

2105
2106
class AmoebaTestForceField(unittest.TestCase):
    """Test the ForceField.createSystem() method with the AMOEBA forcefield."""
2107

2108
    def setUp(self):
2109
        """Set up the tests by loading the input pdb files and force field
2110
2111
2112
2113
2114
        xml files.

        """

        self.pdb1 = PDBFile('systems/amoeba-ion-in-water.pdb')
2115
        self.forcefield1 = ForceField('amoeba2013.xml')
2116
2117
2118
2119
        self.topology1 = self.pdb1.topology


    def test_NonbondedMethod(self):
Peter Eastman's avatar
Peter Eastman committed
2120
        """Test both options for the nonbondedMethod parameter."""
2121

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
2122
2123
        methodMap = {NoCutoff:AmoebaMultipoleForce.NoCutoff,
                     PME:AmoebaMultipoleForce.PME}
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134

        for method in methodMap:
            system = self.forcefield1.createSystem(self.pdb1.topology,
                                                  nonbondedMethod=method)
            forces = system.getForces()
            self.assertTrue(any(isinstance(f, AmoebaMultipoleForce) and
                                f.getNonbondedMethod()==methodMap[method]
                                for f in forces))
    def test_Cutoff(self):
        """Test to make sure the nonbondedCutoff parameter is passed correctly."""

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
2135
        cutoff_distance = 0.7*nanometer
2136
2137
2138
        for method in [NoCutoff, PME]:
            system = self.forcefield1.createSystem(self.pdb1.topology,
                                                   nonbondedMethod=method,
2139
                                                   nonbondedCutoff=cutoff_distance,
2140
2141
2142
                                                   constraints=None)

            for force in system.getForces():
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
2143
2144
2145
2146
                if isinstance(force, AmoebaVdwForce):
                    self.assertEqual(force.getCutoff(), cutoff_distance)
                if isinstance(force, AmoebaMultipoleForce):
                    self.assertEqual(force.getCutoffDistance(), cutoff_distance)
2147
2148
2149
2150
2151
2152

    def test_DispersionCorrection(self):
        """Test to make sure the nonbondedCutoff parameter is passed correctly."""

        for useDispersionCorrection in [True, False]:
            system = self.forcefield1.createSystem(self.pdb1.topology,
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
2153
                                                   nonbondedMethod=PME,
2154
2155
2156
                                                   useDispersionCorrection=useDispersionCorrection)

            for force in system.getForces():
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
2157
                if isinstance(force, AmoebaVdwForce):
2158
2159
                    self.assertEqual(useDispersionCorrection, force.getUseDispersionCorrection())

2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
    def test_RigidWater(self):
        """Test that AMOEBA creates rigid water with the correct geometry."""

        system = self.forcefield1.createSystem(self.pdb1.topology, rigidWater=True)
        constraints = dict()
        for i in range(system.getNumConstraints()):
            p1,p2,dist = system.getConstraintParameters(i)
            if p1 < 3:
                constraints[(min(p1,p2), max(p1,p2))] = dist.value_in_unit(nanometers)
        hoDist = 0.09572
        hohAngle = 108.50*math.pi/180.0
        hohDist = math.sqrt(2*hoDist**2 - 2*hoDist**2*math.cos(hohAngle))
        self.assertAlmostEqual(constraints[(0,1)], hoDist)
        self.assertAlmostEqual(constraints[(0,2)], hoDist)
        self.assertAlmostEqual(constraints[(1,2)], hohDist)
2175
2176
2177
2178
2179
2180
2181
2182
2183
        
        # Check that all values of rigidWater are interpreted correctly.
        
        numWaters = 215
        self.assertEqual(3*numWaters, system.getNumConstraints())
        system = self.forcefield1.createSystem(self.pdb1.topology, rigidWater=False)
        self.assertEqual(0, system.getNumConstraints())
        system = self.forcefield1.createSystem(self.pdb1.topology, rigidWater=None)
        self.assertEqual(0, system.getNumConstraints())
2184

2185
2186
2187
2188
2189
2190
2191
    def test_Forces(self):
        """Compute forces and compare them to ones generated with a previous version of OpenMM to ensure they haven't changed."""

        pdb = PDBFile('systems/alanine-dipeptide-implicit.pdb')
        forcefield = ForceField('amoeba2013.xml', 'amoeba2013_gk.xml')
        system = forcefield.createSystem(pdb.topology, polarization='direct')
        integrator = VerletIntegrator(0.001)
Peter Eastman's avatar
Peter Eastman committed
2192
        context = Context(system, integrator, Platform.getPlatform('Reference'))
2193
2194
2195
2196
2197
2198
2199
2200
        context.setPositions(pdb.positions)
        state1 = context.getState(getForces=True)
        with open('systems/alanine-dipeptide-amoeba-forces.xml') as input:
            state2 = XmlSerializer.deserialize(input.read())
        for f1, f2, in zip(state1.getForces().value_in_unit(kilojoules_per_mole/nanometer), state2.getForces().value_in_unit(kilojoules_per_mole/nanometer)):
            diff = norm(f1-f2)
            self.assertTrue(diff < 0.1 or diff/norm(f1) < 1e-3)

2201
2202
2203
2204
2205
2206
2207
    def computeAmoeba18Energies(self, filename):
        pdb = PDBFile(filename)
        forcefield = ForceField('amoeba2018.xml')
        system = forcefield.createSystem(pdb.topology, polarization='mutual', mutualInducedTargetEpsilon=1e-5)
        for i, f in enumerate(system.getForces()):
            f.setForceGroup(i)
        integrator = VerletIntegrator(0.001)
Peter Eastman's avatar
Peter Eastman committed
2208
        context = Context(system, integrator, Platform.getPlatform('Reference'))
2209
2210
2211
2212
2213
2214
2215
2216
        context.setPositions(pdb.positions)
        energies = {}
        for i, f in enumerate(system.getForces()):
            state = context.getState(getEnergy=True, groups={i})
            energies[f.getName()] = state.getPotentialEnergy().value_in_unit(kilocalories_per_mole)
        return energies

    def test_Amoeba18BPTI(self):
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
        """
        Test that AMOEBA18 computes energies correctly for BPTI.
        
        Total Potential Energy :               -259.8636 Kcal/mole

        Energy Component Breakdown :           Kcal/mole        Interactions

        Bond Stretching                         290.2445              906
        Angle Bending                           496.4300             1626
        Stretch-Bend                              5.7695             1455
        Out-of-Plane Bend                        51.2913              597
        Torsional Angle                          75.6890             2391
        Pi-Orbital Torsion                       19.3364              109
        Torsion-Torsion                         -32.6689                6
        Van der Waals                           383.8705           394854
        Atomic Multipoles                     -1325.1825           394854
        Polarization                           -224.6434           394854
        """
2235
2236
2237
2238
        energies = self.computeAmoeba18Energies('systems/bpti.pdb')

        # Compare to values computed with Tinker.

2239
2240
2241
2242
        self.assertAlmostEqual(290.2445, energies['AmoebaBondForce'], 4)
        self.assertAlmostEqual(496.4300, energies['AmoebaAngleForce']+energies['AmoebaInPlaneAngleForce'], 4)
        self.assertAlmostEqual(51.2913, energies['AmoebaOutOfPlaneBendForce'], 4)
        self.assertAlmostEqual(5.7695, energies['AmoebaStretchBendForce'], 4)
2243
        self.assertAlmostEqual(75.6890, energies['PeriodicTorsionForce'], 4)
2244
        self.assertAlmostEqual(19.3364, energies['AmoebaPiTorsionForce'], 4)
2245
2246
        self.assertAlmostEqual(-32.6689, energies['AmoebaTorsionTorsionForce'], 4)
        self.assertAlmostEqual(383.8705, energies['AmoebaVdwForce'], 4)
2247
2248
        self.assertAlmostEqual(-1325.1825-224.6434, energies['AmoebaMultipoleForce'], 2)
        self.assertAlmostEqual(-259.8636, sum(list(energies.values())), 2)
2249

2250
2251
2252
    def test_Amoeba18Nucleic(self):
        """Test that AMOEBA18 computes energies correctly for DNA and RNA."""
        energies = self.computeAmoeba18Energies('systems/nucleic.pdb')
2253
2254
2255

        # Compare to values computed with Tinker.

2256
2257
2258
2259
        self.assertAlmostEqual(749.6953, energies['AmoebaBondForce'], 4)
        self.assertAlmostEqual(579.9971, energies['AmoebaAngleForce']+energies['AmoebaInPlaneAngleForce'], 4)
        self.assertAlmostEqual(10.6630, energies['AmoebaOutOfPlaneBendForce'], 4)
        self.assertAlmostEqual(5.2225, energies['AmoebaStretchBendForce'], 4)
2260
        self.assertAlmostEqual(166.7233, energies['PeriodicTorsionForce'], 4)
2261
2262
2263
        self.assertAlmostEqual(57.2066, energies['AmoebaPiTorsionForce'], 4)
        self.assertAlmostEqual(-4.2538, energies['AmoebaStretchTorsionForce'], 4)
        self.assertAlmostEqual(-5.0402, energies['AmoebaAngleTorsionForce'], 4)
2264
2265
        self.assertAlmostEqual(187.1103, energies['AmoebaVdwForce'], 4)
        self.assertAlmostEqual(1635.1289-236.1484, energies['AmoebaMultipoleForce'], 3)
2266
        self.assertAlmostEqual(3146.3045, sum(list(energies.values())), 3)
2267

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