TestModeller.py 46.1 KB
Newer Older
1
2
3
4
5
import unittest
from validateModeller import *
from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
6
7
8
9
if sys.version_info >= (3, 0):
    from io import StringIO
else:
    from cStringIO import StringIO
10
11
12
13
14
15
16
17

class TestModeller(unittest.TestCase):
    """ Test the Modeller class. """

    def setUp(self):
        # load the alanine dipeptide pdb file
        self.pdb = PDBFile('systems/alanine-dipeptide-explicit.pdb')
        self.topology_start = self.pdb.topology
jchodera's avatar
jchodera committed
18
        self.positions = self.pdb.positions
19
20
21
22
23
24
        self.forcefield = ForceField('amber10.xml', 'tip3p.xml')

        # load the T4-lysozyme-L99A receptor pdb file
        self.pdb2 = PDBFile('systems/lysozyme-implicit.pdb')
        self.topology_start2 = self.pdb2.topology
        self.positions2 = self.pdb2.positions
jchodera's avatar
jchodera committed
25

26
27
28
29
30
31
32
        # load the metallothionein pdb file
        self.pdb3 =  PDBFile('systems/1T2Y.pdb')
        self.topology_start3 = self.pdb3.topology
        self.positions3 = self.pdb3.positions

    def test_deleteWater(self):
        """ Test the deleteWater() method. """
jchodera's avatar
jchodera committed
33

34
35
36
37
        # build the chain dictionary
        chain_dict = {0:0}
        # 749 water chains are deleted
        chain_delta = -749
jchodera's avatar
jchodera committed
38

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
        # Build the residue and atom dictionaries for validate_preserved.
        # Also, count the number of deleted residues and atoms.
        residues_preserved = 0
        residue_delta = 0
        residue_dict = {}
        atoms_preserved = 0
        atom_delta = 0
        atom_dict = {}
        for residue in self.topology_start.residues():
            if residue.name!='HOH' and residue.name!='WAT':
                residue_dict[residue.index] = residues_preserved
                residues_preserved += 1
                for atom in residue.atoms():
                    atom_dict[atom.index] = atoms_preserved
                    atoms_preserved += 1
            else:
                residue_delta -= 1
                for atom in residue.atoms():
                    atom_delta -= 1
jchodera's avatar
jchodera committed
58

59
60
61
        modeller = Modeller(self.topology_start, self.positions)
        modeller.deleteWater()
        topology_after = modeller.getTopology()
jchodera's avatar
jchodera committed
62
63

        validate_preserved(self, self.topology_start, topology_after,
64
                           chain_dict, residue_dict, atom_dict)
jchodera's avatar
jchodera committed
65
        validate_deltas(self, self.topology_start, topology_after,
66
                         chain_delta, residue_delta, atom_delta)
jchodera's avatar
jchodera committed
67

68
69
    def test_delete(self):
        """ Test the delete() method. """
jchodera's avatar
jchodera committed
70

71
72
        modeller = Modeller(self.topology_start, self.positions)
        topology_before = modeller.getTopology()
jchodera's avatar
jchodera committed
73

74
75
76
77
        # Create the list of items to be deleted.
        # Start with the first 50 water chains
        chains = [chain for chain in topology_before.chains()]
        toDelete = chains[1:51]
jchodera's avatar
jchodera committed
78

79
80
81
        # Next add water residues 103->152 to the list of items to be deleted
        residues = [residue for residue in topology_before.residues()]
        toDelete.extend(residues[103:153])
jchodera's avatar
jchodera committed
82

83
84
85
        # Finally add water atoms 622->771 to the list of items to be deleted
        atoms = [atom for atom in topology_before.atoms()]
        toDelete.extend(atoms[622:772])
jchodera's avatar
jchodera committed
86

87
88
        modeller.delete(toDelete)
        topology_after = modeller.getTopology()
jchodera's avatar
jchodera committed
89

90
91
92
93
94
95
96
97
        # build the chain dictionary
        chain_dict = {0:0}
        for i in range(1,51):
            chain_dict[i+50] = i
        for i in range(51,101):
            chain_dict[i+100] = i
        for i in range(101, 600):
            chain_dict[i+150] = i
jchodera's avatar
jchodera committed
98

99
100
101
102
103
104
105
106
107
108
        # build the residue dictionary
        residue_dict = {}
        for i in range(3):
            residue_dict[i] = i
        for i in range(3,53):
            residue_dict[i+50] = i
        for i in range(53, 103):
            residue_dict[i+100] = i
        for i in range(103, 602):
            residue_dict[i+150] = i
jchodera's avatar
jchodera committed
109

110
111
112
113
114
115
116
117
118
119
        # build the atom dictionary
        atom_dict = {}
        for i in range(22):
            atom_dict[i] = i
        for i in range(22,172):
            atom_dict[i+150] = i
        for i in range(172,322):
            atom_dict[i+300] = i
        for i in range(322,1819):
            atom_dict[i+450] = i
jchodera's avatar
jchodera committed
120

121
        validate_preserved(self, topology_before, topology_after, chain_dict, residue_dict, atom_dict)
jchodera's avatar
jchodera committed
122

123
124
125
        chain_delta = -150
        residue_delta = -150
        atom_delta = -450
jchodera's avatar
jchodera committed
126

127
        validate_deltas(self, topology_before, topology_after, chain_delta, residue_delta, atom_delta)
jchodera's avatar
jchodera committed
128

129
130
    def test_add(self):
        """ Test the add() method. """
jchodera's avatar
jchodera committed
131

132
133
134
135
        # load the methanol-box pdb file
        pdb2 = PDBFile('systems/methanol-box.pdb')
        topology_toAdd = pdb2.topology
        positions_toAdd = pdb2.positions
jchodera's avatar
jchodera committed
136

137
138
139
        modeller = Modeller(self.topology_start, self.positions)
        modeller.deleteWater()
        topology_before = modeller.getTopology()
jchodera's avatar
jchodera committed
140

141
142
        modeller.add(topology_toAdd, positions_toAdd)
        topology_after = modeller.getTopology()
jchodera's avatar
jchodera committed
143

144
145
146
147
148
149
        # build the first chain dictionary for the first call of validate_preserved()
        chain_counter = 0
        chain_dict = {}
        for chain in topology_before.chains():
            chain_dict[chain.index] = chain_counter
            chain_counter += 1
jchodera's avatar
jchodera committed
150

