TestModeller.py 40.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import unittest
from validateModeller import *
from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *

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
        self.positions = self.pdb.positions       
        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
        
        # 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. """
    
        # build the chain dictionary
        chain_dict = {0:0}
        # 749 water chains are deleted
        chain_delta = -749
    
        # 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
    
        modeller = Modeller(self.topology_start, self.positions)
        modeller.deleteWater()
        topology_after = modeller.getTopology()
    
        validate_preserved(self, self.topology_start, topology_after, 
                           chain_dict, residue_dict, atom_dict)
        validate_deltas(self, self.topology_start, topology_after, 
                         chain_delta, residue_delta, atom_delta)
    
    def test_delete(self):
        """ Test the delete() method. """
    
        modeller = Modeller(self.topology_start, self.positions)
        topology_before = modeller.getTopology()
    
        # 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]
    
        # 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])
    
        # 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])
    
        modeller.delete(toDelete)
        topology_after = modeller.getTopology()
    
        # 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
    
        # 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
    
        # 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
    
        validate_preserved(self, topology_before, topology_after, chain_dict, residue_dict, atom_dict)
    
        chain_delta = -150
        residue_delta = -150
        atom_delta = -450
    
        validate_deltas(self, topology_before, topology_after, chain_delta, residue_delta, atom_delta)
    
    def test_add(self):
        """ Test the add() method. """
    
        # load the methanol-box pdb file
        pdb2 = PDBFile('systems/methanol-box.pdb')
        topology_toAdd = pdb2.topology
        positions_toAdd = pdb2.positions
    
        modeller = Modeller(self.topology_start, self.positions)
        modeller.deleteWater()
        topology_before = modeller.getTopology()
    
        modeller.add(topology_toAdd, positions_toAdd)
        topology_after = modeller.getTopology()
    
        # 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
    
        # 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
    
        # 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)
    
        # 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.
    
        # 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
    
        # 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
    
        # 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)
    
    def test_convertWater(self):
        """ Test the convertWater() method. """
    
        for model in ['tip3p', 'spce', 'tip4pew', 'tip5p']:
            if model == 'tip5p':
                firstmodel = 'tip4pew'
            else:
                firstmodel = 'tip5p'
    
            modeller = Modeller(self.topology_start, self.positions)
            modeller.convertWater(model=firstmodel)
            modeller.convertWater(model=model)
            topology_after = modeller.getTopology()
    
            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)
    
                    # 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
    
                    # 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
    
            validate_preserved(self, self.topology_start, topology_after, 
                               chain_dict, residue_dict, atom_dict)
    
            validate_deltas(self, self.topology_start, topology_after, 
                            chain_delta, residue_delta, atom_delta)
    
    def test_addSolventWaterModels(self):
        """ Test all addSolvent() method with all possible water models. """
    
        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()
    
            # First, check that everything that was there before has been preserved.
    
            # 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
    
            # 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
    
            # 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)
    
            # 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)
    
    def test_addSolventPeriodicBox(self):
311
        """ Test the addSolvent() method; test that the five ways of passing in the periodic box all work. """
312
    
313
        # First way of passing in periodic box vectors:  set it in the original topology.
314
315
316
317
318
319
        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()
320
        dim3 = topology_after.getPeriodicBoxVectors()
321
    
322
323
324
        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))
325
    
326
        # Second way of passing in the periodic box vectors: with the boxSize parameter to addSolvent()
327
328
329
330
331
        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()
332
        dim3 = topology_after.getPeriodicBoxVectors()
333
    
334
335
336
        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))
337
    
338
339
340
341
342
343
344
345
346
347
348
349
350
        # 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()
    
        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))
    
        # Fourth way of passing in the periodic box vectors: pass a 'padding' value to addSolvent()
351
352
353
354
355
        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()
356
        dim3 = topology_after.getPeriodicBoxVectors()
357
    
358
359
360
        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))
361
362
363
364
365
366
367
368
        
        # 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())))
369
370
371

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

373
374
375
376
377
378
        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()
379

380
381
382
383
384
385
386
387
388
389
        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
390

391
392
393
394
395
396
        total_added = water_count+sodium_count+chlorine_count
        self.assertEqual(total_added, 1364)
        expected_ion_fraction = 2.0*molar/(55.4*molar)
        expected_ions = math.floor(total_added*expected_ion_fraction/2+0.5)
        self.assertEqual(sodium_count, expected_ions)
        self.assertEqual(chlorine_count, expected_ions)
