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

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

19
    def setUp(self):
20
        """Set up the tests by loading the input pdb files and force field
21
22
23
24
25
26
27
28
        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))
29

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


    def test_NonbondedMethod(self):
        """Test all five options for the nonbondedMethod parameter."""

38
39
40
        methodMap = {NoCutoff:NonbondedForce.NoCutoff,
                     CutoffNonPeriodic:NonbondedForce.CutoffNonPeriodic,
                     CutoffPeriodic:NonbondedForce.CutoffPeriodic,
41
42
43
44
45
                     Ewald:NonbondedForce.Ewald, PME: NonbondedForce.PME}
        for method in methodMap:
            system = self.forcefield1.createSystem(self.pdb1.topology,
                                                  nonbondedMethod=method)
            forces = system.getForces()
46
47
            self.assertTrue(any(isinstance(f, NonbondedForce) and
                                f.getNonbondedMethod()==methodMap[method]
48
49
                                for f in forces))

50
51
52
53
54
    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,
55
                                                   nonbondedCutoff=2*nanometer,
56
57
58
59
60
61
                                                   useDispersionCorrection=useDispersionCorrection)

            for force in system.getForces():
                if isinstance(force, NonbondedForce):
                    self.assertEqual(useDispersionCorrection, force.getUseDispersionCorrection())

62
63
64
65
66
    def test_Cutoff(self):
        """Test to make sure the nonbondedCutoff parameter is passed correctly."""

        for method in [CutoffNonPeriodic, CutoffPeriodic, Ewald, PME]:
            system = self.forcefield1.createSystem(self.pdb1.topology,
67
68
                                                   nonbondedMethod=method,
                                                   nonbondedCutoff=2*nanometer,
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
                                                   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)

    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."""
86

87
88
89
90
        topology = self.pdb1.topology
        for constraints_value in [None, HBonds, AllBonds, HAngles]:
            for rigidWater_value in [True, False]:
                system = self.forcefield1.createSystem(topology,
91
                                                       constraints=constraints_value,
92
                                                       rigidWater=rigidWater_value)
93
                validateConstraints(self, topology, system,
94
95
96
                                    constraints_value, rigidWater_value)

    def test_ImplicitSolvent(self):
97
        """Test the four types of implicit solvents using the implicitSolvent
98
99
100
        parameter.

        """
101
102

        topology = self.pdb2.topology
103
104
105
106
107
        system = self.forcefield2.createSystem(topology)
        forces = system.getForces()
        self.assertTrue(any(isinstance(f, GBSAOBCForce) for f in forces))

    def test_ImplicitSolventParameters(self):
108
        """Test that solventDielectric and soluteDielectric are passed correctly
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
        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)
126
        self.assertTrue(found_matching_solvent_dielectric and
127
128
                        found_matching_solute_dielectric)

129
130
    def test_HydrogenMass(self):
        """Test that altering the mass of hydrogens works correctly."""
131

132
133
134
135
136
137
138
139
140
141
142
        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))
                self.assertEqual(hydrogenMass, system2.getParticleMass(atom.index))
        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)
143

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

147
148
149
150
151
152
        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)
153
154
        with open('systems/lysozyme-implicit-forces.xml') as input:
            state2 = XmlSerializer.deserialize(input.read())
155
        numDifferences = 0
156
        for f1, f2, in zip(state1.getForces().value_in_unit(kilojoules_per_mole/nanometer), state2.getForces().value_in_unit(kilojoules_per_mole/nanometer)):
157
158
159
160
            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
161

162
163
    def test_ProgrammaticForceField(self):
        """Test building a ForceField programmatically."""
164

165
166
        # Build the ForceField for TIP3P programmatically.
        ff = ForceField()
167
168
        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})
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
        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)
        nonbonded = forcefield.NonbondedGenerator(ff, 0.833333, 0.5)
        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)
186

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

191
192
193
194
195
        # 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))
196

197
198
199
200
201
202
203
204
205
206
    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])
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

    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)
252

253
254
    def test_residueTemplateGenerator(self):
        """Test the ability to add residue template generators to parameterize unmatched residues."""
255
        def simpleTemplateGenerator(forcefield, residue):
256
257
258
259
260
261
262
            """\
            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.
263
264
            from uuid import uuid4
            template_name = uuid4()