151
152
153
154
155
156
157
158
159
160
161
        # build the residue and atom dictionaries for the first call of validate_preserved()
        residue_counter = 0
        residue_dict = {}
        atom_counter = 0
        atom_dict = {}
        for residue in topology_before.residues():
            residue_dict[residue.index] = residue_counter
            residue_counter += 1
            for atom in residue.atoms():
                atom_dict[atom.index] = atom_counter
                atom_counter += 1
jchodera's avatar
jchodera committed
162

163
164
        # Validate that the items from the before topology are preserved after addition of items.
        validate_preserved(self, topology_before, topology_after, chain_dict, residue_dict, atom_dict)
jchodera's avatar
jchodera committed
165

166
167
        # Next, we build another set of dictionaries to validate that the items added are
        # preserved.  Also, we calculate the number of chains, residues, and atoms added.
jchodera's avatar
jchodera committed
168

169
170
171
172
173
174
175
        # build the chain dictionary
        chain_delta = 0
        chain_dict = {}
        for chain in topology_toAdd.chains():
            chain_dict[chain.index] = chain_counter
            chain_counter += 1
            chain_delta += 1
jchodera's avatar
jchodera committed
176

177
178
179
180
181
182
183
184
185
186
187
188
189
        # build the residue and atom dictionaries for the second call of validate_preserved
        residue_delta = 0
        residue_dict = {}
        atom_delta = 0
        atom_dict = {}
        for residue in topology_toAdd.residues():
            residue_dict[residue.index] = residue_counter
            residue_counter += 1
            residue_delta += 1
            for atom in residue.atoms():
                atom_dict[atom.index] = atom_counter
                atom_counter += 1
                atom_delta += 1
jchodera's avatar
jchodera committed
190

191
192
193
194
        # validate that the items in the added topology are preserved
        validate_preserved(self, topology_toAdd, topology_after, chain_dict, residue_dict, atom_dict)
        # validate that the final topology has the correct number of items
        validate_deltas(self, topology_before, topology_after, chain_delta, residue_delta, atom_delta)
jchodera's avatar
jchodera committed
195

196
197
    def test_convertWater(self):
        """ Test the convertWater() method. """
jchodera's avatar
jchodera committed
198

199
200
201
202
203
        for model in ['tip3p', 'spce', 'tip4pew', 'tip5p']:
            if model == 'tip5p':
                firstmodel = 'tip4pew'
            else:
                firstmodel = 'tip5p'
jchodera's avatar
jchodera committed
204

205
206
207
208
            modeller = Modeller(self.topology_start, self.positions)
            modeller.convertWater(model=firstmodel)
            modeller.convertWater(model=model)
            topology_after = modeller.getTopology()
jchodera's avatar
jchodera committed
209

210
211
212
213
214
215
216
217
218
219
220
221
222
223
            for residue in topology_after.residues():
                if residue.name == "HOH":
                    oatom = [atom for atom in residue.atoms() if atom.element == element.oxygen]
                    hatoms = [atom for atom in residue.atoms() if atom.element == element.hydrogen]
                    matoms = [atom for atom in residue.atoms() if atom.name == 'M']
                    m1atoms = [atom for atom in residue.atoms() if atom.name == 'M1']
                    m2atoms = [atom for atom in residue.atoms() if atom.name == 'M2']
                    self.assertTrue(len(oatom)==1 and len(hatoms)==2)
                    if model=='tip3p' or model=='spce':
                        self.assertTrue(len(matoms)==0 and len(m1atoms)==0 and len(m2atoms)==0)
                    elif model=='tip4pew':
                        self.assertTrue(len(matoms)==1 and len(m1atoms)==0 and len(m2atoms)==0)
                    elif model=='tip5p':
                        self.assertTrue(len(matoms)==0 and len(m1atoms)==1 and len(m2atoms)==1)
jchodera's avatar
jchodera committed
224

225
226
227
228
229
230
231
                    # build the chain dictionary for validate_preserved
                    chain_counter = 0
                    chain_dict = {}
                    chain_delta = 0
                    for chain in self.topology_start.chains():
                        chain_dict[chain.index] = chain_counter
                        chain_counter += 1
jchodera's avatar
jchodera committed
232

233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
                    # build the residue and atom dictionaries for validate_preserved
                    residue_counter = 0
                    residue_dict = {}
                    residue_delta = 0
                    atom_counter = 0
                    atom_dict = {}
                    atom_delta = 0
                    for residue in self.topology_start.residues():
                        residue_dict[residue.index] = residue_counter
                        residue_counter += 1
                        for atom in residue.atoms():
                            atom_dict[atom.index] = atom_counter
                            atom_counter += 1
                        if residue.name == 'HOH' and model == 'tip4pew':
                            atom_counter += 1
                            atom_delta += 1
                        if residue.name == 'HOH' and model == 'tip5p':
                            atom_counter += 2
                            atom_delta += 2
jchodera's avatar
jchodera committed
252
253

            validate_preserved(self, self.topology_start, topology_after,
254
                               chain_dict, residue_dict, atom_dict)
jchodera's avatar
jchodera committed
255
256

            validate_deltas(self, self.topology_start, topology_after,
257
                            chain_delta, residue_delta, atom_delta)
jchodera's avatar
jchodera committed
258

259
260
    def test_addSolventWaterModels(self):
        """ Test all addSolvent() method with all possible water models. """
jchodera's avatar
jchodera committed
261

262
263
264
265
266
267
268
269
270
271
272
        topology_start = self.pdb.topology
        topology_start.setUnitCellDimensions(Vec3(3.5, 3.5, 3.5)*nanometers)
        for model in ['tip3p', 'spce', 'tip4pew', 'tip5p']:
            forcefield = ForceField('amber10.xml', model + '.xml')
            modeller = Modeller(topology_start, self.positions)
            # delete water to get the "before" topology
            modeller.deleteWater()
            topology_before = modeller.getTopology()
            # add the solvent to get the "after" topology
            modeller.addSolvent(forcefield, model=model)
            topology_after = modeller.getTopology()
jchodera's avatar
jchodera committed
273

274
            # First, check that everything that was there before has been preserved.
jchodera's avatar
jchodera committed
275

276
277
278
279
280
281
            # build the chain dictionary for validate_preserved
            chain_counter = 0
            chain_dict = {0:0}
            for chain in topology_before.chains():
                chain_dict[chain.index] = chain_counter
                chain_counter += 1
jchodera's avatar
jchodera committed
282