397

398
399
    def test_addSolventNegativeSolvent(self):
        """ Test the addSolvent() method; test adding ions to a negatively charged solvent. """
400

401
402
        topology_start = self.pdb.topology
        topology_start.setUnitCellDimensions(Vec3(3.5, 3.5, 3.5)*nanometers)
403

404
405
406
407
        for neutralize in (True, False):
            # set up modeller with no solvent
            modeller = Modeller(topology_start, self.positions)
            modeller.deleteWater()
408

409
410
411
412
413
414
415
416
417
418
419
420
421
            # 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):
                topology_toAdd.addAtom('Cl',Element.getBySymbol('Cl'), residues[i]) 
            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()
422

423
424
425
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)
            expected_chlorine = math.floor((total_water_ions-10)*expected_ion_fraction/2+0.5)+5
            expected_sodium = expected_chlorine if neutralize else expected_chlorine-5
            self.assertEqual(sodium_count, expected_sodium)
            self.assertEqual(chlorine_count, expected_chlorine)
440

441
442
    def test_addSolventPositiveSolvent(self):
        """ Test the addSolvent() method; test adding ions to a positively charged solvent. """
443

444
445
        topology_start = self.pdb.topology
        topology_start.setUnitCellDimensions(Vec3(3.5, 3.5, 3.5)*nanometers)
446

447
448
449
450
        for neutralize in (True, False):
            # set up modeller with no solvent
            modeller = Modeller(topology_start, self.positions)
            modeller.deleteWater()
451

452
453
454
455
456
457
458
459
460
461
            # 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):
                 topology_toAdd.addAtom('Na',Element.getBySymbol('Na'), residues[i]) 
            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
462

463
464
465
466
            # 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()
467

468
469
470
471
472
473
474
475
476
477
            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
478

479
480
481
482
483
484
            total_water_ions = water_count+sodium_count+chlorine_count
            expected_ion_fraction = 1.0*molar/(55.4*molar)
            expected_sodium = math.floor((total_water_ions-10)*expected_ion_fraction/2+0.5)+5
            expected_chlorine = expected_sodium if neutralize else expected_sodium-5
            self.assertEqual(sodium_count, expected_sodium)
            self.assertEqual(chlorine_count, expected_chlorine)
485

486
487
488
489
490
    def test_addSolventIons(self):
        """ Test the addSolvent() method with all possible choices for positive and negative ions. """
       
        topology_start = self.pdb.topology
        topology_start.setUnitCellDimensions(Vec3(3.5, 3.5, 3.5)*nanometers)
491

492
493
494
495
496
        # set up modeller with no solvent
        modeller = Modeller(topology_start, self.positions)
        modeller.deleteWater()
        topology_nowater = modeller.getTopology()
        positions_nowater = modeller.getPositions()
497

498
499
500
501
502
503
504
        expected_ion_fraction = 1.0*molar/(55.4*molar)
        
        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()
505

506
507
508
509
510
511
512
513
514
515
            water_count = 0 
            positive_ion_count = 0
            chlorine_count = 0
            for residue in topology_after.residues():
                if residue.name=='HOH':
                    water_count += 1       
                elif residue.name==ionName:
                    positive_ion_count += 1
                elif residue.name=='CL':
                    chlorine_count += 1
516

517
518
519
520
521
            total_added = water_count+positive_ion_count+chlorine_count
            self.assertEqual(total_added, 1364)
            expected_ions = math.floor(total_added*expected_ion_fraction/2+0.5)
            self.assertEqual(positive_ion_count, expected_ions)
            self.assertEqual(chlorine_count, expected_ions)
522

523
524
525
526
        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)
527

528
            topology_after = modeller.getTopology()
529

530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
            water_count = 0
            sodium_count = 0   
            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
                    
            total_added = water_count+sodium_count+negative_ion_count
            self.assertEqual(total_added, 1364)
            expected_ions = math.floor(total_added*expected_ion_fraction/2+0.5)
            self.assertEqual(positive_ion_count, expected_ions)
            self.assertEqual(chlorine_count, expected_ions)
546