265
            # Create residue template.
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
266
267
            from simtk.openmm.app.forcefield import _createResidueTemplate
            template = _createResidueTemplate(residue) # use helper function
268
            template.name = template_name # replace template name
269
            for (template_atom, residue_atom) in zip(template.atoms, residue.atoms()):
270
                template_atom.type = 'XXX' # replace atom type
271
            # Register the template.
272
            forcefield.registerResidueTemplate(template)
273
274
275
276
277
278
279

            # 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.
280
        simple_ffxml_contents = """
281
<ForceField>
282
283
284
285
286
287
288
289
290
291
292
293
 <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>
294
295
296
</ForceField>"""

        #
297
        # Test where we generate parameters for only a ligand.
298
299
300
301
302
        #

        # Load the PDB file.
        pdb = PDBFile(os.path.join('systems', 'T4-lysozyme-L99A-p-xylene-implicit.pdb'))
        # Create a ForceField object.
303
        forcefield = ForceField('amber99sb.xml', 'tip3p.xml', StringIO(simple_ffxml_contents))
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
        # 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.
325
            forcefield = ForceField(StringIO(simple_ffxml_contents))
326
327
328
329
330
331
332
333
            # 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.
334
        forcefield = ForceField(StringIO(simple_ffxml_contents))
335
336
337
338
339
340
341
342
343
        # 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?

344
345
346
347
348
349
350
351
352
353
354
355
    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
356
        self.assertEqual(unmatched_residues[0].id, '163')
357
358
359
360
361
362
363
364
365
366

        # 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
367
        self.assertEqual(unmatched_residues[0].chain.id, 'X')
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
368
        self.assertEqual(unmatched_residues[0].id, '1')
369

370
371
    def test_ggenerateTemplatesForUnmatchedResidues(self):
        """Test generation of blank forcefield residue templates for unmatched residues."""
372
373
374
375
376
377
378
379
380
381
        #
        # 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)
382
        [templates, residues] = forcefield.generateTemplatesForUnmatchedResidues(pdb.topology)
383
        # Check results.
384
        self.assertEqual(len(unmatched_residues), 24)
385
        self.assertEqual(len(residues), 2)
386
        self.assertEqual(len(templates), 2)
387
        unique_names = set([ residue.name for residue in residues ])
388
        self.assertTrue('HOH' not in unique_names)
389
390
        self.assertTrue('NA' in unique_names)
        self.assertTrue('CL' in unique_names)
391
392
393
394
        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)
395

396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
        # 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>"""

        #
416
        # Test the pre-geenration of missing residue template for a ligand.
417
418
419
420
421
422
423
        #

        # 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.
424
        [templates, residues] = forcefield.generateTemplatesForUnmatchedResidues(pdb.topology)
425
426
427
        # Add residue templates to forcefield.
        for template in templates:
            # Replace atom types.
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
428
429
            for atom in template.atoms:
                atom.type = 'XXX'
430
431
432
433
434
435
            # Register the template.
            forcefield.registerResidueTemplate(template)
        # Parameterize system.
        system = forcefield.createSystem(pdb.topology, nonbondedMethod=NoCutoff)
        # TODO: Test energies are finite?

436
437
438
439
440
441
442
443
444
445
    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
446
        residues = [ residue for residue in pdb.topology.residues() ]
447
        self.assertEqual(len(templates), len(residues))
jchodera's avatar
jchodera committed
448
449
450
        self.assertEqual(templates[0].name, 'NALA')
        self.assertEqual(templates[1].name, 'ALA')
        self.assertEqual(templates[2].name, 'CALA')
451

452
453
class AmoebaTestForceField(unittest.TestCase):
    """Test the ForceField.createSystem() method with the AMOEBA forcefield."""
454

455
    def setUp(self):
456
        """Set up the tests by loading the input pdb files and force field
457
458
459
460
461
        xml files.

        """

        self.pdb1 = PDBFile('systems/amoeba-ion-in-water.pdb')
462
        self.forcefield1 = ForceField('amoeba2013.xml')
463
464
465
466
467
468
        self.topology1 = self.pdb1.topology


    def test_NonbondedMethod(self):
        """Test all five options for the nonbondedMethod parameter."""

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
469
470
        methodMap = {NoCutoff:AmoebaMultipoleForce.NoCutoff,
                     PME:AmoebaMultipoleForce.PME}