283
284
285
286
287
288
289
290
291
292
293
            # build the residue and atom dictionaries for validate_preserved
            residue_counter = 0
            residue_dict = {}
            atom_counter = 0
            atom_dict = {}
            for residue in topology_before.residues():
                residue_dict[residue.index] = residue_counter
                residue_counter += 1
                for atom in residue.atoms():
                    atom_dict[atom.index] = atom_counter
                    atom_counter += 1
jchodera's avatar
jchodera committed
294

295
296
            # validate that the items in the before topology remain after solvent is added
            validate_preserved(self, topology_before, topology_after, chain_dict, residue_dict, atom_dict)
jchodera's avatar
jchodera committed
297

298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
            # Make sure water that was added was the correct model
            for residue in topology_after.residues():
                if residue.name == 'HOH':
                    oatom = [atom for atom in residue.atoms() if atom.element == element.oxygen]
                    hatoms = [atom for atom in residue.atoms() if atom.element == element.hydrogen]
                    matoms = [atom for atom in residue.atoms() if atom.name == 'M']
                    m1atoms = [atom for atom in residue.atoms() if atom.name == 'M1']
                    m2atoms = [atom for atom in residue.atoms() if atom.name == 'M2']
                    self.assertTrue(len(oatom)==1 and len(hatoms)==2)
                    if model=='tip3p' or model=='spce':
                        self.assertTrue(len(matoms)==0 and len(m1atoms)==0 and len(m2atoms)==0)
                    elif model=='tip4pew':
                        self.assertTrue(len(matoms)==1 and len(m1atoms)==0 and len(m2atoms)==0)
                    elif model=='tip5p':
                        self.assertTrue(len(matoms)==0 and len(m1atoms)==1 and len(m2atoms)==1)
jchodera's avatar
jchodera committed
313

314
    def test_addSolventPeriodicBox(self):
315
        """ Test the addSolvent() method; test that the five ways of passing in the periodic box all work. """
jchodera's avatar
jchodera committed
316

317
        # First way of passing in periodic box vectors:  set it in the original topology.
318
319
320
321
322
323
        topology_start = self.pdb.topology
        topology_start.setUnitCellDimensions(Vec3(3.5, 4.5, 5.5)*nanometers)
        modeller = Modeller(topology_start, self.positions)
        modeller.deleteWater()
        modeller.addSolvent(self.forcefield)
        topology_after = modeller.getTopology()
324
        dim3 = topology_after.getPeriodicBoxVectors()
jchodera's avatar
jchodera committed
325

326
327
328
        self.assertVecAlmostEqual(dim3[0]/nanometers, Vec3(3.5, 0, 0))
        self.assertVecAlmostEqual(dim3[1]/nanometers, Vec3(0, 4.5, 0))
        self.assertVecAlmostEqual(dim3[2]/nanometers, Vec3(0, 0, 5.5))
jchodera's avatar
jchodera committed
329

330
        # Second way of passing in the periodic box vectors: with the boxSize parameter to addSolvent()
331
332
333
334
335
        topology_start = self.pdb.topology
        modeller = Modeller(topology_start, self.positions)
        modeller.deleteWater()
        modeller.addSolvent(self.forcefield, boxSize = Vec3(3.6, 4.6, 5.6)*nanometers)
        topology_after = modeller.getTopology()
336
        dim3 = topology_after.getPeriodicBoxVectors()
jchodera's avatar
jchodera committed
337

338
339
340
        self.assertVecAlmostEqual(dim3[0]/nanometers, Vec3(3.6, 0, 0))
        self.assertVecAlmostEqual(dim3[1]/nanometers, Vec3(0, 4.6, 0))
        self.assertVecAlmostEqual(dim3[2]/nanometers, Vec3(0, 0, 5.6))
jchodera's avatar
jchodera committed
341

342
343
344
345
346
347
348
        # Third way of passing in the periodic box vectors: with the boxVectors parameter to addSolvent()
        topology_start = self.pdb.topology
        modeller = Modeller(topology_start, self.positions)
        modeller.deleteWater()
        modeller.addSolvent(self.forcefield, boxVectors = (Vec3(3.4, 0, 0), Vec3(0.5, 4.4, 0), Vec3(-1.0, -1.5, 5.4))*nanometers)
        topology_after = modeller.getTopology()
        dim3 = topology_after.getPeriodicBoxVectors()
jchodera's avatar
jchodera committed
349

350
351
352
        self.assertVecAlmostEqual(dim3[0]/nanometers, Vec3(3.4, 0, 0))
        self.assertVecAlmostEqual(dim3[1]/nanometers, Vec3(0.5, 4.4, 0))
        self.assertVecAlmostEqual(dim3[2]/nanometers, Vec3(-1.0, -1.5, 5.4))
jchodera's avatar
jchodera committed
353

354
        # Fourth way of passing in the periodic box vectors: pass a 'padding' value to addSolvent()
355
356
357
358
359
        topology_start = self.pdb.topology
        modeller = Modeller(topology_start, self.positions)
        modeller.deleteWater()
        modeller.addSolvent(self.forcefield, padding = 1.0*nanometers)
        topology_after = modeller.getTopology()
360
        dim3 = topology_after.getPeriodicBoxVectors()
jchodera's avatar
jchodera committed
361

362
363
364
        self.assertVecAlmostEqual(dim3[0]/nanometers, Vec3(2.8802, 0, 0))
        self.assertVecAlmostEqual(dim3[1]/nanometers, Vec3(0, 2.8802, 0))
        self.assertVecAlmostEqual(dim3[2]/nanometers, Vec3(0, 0, 2.8802))
jchodera's avatar
jchodera committed
365

366
367
368
369
370
371
372
        # Fifth way: specify a number of molecules to add instead of a box size
        topology_start = self.pdb.topology
        modeller = Modeller(topology_start, self.positions)
        modeller.deleteWater()
        numInitial = len(list(modeller.topology.residues()))
        modeller.addSolvent(self.forcefield, numAdded=1000)
        self.assertEqual(numInitial+1000, len(list(modeller.topology.residues())))
373
374
375

    def test_addSolventNeutralSolvent(self):
        """ Test the addSolvent() method; test adding ions to neutral solvent. """
376

377
378
379
380
381
382
        topology_start = self.pdb.topology
        topology_start.setUnitCellDimensions(Vec3(3.5, 3.5, 3.5)*nanometers)
        modeller = Modeller(topology_start, self.positions)
        modeller.deleteWater()
        modeller.addSolvent(self.forcefield, ionicStrength = 2.0*molar)
        topology_after = modeller.getTopology()
