TestModeller.py 47.2 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 *
peastman's avatar
peastman committed
6
from collections import defaultdict
7
8
9
10
if sys.version_info >= (3, 0):
    from io import StringIO
else:
    from cStringIO import StringIO
11
12
13
14
15
16
17
18

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
19
        self.positions = self.pdb.positions
20
21
22
23
24
25
        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
26

27
28
29
30
31
32
33
        # 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
34

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

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
        # 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
59

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

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

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

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

75
76
77
78
        # 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
79

80
81
82
        # 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
83

84
85
86
        # 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
87

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

91
92
93
94
95
96
97
98
        # 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
99

100
101
102
103
104
105
106
107
108
109
        # 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
110

111
112
113
114
115
116
117
118
119
120
        # 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
121

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

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

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

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

133
134
135
136
        # 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
137

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

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

145
146
147
148
149
150
        # 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
151

152
153
154
155
156
157
158
159
160
161
162
        # 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
163

164
165
        # 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
166

167
168
        # 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
169

170
171
172
173
174
175
176
        # 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
177

178
179
180
181
182
183
184
185
186
187
188
189
190
        # 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
191

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

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

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

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

211
212
213
214
215
216
217
218
219
220
221
222
223
224
            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
225

226
227
228
229
230
231
232
                    # 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
233

234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
                    # 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
253
254

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

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

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

263
264
265
266
267
268
269
270
271
272
273
        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
274

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

277
278
279
280
281
282
            # 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
283

284
285
286
287
288
289
290
291
292
293
294
            # 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
295

296
297
            # 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
298

299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
            # 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
314

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

318
        # First way of passing in periodic box vectors:  set it in the original topology.
319
320
321
322
323
324
        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()
325
        dim3 = topology_after.getPeriodicBoxVectors()
jchodera's avatar
jchodera committed
326

327
328
329
        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
330

331
        # Second way of passing in the periodic box vectors: with the boxSize parameter to addSolvent()
332
333
334
335
336
        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()
337
        dim3 = topology_after.getPeriodicBoxVectors()
jchodera's avatar
jchodera committed
338

339
340
341
        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
342

343
344
345
346
347
348
349
        # 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
350

351
352
353
        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
354

355
        # Fourth way of passing in the periodic box vectors: pass a 'padding' value to addSolvent()
356
357
358
359
360
        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()
361
        dim3 = topology_after.getPeriodicBoxVectors()
jchodera's avatar
jchodera committed
362

363
364
365
        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
366

367
368
369
370
371
372
373
        # 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())))
374
375
376

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

378
379
380
381
382
383
        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()
384

385
386
387
388
389
390
391
392
393
394
        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
395

396
397
398
        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
399
        expected_ions = math.floor(total_added*expected_ion_fraction+0.5)
400
401
        self.assertEqual(sodium_count, expected_ions)
        self.assertEqual(chlorine_count, expected_ions)
402

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

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

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

414
415
416
417
418
419
420
            # 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
421
                topology_toAdd.addAtom('Cl',Element.getBySymbol('Cl'), residues[i])
422
423
424
425
426
            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()
427

428
429
430
431
432
433
434
435
436
437
438
439
440
            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
441
            expected_chlorine = math.floor((total_water_ions-10)*expected_ion_fraction+0.5)+5
442
443
444
            expected_sodium = expected_chlorine if neutralize else expected_chlorine-5
            self.assertEqual(sodium_count, expected_sodium)
            self.assertEqual(chlorine_count, expected_chlorine)
445

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

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

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

457
458
459
460
461
462
463
            # 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
464
                 topology_toAdd.addAtom('Na',Element.getBySymbol('Na'), residues[i])
465
466
            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
467

468
469
470
471
            # 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()
472

473
474
475
476
477
478
479
480
481
482
            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
483

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

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

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

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

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

505
506
507
508
509
        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()
510

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

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

528
529
530
531
        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)
532

533
            topology_after = modeller.getTopology()
534

535
            water_count = 0
jchodera's avatar
jchodera committed
536
            sodium_count = 0
537
538
539
540
541
542
543
544
            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
545

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

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

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

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

564
565
566
567
568
569
570
        # 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'
571

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

576
        validate_equivalence(self, topology_start, topology_after)
577

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

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

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

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

594
        validate_equivalence(self, topology_start, topology_after)
595

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

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

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

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

610
611
612
613
614
615
616
        # 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'
617

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

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

626
627
628
629
630
631
632
633
634
635
        # 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()
636

637
        validate_equivalence(self, topology_ASP, topology_start)
638

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

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

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

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

653
654
655
656
657
658
        # 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'
659

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

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

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

671
672
673
674
       # 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
675
        for index in index_list_CYS:
676
677
678
679
            self.assertTrue(atoms[index].element.symbol=='H')
            toDelete2.append(atoms[index])
        modeller2.delete(toDelete2)
        topology_after = modeller2.getTopology()
680

681
        validate_equivalence(self, topology_CYX, topology_after)
682

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

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

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

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

697
698
699
700
701
702
703
        # 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'
704

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

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

jchodera's avatar
jchodera committed
713
        # There should be extra hydrogens on the GLU residues.  Assert that they exist,
714
715
716
717
718
        # 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
719
            self.assertTrue(atoms[index].element.symbol=='H')
720
721
722
            toDelete2.append(atoms[index])
        modeller.delete(toDelete2)
        topology_GLU = modeller.getTopology()
723

724
        validate_equivalence(self, topology_GLU, topology_start)
725

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

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

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

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

740
741
742
743
744
745
746
        # 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'
747

748
749
750
751
752
753
        # 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'
754

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

758
        topology_LYN = modeller.getTopology()
759

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

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

766
767
768
769
770
771
772
773
774
        # 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()
775

776
        validate_equivalence(self, topology_LYN, topology_after)
777

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

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

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

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

792
793
794
795
796
797
798
        # 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'
799

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

803
        topology_ASH_GLH = modeller.getTopology()
804

805
806
807
808
809
810
811
812
813
814
        # 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
815
            self.assertTrue(atoms[index].element.symbol=='H')
816
817
818
            toDelete2.append(atoms[index])
        modeller.delete(toDelete2)
        topology_ASP_GLU = modeller.getTopology()
819

820
        validate_equivalence(self, topology_ASP_GLU, topology_start)
821

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

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

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

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

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

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

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

847
848
849
850
        # 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
851
        for index in index_list_CYS:
852
853
854
855
            self.assertTrue(atoms[index].element.symbol=='H')
            toDelete2.append(atoms[index])
        modeller2.delete(toDelete2)
        topology_after = modeller2.getTopology()
856

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

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

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

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

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

873
        # Create a variants list to force the one histidine to be of the right variation.
jchodera's avatar
jchodera committed
874
        residues = [residue for residue in topology_start.residues()]
875
876
877
878
879
        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'
880

881
882
883
        # 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'
884

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

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

892
893
894
895
896
897
898
899
        # 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])
900

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

904
        validate_equivalence(self, topology_LYN, topology_after)
905
906


Peter Eastman's avatar
Peter Eastman committed
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
    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()))


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

933
        # Create a box of water.
934

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

939
        # Now convert the water to TIP4P.
940

941
942
943
944
945
946
947
948
949
        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))


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
985
    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
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
1012

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


1013
1014
1015
    def test_multiSiteIon(self):
        """Test adding extra particles whose positions are determined based on bonds."""
        xml = """
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
1044
            <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>"""
1045
1046
        ff = ForceField(StringIO(xml))

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

        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
1053
1054
        residue = topology.addResidue('ZN', chain)
        topology.addAtom('ZN', element.zinc, residue)
1055
1056
1057

        # Add the extra particles.

Peter Eastman's avatar
Bug fix  
Peter Eastman committed
1058
        modeller = Modeller(topology, [Vec3(0.5, 1.0, 1.5), Vec3(2.0, 2.0, 0.0)]*nanometers)
1059
1060
1061
1062
1063
1064
        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
1065
        self.assertEqual(len(pos), 10)
1066
        for i, atom in enumerate(top.atoms()):
Peter Eastman's avatar
Bug fix  
Peter Eastman committed
1067
            self.assertEqual(element.zinc if i in (0,5) else None, atom.element)
1068

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

        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)

peastman's avatar
peastman committed
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103

    def test_addMembrane(self):
        """Test adding a membrane."""
        pdb = PDBFile('systems/alanine-dipeptide-implicit.pdb')
        modeller = Modeller(pdb.topology, pdb.positions)
        ff = ForceField('amber14-all.xml', 'amber14/tip3p.xml')

        # Add a membrane around alanine dipeptide???  I know, it's a silly thing to do,
        # but it's fast, and all we care about is whether it works!

        modeller.addMembrane(ff, minimumPadding=0.5*nanometers, ionicStrength=1*molar)
        resCount = defaultdict(int)
        for res in modeller.topology.residues():
            resCount[res.name] += 1
        self.assertTrue(resCount['POP'] > 1)
        self.assertTrue(resCount['HOH'] > 1)
        self.assertTrue(resCount['CL'] > 1)
        self.assertEqual(resCount['CL'], resCount['NA'])
        self.assertEqual(1, resCount['ALA'])
        originalSize = max(pdb.positions) - min(pdb.positions)
        newSize = modeller.topology.getUnitCellDimensions()
        for i in range(3):
            self.assertTrue(newSize[i] >= originalSize[i]+0.5*nanometers)


1104
1105
1106
1107
1108
1109
    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)

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