471
472
473
474
475
476
477
478
479
480
481

        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
482
        cutoff_distance = 0.7*nanometer
483
484
485
        for method in [NoCutoff, PME]:
            system = self.forcefield1.createSystem(self.pdb1.topology,
                                                   nonbondedMethod=method,
486
                                                   nonbondedCutoff=cutoff_distance,
487
488
489
                                                   constraints=None)

            for force in system.getForces():
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
490
491
492
493
                if isinstance(force, AmoebaVdwForce):
                    self.assertEqual(force.getCutoff(), cutoff_distance)
                if isinstance(force, AmoebaMultipoleForce):
                    self.assertEqual(force.getCutoffDistance(), cutoff_distance)
494
495
496
497
498
499

    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
500
                                                   nonbondedMethod=PME,
501
502
503
                                                   useDispersionCorrection=useDispersionCorrection)

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

507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
    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)
522

523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
    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)
        context = Context(system, integrator)
        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)

ChayaSt's avatar
ChayaSt committed
539
540
    def test_LennardJones_generator(self):
        """ Test the LennardJones generator"""
ChayaSt's avatar
ChayaSt committed
541
        warnings.filterwarnings('ignore', category=CharmmPSFWarning)
ChayaSt's avatar
ChayaSt committed
542
543
544
545
546
547
        psf = CharmmPsfFile('systems/methanol_ions.psf')
        pdb = PDBFile('systems/methanol_ions.pdb')
        params = CharmmParameterSet('systems/top_all36_cgenff.rtf',
                                    'systems/par_all36_cgenff.prm',
                                    'systems/toppar_water_ions.str'
                                    )