383

384
385
386
387
388
389
390
391
392
393
        water_count=0
        sodium_count=0
        chlorine_count=0
        for residue in topology_after.residues():
            if residue.name=='HOH':
                water_count += 1
            elif residue.name=='NA':
                sodium_count += 1
            elif residue.name=='CL':
                chlorine_count += 1
394

395
396
397
        total_added = water_count+sodium_count+chlorine_count
        self.assertEqual(total_added, 1364)
        expected_ion_fraction = 2.0*molar/(55.4*molar)
jchodera's avatar
jchodera committed
398
        expected_ions = math.floor(total_added*expected_ion_fraction+0.5)
399
400
        self.assertEqual(sodium_count, expected_ions)
        self.assertEqual(chlorine_count, expected_ions)
401

402
403
    def test_addSolventNegativeSolvent(self):
        """ Test the addSolvent() method; test adding ions to a negatively charged solvent. """
404

405
406
        topology_start = self.pdb.topology
        topology_start.setUnitCellDimensions(Vec3(3.5, 3.5, 3.5)*nanometers)
407

408
409
410
411
        for neutralize in (True, False):
            # set up modeller with no solvent
            modeller = Modeller(topology_start, self.positions)
            modeller.deleteWater()
412

413
414
415
416
417
418
419
            # add 5 Cl- ions to the original topology
            topology_toAdd = Topology()
            newChain = topology_toAdd.addChain()
            for i in range(5):
                topology_toAdd.addResidue('CL',  newChain)
            residues = [residue for residue in topology_toAdd.residues()]
            for i in range(5):
jchodera's avatar
jchodera committed
420
                topology_toAdd.addAtom('Cl',Element.getBySymbol('Cl'), residues[i])
421
422
423
424
425
            positions_toAdd = [Vec3(1.0,1.2,1.5), Vec3(1.7,1.0,1.4), Vec3(1.5,2.0,1.0),
                               Vec3(2.0,2.0,2.0), Vec3(2.0,1.5,1.0)]*nanometers
            modeller.add(topology_toAdd, positions_toAdd)
            modeller.addSolvent(self.forcefield, ionicStrength=1.0*molar, neutralize=neutralize)
            topology_after = modeller.getTopology()
426

427
428
429
430
431
432
433
434
435
436
437
438
439
            water_count = 0
            sodium_count = 0
            chlorine_count = 0
            for residue in topology_after.residues():
                if residue.name=='HOH':
                    water_count += 1
                elif residue.name=='NA':
                    sodium_count += 1
                elif residue.name=='CL':
                    chlorine_count += 1

            total_water_ions = water_count+sodium_count+chlorine_count
            expected_ion_fraction = 1.0*molar/(55.4*molar)
jchodera's avatar
jchodera committed
440
            expected_chlorine = math.floor((total_water_ions-10)*expected_ion_fraction+0.5)+5
441
442
443
            expected_sodium = expected_chlorine if neutralize else expected_chlorine-5
            self.assertEqual(sodium_count, expected_sodium)
            self.assertEqual(chlorine_count, expected_chlorine)
444

445
446
    def test_addSolventPositiveSolvent(self):
        """ Test the addSolvent() method; test adding ions to a positively charged solvent. """
447

448
449
        topology_start = self.pdb.topology
        topology_start.setUnitCellDimensions(Vec3(3.5, 3.5, 3.5)*nanometers)
450

451
452
453
454
        for neutralize in (True, False):
            # set up modeller with no solvent
            modeller = Modeller(topology_start, self.positions)
            modeller.deleteWater()
455

456
457
458
459
460
461
462
            # add 5 Na+ ions to the original topology
            topology_toAdd = Topology()
            newChain = topology_toAdd.addChain()
            for i in range(5):
                topology_toAdd.addResidue('NA', newChain)
            residues = [residue for residue in topology_toAdd.residues()]
            for i in range(5):
jchodera's avatar
jchodera committed
463
                 topology_toAdd.addAtom('Na',Element.getBySymbol('Na'), residues[i])
464
465
            positions_toAdd = [Vec3(1.0,1.2,1.5), Vec3(1.7,1.0,1.4), Vec3(1.5,2.0,1.0),
                               Vec3(2.0,2.0,2.0), Vec3(2.0,1.5,1.0)]*nanometers
466

467
468
469
470
            # positions_toAdd doesn't need to change
            modeller.add(topology_toAdd, positions_toAdd)
            modeller.addSolvent(self.forcefield, ionicStrength=1.0*molar, neutralize=neutralize)
            topology_after = modeller.getTopology()
471

472
473
474
475
476
477
478
479
480
481
            water_count = 0
            sodium_count = 0
            chlorine_count = 0
            for residue in topology_after.residues():
                if residue.name=='HOH':
                    water_count += 1
                elif residue.name=='NA':
                    sodium_count += 1
                elif residue.name=='CL':
                    chlorine_count += 1
482

483
484
            total_water_ions = water_count+sodium_count+chlorine_count
            expected_ion_fraction = 1.0*molar/(55.4*molar)
jchodera's avatar
jchodera committed
485
            expected_sodium = math.floor((total_water_ions-10)*expected_ion_fraction+0.5)+5
486
487
488
            expected_chlorine = expected_sodium if neutralize else expected_sodium-5
            self.assertEqual(sodium_count, expected_sodium)
            self.assertEqual(chlorine_count, expected_chlorine)
489

490
491
    def test_addSolventIons(self):
        """ Test the addSolvent() method with all possible choices for positive and negative ions. """
jchodera's avatar
jchodera committed
492

493
494
        topology_start = self.pdb.topology
        topology_start.setUnitCellDimensions(Vec3(3.5, 3.5, 3.5)*nanometers)
495

496
497
498
499
500
        # set up modeller with no solvent
        modeller = Modeller(topology_start, self.positions)
        modeller.deleteWater()
        topology_nowater = modeller.getTopology()
        positions_nowater = modeller.getPositions()
501

502
        expected_ion_fraction = 1.0*molar/(55.4*molar)
jchodera's avatar
jchodera committed
503

504
505
506
507
508
        for positiveIon in ['Cs+', 'K+', 'Li+', 'Na+', 'Rb+']:
            ionName = positiveIon[:-1].upper()
            modeller = Modeller(topology_nowater, positions_nowater)
            modeller.addSolvent(self.forcefield, positiveIon=positiveIon, ionicStrength=1.0*molar)
            topology_after = modeller.getTopology()