547
548
549
550
551
552
553
    def test_addHydrogensPdb2(self):
        """ Test the addHydrogens() method on the T4-lysozyme-L99A pdb file. """
        
        # build the Modeller
        topology_start = self.topology_start2
        positions = self.positions2
        modeller = Modeller(topology_start, positions)
554

555
556
557
        # remove hydrogens from the topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
558

559
560
561
562
563
564
565
        # 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'
566

567
568
569
        # add the hydrogens back
        modeller.addHydrogens(self.forcefield, variants=variants)
        topology_after = modeller.getTopology()
570

571
        validate_equivalence(self, topology_start, topology_after)
572

573
574
575
576
577
578
579
    def test_addHydrogensPdb3(self):
        """ Test the addHydrogens() method on the metallothionein pdb file. """
        
        # build the Modeller
        topology_start = self.topology_start3
        positions = self.positions3
        modeller = Modeller(topology_start, positions)
580

581
582
583
        # remove hydrogens from the topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
584

585
586
587
        # add the hydrogens back
        modeller.addHydrogens(self.forcefield)
        topology_after = modeller.getTopology()
588

589
        validate_equivalence(self, topology_start, topology_after)
590

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

594
595
596
        # use the T4-lysozyme-L99A pdb file
        topology_start = self.topology_start2
        positions = self.positions2
597

598
599
        # build the Modeller
        modeller = Modeller(topology_start, positions)
600

601
602
603
        # remove hydrogens from the topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
604

605
606
607
608
609
610
611
        # 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'
612

613
614
615
        ASP_residue_list = [9,19,46,60,69,71,88,91,126,158]
        for residue_index in ASP_residue_list:
            variants[residue_index] = 'ASH'
616

617
618
619
        # add the hydrogens back, using the variants list we just built
        modeller.addHydrogens(self.forcefield, variants=variants)
        topology_ASH = modeller.getTopology()
620

621
622
623
624
625
626
627
628
629
630
        # 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()
631

632
        validate_equivalence(self, topology_ASP, topology_start)
633

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

637
638
639
        # use the metallothionein pdb file
        topology_start = self.topology_start3
        positions = self.positions3
640

641
642
        # build the Modeller
        modeller = Modeller(topology_start, positions)
643

644
645
646
        # remove hydrogens from the topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
647

648
649
650
651
652
653
        # 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'
654

655
656
657
        # add the hydrogens
        modeller.addHydrogens(self.forcefield, variants=variants)
        topology_CYX = modeller.getTopology()
658

659
660
661
        # create a second modeller that we will attempt to match with topology_CYX
        modeller2 = Modeller(topology_start, positions)
        topology2 = modeller2.getTopology()
662

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

666
667
668
669
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 = []
        for index in index_list_CYS: 
            self.assertTrue(atoms[index].element.symbol=='H')
            toDelete2.append(atoms[index])
        modeller2.delete(toDelete2)
        topology_after = modeller2.getTopology()
675

676
        validate_equivalence(self, topology_CYX, topology_after)
677

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

681
682
683
        # use the T4-lysozyme-L99A pdb file
        topology_start = self.topology_start2
        positions = self.positions2
684

685
686
        # build the Modeller
        modeller = Modeller(topology_start, positions)
687

688
689
690
        # remove hydrogens from the topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]      
        modeller.delete(toDelete)
691

692
693
694
695
696
697
698
        # 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'
699

700
701
702
        GLU_residue_list = [4,10,21,44,61,63,107,127]
        for residue_index in GLU_residue_list:
            variants[residue_index] = 'GLH'
703

704
705
706
        # add the hydrogens back, this time with the GLH variant in place of GLU
        modeller.addHydrogens(self.forcefield, variants=variants)
        topology_GLH = modeller.getTopology()
707

708
709
710
711
712
713
714
715
716
717
        # There should be extra hydrogens on the GLU residues.  Assert that they exist,     
        # 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:
            self.assertTrue(atoms[index].element.symbol=='H') 
            toDelete2.append(atoms[index])
        modeller.delete(toDelete2)
        topology_GLU = modeller.getTopology()
718

719
        validate_equivalence(self, topology_GLU, topology_start)
720

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

724
725
726
        # use the T4-lysozyme-L99A pdb file
        topology_start = self.topology_start2
        positions = self.positions2
727

728
729
        # build the Modeller
        modeller = Modeller(topology_start, positions)
730

731
732
733
        # remove hydrogens from topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
734