ChayaSt's avatar
ChayaSt committed
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567

        # 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
        plat = Platform.getPlatformByName('Reference')
        system = psf.createSystem(params, nonbondedMethod=PME,
                                  nonbondedCutoff=5*angstroms)

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

        # Now set up stystem from ffxml. Setting chareges to 0 so we only test the Lennard-Jones energies
        xml = """
<ForceField>
 <AtomTypes>
ChayaSt's avatar
ChayaSt committed
568
569
570
571
  <Type name="CG331" class="CG331" element="C" mass="12.011"/>
  <Type name="OG311" class="OG311" element="O" mass="15.9994"/>
  <Type name="HGP1" class="HGP1" element="H" mass="1.008"/>
  <Type name="HGA3" class="HGA3" element="H" mass="1.008"/>
ChayaSt's avatar
ChayaSt committed
572
573
574
575
  <Type name="SOD" class="SOD" element="Na" mass="22.98977"/>
  <Type name="CLA" class="CLA" element="Cl" mass="35.45"/>
 </AtomTypes>
 <Residues>
ChayaSt's avatar
ChayaSt committed
576
577
578
579
580
581
582
583
584
585
586
587
588
  <Residue name="MEOH">
   <Atom name="CB" type="CG331" charge="0.0"/>
   <Atom name="OG" type="OG311" charge="0.0"/>
   <Atom name="HG1" type="HGP1" charge="0.0"/>
   <Atom name="HB1" type="HGA3" charge="0.0"/>
   <Atom name="HB2" type="HGA3" charge="0.0"/>
   <Atom name="HB3" type="HGA3" charge="0.0"/>
   <Bond atomName1="CB" atomName2="OG"/>
   <Bond atomName1="OG" atomName2="HG1"/>
   <Bond atomName1="CB" atomName2="HB1"/>
   <Bond atomName1="CB" atomName2="HB2"/>
   <Bond atomName1="CB" atomName2="HB3"/>
  </Residue>
ChayaSt's avatar
ChayaSt committed
589
  <Residue name="CLA">
ChayaSt's avatar
ChayaSt committed
590
   <Atom name="CLA" type="CLA" charge="0.0"/>
ChayaSt's avatar
ChayaSt committed
591
592
  </Residue>
  <Residue name="SOD">
ChayaSt's avatar
ChayaSt committed
593
   <Atom name="SOD" type="SOD" charge="0.0"/>
ChayaSt's avatar
ChayaSt committed
594
595
  </Residue>
 </Residues>
ChayaSt's avatar
ChayaSt committed
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
 <HarmonicBondForce>
  <Bond type1="CG331" type2="OG311" length="0.142" k="358150.4"/>
  <Bond type1="CG331" type2="HGA3" length="0.1111" k="269449.6"/>
  <Bond type1="OG311" type2="HGP1" length="0.096" k="456056.0"/>
 </HarmonicBondForce>
 <HarmonicAngleForce>
  <Angle type1="HGA3" type2="CG331" type3="HGA3" angle="1.89193690916" k="297.064"/>
  <Angle type1="CG331" type2="OG311" type3="HGP1" angle="1.85004900711" k="481.16"/>
  <Angle type1="OG311" type2="CG331" type3="HGA3" angle="1.9004890225" k="384.0912"/>
 </HarmonicAngleForce>
 <!-- Urey-Bradley terms -->
 <AmoebaUreyBradleyForce>
  <UreyBradley type1="HGA3" type2="CG331" type3="HGA3" d="0.1802" k="2259.36"/>
 </AmoebaUreyBradleyForce>
 <PeriodicTorsionForce>
  <Proper type1="HGA3" type2="CG331" type3="OG311" type4="HGP1" periodicity1="3" phase1="0.0" k1="0.75312"/>
 </PeriodicTorsionForce>
ChayaSt's avatar
ChayaSt committed
613
614
 <NonbondedForce coulomb14scale="1.0" lj14scale="1.0">
  <UseAttributeFromResidue name="charge"/>
ChayaSt's avatar
ChayaSt committed
615
616
617
618
  <Atom type="CG331" sigma="1.0" epsilon="0.0"/>
  <Atom type="OG311" sigma="1.0" epsilon="0.0"/>
  <Atom type="HGP1" sigma="1.0" epsilon="0.0"/>
  <Atom type="HGA3" sigma="1.0" epsilon="0.0"/>
ChayaSt's avatar
ChayaSt committed
619
620
  <Atom type="SOD" sigma="1.0" epsilon="0.0"/>
  <Atom type="CLA" sigma="1.0" epsilon="0.0"/>
ChayaSt's avatar
ChayaSt committed
621
 </NonbondedForce>
ChayaSt's avatar
ChayaSt committed
622
 <LennardJonesForce lj14scale="1.0">
ChayaSt's avatar
ChayaSt committed
623
624
625
626
  <Atom type="CG331" sigma="0.365268474438" epsilon="0.326352"/>
  <Atom type="OG311" sigma="0.314487247504" epsilon="0.8037464"/>
  <Atom type="HGP1" sigma="0.0400013524445" epsilon="0.192464"/>
  <Atom type="HGA3" sigma="0.238760856462" epsilon="0.100416"/>
ChayaSt's avatar
ChayaSt committed
627
628
  <Atom type="CLA" sigma="0.404468018036" epsilon="0.6276"/>
  <Atom type="SOD" sigma="0.251367073323" epsilon="0.1962296"/>
ChayaSt's avatar
ChayaSt committed
629
  <NBFixPair type1="CLA" type2="SOD" emin="0.350933" rmin="0.3731"/>
ChayaSt's avatar
ChayaSt committed
630
 </LennardJonesForce>
ChayaSt's avatar
ChayaSt committed
631
632
633
634
635
636
637
638
639
640
641
642
643
644
</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)


Rafal P. Wiewiora's avatar
tests  
Rafal P. Wiewiora committed
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
    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>"""

Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
661
        ff = ForceField(StringIO(xml))
Rafal P. Wiewiora's avatar
tests  
Rafal P. Wiewiora committed
662

Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
663
664
        self.assertEqual(len(ff._forces[0].proper), 1)
        self.assertEqual(len(ff._forces[0].improper), 1)
Rafal P. Wiewiora's avatar
tests  
Rafal P. Wiewiora committed
665
666
667
668
669
670
671
672
673
674
675
676
677
678

       # 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>"""

Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
679
        ff = ForceField(StringIO(xml))
Rafal P. Wiewiora's avatar
tests  
Rafal P. Wiewiora committed
680

Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
681
682
        self.assertEqual(len(ff._forces[0].proper), 1)
        self.assertEqual(len(ff._forces[0].improper), 1)
Rafal P. Wiewiora's avatar
tests  
Rafal P. Wiewiora committed
683

684
685
686
687
688
    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

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