509

jchodera's avatar
jchodera committed
510
            water_count = 0
511
512
513
514
            positive_ion_count = 0
            chlorine_count = 0
            for residue in topology_after.residues():
                if residue.name=='HOH':
jchodera's avatar
jchodera committed
515
                    water_count += 1
516
517
518
519
                elif residue.name==ionName:
                    positive_ion_count += 1
                elif residue.name=='CL':
                    chlorine_count += 1
520

521
522
            total_added = water_count+positive_ion_count+chlorine_count
            self.assertEqual(total_added, 1364)
jchodera's avatar
jchodera committed
523
            expected_ions = math.floor(total_added*expected_ion_fraction+0.5)
524
525
            self.assertEqual(positive_ion_count, expected_ions)
            self.assertEqual(chlorine_count, expected_ions)
526

527
528
529
530
        for negativeIon in ['Cl-', 'Br-', 'F-', 'I-']:
            ionName = negativeIon[:-1].upper()
            modeller = Modeller(topology_nowater, positions_nowater)
            modeller.addSolvent(self.forcefield, negativeIon=negativeIon, ionicStrength=1.0*molar)
531

532
            topology_after = modeller.getTopology()
533

534
            water_count = 0
jchodera's avatar
jchodera committed
535
            sodium_count = 0
536
537
538
539
540
541
542
543
            negative_ion_count = 0
            for residue in topology_after.residues():
                if residue.name=='HOH':
                    water_count += 1
                elif residue.name=='NA':
                    sodium_count += 1
                elif residue.name==ionName:
                    negative_ion_count += 1
jchodera's avatar
jchodera committed
544

545
546
            total_added = water_count+sodium_count+negative_ion_count
            self.assertEqual(total_added, 1364)
jchodera's avatar
jchodera committed
547
            expected_ions = math.floor(total_added*expected_ion_fraction+0.5)
548
549
            self.assertEqual(positive_ion_count, expected_ions)
            self.assertEqual(chlorine_count, expected_ions)
550

551
552
    def test_addHydrogensPdb2(self):
        """ Test the addHydrogens() method on the T4-lysozyme-L99A pdb file. """
jchodera's avatar
jchodera committed
553

554
555
556
557
        # build the Modeller
        topology_start = self.topology_start2
        positions = self.positions2
        modeller = Modeller(topology_start, positions)
558

559
560
561
        # remove hydrogens from the topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
562

563
564
565
566
567
568
569
        # Create a variants list to force the one histidine to be of the right variation.
        residues = [residue for residue in topology_start.residues()]
        variants = [None]*len(residues)
        # For this protein, when you add hydrogens, the hydrogen is added to the delta nitrogen.
        # By setting variants[30] to 'HIE', we force the hydrogen onto the epsilon nitrogen, so
        # that it will match the topology in topology_start.
        variants[30] = 'HIE'
570

571
572
573
        # add the hydrogens back
        modeller.addHydrogens(self.forcefield, variants=variants)
        topology_after = modeller.getTopology()
574

575
        validate_equivalence(self, topology_start, topology_after)
576

577
578
    def test_addHydrogensPdb3(self):
        """ Test the addHydrogens() method on the metallothionein pdb file. """
jchodera's avatar
jchodera committed
579

580
581
582
583
        # build the Modeller
        topology_start = self.topology_start3
        positions = self.positions3
        modeller = Modeller(topology_start, positions)
584

585
586
587
        # remove hydrogens from the topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
588

589
590
591
        # add the hydrogens back
        modeller.addHydrogens(self.forcefield)
        topology_after = modeller.getTopology()
592

593
        validate_equivalence(self, topology_start, topology_after)
594

595
596
    def test_addHydrogensASH(self):
        """ Test of addHydrogens() in which we force ASH to be a variant using the variants parameter. """
597

598
599
600
        # use the T4-lysozyme-L99A pdb file
        topology_start = self.topology_start2
        positions = self.positions2
601

602
603
        # build the Modeller
        modeller = Modeller(topology_start, positions)
604

605
606
607
        # remove hydrogens from the topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
608

609
610
611
612
613
614
615
        # Create a variants list to force the one histidine to be of the right variation.
        residues = [residue for residue in topology_start.residues()]
        variants = [None]*len(residues)
        # For this protein, when you add hydrogens, the hydrogen is added to the delta nitrogen.
        # By setting variants[30] to 'HIE', we force the hydrogen onto the epsilon nitrogen, so
        # that it will match the topology in topology_start.
        variants[30] = 'HIE'
616

617
618
619
        ASP_residue_list = [9,19,46,60,69,71,88,91,126,158]
        for residue_index in ASP_residue_list:
            variants[residue_index] = 'ASH'
620

621
622
623
        # add the hydrogens back, using the variants list we just built
        modeller.addHydrogens(self.forcefield, variants=variants)
        topology_ASH = modeller.getTopology()
624

625
626
627
628
629
630
631
632
633
634
        # There should be extra hydrogens on the ASP residues.  Assert that they exist,
        # then we delete them and validate that the topology matches what we started with.
        index_list_ASH = [176, 357, 761, 976, 1121, 1150, 1430, 1473, 2028, 2556]
        atoms = [atom for atom in topology_ASH.atoms()]
        toDelete2 = []
        for index in index_list_ASH:
            self.assertTrue(atoms[index].element.symbol=='H')
            toDelete2.append(atoms[index])
        modeller.delete(toDelete2)
        topology_ASP = modeller.getTopology()
635

636
        validate_equivalence(self, topology_ASP, topology_start)
637

638
639
    def test_addHydrogensCYX(self):
        """ Test of addHydrogens() in which we force CYX to be a variant using the variants parameter. """
640

641
642
643
        # use the metallothionein pdb file
        topology_start = self.topology_start3
        positions = self.positions3
644

645
646
        # build the Modeller
        modeller = Modeller(topology_start, positions)
647

648
649
650
        # remove hydrogens from the topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
651

652
653
654
655
656
657
        # Create a variants list to force the cysteins to be of the CYX variety.
        residues = [residue for residue in topology_start.residues()]
        variants = [None]*len(residues)
        CYS_residues = [2,4,10,12,16,18,21]
        for index in CYS_residues:
             variants[index] = 'CYX'
658