735
736
737
738
739
740
741
        # 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'
742

743
744
745
746
747
748
        # 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'
749

750
751
        # add the hydrogens back, using the variants list we just built
        modeller.addHydrogens(self.forcefield, variants=variants)
752

753
        topology_LYN = modeller.getTopology()
754

755
756
        # create a second modeller that we will attempt to match with topology_LYN
        modeller2 = Modeller(topology_start, positions)
757

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

761
762
763
764
765
766
767
768
769
        # 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()
770

771
        validate_equivalence(self, topology_LYN, topology_after)
772

773
774
    def test_addHydrogenspH4(self):
        """ Test of addHydrogens() with pH=4. """
775

776
777
778
        # use the T4-lysozyme-L99A pdb file
        topology_start = self.topology_start2
        positions = self.positions2
779

780
781
        # build the Modeller
        modeller = Modeller(topology_start, positions)
782

783
784
785
        # remove hydrogens from the topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
786

787
788
789
790
791
792
793
        # 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'
794

795
796
        # add the hydrogens back, this time at a lower pH
        modeller.addHydrogens(self.forcefield, variants=variants, pH=4.0)
797

798
        topology_ASH_GLH = modeller.getTopology()
799

800
801
802
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:
            self.assertTrue(atoms[index].element.symbol=='H') 
            toDelete2.append(atoms[index])
        modeller.delete(toDelete2)
        topology_ASP_GLU = modeller.getTopology()
814

815
        validate_equivalence(self, topology_ASP_GLU, topology_start)
816

817
818
    def test_addHydrogenspH9(self):
        """ Test of addHydrogens() with pH=9. """
819

820
821
822
        # use the metallothionein pdb file
        topology_start = self.topology_start3
        positions = self.positions3
823

824
825
        # build the Modeller
        modeller = Modeller(topology_start, positions)
826

827
828
829
        # remove hydrogens from topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
830

831
832
833
        # add hydrogens with pH=9, so that the variation CYX will be chosen
        modeller.addHydrogens(self.forcefield, pH=9.0)
        topology_CYX = modeller.getTopology()
834

835
836
837
        # create a second modeller that we will attempt to match with topology_CYX
        modeller2 = Modeller(topology_start, positions)
        topology2 = modeller2.getTopology()
838

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

842
843
844
845
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 = []
        for index in index_list_CYS: 
            self.assertTrue(atoms[index].element.symbol=='H')
            toDelete2.append(atoms[index])
        modeller2.delete(toDelete2)
        topology_after = modeller2.getTopology()
851

852
        validate_equivalence(self, topology_CYX, topology_after) 
853

854
855
    def test_addHydrogenspH11(self):
        """ Test of addHydrogens() with pH=11. """
856

857
858
859
        # use the T4-lysozyme-L99A pdb file
        topology_start = self.topology_start2
        positions = self.positions2
860

861
862
        # build the Modeller
        modeller = Modeller(topology_start, positions)
863

864
865
866
        # remove hydrogens from topology
        toDelete = [atom for atom in topology_start.atoms() if atom.element==Element.getBySymbol('H')]
        modeller.delete(toDelete)
867

868
869
870
871
872
873
874
        # 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'
875

876
877
878
        # 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'
879

880
881
882
        # add the hydrogens back at pH = 11
        modeller.addHydrogens(self.forcefield, variants=variants, pH=11.0)
        topology_LYN = modeller.getTopology()
883

884
885
        # create a second modeller that we will attempt to match with topology_LYN
        modeller2 = Modeller(topology_start, positions)
886

887
888
889
890
891
892
893
894
        # 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])
895

896
897
        modeller2.delete(toDelete2)
        topology_after = modeller2.getTopology()
898

899
        validate_equivalence(self, topology_LYN, topology_after)
900
901


902
903
    def test_addExtraParticles(self):
        """Test addExtraParticles()."""
904

905
        # Create a box of water.
906

907
908
909
        ff1 = ForceField('tip3p.xml')
        modeller = Modeller(Topology(), []*nanometers)
        modeller.addSolvent(ff1, 'tip3p', boxSize=Vec3(2,2,2)*nanometers)
910

911
        # Now convert the water to TIP4P.
912

913
914
915
916
917
918
919
920
921
        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))


922
923
924
925
926
927
    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)

928
929
930
931
if __name__ == '__main__':
    unittest.main()