659
660
661
        # add the hydrogens
        modeller.addHydrogens(self.forcefield, variants=variants)
        topology_CYX = modeller.getTopology()
662

663
664
665
        # create a second modeller that we will attempt to match with topology_CYX
        modeller2 = Modeller(topology_start, positions)
        topology2 = modeller2.getTopology()
666

667
668
        # There should be extra hydrogens on the CYS residues.  Assert that they exist
        # on modeller2, then delete them and validate that the topologies match.
669

670
671
672
673
       # These are the indices of the hydrogens to delete from CYS to make CYX.
        index_list_CYS = [31, 49, 110, 135, 171, 193, 229]
        atoms = [atom for atom in topology2.atoms()]
        toDelete2 = []
jchodera's avatar
jchodera committed
674
        for index in index_list_CYS:
675
676
677
678
            self.assertTrue(atoms[index].element.symbol=='H')
            toDelete2.append(atoms[index])
        modeller2.delete(toDelete2)
        topology_after = modeller2.getTopology()
679

680
        validate_equivalence(self, topology_CYX, topology_after)
681

682
683
    def test_addHydrogensGLH(self):
        """ Test of addHydrogens() in which we force GLH to be a variant using the variants parameter. """
684

685
686
687
        # use the T4-lysozyme-L99A pdb file
        topology_start = self.topology_start2
        positions = self.positions2
688

689
690
        # build the Modeller
        modeller = Modeller(topology_start, positions)
691

692
        # remove hydrogens from the topology
jchodera's avatar
jchodera committed
693
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
694
        modeller.delete(toDelete)
695

696
697
698
699
700
701
702
        # Create a variants list to force the one histidine to be of the right variation.
        residues = [residue for residue in topology_start.residues()]
        variants = [None]*len(residues)
        # For this protein, when you add hydrogens, the hydrogen is added to the delta nitrogen.
        # By setting variants[30] to 'HIE', we force the hydrogen onto the epsilon nitrogen, so
        # that it will match the topology in topology_start.
        variants[30] = 'HIE'
703

704
705
706
        GLU_residue_list = [4,10,21,44,61,63,107,127]
        for residue_index in GLU_residue_list:
            variants[residue_index] = 'GLH'
707

708
709
710
        # add the hydrogens back, this time with the GLH variant in place of GLU
        modeller.addHydrogens(self.forcefield, variants=variants)
        topology_GLH = modeller.getTopology()
711

jchodera's avatar
jchodera committed
712
        # There should be extra hydrogens on the GLU residues.  Assert that they exist,
713
714
715
716
717
        # then we delete them and validate that the topology matches what we started with.
        index_list_GLH = [85, 192, 387, 731, 992, 1018, 1718, 2042]
        atoms = [atom for atom in topology_GLH.atoms()]
        toDelete2 = []
        for index in index_list_GLH:
jchodera's avatar
jchodera committed
718
            self.assertTrue(atoms[index].element.symbol=='H')
719
720
721
            toDelete2.append(atoms[index])
        modeller.delete(toDelete2)
        topology_GLU = modeller.getTopology()
722

723
        validate_equivalence(self, topology_GLU, topology_start)
724

725
726
    def test_addHydrogensLYN(self):
        """ Test of addHydrogens() in which we force LYN to be a variant using the variants parameter. """
727

728
729
730
        # use the T4-lysozyme-L99A pdb file
        topology_start = self.topology_start2
        positions = self.positions2
731

732
733
        # build the Modeller
        modeller = Modeller(topology_start, positions)
734

735
736
737
        # remove hydrogens from topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
738

739
740
741
742
743
744
745
        # Create a variants list to force the one histidine to be of the right variation.
        residues = [residue for residue in topology_start.residues()]
        variants = [None]*len(residues)
        # For this protein, when you add hydrogens, the hydrogen is added to the delta nitrogen.
        # By setting variants[30] to 'HIE', we force the hydrogen onto the epsilon nitrogen, so
        # that it will match the topology in topology_start.
        variants[30] = 'HIE'
746

747
748
749
750
751
752
        # Here we add the residues in which LYS is present to the variant list.  The final
        # LYS residue, 161, is not on the list because Amber force fields do not have an
        # entry for a terminal LYN residue.
        residue_list_LYS = [15,18,34,42,47,59,64,82,84,123,134,146]
        for residue_index in residue_list_LYS:
            variants[residue_index] = 'LYN'
753

754
755
        # add the hydrogens back, using the variants list we just built
        modeller.addHydrogens(self.forcefield, variants=variants)
756

757
        topology_LYN = modeller.getTopology()
758

759
760
        # create a second modeller that we will attempt to match with topology_LYN
        modeller2 = Modeller(topology_start, positions)
761

762
763
        # There should be extra hydrogens on the LYS residues.  Assert that they exist
        # on modeller2, then delete them and validate that the topologies match.
764

765
766
767
768
769
770
771
772
773
        # These are the indices of the hydrogens to delete from LYN to make LYS.
        index_list_LYN = [281,343,590,701,780,960,1034,1319,1360,1959,2135,2344]
        atoms = [atom for atom in topology_start.atoms()]
        toDelete2 = []
        for index in index_list_LYN:
             self.assertTrue(atoms[index].element.symbol=='H')
             toDelete2.append(atoms[index])
        modeller2.delete(toDelete2)
        topology_after = modeller2.getTopology()
774

775
        validate_equivalence(self, topology_LYN, topology_after)
776

777
778
    def test_addHydrogenspH4(self):
        """ Test of addHydrogens() with pH=4. """
779

780
781
782
        # use the T4-lysozyme-L99A pdb file
        topology_start = self.topology_start2
        positions = self.positions2
783

784
785
        # build the Modeller
        modeller = Modeller(topology_start, positions)
786

787
788
789
        # remove hydrogens from the topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
790

791
792
793
794
795
796
797
        # Create a variants list to force the one histidine to be of the right variation.
        residues = [residue for residue in topology_start.residues()]
        variants = [None]*len(residues)
        # For this protein, when you add hydrogens, the hydrogen is added to the delta nitrogen.
        # By setting variants[30] to 'HIE', we force the hydrogen onto the epsilon nitrogen, so
        # that it will match the topology in topology_start.
        variants[30] = 'HIE'
798

799
800
        # add the hydrogens back, this time at a lower pH
        modeller.addHydrogens(self.forcefield, variants=variants, pH=4.0)
801

802
        topology_ASH_GLH = modeller.getTopology()
803

804
805
806
807
808
809
810
811
812
813
        # There should be extra hydrogens on the ASP and GLU residues.  Assert that they exist,
        # then we delete them and validate that the topology matches what we started with.
        index_list_ASH = [177, 359, 765, 980, 1127, 1156, 1436, 1479, 2035, 2564]
        index_list_GLH = [85, 193, 389, 733, 996, 1022, 1726, 2051]
        atoms = [atom for atom in topology_ASH_GLH.atoms()]
        toDelete2 = []
        for index in index_list_ASH:
            self.assertTrue(atoms[index].element.symbol=='H')
            toDelete2.append(atoms[index])
        for index in index_list_GLH:
jchodera's avatar
jchodera committed
814
            self.assertTrue(atoms[index].element.symbol=='H')
815
816
817
            toDelete2.append(atoms[index])
        modeller.delete(toDelete2)
        topology_ASP_GLU = modeller.getTopology()
818

819
        validate_equivalence(self, topology_ASP_GLU, topology_start)
820

821
822
    def test_addHydrogenspH9(self):
        """ Test of addHydrogens() with pH=9. """
823

824
825
826
        # use the metallothionein pdb file
        topology_start = self.topology_start3
        positions = self.positions3
827

828
829
        # build the Modeller
        modeller = Modeller(topology_start, positions)
830

831
832
833
        # remove hydrogens from topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
834

835
836
837
        # add hydrogens with pH=9, so that the variation CYX will be chosen
        modeller.addHydrogens(self.forcefield, pH=9.0)
        topology_CYX = modeller.getTopology()
838

839
840
841
        # create a second modeller that we will attempt to match with topology_CYX
        modeller2 = Modeller(topology_start, positions)
        topology2 = modeller2.getTopology()
842

843
844
        # There should be extra hydrogens on the CYS residues.  Assert that they exist
        # on modeller2, then delete them and validate that the topologies match.
845

846
847
848
849
        # These are the indices of the hydrogens to delete from CYS to make CYX.
        index_list_CYS = [31, 49, 110, 135, 171, 193, 229]
        atoms = [atom for atom in topology2.atoms()]
        toDelete2 = []
jchodera's avatar
jchodera committed
850
        for index in index_list_CYS:
851
852
853
854
            self.assertTrue(atoms[index].element.symbol=='H')
            toDelete2.append(atoms[index])
        modeller2.delete(toDelete2)
        topology_after = modeller2.getTopology()
855

jchodera's avatar
jchodera committed
856
        validate_equivalence(self, topology_CYX, topology_after)
857

858
859
    def test_addHydrogenspH11(self):
        """ Test of addHydrogens() with pH=11. """
860

861
862
863
        # use the T4-lysozyme-L99A pdb file
        topology_start = self.topology_start2
        positions = self.positions2
864

865
866
        # build the Modeller
        modeller = Modeller(topology_start, positions)
867

868
869
870
        # remove hydrogens from topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
871

872
        # Create a variants list to force the one histidine to be of the right variation.
jchodera's avatar
jchodera committed
873
        residues = [residue for residue in topology_start.residues()]
874
875
876
877
878
        variants = [None]*len(residues)
        # For this protein, when you add hydrogens, the hydrogen is added to the delta nitrogen.
        # By setting variants[30] to 'HIE', we force the hydrogen onto the epsilon nitrogen, so
        # that it will match the topology in topology_start.
        variants[30] = 'HIE'
879

880
881
882
        # The Amber force fields do not have an entry for terminal LYN residues, so we need to
        # force residue 161 to be the LYS variant.
        variants[161] = 'LYS'
883

884
885
886
        # add the hydrogens back at pH = 11
        modeller.addHydrogens(self.forcefield, variants=variants, pH=11.0)
        topology_LYN = modeller.getTopology()
887

888
889
        # create a second modeller that we will attempt to match with topology_LYN
        modeller2 = Modeller(topology_start, positions)
890

891
892
893
894
895
896
897
898
        # There should be extra hydrogens on the LYS residues.  Assert that they exist
        # on modeller2, then delete them and validate that the topologies match.
        index_list_LYN = [281,343,590,701,780,960,1034,1319,1360,1959,2135,2344]
        atoms = [atom for atom in topology_start.atoms()]
        toDelete2 = []
        for index in index_list_LYN:
            self.assertTrue(atoms[index].element.symbol=='H')
            toDelete2.append(atoms[index])
899

900
901
        modeller2.delete(toDelete2)
        topology_after = modeller2.getTopology()
902

903
        validate_equivalence(self, topology_LYN, topology_after)
904
905


Peter Eastman's avatar
Peter Eastman committed
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
    def test_removeExtraHydrogens(self):
        """Test that addHydrogens() can remove hydrogens that shouldn't be there. """

        topology_start = self.topology_start3
        positions = self.positions3
        modeller = Modeller(topology_start, positions)

        # Add hydrogens, forcing residue 1 to be ASH.

        variants = [None]*25
        variants[1] = 'ASH'
        modeller.addHydrogens(self.forcefield, variants=variants)
        residue = list(modeller.topology.residues())[1]
        self.assertTrue(any(a.name == 'HD2' for a in residue.atoms()))

        # Now force it to be ASP and see if HD2 gets removed.

        variants[1] = 'ASP'
        modeller.addHydrogens(self.forcefield, variants=variants)
        residue = list(modeller.topology.residues())[1]
        self.assertFalse(any(a.name == 'HD2' for a in residue.atoms()))


929
930
    def test_addExtraParticles(self):
        """Test addExtraParticles()."""
931

932
        # Create a box of water.
933

934
935
936
        ff1 = ForceField('tip3p.xml')
        modeller = Modeller(Topology(), []*nanometers)
        modeller.addSolvent(ff1, 'tip3p', boxSize=Vec3(2,2,2)*nanometers)
937

938
        # Now convert the water to TIP4P.
939

940
941
942
943
944
945
946
947
948
        ff2 = ForceField('tip4pew.xml')
        modeller.addExtraParticles(ff2)
        for residue in modeller.topology.residues():
            atoms = list(residue.atoms())
            self.assertEqual(4, len(atoms))
            ep = [atom for atom in atoms if atom.element is None]
            self.assertEqual(1, len(ep))


949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
    def test_addVirtualSites(self):
        """Test adding extra particles defined by virtual sites."""
        xml = """
            <ForceField>
             <AtomTypes>
              <Type name="C" class="C" element="C" mass="10"/>
              <Type name="N" class="N" element="N" mass="10"/>
              <Type name="O" class="O" element="O" mass="10"/>
              <Type name="V" class="V" mass="0.0"/>
             </AtomTypes>
             <Residues>
              <Residue name="Test">
               <Atom name="C" type="C"/>
               <Atom name="N" type="N"/>
               <Atom name="O" type="O"/>
               <Atom name="V1" type="V"/>
               <Atom name="V2" type="V"/>
               <Atom name="V3" type="V"/>
               <Atom name="V4" type="V"/>
               <VirtualSite type="average2" index="3" atom1="0" atom2="1" weight1="0.7" weight2="0.3"/>
               <VirtualSite type="average3" index="4" atom1="0" atom2="1" atom3="2" weight1="0.2" weight2="0.3" weight3="0.5"/>
               <VirtualSite type="outOfPlane" index="5" atom1="0" atom2="1" atom3="2" weight12="0.1" weight13="-0.2" weightCross="0.8"/>
               <VirtualSite type="localCoords" index="6" atom1="0" atom2="1" atom3="2" wo1="0.1" wo2="0.5" wo3="0.4" wx1="1" wx2="-0.6" wx3="-0.4" wy1="0.1" wy2="0.9" wy3="-1" p1="-0.5" p2="0.4" p3="1.1"/>
              </Residue>
             </Residues>
            </ForceField>"""
        ff = ForceField(StringIO(xml))

        # Create the three real atoms.

        topology = Topology()
        chain = topology.addChain()
        residue = topology.addResidue('Test', chain)
        topology.addAtom('C', element.carbon, residue)
        topology.addAtom('N', element.nitrogen, residue)
        topology.addAtom('V', element.oxygen, residue)
jchodera's avatar
jchodera committed
985

986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011

        # Add the virtual sites.

        modeller = Modeller(topology, [Vec3(0.1, 0.2, 0.3), Vec3(1.0, 0.9, 0.8), Vec3(1.5, 1.1, 0.7)]*nanometers)
        modeller.addExtraParticles(ff)
        top = modeller.topology
        pos = modeller.positions

        # Check that the correct particles were added.

        self.assertEqual(len(pos), 7)
        for atom, elem in zip(top.atoms(), [element.carbon, element.nitrogen, element.oxygen, None, None, None, None]):
            self.assertEqual(elem, atom.element)

        # Check that the positions were calculated correctly.

        system = ff.createSystem(top)
        integ = VerletIntegrator(1.0)
        context = Context(system, integ)
        context.setPositions(pos)
        context.computeVirtualSites()
        state = context.getState(getPositions=True)
        for p1, p2 in zip (pos, state.getPositions()):
            self.assertVecAlmostEqual(p1.value_in_unit(nanometers), p2.value_in_unit(nanometers), 1e-6)


1012
1013
1014
    def test_multiSiteIon(self):
        """Test adding extra particles whose positions are determined based on bonds."""
        xml = """
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
            <ForceField>
             <AtomTypes>
              <Type name="Zn" class="Zn" element="Zn" mass="53.380"/>
              <Type name="DA" class="DA" mass="3.0"/>
             </AtomTypes>
             <Residues>
              <Residue name="ZN">
               <Atom name="ZN" type="Zn"/>
               <Atom name="D1" type="DA"/>
               <Atom name="D2" type="DA"/>
               <Atom name="D3" type="DA"/>
               <Atom name="D4" type="DA"/>
               <Bond from="0" to="2"/>
               <Bond from="0" to="1"/>
               <Bond from="0" to="3"/>
               <Bond from="0" to="4"/>
               <Bond from="1" to="2"/>
               <Bond from="1" to="3"/>
               <Bond from="1" to="4"/>
               <Bond from="2" to="4"/>
               <Bond from="2" to="3"/>
               <Bond from="3" to="4"/>
              </Residue>
             </Residues>
             <HarmonicBondForce>
              <Bond class1="DA" class2="Zn" length="0.09" k="535552.0"/>
              <Bond class1="DA" class2="DA" length="0.147" k="535552.0"/>
             </HarmonicBondForce>
            </ForceField>"""
1044
1045
        ff = ForceField(StringIO(xml))

Peter Eastman's avatar
Bug fix  
Peter Eastman committed
1046
        # Create two zinc atoms.
1047
1048
1049
1050
1051

        topology = Topology()
        chain = topology.addChain()
        residue = topology.addResidue('ZN', chain)
        topology.addAtom('ZN', element.zinc, residue)
Peter Eastman's avatar
Bug fix  
Peter Eastman committed
1052
1053
        residue = topology.addResidue('ZN', chain)
        topology.addAtom('ZN', element.zinc, residue)
1054
1055
1056

        # Add the extra particles.

Peter Eastman's avatar
Bug fix  
Peter Eastman committed
1057
        modeller = Modeller(topology, [Vec3(0.5, 1.0, 1.5), Vec3(2.0, 2.0, 0.0)]*nanometers)
1058
1059
1060
1061
1062
1063
        modeller.addExtraParticles(ff)
        top = modeller.topology
        pos = modeller.positions

        # Check that the correct particles were added.

Peter Eastman's avatar
Bug fix  
Peter Eastman committed
1064
        self.assertEqual(len(pos), 10)
1065
        for i, atom in enumerate(top.atoms()):
Peter Eastman's avatar
Bug fix  
Peter Eastman committed
1066
            self.assertEqual(element.zinc if i in (0,5) else None, atom.element)
1067

Peter Eastman's avatar
Bug fix  
Peter Eastman committed
1068
        # Check that the positions in the first residue are reasonable.
1069
1070
1071
1072
1073
1074
1075
1076
1077

        center = Vec3(0.5, 1.0, 1.5)*nanometers
        self.assertEqual(center, modeller.positions[0])
        for i in range(1, 5):
            for j in range(i):
                dist = norm(pos[i]-pos[j])
                expectedDist = 0.09 if j == 0 else 0.147
                self.assertTrue(dist > (expectedDist-0.01)*nanometers and dist < (expectedDist+0.01)*nanometers)

1078
1079
1080
1081
1082
1083
    def assertVecAlmostEqual(self, p1, p2, tol=1e-7):
        scale = max(1.0, norm(p1),)
        for i in range(3):
            diff = abs(p1[i]-p2[i])/scale
            self.assertTrue(diff < tol)

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