forcefield.py 165 KB
Newer Older
1
2
"""
forcefield.py: Constructs OpenMM System objects based on a Topology and an XML force field description
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

This is part of the OpenMM molecular simulation toolkit originating from
Simbios, the NIH National Center for Physics-Based Simulation of
Biological Structures at Stanford, funded under the NIH Roadmap for
Medical Research, grant U54 GM072970. See https://simtk.org.

Portions copyright (c) 2012 Stanford University and the Authors.
Authors: Peter Eastman, Mark Friedrichs
Contributors:

Permission is hereby granted, free of charge, to any person obtaining a 
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
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
"""
__author__ = "Peter Eastman"
__version__ = "1.0"

import os
import itertools
import xml.etree.ElementTree as etree
from math import sqrt, cos
import simtk.openmm as mm
import simtk.unit as unit
import element as elem
from simtk.openmm.app import Topology

# Enumerated values for nonbonded method

NoCutoff = object()
CutoffNonPeriodic = object()
CutoffPeriodic = object()
Ewald = object()
PME = object()

# Enumerated values for constraint type

HBonds = object()
AllBonds = object()
HAngles = object()

# A map of functions to parse elements of the XML file.

parsers = {}

class ForceField(object):
    """A ForceField constructs OpenMM System objects based on a Topology."""

    def __init__(self, *files):
        """Load one or more XML files and create a ForceField object based on them.
        
        Parameters:
68
         - files A list of XML files defining the force field.  Each entry may be an absolute file path, a path relative to the
69
70
71
72
           current working directory, or a path relative to this module's data subdirectory (for built in force fields).
        """
        self._atomTypes = {}
        self._templates = {}
73
        self._templateSignatures = {None:[]}
74
        self._atomClasses = {'':set()}
75
        self._forces = []
76
        self._scripts = []
77
78
79
80
81
82
83
84
85
86
87
        for file in files:
            try:
                tree = etree.parse(file)
            except IOError:
                tree = etree.parse(os.path.join(os.path.dirname(__file__), 'data', file))
            root = tree.getroot()
            
            # Load the atom types.
            
            if tree.getroot().find('AtomTypes') is not None:
                for type in tree.getroot().find('AtomTypes').findall('Type'):
88
89
90
                    element = None
                    if 'element' in type.attrib:
                        element = elem.get_by_symbol(type.attrib['element'])
91
92
93
94
                    name = type.attrib['name']
                    if name in self._atomTypes:
                        raise ValueError('Found multiple definitions for atom type: '+name)
                    self._atomTypes[name] = (type.attrib['class'], float(type.attrib['mass']), element)
95
96
97
98
99
100
101
102
103
104
            
            # Load the residue templates.
            
            if tree.getroot().find('Residues') is not None:
                for residue in root.find('Residues').findall('Residue'):
                    resName = residue.attrib['name']
                    template = ForceField._TemplateData(resName)
                    self._templates[resName] = template
                    for atom in residue.findall('Atom'):
                        template.atoms.append(ForceField._TemplateAtomData(atom.attrib['name'], atom.attrib['type'], self._atomTypes[atom.attrib['type']][2]))
105
106
                    for site in residue.findall('VirtualSite'):
                        template.virtualSites.append(ForceField._VirtualSiteData(site))
107
108
109
110
111
112
113
114
115
116
117
                    for bond in residue.findall('Bond'):
                        b = (int(bond.attrib['from']), int(bond.attrib['to']))
                        template.bonds.append(b)
                        template.atoms[b[0]].bondedTo.append(b[1])
                        template.atoms[b[1]].bondedTo.append(b[0])
                    for bond in residue.findall('ExternalBond'):
                        b = int(bond.attrib['from'])
                        template.externalBonds.append(b)
                        template.atoms[b].externalBonds += 1
            for template in self._templates.values():
                template.signature = _createResidueSignature([atom.element for atom in template.atoms])
118
119
120
121
                if template.signature is None:
                    sigString = None
                else:
                    sigString = _signatureToString(template.signature)
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
                if sigString in self._templateSignatures:
                    self._templateSignatures[sigString].append(template)
                else:
                    self._templateSignatures[sigString] = [template]
            
            # Build sets of every atom type belonging to each class
            
            for type in self._atomTypes:
                atomClass = self._atomTypes[type][0]
                if atomClass in self._atomClasses:
                    typeSet = self._atomClasses[atomClass]
                else:
                    typeSet = set()
                    self._atomClasses[atomClass] = typeSet
                typeSet.add(type)
137
                self._atomClasses[''].add(type)
138
139
140
141
142
143
            
            # Load force definitions
            
            for child in root:
                if child.tag in parsers:
                    parsers[child.tag](child, self)
144
145
146
147
148
            
            # Load scripts
            
            for node in tree.getroot().findall('Script'):
                self._scripts.append(node.text)
149
150
151
152
153
154
155
156
157
158
159

    def _findAtomTypes(self, node, num):
        """Parse the attributes on an XML tag to find the set of atom types for each atom it involves."""
        types = []
        attrib = node.attrib
        for i in range(num):
            if num == 1:
                suffix = ''
            else:
                suffix = str(i+1)
            classAttrib = 'class'+suffix
160
            typeAttrib = 'type'+suffix
161
            if classAttrib in attrib:
162
163
                if typeAttrib in attrib:
                    raise ValueError('Tag specifies both a type and a class for the same atom: '+etree.tostring(node))
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
                if attrib[classAttrib] not in self._atomClasses:
                    return None # Unknown atom class
                types.append(self._atomClasses[attrib[classAttrib]])
            else:
                if typeAttrib not in attrib or attrib[typeAttrib] not in self._atomTypes:
                    return None # Unknown atom type
                types.append([attrib[typeAttrib]])
        return types

    def _parseTorsion(self, node):
        """Parse the node defining a torsion."""
        types = self._findAtomTypes(node, 4)
        if types is None:
            return None
        torsion = PeriodicTorsion(types)
        attrib = node.attrib
        index = 1
        while 'phase%d'%index in attrib:
            torsion.periodicity.append(int(attrib['periodicity%d'%index]))
            torsion.phase.append(float(attrib['phase%d'%index]))
            torsion.k.append(float(attrib['k%d'%index]))
            index += 1
186
        return torsion            
187
188
189
190
191
192
        
    class _SystemData:
        """Inner class used to encapsulate data about the system being created."""
        def __init__(self):
            self.atomType = {}
            self.atoms = []
193
            self.virtualSites = {}
194
195
196
197
198
199
200
201
202
203
204
205
            self.bonds = []
            self.angles = []
            self.propers = []
            self.impropers = []
            self.atomBonds = []
            self.isAngleConstrained = []

    class _TemplateData:
        """Inner class used to encapsulate data about a residue template definition."""
        def __init__(self, name):
            self.name = name
            self.atoms = []
206
            self.virtualSites = []
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
            self.bonds = []
            self.externalBonds = []

    class _TemplateAtomData:
        """Inner class used to encapsulate data about an atom in a residue template definition."""
        def __init__(self, name, type, element):
            self.name = name
            self.type = type
            self.element = element
            self.bondedTo = []
            self.externalBonds = 0

    class _BondData:
        """Inner class used to encapsulate data about a bond."""
        def __init__(self, atom1, atom2):
            self.atom1 = atom1
            self.atom2 = atom2
            self.isConstrained = False
            self.length = 0.0
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
    
    class _VirtualSiteData:
        """Inner class used to encapsulate data about a virtual site."""
        def __init__(self, node):
            attrib = node.attrib
            self.index = int(attrib['index'])
            self.type = attrib['type']
            if self.type == 'average2':
                self.atoms = [int(attrib['atom1']), int(attrib['atom2'])]
                self.weights = [float(attrib['weight1']), float(attrib['weight2'])]
            elif self.type == 'average3':
                self.atoms = [int(attrib['atom1']), int(attrib['atom2']), int(attrib['atom3'])]
                self.weights = [float(attrib['weight1']), float(attrib['weight2']), float(attrib['weight3'])]
            elif self.type == 'outOfPlane':
                self.atoms = [int(attrib['atom1']), int(attrib['atom2']), int(attrib['atom3'])]
                self.weights = [float(attrib['weight12']), float(attrib['weight13']), float(attrib['weightCross'])]
            else:
                raise ValueError('Unknown virtual site type: %s' % self.type)
            self.atoms = [x-self.index for x in self.atoms]
245
246

    def createSystem(self, topology, nonbondedMethod=NoCutoff, nonbondedCutoff=1.0*unit.nanometer,
247
                     constraints=None, rigidWater=True, removeCMMotion=True, **args):
248
249
250
251
252
253
254
        """Construct an OpenMM System representing a Topology with this force field.
        
        Parameters:
         - topology (Topology) The Topology for which to create a System
         - nonbondedMethod (object=NoCutoff) The method to use for nonbonded interactions.  Allowed values are
           NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, or PME.
         - nonbondedCutoff (distance=1*nanometer) The cutoff distance to use for nonbonded interactions
Peter Eastman's avatar
Peter Eastman committed
255
         - constraints (object=None) Specifies which bonds and angles should be implemented with constraints.
256
257
           Allowed values are None, HBonds, AllBonds, or HAngles.
         - rigidWater (boolean=True) If true, water molecules will be fully rigid regardless of the value passed for the constraints argument
258
         - removeCMMotion (boolean=True) If true, a CMMotionRemover will be added to the System
259
         - args Arbitrary additional keyword arguments may also be specified.  This allows extra parameters to be specified that are specific to
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
           particular force fields.
        Returns: the newly created System
        """
        
        # Record atom indices
        
        data = ForceField._SystemData()
        atomIndices = {}
        for index, atom in enumerate(topology.atoms()):
            data.atoms.append(atom)
            atomIndices[atom] = index

        # Make a list of all bonds
        
        for bond in topology.bonds():
            if bond[0] in atomIndices and bond[1] in atomIndices:
                data.bonds.append(ForceField._BondData(atomIndices[bond[0]], atomIndices[bond[1]]))

        # Record which atoms are bonded to each other atom
        
        bondedToAtom = []
        for i in range(len(data.atoms)):
            bondedToAtom.append(set())
            data.atomBonds.append([])
        for i in range(len(data.bonds)):
            bond = data.bonds[i]
            bondedToAtom[bond.atom1].add(bond.atom2)
            bondedToAtom[bond.atom2].add(bond.atom1)
            data.atomBonds[bond.atom1].append(i)
            data.atomBonds[bond.atom2].append(i)

        # Find the template matching each residue and assign atom types.
        
        for chain in topology.chains():
            for res in chain.residues():
                template = None
                matches = None
297
298
299
300
301
302
303
304
305
306
307
308
                sig = _createResidueSignature([atom.element for atom in res.atoms()])
                if sig is not None:
                    signature = _signatureToString(sig)
                    if signature in self._templateSignatures:
                        for t in self._templateSignatures[signature]:
                            matches = _matchResidue(res, t, bondedToAtom, atomIndices)
                            if matches is not None:
                                template = t
                                break
                if matches is None:
                    # Check templates involving virtual sites
                    for t in self._templateSignatures[None]:
309
310
311
312
313
                        matches = _matchResidue(res, t, bondedToAtom, atomIndices)
                        if matches is not None:
                            template = t
                            break
                if matches is None:
314
                    raise ValueError('No template found for residue %d (%s).  This might mean your input topology is missing some atoms or bonds, or possibly that you are using the wrong force field.' % (res.index+1, res.name))
315
316
                for atom, match in zip(res.atoms(), matches):
                    data.atomType[atom] = template.atoms[match].type
317
318
319
                    for site in template.virtualSites:
                        if match == site.index:
                            data.virtualSites[atom] = site
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418

        # Create the System and add atoms
        
        sys = mm.System()
        for atom in topology.atoms():
            sys.addParticle(self._atomTypes[data.atomType[atom]][1])
        
        # Set periodic boundary conditions.
        
        boxSize = topology.getUnitCellDimensions()
        if boxSize is not None:
            sys.setDefaultPeriodicBoxVectors((boxSize[0], 0, 0), (0, boxSize[1], 0), (0, 0, boxSize[2]))
        elif nonbondedMethod is not NoCutoff and nonbondedMethod is not CutoffNonPeriodic:
            raise ValueError('Requested periodic boundary conditions for a Topology that does not specify periodic box dimensions')

        # Make a list of all unique angles
        
        uniqueAngles = set()
        for bond in data.bonds:
            for atom in bondedToAtom[bond.atom1]:
                if atom != bond.atom2:
                    if atom < bond.atom2:
                        uniqueAngles.add((atom, bond.atom1, bond.atom2))
                    else:
                        uniqueAngles.add((bond.atom2, bond.atom1, atom))
            for atom in bondedToAtom[bond.atom2]:
                if atom != bond.atom1:
                    if atom > bond.atom1:
                        uniqueAngles.add((bond.atom1, bond.atom2, atom))
                    else:
                        uniqueAngles.add((atom, bond.atom2, bond.atom1))
        data.angles = sorted(list(uniqueAngles))
        
        # Make a list of all unique proper torsions
        
        uniquePropers = set()
        for angle in data.angles:
            for atom in bondedToAtom[angle[0]]:
                if atom != angle[1]:
                    if atom < angle[2]:
                        uniquePropers.add((atom, angle[0], angle[1], angle[2]))
                    else:
                        uniquePropers.add((angle[2], angle[1], angle[0], atom))
            for atom in bondedToAtom[angle[2]]:
                if atom != angle[1]:
                    if atom > angle[0]:
                        uniquePropers.add((angle[0], angle[1], angle[2], atom))
                    else:
                        uniquePropers.add((atom, angle[2], angle[1], angle[0]))
        data.propers = sorted(list(uniquePropers))
        
        # Make a list of all unique improper torsions
        
        for atom in range(len(bondedToAtom)):
            bondedTo = bondedToAtom[atom]
            if len(bondedTo) > 2:
                for subset in itertools.combinations(bondedTo, 3):
                    data.impropers.append((atom, subset[0], subset[1], subset[2]))
        
        # Identify bonds that should be implemented with constraints
        
        if constraints == AllBonds or constraints == HAngles:
            for bond in data.bonds:
                bond.isConstrained = True
        elif constraints == HBonds:
            for bond in data.bonds:
                atom1 = data.atoms[bond.atom1]
                atom2 = data.atoms[bond.atom2]
                bond.isConstrained = atom1.name.startswith('H') or atom2.name.startswith('H')
        if rigidWater:
            for bond in data.bonds:
                atom1 = data.atoms[bond.atom1]
                atom2 = data.atoms[bond.atom2]
                if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH':
                    bond.isConstrained = True
        
        # Identify angles that should be implemented with constraints
        
        if constraints == HAngles:
            for angle in data.angles:
                atom1 = data.atoms[angle[0]]
                atom2 = data.atoms[angle[1]]
                atom3 = data.atoms[angle[2]]
                numH = 0
                if atom1.name.startswith('H'):
                    numH += 1
                if atom3.name.startswith('H'):
                    numH += 1
                data.isAngleConstrained.append(numH == 2 or (numH == 1 and atom2.name.startswith('O')))
        else:
            data.isAngleConstrained = len(data.angles)*[False]
        if rigidWater:
            for i in range(len(data.angles)):
                angle = data.angles[i]
                atom1 = data.atoms[angle[0]]
                atom2 = data.atoms[angle[1]]
                atom3 = data.atoms[angle[2]]
                if atom1.residue.name == 'HOH' and atom2.residue.name == 'HOH' and atom3.residue.name == 'HOH':
                    data.isAngleConstrained[i] = True
419
420
421
422
423
424
425
426
427
428
429
430
431
        
        # Add virtual sites
        
        for atom in data.virtualSites:
            site = data.virtualSites[atom]
            index = atomIndices[atom]
            if site.type == 'average2':
                sys.setVirtualSite(index, mm.TwoParticleAverageSite(index+site.atoms[0], index+site.atoms[1], site.weights[0], site.weights[1]))
            elif site.type == 'average3':
                sys.setVirtualSite(index, mm.ThreeParticleAverageSite(index+site.atoms[0], index+site.atoms[1], index+site.atoms[2], site.weights[0], site.weights[1], site.weights[2]))
            elif site.type == 'outOfPlane':
                sys.setVirtualSite(index, mm.OutOfPlaneSite(index+site.atoms[0], index+site.atoms[1], index+site.atoms[2], site.weights[0], site.weights[1], site.weights[2]))
        
432
433
434
435
        # Add forces to the System
        
        for force in self._forces:
            force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
436
437
        if removeCMMotion:
            sys.addForce(mm.CMMotionRemover())
438
439
440
441
442
        
        # Execute scripts found in the XML files.
        
        for script in self._scripts:
            exec script
443
444
445
446
447
448
449
        return sys


def _createResidueSignature(elements):
    """Create a signature for a residue based on the elements of the atoms it contains."""
    counts = {}
    for element in elements:
450
451
        if element is None:
            return None # This residue contains "atoms" (probably virtual sites) that should match any element
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
        if element in counts:
            counts[element] += 1
        else:
            counts[element] = 1
    sig = []
    for c in counts:
        sig.append((c, counts[c]))
    sig.sort(key=lambda x: -x[0].mass)
    return sig


def _signatureToString(signature):
    """Convert the signature returned by _createResidueSignature() to a string."""
    s = ''
    for element, count in signature:
        s += element.symbol+str(count)
    return s


def _matchResidue(res, template, bondedToAtom, atomIndices):
    """Determine whether a residue matches a template and return a list of corresponding atoms.
    
    Parameters:
     - res (Residue) The residue to check
     - template (_TemplateData) The template to compare it to
     - bondedToAtom (list) Enumerates which other atoms each atom is bonded to
     - atomIndices (map) Maps from atoms to their indices in the System
    Returns: a list specifying which atom of the template each atom of the residue corresponds to,
    or None if it does not match the template
    """
    atoms = list(res.atoms())
483
484
    if len(atoms) != len(template.atoms):
        return None
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
    residueAtomBonds = []
    templateAtomBonds = []
    matches = len(atoms)*[0]
    hasMatch = len(atoms)*[False]
    
    # Translate from global to local atom indices, and record the bonds for each atom.
    
    renumberAtoms = {}
    for i in range(len(atoms)):
        renumberAtoms[atomIndices[atoms[i]]] = i
    bondedTo = []
    externalBonds = []
    for atom in atoms:
        bonds = [renumberAtoms[x] for x in bondedToAtom[atomIndices[atom]] if x in renumberAtoms]
        bondedTo.append(bonds)
        externalBonds.append(len([x for x in bondedToAtom[atomIndices[atom]] if x not in renumberAtoms]))
    if _findAtomMatches(atoms, template, bondedTo, externalBonds, matches, hasMatch, 0):
        return matches
    return None


def _findAtomMatches(atoms, template, bondedTo, externalBonds, matches, hasMatch, position):
    """This is called recursively from inside _matchResidue() to identify matching atoms."""
    if position == len(atoms):
        return True
    elem = atoms[position].element
    for i in range(len(atoms)):
        atom = template.atoms[i]
513
        if (atom.element == elem or atom.element is None) and not hasMatch[i] and len(atom.bondedTo) == len(bondedTo[position]) and atom.externalBonds == externalBonds[position]:
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
            # See if the bonds for this identification are consistent
            
            allBondsMatch = all((bonded > position or matches[bonded] in atom.bondedTo for bonded in bondedTo[position]))
            if allBondsMatch:
                # This is a possible match, so trying matching the rest of the residue.
                
                matches[position] = i
                hasMatch[i] = True
                if _findAtomMatches(atoms, template, bondedTo, externalBonds, matches, hasMatch, position+1):
                    return True
                hasMatch[i] = False
    return False


# The following classes are generators that know how to create Force subclasses and add them to a System that is being
# created.  Each generator class must define two methods: 1) a static method that takes an etree Element and a ForceField,
# and returns the corresponding generator object; 2) a createForce() method that constructs the Force object and adds it
# to the System.  The static method should be added to the parsers map.

533
## @private
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
class HarmonicBondGenerator:
    """A HarmonicBondGenerator constructs a HarmonicBondForce."""
    
    def __init__(self):
        self.types1 = []
        self.types2 = []
        self.length = []
        self.k = []
    
    @staticmethod
    def parseElement(element, ff):
        generator = HarmonicBondGenerator()
        ff._forces.append(generator)
        for bond in element.findall('Bond'):
            types = ff._findAtomTypes(bond, 2)
            if types is not None:
                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.length.append(float(bond.attrib['length']))
                generator.k.append(float(bond.attrib['k']))
    
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
        existing = [f for f in existing if type(f) == mm.HarmonicBondForce]
        if len(existing) == 0:
            force = mm.HarmonicBondForce()
            sys.addForce(force)
        else:
            force = existing[0]
        for bond in data.bonds:
            type1 = data.atomType[data.atoms[bond.atom1]]
            type2 = data.atomType[data.atoms[bond.atom2]]
            for i in range(len(self.types1)):
                types1 = self.types1[i]
                types2 = self.types2[i]
                if (type1 in types1 and type2 in types2) or (type1 in types2 and type2 in types1):
                    bond.length = self.length[i]
                    if bond.isConstrained:
                        sys.addConstraint(bond.atom1, bond.atom2, self.length[i])
                    elif self.k[i] != 0:
                        force.addBond(bond.atom1, bond.atom2, self.length[i], self.k[i])
                    break

parsers["HarmonicBondForce"] = HarmonicBondGenerator.parseElement


580
## @private
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
class HarmonicAngleGenerator:
    """A HarmonicAngleGenerator constructs a HarmonicAngleForce."""
    
    def __init__(self):
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.angle = []
        self.k = []
    
    @staticmethod
    def parseElement(element, ff):
        generator = HarmonicAngleGenerator()
        ff._forces.append(generator)
        for angle in element.findall('Angle'):
            types = ff._findAtomTypes(angle, 3)
            if types is not None:
                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.types3.append(types[2])
                generator.angle.append(float(angle.attrib['angle']))
                generator.k.append(float(angle.attrib['k']))
    
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
        existing = [f for f in existing if type(f) == mm.HarmonicAngleForce]
        if len(existing) == 0:
            force = mm.HarmonicAngleForce()
            sys.addForce(force)
        else:
            force = existing[0]
        for (angle, isConstrained) in zip(data.angles, data.isAngleConstrained):
            type1 = data.atomType[data.atoms[angle[0]]]
            type2 = data.atomType[data.atoms[angle[1]]]
            type3 = data.atomType[data.atoms[angle[2]]]
            for i in range(len(self.types1)):
                types1 = self.types1[i]
                types2 = self.types2[i]
                types3 = self.types3[i]
                if (type1 in types1 and type2 in types2 and type3 in types3) or (type1 in types3 and type2 in types2 and type3 in types1):
                    if isConstrained:
                        # Find the two bonds that make this angle.
                        
                        bond1 = None
                        bond2 = None
                        for bond in data.atomBonds[angle[1]]:
                            atom1 = data.bonds[bond].atom1
                            atom2 = data.bonds[bond].atom2
                            if atom1 == angle[0] or atom2 == angle[0]:
                                bond1 = bond
                            elif atom1 == angle[2] or atom2 == angle[2]:
                                bond2 = bond
                        
                        # Compute the distance between atoms and add a constraint
                        
                        if bond1 is not None and bond2 is not None:
                            l1 = data.bonds[bond1].length
                            l2 = data.bonds[bond2].length
                            if l1 is not None and l2 is not None:
                                length = sqrt(l1*l1 + l2*l2 - 2*l1*l2*cos(self.angle[i]))
                                sys.addConstraint(angle[0], angle[2], length)
                    elif self.k[i] != 0:
                        force.addAngle(angle[0], angle[1], angle[2], self.angle[i], self.k[i])
                    break

parsers["HarmonicAngleForce"] = HarmonicAngleGenerator.parseElement


649
## @private
650
651
652
653
654
655
656
657
658
659
660
661
class PeriodicTorsion:
    """A PeriodicTorsion records the information for a periodic torsion definition."""

    def __init__(self, types):
        self.types1 = types[0]
        self.types2 = types[1]
        self.types3 = types[2]
        self.types4 = types[3]
        self.periodicity = []
        self.phase = []
        self.k = []

662
## @private
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
class PeriodicTorsionGenerator:
    """A PeriodicTorsionGenerator constructs a PeriodicTorsionForce."""
    
    def __init__(self):
        self.proper = []
        self.improper = []
    
    @staticmethod
    def parseElement(element, ff):
        generator = PeriodicTorsionGenerator()
        generator.ff = ff
        ff._forces.append(generator)
        for torsion in element.findall('Proper'):
            torsion = ff._parseTorsion(torsion)
            if torsion is not None:
                generator.proper.append(torsion)
        for torsion in element.findall('Improper'):
            torsion = ff._parseTorsion(torsion)
            if torsion is not None:
                generator.improper.append(torsion)
    
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
        existing = [f for f in existing if type(f) == mm.PeriodicTorsionForce]
        if len(existing) == 0:
            force = mm.PeriodicTorsionForce()
            sys.addForce(force)
        else:
            force = existing[0]
        wildcard = self.ff._atomClasses['']
        for torsion in data.propers:
            type1 = data.atomType[data.atoms[torsion[0]]]
            type2 = data.atomType[data.atoms[torsion[1]]]
            type3 = data.atomType[data.atoms[torsion[2]]]
            type4 = data.atomType[data.atoms[torsion[3]]]
            match = None
            for tordef in self.proper:
                types1 = tordef.types1
                types2 = tordef.types2
                types3 = tordef.types3
                types4 = tordef.types4
                if (type2 in types2 and type3 in types3 and type4 in types4 and type1 in types1) or (type2 in types3 and type3 in types2 and type4 in types1 and type1 in types4):
                    hasWildcard = (wildcard in (types1, types2, types3, types4))
                    if match is None or not hasWildcard: # Prefer specific definitions over ones with wildcards
                        match = tordef
                    if not hasWildcard:
                        break
            if match is not None:
                for i in range(len(match.phase)):
                    if match.k[i] != 0:
                        force.addTorsion(torsion[0], torsion[1], torsion[2], torsion[3], match.periodicity[i], match.phase[i], match.k[i])
        for torsion in data.impropers:
            type1 = data.atomType[data.atoms[torsion[0]]]
            type2 = data.atomType[data.atoms[torsion[1]]]
            type3 = data.atomType[data.atoms[torsion[2]]]
            type4 = data.atomType[data.atoms[torsion[3]]]
            done = False
            for tordef in self.improper:
                if done:
                    break
                types1 = tordef.types1
                types2 = tordef.types2
                types3 = tordef.types3
                types4 = tordef.types4
                if type1 in types1:
                    for (t2, t3, t4) in itertools.permutations(((type2, 1), (type3, 2), (type4, 3))):
                        if t2[0] in types2 and t3[0] in types3 and t4[0] in types4:
                            # Workaround to be more consistent with AMBER.  It uses wildcards to define most of its
                            # impropers, which leaves the ordering ambigous.  It then follows some bizarre rules
                            # to pick the order.
                            a1 = torsion[t2[1]]
                            a2 = torsion[t3[1]]
                            e1 = data.atoms[a1].element
                            e2 = data.atoms[a2].element
                            if e1 == e2 and a1 > a2:
                                (a1, a2) = (a2, a1)
                            elif e1 != elem.carbon and (e2 == elem.carbon or e1.mass < e2.mass):
                                (a1, a2) = (a2, a1)
                            for i in range(len(tordef.phase)):
                                if tordef.k[i] != 0:
                                    force.addTorsion(a1, a2, torsion[0], torsion[t4[1]], tordef.periodicity[i], tordef.phase[i], tordef.k[i])
                            done = True
                            break

parsers["PeriodicTorsionForce"] = PeriodicTorsionGenerator.parseElement


750
## @private
751
752
753
754
755
756
757
758
759
760
class RBTorsion:
    """An RBTorsion records the information for a Ryckaert-Bellemans torsion definition."""

    def __init__(self, types, c):
        self.types1 = types[0]
        self.types2 = types[1]
        self.types3 = types[2]
        self.types4 = types[3]
        self.c = c

761
## @private
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
class RBTorsionGenerator:
    """An RBTorsionGenerator constructs an RBTorsionForce."""
    
    def __init__(self):
        self.proper = []
        self.improper = []
    
    @staticmethod
    def parseElement(element, ff):
        generator = RBTorsionGenerator()
        generator.ff = ff
        ff._forces.append(generator)
        for torsion in element.findall('Proper'):
            types = ff._findAtomTypes(torsion, 4)
            if types is not None:
                generator.proper.append(RBTorsion(types, [float(torsion.attrib['c'+str(i)]) for i in range(6)]))
        for torsion in element.findall('Improper'):
            types = ff._findAtomTypes(torsion, 4)
            if types is not None:
                generator.improper.append(RBTorsion(types, [float(torsion.attrib['c'+str(i)]) for i in range(6)]))
    
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
        existing = [f for f in existing if type(f) == mm.RBTorsionForce]
        if len(existing) == 0:
            force = mm.RBTorsionForce()
            sys.addForce(force)
        else:
            force = existing[0]
        wildcard = self.ff._atomClasses['']
        for torsion in data.propers:
            type1 = data.atomType[data.atoms[torsion[0]]]
            type2 = data.atomType[data.atoms[torsion[1]]]
            type3 = data.atomType[data.atoms[torsion[2]]]
            type4 = data.atomType[data.atoms[torsion[3]]]
            match = None
            for tordef in self.proper:
                types1 = tordef.types1
                types2 = tordef.types2
                types3 = tordef.types3
                types4 = tordef.types4
                if (type2 in types2 and type3 in types3 and type4 in types4 and type1 in types1) or (type2 in types3 and type3 in types2 and type4 in types1 and type1 in types4):
                    hasWildcard = (wildcard in (types1, types2, types3, types4))
                    if match is None or not hasWildcard: # Prefer specific definitions over ones with wildcards
                        match = tordef
                    if not hasWildcard:
                        break
            if match is not None:
                force.addTorsion(torsion[0], torsion[1], torsion[2], torsion[3], match.c[0], match.c[1], match.c[2], match.c[3], match.c[4], match.c[5])
        for torsion in data.impropers:
            type1 = data.atomType[data.atoms[torsion[0]]]
            type2 = data.atomType[data.atoms[torsion[1]]]
            type3 = data.atomType[data.atoms[torsion[2]]]
            type4 = data.atomType[data.atoms[torsion[3]]]
            done = False
            for tordef in self.improper:
                if done:
                    break
                types1 = tordef.types1
                types2 = tordef.types2
                types3 = tordef.types3
                types4 = tordef.types4
                if type1 in types1:
                    for (t2, t3, t4) in itertools.permutations(((type2, 1), (type3, 2), (type4, 3))):
                        if t2[0] in types2 and t3[0] in types3 and t4[0] in types4:
                            # Workaround to be more consistent with AMBER.  It uses wildcards to define most of its
                            # impropers, which leaves the ordering ambigous.  It then follows some bizarre rules
                            # to pick the order.
                            a1 = torsion[t2[1]]
                            a2 = torsion[t3[1]]
                            e1 = data.atoms[a1].element
                            e2 = data.atoms[a2].element
                            if e1 == e2 and a1 > a2:
                                (a1, a2) = (a2, a1)
                            elif e1 != elem.carbon and (e2 == elem.carbon or e1.mass < e2.mass):
                                (a1, a2) = (a2, a1)
                            force.addTorsion(a1, a2, torsion[0], torsion[t4[1]], tordef.c[0], tordef.c[1], tordef.c[2], tordef.c[3], tordef.c[4], tordef.c[5])
                            done = True
                            break

parsers["RBTorsionForce"] = RBTorsionGenerator.parseElement


845
## @private
846
847
848
849
850
851
852
853
854
855
856
class CMAPTorsion:
    """A CMAPTorsion records the information for a CMAP torsion definition."""

    def __init__(self, types, map):
        self.types1 = types[0]
        self.types2 = types[1]
        self.types3 = types[2]
        self.types4 = types[3]
        self.types5 = types[4]
        self.map = map

857
## @private
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
class CMAPTorsionGenerator:
    """A CMAPTorsionGenerator constructs a CMAPTorsionForce."""
    
    def __init__(self):
        self.torsions = []
        self.maps = []
    
    @staticmethod
    def parseElement(element, ff):
        generator = CMAPTorsionGenerator()
        generator.ff = ff
        ff._forces.append(generator)
        for map in element.findall('Map'):
            values = [float(x) for x in map.text.split()]
            size = sqrt(len(values))
            if size*size != len(values):
                raise ValueError('CMAP must have the same number of elements along each dimension')
            generator.maps.append(values)
        for torsion in element.findall('Torsion'):
            types = ff._findAtomTypes(torsion, 5)
            if types is not None:
                generator.torsions.append(CMAPTorsion(types, int(torsion.attrib['map'])))
    
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
        existing = [f for f in existing if type(f) == mm.CMAPTorsionForce]
        if len(existing) == 0:
            force = mm.CMAPTorsionForce()
            sys.addForce(force)
        else:
            force = existing[0]
        for map in self.maps:
            force.addMap(int(sqrt(len(map))), map)
        
        # Find all chains of length 5
        
        uniqueTorsions = set()
        for torsion in data.propers:
            for bond in (data.bonds[x] for x in data.atomBonds[torsion[0]]):
                if bond.atom1 == torsion[0]:
                    atom = bond.atom2
                else:
                    atom = bond.atom1
                if atom != torsion[1]:
                    uniqueTorsions.add((atom, torsion[0], torsion[1], torsion[2], torsion[3]))
            for bond in (data.bonds[x] for x in data.atomBonds[torsion[3]]):
                if bond.atom1 == torsion[3]:
                    atom = bond.atom2
                else:
                    atom = bond.atom1
                if atom != torsion[2]:
                    uniqueTorsions.add((torsion[0], torsion[1], torsion[2], torsion[3], atom))
        torsions = sorted(list(uniqueTorsions))
        wildcard = self.ff._atomClasses['']
        for torsion in torsions:
            type1 = data.atomType[data.atoms[torsion[0]]]
            type2 = data.atomType[data.atoms[torsion[1]]]
            type3 = data.atomType[data.atoms[torsion[2]]]
            type4 = data.atomType[data.atoms[torsion[3]]]
            type5 = data.atomType[data.atoms[torsion[4]]]
            match = None
            for tordef in self.torsions:
                types1 = tordef.types1
                types2 = tordef.types2
                types3 = tordef.types3
                types4 = tordef.types4
                types5 = tordef.types5
                if (type1 in types1 and type2 in types2 and type3 in types3 and type4 in types4 and type5 in types5) or (type1 in types5 and type2 in types4 and type3 in types3 and type4 in types2 and type5 in types1):
                    hasWildcard = (wildcard in (types1, types2, types3, types4, types5))
                    if match is None or not hasWildcard: # Prefer specific definitions over ones with wildcards
                        match = tordef
                    if not hasWildcard:
                        break
            if match is not None:
                force.addTorsion(match.map, torsion[0], torsion[1], torsion[2], torsion[3], torsion[1], torsion[2], torsion[3], torsion[4])

parsers["CMAPTorsionForce"] = CMAPTorsionGenerator.parseElement


937
## @private
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
class NonbondedGenerator:
    """A NonbondedGenerator constructs a NonbondedForce."""
    
    def __init__(self, coulomb14scale, lj14scale):
        self.coulomb14scale = coulomb14scale
        self.lj14scale = lj14scale
        self.typeMap = {}

    @staticmethod
    def parseElement(element, ff):
        existing = [f for f in ff._forces if isinstance(f, NonbondedGenerator)]
        if len(existing) == 0:
            generator = NonbondedGenerator(float(element.attrib['coulomb14scale']), float(element.attrib['lj14scale']))
            ff._forces.append(generator)
        else:
            # Multiple <NonbondedForce> tags were found, probably in different files.  Simply add more types to the existing one.
            generator = existing[0]
            if generator.coulomb14scale != float(element.attrib['coulomb14scale']) or generator.lj14scale != float(element.attrib['lj14scale']):
                raise ValueError('Found multiple NonbondedForce tags with different 1-4 scales') 
        for atom in element.findall('Atom'):
            types = ff._findAtomTypes(atom, 1)
            if types is not None:
                values = (float(atom.attrib['charge']), float(atom.attrib['sigma']), float(atom.attrib['epsilon']))
                for t in types[0]:
                    generator.typeMap[t] = values
    
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        methodMap = {NoCutoff:mm.NonbondedForce.NoCutoff,
                     CutoffNonPeriodic:mm.NonbondedForce.CutoffNonPeriodic,
                     CutoffPeriodic:mm.NonbondedForce.CutoffPeriodic,
                     Ewald:mm.NonbondedForce.Ewald,
                     PME:mm.NonbondedForce.PME}
        if nonbondedMethod not in methodMap:
            raise ValueError('Illegal nonbonded method for NonbondedForce') 
        force = mm.NonbondedForce()
        for atom in data.atoms:
            t = data.atomType[atom]
            if t in self.typeMap:
                values = self.typeMap[t]
                force.addParticle(values[0], values[1], values[2])
            else:
979
980
                raise ValueError('No nonbonded parameters defined for atom type '+t)
        # Create exceptions based on bonds and virtual sites.
981
982
983
        bondIndices = []
        for bond in data.bonds:
            bondIndices.append((bond.atom1, bond.atom2))
984
985
986
987
988
        for i in range(sys.getNumParticles()):
            if sys.isVirtualSite(i):
                site = sys.getVirtualSite(i)
                for j in range(site.getNumParticles()):
                    bondIndices.append((i, site.getParticle(j)))
989
990
991
992
993
994
995
996
997
998
        force.createExceptionsFromBonds(bondIndices, self.coulomb14scale, self.lj14scale)
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
        if 'ewaldErrorTolerance' in args:
            force.setEwaldErrorTolerance(args['ewaldErrorTolerance'])
        sys.addForce(force)

parsers["NonbondedForce"] = NonbondedGenerator.parseElement


999
## @private
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
class GBSAOBCGenerator:
    """A GBSAOBCGenerator constructs a GBSAOBCForce."""
    
    def __init__(self):
        self.typeMap = {}

    @staticmethod
    def parseElement(element, ff):
        generator = GBSAOBCGenerator()
        ff._forces.append(generator)
        for atom in element.findall('Atom'):
            types = ff._findAtomTypes(atom, 1)
            if types is not None:
                values = (float(atom.attrib['charge']), float(atom.attrib['radius']), float(atom.attrib['scale']))
                for t in types[0]:
                    generator.typeMap[t] = values
    
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        methodMap = {NoCutoff:mm.NonbondedForce.NoCutoff,
                     CutoffNonPeriodic:mm.NonbondedForce.CutoffNonPeriodic,
                     CutoffPeriodic:mm.NonbondedForce.CutoffPeriodic}
        if nonbondedMethod not in methodMap:
            raise ValueError('Illegal nonbonded method for GBSAOBCForce') 
        force = mm.GBSAOBCForce()
        for atom in data.atoms:
            t = data.atomType[atom]
            if t in self.typeMap:
                values = self.typeMap[t]
                force.addParticle(values[0], values[1], values[2])
            else:
                raise ValueError('No GBSAOBC parameters defined for atom type '+t) 
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
1033
1034
1035
1036
        if 'soluteDielectric' in args:
            force.setSoluteDielectric(float(args['soluteDielectric']))
        if 'solventDielectric' in args:
            force.setSolventDielectric(float(args['solventDielectric']))
1037
1038
1039
1040
1041
        sys.addForce(force)

parsers["GBSAOBCForce"] = GBSAOBCGenerator.parseElement


1042
## @private
1043
1044
1045
1046
1047
1048
class GBVIGenerator:

    """A GBVIGenerator constructs a GBVIForce."""
    
    def __init__(self,ff):

Peter Eastman's avatar
Peter Eastman committed
1049
1050
1051
1052
1053
        self.ff = ff
        self.fixedParameters = {}
        self.fixedParameters['soluteDielectric'] = 1.0
        self.fixedParameters['solventDielectric'] = 78.3
        self.fixedParameters['scalingMethod'] = 1
1054
        self.fixedParameters['quinticUpperBornRadiusLimit'] = 5.0
Peter Eastman's avatar
Peter Eastman committed
1055
        self.fixedParameters['quinticLowerLimitFactor'] = 0.8
1056

Peter Eastman's avatar
Peter Eastman committed
1057
        self.typeMap = {}
1058
1059
1060

    @staticmethod
    def parseElement(element, ff):
Peter Eastman's avatar
Peter Eastman committed
1061
        generator = GBVIGenerator(ff)
1062
        for key in generator.fixedParameters.iterkeys():
Peter Eastman's avatar
Peter Eastman committed
1063
1064
            if (key in element.attrib):
                generator.fixedParameters[key] = float(element.attrib[key])
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097

        ff._forces.append(generator)
        for atom in element.findall('Atom'):
            types = ff._findAtomTypes(atom, 1)
            if types is not None:
                values = (float(atom.attrib['charge']), float(atom.attrib['radius']), float(atom.attrib['gamma']))
                for t in types[0]:
                    generator.typeMap[t] = values
    
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):

        methodMap = {NoCutoff:mm.NonbondedForce.NoCutoff,
                     CutoffNonPeriodic:mm.NonbondedForce.CutoffNonPeriodic,
                     CutoffPeriodic:mm.NonbondedForce.CutoffPeriodic}

        if nonbondedMethod not in methodMap:
            raise ValueError('Illegal nonbonded method for GB/VI Force') 

        # add particles

        force = mm.GBVIForce()
        for atom in data.atoms:
            t = data.atomType[atom]
            if t in self.typeMap:
                values = self.typeMap[t]
                force.addParticle(values[0], values[1], values[2])
            else:
                raise ValueError('No GB/VI parameters defined for atom type '+t) 

        # get HarmonicBond generator -- exit if not found

        hbGenerator = 0
        for generator in self.ff._forces:
Peter Eastman's avatar
Peter Eastman committed
1098
            if (generator.__class__.__name__ == 'HarmonicBondGenerator'): 
1099
1100
1101
               hbGenerator = generator
               break

Peter Eastman's avatar
Peter Eastman committed
1102
        if (hbGenerator == 0):
1103
1104
1105
1106
1107
1108
1109
            raise ValueError('HarmonicBondGenerator not found.') 

        # add bonds

        for bond in data.bonds:
            type1 = data.atomType[data.atoms[bond.atom1]]
            type2 = data.atomType[data.atoms[bond.atom2]]
Peter Eastman's avatar
Peter Eastman committed
1110
            hit = 0
1111
1112
1113
1114
1115
1116
1117
1118
1119
            for i in range(len(hbGenerator.types1)):
                types1 = hbGenerator.types1[i]
                types2 = hbGenerator.types2[i]
                if (type1 in types1 and type2 in types2) or (type1 in types2 and type2 in types1):
                    #bond.length = hbGenerator.length[i]
                    force.addBond(bond.atom1, bond.atom2, hbGenerator.length[i])

        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
Peter Eastman's avatar
Peter Eastman committed
1120
1121
1122
1123
1124
        force.setSolventDielectric(self.fixedParameters['solventDielectric'])
        force.setSoluteDielectric(self.fixedParameters['soluteDielectric'])
        force.setBornRadiusScalingMethod(self.fixedParameters['scalingMethod'])
        force.setQuinticLowerLimitFactor(self.fixedParameters['quinticLowerLimitFactor'])
        force.setQuinticUpperBornRadiusLimit(self.fixedParameters['quinticUpperBornRadiusLimit'])
1125
1126
1127
1128
1129
        
        sys.addForce(force)

parsers["GBVIForce"] = GBVIGenerator.parseElement

1130
## @private
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
class CustomBondGenerator:
    """A CustomBondGenerator constructs a CustomBondForce."""
    
    def __init__(self):
        self.types1 = []
        self.types2 = []
        self.globalParams = {}
        self.perBondParams = []
        self.paramValues = []
    
    @staticmethod
    def parseElement(element, ff):
        generator = CustomBondGenerator()
        ff._forces.append(generator)
        generator.energy = element.attrib['energy']
        for param in element.findall('GlobalParameter'):
            generator.globalParams[param.attrib['name']] = float(param.attrib['defaultValue'])
        for param in element.findall('PerBondParameter'):
            generator.perBondParams.append(param.attrib['name'])
        for bond in element.findall('Bond'):
            types = ff._findAtomTypes(bond, 2)
            if types is not None:
                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.paramValues.append([float(bond.attrib[param]) for param in generator.perBondParams])
    
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        force = mm.CustomBondForce(self.energy)
        sys.addForce(force)
        for param in self.globalParams:
            force.addGlobalParameter(param, self.globalParams[param])
        for param in self.perBondParams:
            force.addPerBondParameter(param)
        for bond in data.bonds:
            type1 = data.atomType[data.atoms[bond.atom1]]
            type2 = data.atomType[data.atoms[bond.atom2]]
            for i in range(len(self.types1)):
                types1 = self.types1[i]
                types2 = self.types2[i]
                if (type1 in types1 and type2 in types2) or (type1 in types2 and type2 in types1):
                    force.addBond(bond.atom1, bond.atom2, self.paramValues[i])
                    break

parsers["CustomBondForce"] = CustomBondGenerator.parseElement


1177
## @private
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
class CustomAngleGenerator:
    """A CustomAngleGenerator constructs a CustomAngleForce."""
    
    def __init__(self):
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.globalParams = {}
        self.perAngleParams = []
        self.paramValues = []
    
    @staticmethod
    def parseElement(element, ff):
        generator = CustomAngleGenerator()
        ff._forces.append(generator)
        generator.energy = element.attrib['energy']
        for param in element.findall('GlobalParameter'):
            generator.globalParams[param.attrib['name']] = float(param.attrib['defaultValue'])
        for param in element.findall('PerAngleParameter'):
            generator.perAngleParams.append(param.attrib['name'])
        for angle in element.findall('Angle'):
            types = ff._findAtomTypes(angle, 3)
            if types is not None:
                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.types3.append(types[2])
                generator.paramValues.append([float(angle.attrib[param]) for param in generator.perAngleParams])
    
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        force = mm.CustomAngleForce(self.energy)
        sys.addForce(force)
        for param in self.globalParams:
            force.addGlobalParameter(param, self.globalParams[param])
        for param in self.perAngleParams:
            force.addPerAngleParameter(param)
        for angle in data.angles:
            type1 = data.atomType[data.atoms[angle[0]]]
            type2 = data.atomType[data.atoms[angle[1]]]
            type3 = data.atomType[data.atoms[angle[2]]]
            for i in range(len(self.types1)):
                types1 = self.types1[i]
                types2 = self.types2[i]
                types3 = self.types3[i]
                if (type1 in types1 and type2 in types2 and type3 in types3) or (type1 in types3 and type2 in types2 and type3 in types1):
                    force.addAngle(angle[0], angle[1], angle[2], self.paramValues[i])
                    break

parsers["CustomAngleForce"] = CustomAngleGenerator.parseElement


1228
## @private
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
class CustomTorsion:
    """A CustomTorsion records the information for a custom torsion definition."""

    def __init__(self, types, paramValues):
        self.types1 = types[0]
        self.types2 = types[1]
        self.types3 = types[2]
        self.types4 = types[3]
        self.paramValues = paramValues

1239
## @private
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
class CustomTorsionGenerator:
    """A CustomTorsionGenerator constructs a CustomTorsionForce."""
    
    def __init__(self):
        self.proper = []
        self.improper = []
        self.globalParams = {}
        self.perTorsionParams = []
    
    @staticmethod
    def parseElement(element, ff):
        generator = CustomTorsionGenerator()
        generator.ff = ff
        ff._forces.append(generator)
        generator.energy = element.attrib['energy']
        for param in element.findall('GlobalParameter'):
            generator.globalParams[param.attrib['name']] = float(param.attrib['defaultValue'])
        for param in element.findall('PerTorsionParameter'):
            generator.perTorsionParams.append(param.attrib['name'])
        for torsion in element.findall('Proper'):
            types = ff._findAtomTypes(torsion, 4)
            if types is not None:
                generator.proper.append(CustomTorsion(types, [float(torsion.attrib[param]) for param in generator.perTorsionParams]))
        for torsion in element.findall('Improper'):
            types = ff._findAtomTypes(torsion, 4)
            if types is not None:
                generator.improper.append(CustomTorsion(types, [float(torsion.attrib[param]) for param in generator.perTorsionParams]))
    
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        force = mm.CustomTorsionForce(self.energy)
        sys.addForce(force)
        for param in self.globalParams:
            force.addGlobalParameter(param, self.globalParams[param])
        for param in self.perTorsionParams:
            force.addPerTorsionParameter(param)
        wildcard = self.ff._atomClasses['']
        for torsion in data.propers:
            type1 = data.atomType[data.atoms[torsion[0]]]
            type2 = data.atomType[data.atoms[torsion[1]]]
            type3 = data.atomType[data.atoms[torsion[2]]]
            type4 = data.atomType[data.atoms[torsion[3]]]
            match = None
            for tordef in self.proper:
                types1 = tordef.types1
                types2 = tordef.types2
                types3 = tordef.types3
                types4 = tordef.types4
                if (type2 in types2 and type3 in types3 and type4 in types4 and type1 in types1) or (type2 in types3 and type3 in types2 and type4 in types1 and type1 in types4):
                    hasWildcard = (wildcard in (types1, types2, types3, types4))
                    if match is None or not hasWildcard: # Prefer specific definitions over ones with wildcards
                        match = tordef
                    if not hasWildcard:
                        break
            if match is not None:
                force.addTorsion(torsion[0], torsion[1], torsion[2], torsion[3], match.paramValues)
        for torsion in data.impropers:
            type1 = data.atomType[data.atoms[torsion[0]]]
            type2 = data.atomType[data.atoms[torsion[1]]]
            type3 = data.atomType[data.atoms[torsion[2]]]
            type4 = data.atomType[data.atoms[torsion[3]]]
            done = False
            for tordef in self.improper:
                if done:
                    break
                types1 = tordef.types1
                types2 = tordef.types2
                types3 = tordef.types3
                types4 = tordef.types4
                if type1 in types1:
                    for (t2, t3, t4) in itertools.permutations(((type2, 1), (type3, 2), (type4, 3))):
                        if t2[0] in types2 and t3[0] in types3 and t4[0] in types4:
                            # Workaround to be more consistent with AMBER.  It uses wildcards to define most of its
                            # impropers, which leaves the ordering ambigous.  It then follows some bizarre rules
                            # to pick the order.
                            a1 = torsion[t2[1]]
                            a2 = torsion[t3[1]]
                            e1 = data.atoms[a1].element
                            e2 = data.atoms[a2].element
                            if e1 == e2 and a1 > a2:
                                (a1, a2) = (a2, a1)
                            elif e1 != elem.carbon and (e2 == elem.carbon or e1.mass < e2.mass):
                                (a1, a2) = (a2, a1)
                            force.addTorsion(a1, a2, torsion[0], torsion[t4[1]], tordef.paramValues)
                            done = True
                            break

parsers["CustomTorsionForce"] = CustomTorsionGenerator.parseElement


1329
## @private
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
class CustomGBGenerator:
    """A CustomGBGenerator constructs a CustomGBForce."""
    
    def __init__(self):
        self.typeMap = {}
        self.globalParams = {}
        self.perParticleParams = []
        self.paramValues = []
        self.computedValues = []
        self.energyTerms = []
        self.functions = []

    @staticmethod
    def parseElement(element, ff):
        generator = CustomGBGenerator()
        ff._forces.append(generator)
        for param in element.findall('GlobalParameter'):
            generator.globalParams[param.attrib['name']] = float(param.attrib['defaultValue'])
        for param in element.findall('PerParticleParameter'):
            generator.perParticleParams.append(param.attrib['name'])
        for atom in element.findall('Atom'):
            types = ff._findAtomTypes(atom, 1)
            if types is not None:
                values = [float(atom.attrib[param]) for param in generator.perParticleParams]
                for t in types[0]:
                    generator.typeMap[t] = values
        computationMap = {"SingleParticle" : mm.CustomGBForce.SingleParticle,
                          "ParticlePair" : mm.CustomGBForce.ParticlePair,
                          "ParticlePairNoExclusions" : mm.CustomGBForce.ParticlePairNoExclusions}
        for value in element.findall('ComputedValue'):
            generator.computedValues.append((value.attrib['name'], value.text, computationMap[value.attrib['type']]))
        for term in element.findall('EnergyTerm'):
            generator.energyTerms.append((term.text, computationMap[term.attrib['type']]))
        for function in element.findall("Function"):
            values = [float(x) for x in function.text.split()]
            generator.functions.append((function.attrib['name'], values, float(function.attrib['min']), float(function.attrib['max'])))
    
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        methodMap = {NoCutoff:mm.CustomGBForce.NoCutoff,
                     CutoffNonPeriodic:mm.CustomGBForce.CutoffNonPeriodic,
                     CutoffPeriodic:mm.CustomGBForce.CutoffPeriodic}
        if nonbondedMethod not in methodMap:
            raise ValueError('Illegal nonbonded method for CustomGBForce') 
        force = mm.CustomGBForce()
        for param in self.globalParams:
            force.addGlobalParameter(param, self.globalParams[param])
        for param in self.perParticleParams:
            force.addPerParticleParameter(param)
        for value in self.computedValues:
            force.addComputedValue(value[0], value[1], value[2])
        for term in self.energyTerms:
            force.addEnergyTerm(term[0], term[1])
        for function in self.functions:
            force.addFunction(function[0], function[1], function[2], function[3])
        for atom in data.atoms:
            t = data.atomType[atom]
            if t in self.typeMap:
                values = self.typeMap[t]
                force.addParticle(self.typeMap[t])
            else:
                raise ValueError('No CustomGB parameters defined for atom type '+t) 
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
        sys.addForce(force)

parsers["CustomGBForce"] = CustomGBGenerator.parseElement

Peter Eastman's avatar
Peter Eastman committed
1397
def getAtomPrint(data, atomIndex):
1398

Peter Eastman's avatar
Peter Eastman committed
1399
1400
1401
    if (atomIndex < len(data.atoms)):
        atom = data.atoms[atomIndex]
        returnString = "%4s %4s %5d" % (atom.name, atom.residue.name, atom.residue.index)
1402
    else:
Peter Eastman's avatar
Peter Eastman committed
1403
        returnString = "NA"
1404
1405
1406
1407
1408

    return returnString

#=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
1409
def countConstraint(data):
1410

Peter Eastman's avatar
Peter Eastman committed
1411
    bondCount = 0
1412
1413
1414
1415
1416
1417
1418
    angleCount = 0
    for bond in data.bonds:
        if bond.isConstrained:
            bondCount += 1

    angleCount = 0
    for (angle, isConstrained) in zip(data.angles, data.isAngleConstrained):
Peter Eastman's avatar
Peter Eastman committed
1419
        if (isConstrained):
1420
1421
            angleCount += 1
 
Peter Eastman's avatar
Peter Eastman committed
1422
    print "Constraints bond=%d angle=%d  total=%d" % (bondCount, angleCount, (bondCount+angleCount))
1423

1424
## @private
1425
class AmoebaBondGenerator:
1426
1427
1428

    #=============================================================================================

1429
    """An AmoebaBondGenerator constructs a AmoebaBondForce."""
1430
1431
1432
1433
1434

    #=============================================================================================
    
    def __init__(self, cubic, quartic):

Peter Eastman's avatar
Peter Eastman committed
1435
1436
1437
1438
1439
1440
        self.cubic = cubic
        self.quartic = quartic
        self.types1 = []
        self.types2 = []
        self.length = []
        self.k = []
1441
1442
1443
1444
1445
1446
    
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

1447
        # <AmoebaBondForce bond-cubic="-25.5" bond-quartic="379.3125">
1448
1449
        # <Bond class1="1" class2="2" length="0.1437" k="156900.0"/>
    
1450
        generator = AmoebaBondGenerator(float(element.attrib['bond-cubic']), float(element.attrib['bond-quartic']))
1451
1452
1453
1454
1455
1456
1457
1458
1459
        forceField._forces.append(generator)
        for bond in element.findall('Bond'):
            types = forceField._findAtomTypes(bond, 2)
            if types is not None:
                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.length.append(float(bond.attrib['length']))
                generator.k.append(float(bond.attrib['k']))
            else:
1460
                outputString = "AmoebaBondGenerator: error getting types: %s %s" % (
1461
                                    bond.attrib['class1'],
Peter Eastman's avatar
Peter Eastman committed
1462
1463
                                    bond.attrib['class2'])
                raise ValueError(outputString) 
1464
1465
1466
    
    #=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
1467
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
1468

Mark Friedrichs's avatar
Mark Friedrichs committed
1469
        #countConstraint(data)
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
1470

Peter Eastman's avatar
Peter Eastman committed
1471
        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
1472
        existing = [f for f in existing if type(f) == mm.AmoebaBondForce]
1473
        if len(existing) == 0:
1474
            force = mm.AmoebaBondForce()
1475
1476
1477
1478
            sys.addForce(force)
        else:
            force = existing[0]

1479
1480
        force.setAmoebaGlobalBondCubic(self.cubic)
        force.setAmoebaGlobalBondQuartic(self.quartic)
1481
1482
1483
1484

        for bond in data.bonds:
            type1 = data.atomType[data.atoms[bond.atom1]]
            type2 = data.atomType[data.atoms[bond.atom2]]
Peter Eastman's avatar
Peter Eastman committed
1485
            hit = 0
1486
1487
1488
1489
1490
            for i in range(len(self.types1)):
                types1 = self.types1[i]
                types2 = self.types2[i]
                if (type1 in types1 and type2 in types2) or (type1 in types2 and type2 in types1):
                    bond.length = self.length[i]
Peter Eastman's avatar
Peter Eastman committed
1491
                    hit = 1
1492
1493
1494
1495
1496
1497
                    if bond.isConstrained:
                        sys.addConstraint(bond.atom1, bond.atom2, self.length[i])
                    elif self.k[i] != 0:
                        force.addBond(bond.atom1, bond.atom2, self.length[i], self.k[i])
                    break

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
1498
            if (hit == 0): 
1499
                outputString = "AmoebaBondGenerator missing: types=[%5s %5s] atoms=[%6d %6d] " % (type1, type2, bond.atom1, bond.atom2)
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
1500
                raise ValueError(outputString) 
1501

1502
parsers["AmoebaBondForce"] = AmoebaBondGenerator.parseElement
1503
1504
1505
1506
1507

#=============================================================================================
# Add angle constraint
#=============================================================================================
    
Peter Eastman's avatar
Peter Eastman committed
1508
def addAngleConstraint(angle, idealAngle, data, sys):
1509
1510
1511

    # Find the two bonds that make this angle.
                    
Peter Eastman's avatar
Peter Eastman committed
1512
1513
    bond1 = None
    bond2 = None
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
    for bond in data.atomBonds[angle[1]]:
        atom1 = data.bonds[bond].atom1
        atom2 = data.bonds[bond].atom2
        if atom1 == angle[0] or atom2 == angle[0]:
            bond1 = bond
        elif atom1 == angle[2] or atom2 == angle[2]:
            bond2 = bond
                    
        # Compute the distance between atoms and add a constraint
                    
        if bond1 is not None and bond2 is not None:
            l1 = data.bonds[bond1].length
            l2 = data.bonds[bond2].length
            if l1 is not None and l2 is not None:
Peter Eastman's avatar
Peter Eastman committed
1528
                length = sqrt(l1*l1 + l2*l2 - 2*l1*l2*cos(idealAngle))
1529
1530
1531
1532
                sys.addConstraint(angle[0], angle[2], length)
                return

#=============================================================================================
1533
## @private
1534
class AmoebaAngleGenerator:
1535
1536

    #=============================================================================================
1537
    """An AmoebaAngleGenerator constructs a AmoebaAngleForce."""
1538
1539
1540
1541
    #=============================================================================================
    
    def __init__(self, forceField, cubic, quartic, pentic, sextic):

Peter Eastman's avatar
Peter Eastman committed
1542
1543
1544
1545
1546
        self.forceField = forceField
        self.cubic = cubic
        self.quartic = quartic
        self.pentic = pentic
        self.sextic = sextic
1547

Peter Eastman's avatar
Peter Eastman committed
1548
1549
1550
        self.types1 = []
        self.types2 = []
        self.types3 = []
1551

Peter Eastman's avatar
Peter Eastman committed
1552
1553
        self.angle = []
        self.k = []
1554
1555
1556
1557
1558
1559
    
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

1560
        # <AmoebaAngleForce angle-cubic="-0.014" angle-quartic="5.6e-05" angle-pentic="-7e-07" angle-sextic="2.2e-08">
1561
1562
        #   <Angle class1="2" class2="1" class3="3" k="0.0637259642196" angle1="122.00"  />

1563
        generator = AmoebaAngleGenerator(forceField, float(element.attrib['angle-cubic']), float(element.attrib['angle-quartic']),  float(element.attrib['angle-pentic']), float(element.attrib['angle-sextic']))
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
        forceField._forces.append(generator)
        for angle in element.findall('Angle'):
            types = forceField._findAtomTypes(angle, 3)
            if types is not None:

                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.types3.append(types[2])

                angleList = []
Peter Eastman's avatar
Peter Eastman committed
1574
                angleList.append(float(angle.attrib['angle1']))
1575
1576

                try:
Peter Eastman's avatar
Peter Eastman committed
1577
                    angleList.append(float(angle.attrib['angle2']))
1578
                    try:
Peter Eastman's avatar
Peter Eastman committed
1579
                        angleList.append(float(angle.attrib['angle3']))
1580
1581
1582
1583
1584
1585
1586
                    except:
                        pass
                except:
                    pass
                generator.angle.append(angleList)
                generator.k.append(float(angle.attrib['k']))
            else:
1587
                outputString = "AmoebaAngleGenerator: error getting types: %s %s %s" % (
1588
1589
                                    angle.attrib['class1'],
                                    angle.attrib['class2'],
Peter Eastman's avatar
Peter Eastman committed
1590
1591
                                    angle.attrib['class3'])
                raise ValueError(outputString) 
1592
1593
1594
1595
1596
1597
    
    #=============================================================================================
    # createForce is bypassed here since the AmoebaOutOfPlaneBendForce generator must first execute
    # and partition angles into in-plane and non-in-plane angles
    #=============================================================================================
    
Peter Eastman's avatar
Peter Eastman committed
1598
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
1599
1600
1601
1602
1603
1604
1605
        pass

    #=============================================================================================
    # createForcePostOpBendAngle is called by AmoebaOutOfPlaneBendForce with the list of
    # non-in-plane angles
    #=============================================================================================
    
Peter Eastman's avatar
Peter Eastman committed
1606
    def createForcePostOpBendAngle(self, sys, data, nonbondedMethod, nonbondedCutoff, angleList, args):
1607
1608
1609
1610

        # get force

        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
1611
        existing = [f for f in existing if type(f) == mm.AmoebaAngleForce]
1612
1613

        if len(existing) == 0:
1614
            force = mm.AmoebaAngleForce()
1615
1616
1617
1618
            sys.addForce(force)
        else:
            force = existing[0]

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
1619
        # set scalars
1620

1621
1622
1623
1624
        force.setAmoebaGlobalAngleCubic(self.cubic)
        force.setAmoebaGlobalAngleQuartic(self.quartic)
        force.setAmoebaGlobalAnglePentic(self.pentic)
        force.setAmoebaGlobalAngleSextic(self.sextic)
1625
1626

        for angleDict in angleList:
Peter Eastman's avatar
Peter Eastman committed
1627
1628
            angle = angleDict['angle']
            isConstrained = angleDict['isConstrained']
1629

Peter Eastman's avatar
Peter Eastman committed
1630
1631
1632
1633
            type1 = data.atomType[data.atoms[angle[0]]]
            type2 = data.atomType[data.atoms[angle[1]]]
            type3 = data.atomType[data.atoms[angle[2]]]
            hit = 0
1634
1635
1636
1637
1638
            for i in range(len(self.types1)):
                types1 = self.types1[i]
                types2 = self.types2[i]
                types3 = self.types3[i]
                if (type1 in types1 and type2 in types2 and type3 in types3) or (type1 in types3 and type2 in types2 and type3 in types1):
Peter Eastman's avatar
Peter Eastman committed
1639
                    hit = 1
1640
1641
                    if isConstrained and self.k[i] != 0.0:
                        angleDict['idealAngle'] = self.angle[i][0]
Peter Eastman's avatar
Peter Eastman committed
1642
                        addAngleConstraint(angle, self.angle[i][0], data, sys)
1643
                    elif self.k[i] != 0:
Peter Eastman's avatar
Peter Eastman committed
1644
1645
                        lenAngle = len(self.angle[i])
                        if (lenAngle > 1):
1646
1647
1648
1649
1650
1651
                            # get k-index by counting number of non-angle hydrogens on the central atom
                            # based on kangle.f
                            numberOfHydrogens = 0
                            for bond in data.atomBonds[angle[1]]:
                                atom1 = data.bonds[bond].atom1
                                atom2 = data.bonds[bond].atom2
Peter Eastman's avatar
Peter Eastman committed
1652
                                if (atom1 == angle[1] and atom2 != angle[0] and atom2 != angle[2] and (sys.getParticleMass(atom2)/unit.dalton) < 1.90):
1653
                                    numberOfHydrogens += 1
Peter Eastman's avatar
Peter Eastman committed
1654
                                if (atom2 == angle[1] and atom1 != angle[0] and atom1 != angle[2] and (sys.getParticleMass(atom1)/unit.dalton) < 1.90):
1655
                                    numberOfHydrogens += 1
Peter Eastman's avatar
Peter Eastman committed
1656
                            if (numberOfHydrogens < lenAngle):
1657
1658
                                angleValue =  self.angle[i][numberOfHydrogens]
                            else:
1659
                                outputString = "AmoebaAngleGenerator angle index=%d is out of range: [0, %5d] " % (numberOfHydrogens, lenAngle)
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
1660
                                raise ValueError(outputString) 
1661
1662
1663
1664
                        else:
                            angleValue =  self.angle[i][0]
               
                        angleDict['idealAngle'] = angleValue
Peter Eastman's avatar
Peter Eastman committed
1665
                        force.addAngle(angle[0], angle[1], angle[2], angleValue, self.k[i])
1666
                    break
Peter Eastman's avatar
Peter Eastman committed
1667
            if (hit == 0): 
1668
                outputString = "AmoebaAngleGenerator missing types: [%s %s %s] for atoms: " % (type1, type2, type3)
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
1669
1670
1671
1672
1673
                outputString += getAtomPrint( data, angle[0] ) + ' '
                outputString += getAtomPrint( data, angle[1] ) + ' '
                outputString += getAtomPrint( data, angle[2] )
                outputString += " indices: [%6d %6d %6d]" % (angle[0], angle[1], angle[2])
                raise ValueError(outputString) 
1674
1675
1676
1677
1678
1679

    #=============================================================================================
    # createForcePostOpBendInPlaneAngle is called by AmoebaOutOfPlaneBendForce with the list of
    # in-plane angles
    #=============================================================================================
    
Peter Eastman's avatar
Peter Eastman committed
1680
    def createForcePostOpBendInPlaneAngle(self, sys, data, nonbondedMethod, nonbondedCutoff, angleList, args):
1681
1682
1683
1684

        # get force

        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
1685
        existing = [f for f in existing if type(f) == mm.AmoebaInPlaneAngleForce]
1686
1687

        if len(existing) == 0:
1688
            force = mm.AmoebaInPlaneAngleForce()
1689
1690
1691
1692
1693
1694
            sys.addForce(force)
        else:
            force = existing[0]

        # scalars

1695
1696
1697
1698
        force.setAmoebaGlobalInPlaneAngleCubic(self.cubic)
        force.setAmoebaGlobalInPlaneAngleQuartic(self.quartic)
        force.setAmoebaGlobalInPlaneAnglePentic(self.pentic)
        force.setAmoebaGlobalInPlaneAngleSextic(self.sextic)
1699
1700
1701

        for angleDict in angleList:
 
Peter Eastman's avatar
Peter Eastman committed
1702
1703
            angle = angleDict['angle']
            isConstrained = angleDict['isConstrained']
1704

Peter Eastman's avatar
Peter Eastman committed
1705
1706
1707
            type1 = data.atomType[data.atoms[angle[0]]]
            type2 = data.atomType[data.atoms[angle[1]]]
            type3 = data.atomType[data.atoms[angle[2]]]
1708

Peter Eastman's avatar
Peter Eastman committed
1709
            hit = 0
1710
1711
1712
1713
1714
1715
1716
            for i in range(len(self.types1)):

                types1 = self.types1[i]
                types2 = self.types2[i]
                types3 = self.types3[i]

                if (type1 in types1 and type2 in types2 and type3 in types3) or (type1 in types3 and type2 in types2 and type3 in types1):
Peter Eastman's avatar
Peter Eastman committed
1717
                    hit = 1
1718
                    angleDict['idealAngle'] = self.angle[i][0]
Peter Eastman's avatar
Peter Eastman committed
1719
1720
                    if (isConstrained and self.k[i] != 0.0):
                        addAngleConstraint(angle, self.angle[i][0], data, sys)
1721
1722
1723
1724
                    else:
                        force.addAngle(angle[0], angle[1], angle[2], angle[3], self.angle[i][0], self.k[i])
                    break

Peter Eastman's avatar
Peter Eastman committed
1725
            if (hit == 0): 
1726
                outputString = "AmoebaInPlaneAngleGenerator missing types: [%s %s %s] atoms: " % (type1, type2, type3)
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
1727
1728
1729
1730
1731
                outputString += getAtomPrint( data, angle[0] ) + ' '
                outputString += getAtomPrint( data, angle[1] ) + ' '
                outputString += getAtomPrint( data, angle[2] )
                outputString += " indices: [%6d %6d %6d]" % (angle[0], angle[1], angle[2])
                raise ValueError(outputString) 
1732

1733
parsers["AmoebaAngleForce"] = AmoebaAngleGenerator.parseElement
1734
1735
1736

#=============================================================================================
# Generator for the AmoebaOutOfPlaneBend covalent force; also calls methods in the
1737
1738
# AmoebaAngleGenerator to generate the AmoebaAngleForce and
# AmoebaInPlaneAngleForce
1739
1740
#=============================================================================================

1741
## @private
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
class AmoebaOutOfPlaneBendGenerator:

    #=============================================================================================

    """An AmoebaOutOfPlaneBendGenerator constructs a AmoebaOutOfPlaneBendForce."""
    
    #=============================================================================================

    def __init__(self, forceField, type, cubic, quartic, pentic, sextic):

Peter Eastman's avatar
Peter Eastman committed
1752
1753
1754
1755
1756
1757
        self.forceField = forceField
        self.type = type
        self.cubic = cubic
        self.quartic = quartic
        self.pentic = pentic
        self.sextic = sextic
1758

Peter Eastman's avatar
Peter Eastman committed
1759
1760
1761
1762
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.types4 = []
1763

Peter Eastman's avatar
Peter Eastman committed
1764
        self.ks = []
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798

    #=============================================================================================
    # Local version of findAtomTypes needed since class indices are 0 (i.e., not recognized)
    # for types3 and 4
    #=============================================================================================
    
    def findAtomTypes(self, forceField, node, num):
        """Parse the attributes on an XML tag to find the set of atom types for each atom it involves."""
        types = []
        attrib = node.attrib
        for i in range(num):
            if num == 1:
                suffix = ''
            else:
                suffix = str(i+1)
            classAttrib = 'class'+suffix
            if classAttrib in attrib:
                if attrib[classAttrib] in forceField._atomClasses:
                    types.append(forceField._atomClasses[attrib[classAttrib]])
                else:
                    types.append(set())
        return types

    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

        #  <AmoebaOutOfPlaneBendForce type="ALLINGER" opbend-cubic="-0.014" opbend-quartic="5.6e-05" opbend-pentic="-7e-07" opbend-sextic="2.2e-08">
        #   <Angle class1="2" class2="1" class3="0" class4="0" k="0.0531474541591"/>
        #   <Angle class1="3" class2="1" class3="0" class4="0" k="0.0898536095496"/>
         
        # get global scalar parameters

Peter Eastman's avatar
Peter Eastman committed
1799
        generator = AmoebaOutOfPlaneBendGenerator(forceField, element.attrib['type'],
1800
1801
1802
                                                   float(element.attrib['opbend-cubic']),
                                                   float(element.attrib['opbend-quartic']),
                                                   float(element.attrib['opbend-pentic']),
Peter Eastman's avatar
Peter Eastman committed
1803
                                                   float(element.attrib['opbend-sextic']))
1804
1805
1806
1807

        forceField._forces.append(generator)

        for angle in element.findall('Angle'):
Peter Eastman's avatar
Peter Eastman committed
1808
            types = generator.findAtomTypes(forceField, angle, 4)
1809
1810
            if types is not None:

Peter Eastman's avatar
Peter Eastman committed
1811
1812
1813
1814
                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.types3.append(types[2])
                generator.types4.append(types[3])
1815

Peter Eastman's avatar
Peter Eastman committed
1816
                generator.ks.append(float(angle.attrib['k']))
1817
1818

            else:
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
1819
1820
                outputString = "AmoebaOutOfPlaneBendGenerator error getting types: %s %s %s %s." % (
                               angle.attrib['class1'], angle.attrib['class2'], angle.attrib['class3'], angle.attrib['class4'])
Peter Eastman's avatar
Peter Eastman committed
1821
                raise ValueError(outputString) 
1822
1823
1824
1825
1826
1827
1828
1829
    
    #=============================================================================================
    # Get middle atom in a angle
    # return index of middle atom or -1 if no middle is found
    # This method appears not to be needed since the angle[1] entry appears to always
    # be the middle atom. However, was unsure if this is guaranteed
    #=============================================================================================
    
Peter Eastman's avatar
Peter Eastman committed
1830
    def getMiddleAtom(self, angle, data):
1831
1832
1833

        # find atom shared by both bonds making up the angle

Peter Eastman's avatar
Peter Eastman committed
1834
        middleAtom = -1
1835
        for atomIndex in angle: 
Peter Eastman's avatar
Peter Eastman committed
1836
            isMiddle = 0
1837
1838
1839
            for bond in data.atomBonds[atomIndex]:
                atom1 = data.bonds[bond].atom1
                atom2 = data.bonds[bond].atom2
Peter Eastman's avatar
Peter Eastman committed
1840
                if (atom1 != atomIndex):
1841
1842
1843
                    partner = atom1
                else:
                    partner = atom2
Peter Eastman's avatar
Peter Eastman committed
1844
                if (partner == angle[0] or partner == angle[1] or partner == angle[2]): 
1845
1846
                    isMiddle += 1

Peter Eastman's avatar
Peter Eastman committed
1847
            if (isMiddle == 2):
1848
1849
1850
1851
1852
                return atomIndex
        return -1

    #=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
1853
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866

        # get force

        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
        existing = [f for f in existing if type(f) == mm.AmoebaOutOfPlaneBendForce]
        if len(existing) == 0:
            force = mm.AmoebaOutOfPlaneBendForce()
            sys.addForce(force)
        else:
            force = existing[0]

        # set scalars

Peter Eastman's avatar
Peter Eastman committed
1867
1868
1869
1870
        force.setAmoebaGlobalOutOfPlaneBendCubic(  self.cubic)
        force.setAmoebaGlobalOutOfPlaneBendQuartic(self.quartic)
        force.setAmoebaGlobalOutOfPlaneBendPentic( self.pentic)
        force.setAmoebaGlobalOutOfPlaneBendSextic( self.sextic)
1871
1872
1873
1874

        # this hash is used to insure the out-of-plane-bend bonds
        # are only added once

Peter Eastman's avatar
Peter Eastman committed
1875
        skipAtoms = dict()
1876
1877
1878
1879

        # these lists are used in the partitioning of the angles into
        # angle and inPlane angles

Peter Eastman's avatar
Peter Eastman committed
1880
1881
        inPlaneAngles = []
        nonInPlaneAngles = []
1882
        nonInPlaneAnglesConstrained = []
Peter Eastman's avatar
Peter Eastman committed
1883
        idealAngles = []*len(data.angles)
1884
1885
1886

        for (angle, isConstrained) in zip(data.angles, data.isAngleConstrained):

Peter Eastman's avatar
Peter Eastman committed
1887
1888
1889
            middleAtom = self.getMiddleAtom(angle, data)
            if (middleAtom > -1):
                middleType = data.atomType[data.atoms[middleAtom]]
1890
1891
                middleCovalency = len(data.atomBonds[middleAtom])
            else:
Peter Eastman's avatar
Peter Eastman committed
1892
                middleType = -1
1893
1894
1895
1896
                middleCovalency = -1

            # if middle atom has covalency of 3 and 
            # the types of the middle atom and the partner atom (atom bonded to
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
1897
            # middle atom, but not in angle) match types1 and types2, then
1898
            # three out-of-plane bend angles are generated. Three in-plane angle 
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
1899
            # are also generated. If the conditions are not satisfied, the angle is marked as 'generic' angle (not a in-plane angle)
1900

Peter Eastman's avatar
Peter Eastman committed
1901
            if (middleAtom > -1 and middleCovalency == 3 and middleAtom not in skipAtoms):
1902

Peter Eastman's avatar
Peter Eastman committed
1903
1904
1905
1906
                partners = []
                partnerSet = set()
                partnerTypes = []
                partnerK = []
1907
1908
1909
1910

                for bond in data.atomBonds[middleAtom]:
                    atom1 = data.bonds[bond].atom1
                    atom2 = data.bonds[bond].atom2
Peter Eastman's avatar
Peter Eastman committed
1911
                    if (atom1 != middleAtom):
1912
1913
1914
1915
1916
1917
1918
1919
                        partner = atom1
                    else:
                        partner = atom2

                    partnerType = data.atomType[data.atoms[partner]]
                    for i in range(len(self.types1)):
                        types1 = self.types1[i]
                        types2 = self.types2[i]
Peter Eastman's avatar
Peter Eastman committed
1920
1921
1922
1923
1924
                        if (middleType in types2 and partnerType in types1):
                            partners.append(partner)
                            partnerSet.add(partner)
                            partnerTypes.append(partnerType)
                            partnerK.append(self.ks[i])
1925
             
Peter Eastman's avatar
Peter Eastman committed
1926
                if (len(partners) == 3):
1927

Peter Eastman's avatar
Peter Eastman committed
1928
1929
1930
                    force.addOutOfPlaneBend(partners[0], middleAtom, partners[1], partners[2], partnerK[2])
                    force.addOutOfPlaneBend(partners[0], middleAtom, partners[2], partners[1], partnerK[1])
                    force.addOutOfPlaneBend(partners[1], middleAtom, partners[2], partners[0], partnerK[0])
1931

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
1932
1933
                    # skipAtoms is used to insure angles are only included once

1934
                    skipAtoms[middleAtom] = set()
Peter Eastman's avatar
Peter Eastman committed
1935
1936
1937
1938
                    skipAtoms[middleAtom].add(partners[0])
                    skipAtoms[middleAtom].add(partners[1])
                    skipAtoms[middleAtom].add(partners[2])

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
1939
1940
                    # in-plane angle

Peter Eastman's avatar
Peter Eastman committed
1941
1942
1943
1944
1945
                    angleDict = {}
                    angleList = []
                    angleList.append(angle[0])
                    angleList.append(angle[1])
                    angleList.append(angle[2])
1946
1947
                    angleDict['angle'] = angleList

Peter Eastman's avatar
Peter Eastman committed
1948
                    angleDict['isConstrained'] = 0
1949

Peter Eastman's avatar
Peter Eastman committed
1950
1951
1952
1953
                    angleSet = set()
                    angleSet.add(angle[0])
                    angleSet.add(angle[1])
                    angleSet.add(angle[2])
1954
1955

                    for atomIndex in partnerSet:
Peter Eastman's avatar
Peter Eastman committed
1956
1957
                        if (atomIndex not in angleSet):
                            angleList.append(atomIndex)
1958

Peter Eastman's avatar
Peter Eastman committed
1959
                    inPlaneAngles.append(angleDict)
1960
1961

                else:
Peter Eastman's avatar
Peter Eastman committed
1962
1963
1964
1965
                    angleDict = {}
                    angleDict['angle'] = angle
                    angleDict['isConstrained'] = isConstrained
                    nonInPlaneAngles.append(angleDict)
1966
            else:
Peter Eastman's avatar
Peter Eastman committed
1967
                if (middleAtom > -1 and middleCovalency == 3 and middleAtom in skipAtoms):
1968

Peter Eastman's avatar
Peter Eastman committed
1969
                    partnerSet = skipAtoms[middleAtom]
1970
                  
Peter Eastman's avatar
Peter Eastman committed
1971
                    angleDict = {}
1972

Peter Eastman's avatar
Peter Eastman committed
1973
1974
1975
1976
1977
                    angleList = []
                    angleList.append(angle[0])
                    angleList.append(angle[1])
                    angleList.append(angle[2])
                    angleDict['angle'] = angleList
1978

Peter Eastman's avatar
Peter Eastman committed
1979
                    angleDict['isConstrained'] = isConstrained
1980

Peter Eastman's avatar
Peter Eastman committed
1981
1982
1983
1984
                    angleSet = set()
                    angleSet.add(angle[0])
                    angleSet.add(angle[1])
                    angleSet.add(angle[2])
1985
1986

                    for atomIndex in partnerSet:
Peter Eastman's avatar
Peter Eastman committed
1987
1988
                        if (atomIndex not in angleSet):
                            angleList.append(atomIndex)
1989

Peter Eastman's avatar
Peter Eastman committed
1990
                    inPlaneAngles.append(angleDict)
1991
1992

                else:
Peter Eastman's avatar
Peter Eastman committed
1993
1994
                    angleDict = {}
                    angleDict['angle'] = angle
1995
                    angleDict['isConstrained'] = isConstrained
Peter Eastman's avatar
Peter Eastman committed
1996
                    nonInPlaneAngles.append(angleDict)
1997

1998
        # get AmoebaAngleGenerator and add AmoebaAngle and AmoebaInPlaneAngle forces
1999
2000

        for force in self.forceField._forces:
2001
            if (force.__class__.__name__ == 'AmoebaAngleGenerator'): 
Peter Eastman's avatar
Peter Eastman committed
2002
2003
                force.createForcePostOpBendAngle(sys, data, nonbondedMethod, nonbondedCutoff, nonInPlaneAngles, args)
                force.createForcePostOpBendInPlaneAngle(sys, data, nonbondedMethod, nonbondedCutoff, inPlaneAngles, args)
2004
2005

        for force in self.forceField._forces:
Peter Eastman's avatar
Peter Eastman committed
2006
            if (force.__class__.__name__ == 'AmoebaStretchBendGenerator'): 
2007
                for angleDict in inPlaneAngles:
Peter Eastman's avatar
Peter Eastman committed
2008
                    nonInPlaneAngles.append(angleDict)
2009
                force.createForcePostAmoebaBondForce(sys, data, nonbondedMethod, nonbondedCutoff, nonInPlaneAngles, args)
2010
2011
2012
2013
2014

parsers["AmoebaOutOfPlaneBendForce"] = AmoebaOutOfPlaneBendGenerator.parseElement

#=============================================================================================

2015
## @private
2016
2017
2018
2019
2020
2021
2022
2023
class AmoebaTorsionGenerator:

    #=============================================================================================
    """An AmoebaTorsionGenerator constructs a AmoebaTorsionForce."""
    #=============================================================================================

    def __init__(self, torsionUnit):

Peter Eastman's avatar
Peter Eastman committed
2024
        self.torsionUnit = torsionUnit
2025

Peter Eastman's avatar
Peter Eastman committed
2026
2027
2028
2029
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.types4 = []
2030

Peter Eastman's avatar
Peter Eastman committed
2031
2032
2033
        self.t1 = []
        self.t2 = []
        self.t3 = []
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
    
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

        #  <AmoebaTorsionForce torsionUnit="0.5">
        #   <Torsion class1="3" class2="1" class3="2" class4="3"   amp1="0.0" angle1="0.0"   amp2="0.0" angle2="3.14159265359"   amp3="0.0" angle3="0.0" />
        #   <Torsion class1="3" class2="1" class3="2" class4="6"   amp1="0.0" angle1="0.0"   amp2="0.0" angle2="3.14159265359"   amp3="-0.263592" angle3="0.0" />
         
Peter Eastman's avatar
Peter Eastman committed
2044
        generator = AmoebaTorsionGenerator(float(element.attrib['torsionUnit']))
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
        forceField._forces.append(generator)

        # collect particle classes and t1,t2,t3,
        # where ti=[amplitude_i,angle_i]

        for torsion in element.findall('Torsion'):
            types = forceField._findAtomTypes(torsion, 4)
            if types is not None:

                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.types3.append(types[2])
                generator.types4.append(types[3])

                for ii in range(1,4):
Peter Eastman's avatar
Peter Eastman committed
2060
2061
                    tInfo = []
                    suffix = str(ii)
2062
2063
2064
2065
2066
2067
                    ampName = 'amp' + suffix
                    tInfo.append(float(torsion.attrib[ampName]))

                    angName = 'angle' + suffix
                    tInfo.append(float(torsion.attrib[angName]))

Peter Eastman's avatar
Peter Eastman committed
2068
2069
2070
2071
2072
2073
                    if (ii == 1):
                        generator.t1.append(tInfo)
                    elif (ii == 2):
                        generator.t2.append(tInfo)
                    elif (ii == 3):
                        generator.t3.append(tInfo)
2074
2075
2076
2077
2078
2079

            else:
                outputString = "AmoebaTorsionGenerator: error getting types: %s %s %s %s" % (
                                    stretchBend.attrib['class1'],
                                    stretchBend.attrib['class2'],
                                    stretchBend.attrib['class3'],
Peter Eastman's avatar
Peter Eastman committed
2080
2081
                                    stretchBend.attrib['class4'])
                raise ValueError(outputString) 
2082
2083
2084
2085
2086
2087
    
    #=============================================================================================

    def createForce(self, sys, data, nontorsionedMethod, nontorsionedCutoff, args):

        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
2088
        existing = [f for f in existing if type(f) == mm.PeriodicTorsionForce]
2089
        if len(existing) == 0:
2090
            force = mm.PeriodicTorsionForce()
2091
2092
2093
            sys.addForce(force)
        else:
            force = existing[0]
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2094

2095
2096
2097
2098
2099
2100
2101
        for torsion in data.propers:

            type1 = data.atomType[data.atoms[torsion[0]]]
            type2 = data.atomType[data.atoms[torsion[1]]]
            type3 = data.atomType[data.atoms[torsion[2]]]
            type4 = data.atomType[data.atoms[torsion[3]]]

Peter Eastman's avatar
Peter Eastman committed
2102
            hit = 0
2103
2104
2105
2106
2107
2108
2109
2110
2111
            for i in range(len(self.types1)):

                types1 = self.types1[i]
                types2 = self.types2[i]
                types3 = self.types3[i]
                types4 = self.types4[i]

                # match types in forward or reverse direction

Peter Eastman's avatar
Peter Eastman committed
2112
2113
                if (type1 in types1 and type2 in types2 and type3 in types3 and type4 in types4) or (type4 in types1 and type3 in types2 and type2 in types3 and type1 in types4):
                    hit = 1
2114
2115
2116
2117
2118
2119
                    if self.t1[i][0] != 0:
                        force.addTorsion(torsion[0], torsion[1], torsion[2], torsion[3], 1, self.t1[i][1], self.t1[i][0])
                    if self.t2[i][0] != 0:
                        force.addTorsion(torsion[0], torsion[1], torsion[2], torsion[3], 2, self.t2[i][1], self.t2[i][0])
                    if self.t3[i][0] != 0:
                        force.addTorsion(torsion[0], torsion[1], torsion[2], torsion[3], 3, self.t3[i][1], self.t3[i][0])
2120
2121
                    break

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2122
2123
2124
2125
2126
2127
2128
2129
            if (hit == 0): 
                outputString = "AmoebaTorsionGenerator missing type: [%s %s %s %s] atoms: " % (type1, type2, type3, type4)
                outputString += getAtomPrint( data, torsion[0] ) + ' '
                outputString += getAtomPrint( data, torsion[1] ) + ' '
                outputString += getAtomPrint( data, torsion[2] ) + ' '
                outputString += getAtomPrint( data, torsion[3] )
                outputString += " indices: [%6d %6d %6d %6d]" % (torsion[0], torsion[1], torsion[2], torsion[3])
                raise ValueError(outputString) 
2130
2131
2132
2133
2134

parsers["AmoebaTorsionForce"] = AmoebaTorsionGenerator.parseElement

#=============================================================================================

2135
## @private
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
class AmoebaPiTorsionGenerator:

    #=============================================================================================

    """An AmoebaPiTorsionGenerator constructs a AmoebaPiTorsionForce."""

    #=============================================================================================
    
    def __init__(self, piTorsionUnit):
        self.piTorsionUnit = piTorsionUnit 
Peter Eastman's avatar
Peter Eastman committed
2146
2147
2148
        self.types1 = []
        self.types2 = []
        self.k = []
2149
2150
2151
2152
2153
2154
2155
2156
2157
    
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

        #  <AmoebaPiTorsionForce piTorsionUnit="1.0">
        #   <PiTorsion class1="1" class2="3" k="28.6604" />

Peter Eastman's avatar
Peter Eastman committed
2158
        generator = AmoebaPiTorsionGenerator(float(element.attrib['piTorsionUnit']))
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
        forceField._forces.append(generator)

        for piTorsion in element.findall('PiTorsion'):
            types = forceField._findAtomTypes(piTorsion, 2)
            if types is not None:
                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.k.append(float(piTorsion.attrib['k']))
            else:
                outputString = "AmoebaPiTorsionGenerator: error getting types: %s %s " % (
                                    piTorsion.attrib['class1'],
Peter Eastman's avatar
Peter Eastman committed
2170
2171
                                    piTorsion.attrib['class2'])
                raise ValueError(outputString) 
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
    
    #=============================================================================================

    def createForce(self, sys, data, nonpiTorsionedMethod, nonpiTorsionedCutoff, args):

        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
        existing = [f for f in existing if type(f) == mm.AmoebaPiTorsionForce]

        if len(existing) == 0:
            force = mm.AmoebaPiTorsionForce()
            sys.addForce(force)
        else:
            force = existing[0]

        for bond in data.bonds:

            # search for bonds with both atoms in bond having covalency == 3
 
            atom1 = bond.atom1
            atom2 = bond.atom2
 
Peter Eastman's avatar
Peter Eastman committed
2193
            if (len(data.atomBonds[atom1]) == 3 and len(data.atomBonds[atom1]) == 3):
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218

                type1 = data.atomType[data.atoms[atom1]]
                type2 = data.atomType[data.atoms[atom2]]

                for i in range(len(self.types1)):

                   types1 = self.types1[i]
                   types2 = self.types2[i]

                   if (type1 in types1 and type2 in types2) or (type1 in types2 and type2 in types1):

                       # piTorsionAtom1, piTorsionAtom2 are the atoms bonded to atom1, excluding atom2 
                       # piTorsionAtom5, piTorsionAtom6 are the atoms bonded to atom2, excluding atom1 

                       piTorsionAtom1 = -1
                       piTorsionAtom2 = -1
                       piTorsionAtom3 = atom1

                       piTorsionAtom4 = atom2
                       piTorsionAtom5 = -1
                       piTorsionAtom6 = -1

                       for bond in data.atomBonds[atom1]:
                           bondedAtom1 = data.bonds[bond].atom1
                           bondedAtom2 = data.bonds[bond].atom2
Peter Eastman's avatar
Peter Eastman committed
2219
                           if (bondedAtom1 != atom1):
2220
2221
2222
                               b1 = bondedAtom1
                           else:
                               b1 = bondedAtom2
Peter Eastman's avatar
Peter Eastman committed
2223
2224
                           if (b1 != atom2):
                               if (piTorsionAtom1 == -1):
2225
2226
2227
2228
2229
2230
2231
                                   piTorsionAtom1 = b1 
                               else:
                                   piTorsionAtom2 = b1

                       for bond in data.atomBonds[atom2]:
                           bondedAtom1 = data.bonds[bond].atom1
                           bondedAtom2 = data.bonds[bond].atom2
Peter Eastman's avatar
Peter Eastman committed
2232
                           if (bondedAtom1 != atom2):
2233
2234
2235
2236
                               b1 = bondedAtom1
                           else:
                               b1 = bondedAtom2

Peter Eastman's avatar
Peter Eastman committed
2237
2238
                           if (b1 != atom1):
                               if (piTorsionAtom5 == -1):
2239
2240
2241
2242
                                   piTorsionAtom5 = b1 
                               else:
                                   piTorsionAtom6 = b1
    
Peter Eastman's avatar
Peter Eastman committed
2243
                       force.addPiTorsion(piTorsionAtom1, piTorsionAtom2, piTorsionAtom3, piTorsionAtom4, piTorsionAtom5, piTorsionAtom6, self.k[i])
2244
2245
2246
2247
2248

parsers["AmoebaPiTorsionForce"] = AmoebaPiTorsionGenerator.parseElement

#=============================================================================================

2249
## @private
2250
2251
2252
2253
2254
2255
class AmoebaTorsionTorsionGenerator:

    #=============================================================================================
    """An AmoebaTorsionTorsionGenerator constructs a AmoebaTorsionTorsionForce."""
    #=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
2256
    def __init__(self):
2257

Peter Eastman's avatar
Peter Eastman committed
2258
2259
2260
2261
2262
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.types4 = []
        self.types5 = []
2263

Peter Eastman's avatar
Peter Eastman committed
2264
        self.gridIndex = []
2265

Peter Eastman's avatar
Peter Eastman committed
2266
        self.grids = []
2267
2268
2269
2270
2271
2272
    
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

Peter Eastman's avatar
Peter Eastman committed
2273
        generator = AmoebaTorsionTorsionGenerator()
2274
2275
2276
2277
2278
2279
2280
        forceField._forces.append(generator)
        maxGridIndex = -1

        # <AmoebaTorsionTorsionForce >
        # <TorsionTorsion class1="3" class2="1" class3="2" class4="3" class5="1" grid="0" nx="25" ny="25" />

        for torsionTorsion in element.findall('TorsionTorsion'):
Peter Eastman's avatar
Peter Eastman committed
2281
            types = forceField._findAtomTypes(torsionTorsion, 5)
2282
2283
2284
2285
2286
2287
2288
2289
            if types is not None:

                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.types3.append(types[2])
                generator.types4.append(types[3])
                generator.types5.append(types[4])

Peter Eastman's avatar
Peter Eastman committed
2290
2291
                gridIndex = int(torsionTorsion.attrib['grid'])
                if (gridIndex > maxGridIndex):
2292
2293
2294
2295
2296
2297
2298
2299
2300
                    maxGridIndex = gridIndex

                generator.gridIndex.append(gridIndex)
            else:
                outputString = "AmoebaTorsionTorsionGenerator: error getting types: %s %s %s %s %s" % (
                                    torsionTorsion.attrib['class1'],
                                    torsionTorsion.attrib['class2'],
                                    torsionTorsion.attrib['class3'],
                                    torsionTorsion.attrib['class4'],
Peter Eastman's avatar
Peter Eastman committed
2301
2302
                                    torsionTorsion.attrib['class5'] )
                raise ValueError(outputString) 
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
    
        # load grid

        # xml source

        # <TorsionTorsionGrid grid="0" nx="25" ny="25" >
        # <Grid angle1="-180.00" angle2="-180.00" f="0.0" fx="2.31064374824e-05" fy="0.0" fxy="-0.0052801799672" />
        # <Grid angle1="-165.00" angle2="-180.00" f="-0.66600912" fx="-0.06983370052" fy="-0.075058725744" fxy="-0.0044462732032" />

        # output grid:

        #     grid[x][y][0] = x value 
        #     grid[x][y][1] = y value 
        #     grid[x][y][2] = function value 
        #     grid[x][y][3] = dfdx value 
        #     grid[x][y][4] = dfdy value 
        #     grid[x][y][5] = dfd(xy) value 

        maxGridIndex    += 1
Peter Eastman's avatar
Peter Eastman committed
2322
        generator.grids = maxGridIndex*[]
2323
2324
        for torsionTorsionGrid in element.findall('TorsionTorsionGrid'):

Peter Eastman's avatar
Peter Eastman committed
2325
2326
2327
            gridIndex = int(torsionTorsionGrid.attrib[ "grid"])
            nx = int(torsionTorsionGrid.attrib[ "nx"])
            ny = int(torsionTorsionGrid.attrib[ "ny"])
2328

Peter Eastman's avatar
Peter Eastman committed
2329
2330
            grid = []
            gridCol = []
2331
2332
2333
2334
2335

            gridColIndex = 0

            for gridEntry in torsionTorsionGrid.findall('Grid'):

Peter Eastman's avatar
Peter Eastman committed
2336
2337
2338
2339
2340
2341
2342
2343
                gridRow = []
                gridRow.append(float(gridEntry.attrib['angle1']))
                gridRow.append(float(gridEntry.attrib['angle2']))
                gridRow.append(float(gridEntry.attrib['f']))
                gridRow.append(float(gridEntry.attrib['fx']))
                gridRow.append(float(gridEntry.attrib['fy']))
                gridRow.append(float(gridEntry.attrib['fxy']))
                gridCol.append(gridRow)
2344
2345

                gridColIndex  += 1
Peter Eastman's avatar
Peter Eastman committed
2346
2347
2348
                if (gridColIndex == nx):
                    grid.append(gridCol)
                    gridCol = []
2349
2350
2351
                    gridColIndex = 0

            
Peter Eastman's avatar
Peter Eastman committed
2352
2353
            if (gridIndex == len(generator.grids)):
                generator.grids.append(grid)
2354
            else:
Peter Eastman's avatar
Peter Eastman committed
2355
2356
                while(len(generator.grids) < gridIndex):
                    generator.grids.append([])
2357
2358
2359
2360
                generator.grids[gridIndex] = grid

    #=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
2361
    def getChiralAtomIndex(self, data, sys, atomB, atomC, atomD):
2362
2363
2364
2365
2366
2367
2368
2369

        chiralAtomIndex = -1

        # if atomC has four bonds, find the
        # two bonds that do not include atomB and atomD
        # set chiralAtomIndex to one of these, if they are
        # not the same atom(type/mass)

Peter Eastman's avatar
Peter Eastman committed
2370
        if (len(data.atomBonds[atomC]) == 4):
2371
2372
2373
2374
2375
            atomE = -1
            atomF = -1
            for bond in data.atomBonds[atomC]:
                bondedAtom1 = data.bonds[bond].atom1
                bondedAtom2 = data.bonds[bond].atom2
Peter Eastman's avatar
Peter Eastman committed
2376
2377
                hit = -1
                if (  bondedAtom1 == atomC and bondedAtom2 != atomB and bondedAtom2 != atomD):
2378
                    hit = bondedAtom2
Peter Eastman's avatar
Peter Eastman committed
2379
                elif (bondedAtom2 == atomC and bondedAtom1 != atomB and bondedAtom1 != atomD):
2380
2381
                    hit = bondedAtom1

Peter Eastman's avatar
Peter Eastman committed
2382
2383
                if (hit > -1):
                    if (atomE == -1):
2384
2385
2386
2387
2388
2389
                        atomE = hit
                    else:
                        atomF = hit
       
            # raise error if atoms E or F not found

Peter Eastman's avatar
Peter Eastman committed
2390
2391
2392
            if (atomE == -1 or atomF == -1):
                outputString = "getChiralAtomIndex: error getting bonded partners of atomC=%s %d %s" % (atomC.name, atomC.resiude.index, atomC.resiude.name,)
                raise ValueError(outputString) 
2393
2394
2395
2396
2397

            # check for different type/mass between atoms E & F

            typeE = int(data.atomType[data.atoms[atomE]])
            typeF = int(data.atomType[data.atoms[atomF]])
Peter Eastman's avatar
Peter Eastman committed
2398
            if (typeE > typeF):
2399
                chiralAtomIndex = atomE 
Peter Eastman's avatar
Peter Eastman committed
2400
            if (typeF > typeE):
2401
2402
                chiralAtomIndex = atomF 

Peter Eastman's avatar
Peter Eastman committed
2403
2404
2405
            massE = sys.getParticleMass(atomE)/unit.dalton
            massF = sys.getParticleMass(atomE)/unit.dalton
            if (massE > massF):
2406
                chiralAtomIndex = massE 
Peter Eastman's avatar
Peter Eastman committed
2407
            if (massF > massE):
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
                chiralAtomIndex = massF 

        return chiralAtomIndex

    #=============================================================================================
 
    def createForce(self, sys, data, nonpiTorsionedMethod, nonpiTorsionedCutoff, args):

        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
        existing = [f for f in existing if type(f) == mm.AmoebaTorsionTorsionForce]

        if len(existing) == 0:
            force = mm.AmoebaTorsionTorsionForce()
            sys.addForce(force)
        else:
            force = existing[0]

        for angle in data.angles:

            # search for bitorsions; based on TINKER subroutine bitors() 
 
            ib = angle[0]
            ic = angle[1]
            id = angle[2]

            for bondIndex in data.atomBonds[ib]:
                bondedAtom1 = data.bonds[bondIndex].atom1
                bondedAtom2 = data.bonds[bondIndex].atom2
Peter Eastman's avatar
Peter Eastman committed
2436
                if (bondedAtom1 != ib):
2437
2438
2439
2440
                    ia = bondedAtom1
                else:
                    ia = bondedAtom2

Peter Eastman's avatar
Peter Eastman committed
2441
                if (ia != ic and ia != id):
2442
2443
2444
                    for bondIndex in data.atomBonds[id]:
                        bondedAtom1 = data.bonds[bondIndex].atom1
                        bondedAtom2 = data.bonds[bondIndex].atom2
Peter Eastman's avatar
Peter Eastman committed
2445
                        if (bondedAtom1 != id):
2446
2447
2448
2449
                            ie = bondedAtom1
                        else:
                            ie = bondedAtom2

Peter Eastman's avatar
Peter Eastman committed
2450
                        if (ie != ic and ie != ib and ie != ia):
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470

                            # found candidate set of atoms
                            # check if types match in order or reverse order

                            type1 = data.atomType[data.atoms[ia]]
                            type2 = data.atomType[data.atoms[ib]]
                            type3 = data.atomType[data.atoms[ic]]
                            type4 = data.atomType[data.atoms[id]]
                            type5 = data.atomType[data.atoms[ie]]

                            for i in range(len(self.types1)):

                                types1 = self.types1[i]
                                types2 = self.types2[i]
                                types3 = self.types3[i]
                                types4 = self.types4[i]
                                types5 = self.types5[i]

                                # match in order

Peter Eastman's avatar
Peter Eastman committed
2471
2472
2473
                                if (type1 in types1 and type2 in types2 and type3 in types3 and type4 in types4 and type5 in types5):
                                    chiralAtomIndex = self.getChiralAtomIndex(data, sys, ib, ic, id)
                                    force.addTorsionTorsion(ia, ib, ic, id, ie, chiralAtomIndex, self.gridIndex[i])
2474
2475
2476

                                # match in reverse order

Peter Eastman's avatar
Peter Eastman committed
2477
2478
2479
                                if (type5 in types1 and type4 in types2 and type3 in types3 and type2 in types4 and type1 in types5):
                                    chiralAtomIndex = self.getChiralAtomIndex(data, sys, ib, ic, id)
                                    force.addTorsionTorsion(ie, id, ic, ib, ia, chiralAtomIndex, self.gridIndex[i])
2480
2481
2482
2483

        # set grids

        for (index, grid) in enumerate(self.grids):
Peter Eastman's avatar
Peter Eastman committed
2484
            force.setTorsionTorsionGrid(index, grid)
2485
2486
2487
2488
2489
 
parsers["AmoebaTorsionTorsionForce"] = AmoebaTorsionTorsionGenerator.parseElement

#=============================================================================================

2490
## @private
2491
class AmoebaStretchBendGenerator:
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2492
2493

    #=============================================================================================
2494
2495
2496
2497
2498
    """An AmoebaStretchBendGenerator constructs a AmoebaStretchBendForce."""
    #=============================================================================================

    def __init__(self):

Peter Eastman's avatar
Peter Eastman committed
2499
2500
2501
        self.types1 = []
        self.types2 = []
        self.types3 = []
2502

Peter Eastman's avatar
Peter Eastman committed
2503
2504
        self.k1 = []
        self.k2 = []
2505
2506
2507
2508
2509
    
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):
Peter Eastman's avatar
Peter Eastman committed
2510
        generator = AmoebaStretchBendGenerator()
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
        forceField._forces.append(generator)

        # <AmoebaStretchBendForce stretchBendUnit="1.0">
        # <StretchBend class1="2" class2="1" class3="3" k1="5.25776946506" k2="5.25776946506" />
        # <StretchBend class1="2" class2="1" class3="4" k1="3.14005676385" k2="3.14005676385" />

        for stretchBend in element.findall('StretchBend'):
            types = forceField._findAtomTypes(stretchBend, 3)
            if types is not None:

                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.types3.append(types[2])

                generator.k1.append(float(stretchBend.attrib['k1']))
                generator.k2.append(float(stretchBend.attrib['k2']))

            else:
                outputString = "AmoebaStretchBendGenerator : error getting types: %s %s %s" % (
                                    stretchBend.attrib['class1'],
                                    stretchBend.attrib['class2'],
Peter Eastman's avatar
Peter Eastman committed
2532
2533
                                    stretchBend.attrib['class3'])
                raise ValueError(outputString) 
2534
2535
2536
    
    #=============================================================================================

2537
    # The setup of this force is dependent on AmoebaBondForce and AmoebaAngleForce 
2538
2539
    # having been called since the ideal bond lengths and angle are needed here.
    # As a conseqeunce, createForce() is not implemented since it is not guaranteed that the generator for
2540
2541
2542
    # AmoebaBondForce and AmoebaAngleForce have been called prior to AmoebaStretchBendGenerator(). 
    # Instead, createForcePostAmoebaBondForce() is called 
    # after the generators for AmoebaBondForce and AmoebaAngleForce have been called
2543
2544
2545

    #=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
2546
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
2547
2548
2549
2550
2551
2552
2553
2554
        pass

    #=============================================================================================

    # Note: request for constrained bonds is ignored.

    #=============================================================================================

2555
    def createForcePostAmoebaBondForce(self, sys, data, nonbondedMethod, nonbondedCutoff, angleList, args):
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567

        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
        existing = [f for f in existing if type(f) == mm.AmoebaStretchBendForce]
        if len(existing) == 0:
            force = mm.AmoebaStretchBendForce()
            sys.addForce(force)
        else:
            force = existing[0]

        for angleDict in angleList:

            angle = angleDict['angle']
Peter Eastman's avatar
Peter Eastman committed
2568
            if ('isConstrained' in angleDict):
2569
2570
2571
2572
2573
2574
2575
2576
                isConstrained = angleDict['isConstrained']
            else:
                isConstrained = 0

            type1 = data.atomType[data.atoms[angle[0]]]
            type2 = data.atomType[data.atoms[angle[1]]]
            type3 = data.atomType[data.atoms[angle[2]]]

Peter Eastman's avatar
Peter Eastman committed
2577
            radian = 57.2957795130
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
            for i in range(len(self.types1)):

                types1 = self.types1[i]
                types2 = self.types2[i]
                types3 = self.types3[i]

                # match types
                # get ideal bond lengths, bondAB, bondCB
                # get ideal angle

Peter Eastman's avatar
Peter Eastman committed
2588
                if (type2 in types2 and ((type1 in types1 and type3 in types3) or (type3 in types1 and type1 in types3))): 
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
                    bondAB = -1.0
                    bondCB = -1.0
                    swap = 0
                    for bond in data.atomBonds[angle[1]]:
                        atom1 = data.bonds[bond].atom1
                        atom2 = data.bonds[bond].atom2
                        length = data.bonds[bond].length
                        if (atom1 == angle[0]):
                            bondAB = length
                        if (atom1 == angle[2]):
                            bondCB = length
                        if (atom2 == angle[2]):
                            bondCB = length
                        if (atom2 == angle[0]):
                            bondAB = length
                    
                    # check that ideal angle and bonds are set
2606

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2607
                    if ('idealAngle' not in angleDict):
2608

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2609
2610
2611
2612
2613
2614
                       outputString = "AmoebaStretchBendGenerator: ideal angle is not set for following entry:\n"
                       outputString += "   types: %5s %5s %5s atoms: " % (type1, type2, type3)
                       outputString += getAtomPrint( data, angle[0] ) + ' '
                       outputString += getAtomPrint( data, angle[1] ) + ' '
                       outputString += getAtomPrint( data, angle[2] )
                       raise ValueError(outputString) 
2615

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2616
2617
2618
2619
2620
2621
2622
2623
                    elif (bondAB < 0 or bondCB < 0):

                       outputString = "AmoebaStretchBendGenerator: bonds not set: %15.7e %15.7e. for following entry:" % (bondAB, bondCB)
                       outputString += "     types: [%5s %5s %5s] atoms: " % (type1, type2, type3)
                       outputString += getAtomPrint( data, angle[0] ) + ' '
                       outputString += getAtomPrint( data, angle[1] ) + ' '
                       outputString += getAtomPrint( data, angle[2] )
                       raise ValueError(outputString) 
2624

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2625
2626
                    else:
                        force.addStretchBend(angle[0], angle[1], angle[2], bondAB, bondCB, angleDict['idealAngle']/radian, self.k1[i])
2627

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2628
                    break
2629
2630
2631
2632
2633

parsers["AmoebaStretchBendForce"] = AmoebaStretchBendGenerator.parseElement

#=============================================================================================

2634
## @private
2635
2636
2637
2638
2639
2640
class AmoebaVdwGenerator:

    """A AmoebaVdwGenerator constructs a AmoebaVdwForce."""
    
    #=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
2641
    def __init__(self, type, radiusrule, radiustype, radiussize, epsilonrule, vdw13Scale, vdw14Scale, vdw15Scale):
2642

Peter Eastman's avatar
Peter Eastman committed
2643
        self.type = type 
2644

Peter Eastman's avatar
Peter Eastman committed
2645
2646
2647
        self.radiusrule = radiusrule
        self.radiustype = radiustype
        self.radiussize = radiussize
2648

Peter Eastman's avatar
Peter Eastman committed
2649
        self.epsilonrule = epsilonrule
2650

Peter Eastman's avatar
Peter Eastman committed
2651
2652
2653
        self.vdw13Scale = vdw13Scale
        self.vdw14Scale = vdw14Scale
        self.vdw15Scale = vdw15Scale
2654

Peter Eastman's avatar
Peter Eastman committed
2655
        self.typeMap = {}
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665

    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

        # <AmoebaVdwForce type="BUFFERED-14-7" radiusrule="CUBIC-MEAN" radiustype="R-MIN" radiussize="DIAMETER" epsilonrule="HHG" vdw-13-scale="0.0" vdw-14-scale="1.0" vdw-15-scale="1.0" >
        #   <Vdw class="1" sigma="0.371" epsilon="0.46024" reduction="1.0" /> 
        #   <Vdw class="2" sigma="0.382" epsilon="0.422584" reduction="1.0" /> 
         
Peter Eastman's avatar
Peter Eastman committed
2666
2667
        generator = AmoebaVdwGenerator(element.attrib['type'], element.attrib['radiusrule'], element.attrib['radiustype'], element.attrib['radiussize'], element.attrib['epsilonrule'], 
                                        float(element.attrib['vdw-13-scale']), float(element.attrib['vdw-14-scale']), float(element.attrib['vdw-15-scale'])) 
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
        forceField._forces.append(generator)
        two_six = 1.122462048309372

        # types[] = [ sigma, epsilon, reductionFactor, class ]
        # sigma is modified based on radiustype and radiussize

        for atom in element.findall('Vdw'):
            types = forceField._findAtomTypes(atom, 1)
            if types is not None:

Peter Eastman's avatar
Peter Eastman committed
2678
                values = [float(atom.attrib['sigma']), float(atom.attrib['epsilon']), float(atom.attrib['reduction'])]
2679
2680


Peter Eastman's avatar
Peter Eastman committed
2681
                if (generator.radiustype == 'SIGMA'):
2682
2683
                    values[0] *= two_six
      
Peter Eastman's avatar
Peter Eastman committed
2684
                if (generator.radiussize == 'DIAMETER'):
2685
2686
2687
2688
2689
2690
                    values[0] *= 0.5

                for t in types[0]:
                    generator.typeMap[t] = values
    
            else:
Peter Eastman's avatar
Peter Eastman committed
2691
2692
                outputString = "AmoebaVdwGenerator: error getting type: %s" % (atom.attrib['class'])
                raise ValueError(outputString) 
2693
2694
2695
2696
2697
2698
2699
2700
    
    #=============================================================================================

    # Return a set containing the indices of particles bonded to particle with index=particleIndex

    #=============================================================================================

    @staticmethod
Peter Eastman's avatar
Peter Eastman committed
2701
    def getBondedParticleSet(particleIndex, data):
2702
2703
2704
2705
2706
2707

        bondedParticleSet = set()

        for bond in data.atomBonds[particleIndex]:
            atom1 = data.bonds[bond].atom1
            atom2 = data.bonds[bond].atom2
Peter Eastman's avatar
Peter Eastman committed
2708
2709
            if (atom1 != particleIndex):
                bondedParticleSet.add(atom1)
2710
            else:
Peter Eastman's avatar
Peter Eastman committed
2711
                bondedParticleSet.add(atom2)
2712
2713
2714
2715
2716

        return bondedParticleSet
          
    #=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
2717
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
2718

Peter Eastman's avatar
Peter Eastman committed
2719
        sigmaMap = {'ARITHMETIC':1, 'GEOMETRIC':1, 'CUBIC-MEAN':1}
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
        epsilonMap = {'ARITHMETIC':1, 'GEOMETRIC':1, 'HARMONIC':1, 'HHG':1}

        # get or create force depending on whether it has already been added to the system

        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
        existing = [f for f in existing if type(f) == mm.AmoebaVdwForce]
        if len(existing) == 0:
            force = mm.AmoebaVdwForce()
            sys.addForce(force)

            # sigma and epsilon combining rules

Peter Eastman's avatar
Peter Eastman committed
2732
            if ('sigmaCombiningRule' in args):
2733
                sigmaRule = args['sigmaCombiningRule'].upper()
Peter Eastman's avatar
Peter Eastman committed
2734
2735
                if (sigmaRule.upper() in sigmaMap):
                    force.setSigmaCombiningRule(sigmaRule.upper())
2736
                else:
Peter Eastman's avatar
Peter Eastman committed
2737
                    stringList = ' ' . join(str(x) for x in sigmaMap.keys())
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2738
                    raise ValueError( "AmoebaVdwGenerator: sigma combining rule %s not recognized; valid values are %s; using default." % (sigmaRule, stringList) )
2739
            else:
Peter Eastman's avatar
Peter Eastman committed
2740
                force.setSigmaCombiningRule(self.radiusrule)
2741

Peter Eastman's avatar
Peter Eastman committed
2742
            if ('epsilonCombiningRule' in args):
2743
                epsilonRule = args['epsilonCombiningRule'].upper()
Peter Eastman's avatar
Peter Eastman committed
2744
2745
                if (epsilonRule.upper() in epsilonMap):
                    force.setEpsilonCombiningRule(epsilonRule.upper())
2746
                else:
Peter Eastman's avatar
Peter Eastman committed
2747
                    stringList = ' ' . join(str(x) for x in epsilonMap.keys())
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2748
                    raise ValueError( "AmoebaVdwGenerator: epsilon combining rule %s not recognized; valid values are %s; using default." % (epsilonRule, stringList) )  
2749
            else:
Peter Eastman's avatar
Peter Eastman committed
2750
                force.setEpsilonCombiningRule(self.epsilonrule)
2751
2752
2753
               
            # cutoff

Peter Eastman's avatar
Peter Eastman committed
2754
            if ('vdwCutoff' in args):
2755
                force.setCutoff(args['vdwCutoff'])
2756
            else:
Peter Eastman's avatar
Peter Eastman committed
2757
                force.setCutoff(nonbondedCutoff)
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2758

2759
2760
2761
2762
2763
            # dispersion correction

            if ('useDispersionCorrection' in args):
                force.setUseDispersionCorrection(int(args['useDispersionCorrection']))

Peter Eastman's avatar
Peter Eastman committed
2764
            if (nonbondedMethod == PME):
2765
                force.setNonbondedMethod(mm.AmoebaVdwForce.CutoffPeriodic)
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
           
        else:
            force = existing[0]

        # add particles to force
        # throw error if particle type not available 

        for (i, atom) in enumerate(data.atoms):
            t = data.atomType[atom]
            if t in self.typeMap:

Peter Eastman's avatar
Peter Eastman committed
2777
                values = self.typeMap[t]
2778
2779
2780
   
                # ivIndex = index of bonded partner for hydrogens; otherwise ivIndex = particle index

Peter Eastman's avatar
Peter Eastman committed
2781
2782
2783
                ivIndex = i
                mass = sys.getParticleMass(i)/unit.dalton
                if (mass < 1.9 and len(data.atomBonds[i]) == 1):
2784
                    bondIndex = data.atomBonds[i][0]
Peter Eastman's avatar
Peter Eastman committed
2785
                    if (data.bonds[bondIndex].atom1 == i):
2786
2787
2788
2789
                        ivIndex = data.bonds[bondIndex].atom2
                    else:
                        ivIndex = data.bonds[bondIndex].atom1

2790
                force.addParticle(ivIndex, values[0], values[1], values[2])
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
            else:
                raise ValueError('No vdw type for atom %s' % (atom.name))

        # set combining rules

        # set particle exclusions: self, 1-2 and 1-3 bonds
        # (1) collect in bondedParticleSets[i], 1-2 indices for all bonded partners of particle i
        # (2) add 1-2,1-3 and self to exclusion set

        bondedParticleSets = []
        for i in range(len(data.atoms)):
Peter Eastman's avatar
Peter Eastman committed
2802
            bondedParticleSets.append(AmoebaVdwGenerator.getBondedParticleSet(i, data))
2803
2804
2805
2806
2807
2808
2809
2810
2811

        for (i,atom) in enumerate(data.atoms):
 
            # 1-2 partners

            exclusionSet = bondedParticleSets[i].copy()

            # 1-3 partners

Peter Eastman's avatar
Peter Eastman committed
2812
            if (self.vdw13Scale == 0.0):
2813
                for bondedParticle in bondedParticleSets[i]:
Peter Eastman's avatar
Peter Eastman committed
2814
                    exclusionSet = exclusionSet.union(bondedParticleSets[bondedParticle])
2815
2816
2817
2818
2819

            # self

            exclusionSet.add(i)

Peter Eastman's avatar
Peter Eastman committed
2820
            force.setParticleExclusions(i, exclusionSet)
2821
2822
2823
2824
2825

parsers["AmoebaVdwForce"] = AmoebaVdwGenerator.parseElement

#=============================================================================================

2826
## @private
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
class AmoebaMultipoleGenerator:

    #=============================================================================================

    """A AmoebaMultipoleGenerator constructs a AmoebaMultipoleForce."""
    
    #=============================================================================================

    def __init__(self, forceField,
                       direct11Scale, direct12Scale, direct13Scale, direct14Scale,
                       mpole12Scale,  mpole13Scale,  mpole14Scale,  mpole15Scale,
                       mutual11Scale, mutual12Scale, mutual13Scale, mutual14Scale,
Peter Eastman's avatar
Peter Eastman committed
2839
                       polar12Scale,  polar13Scale,  polar14Scale,  polar15Scale):
2840

Peter Eastman's avatar
Peter Eastman committed
2841
        self.forceField = forceField
2842

Peter Eastman's avatar
Peter Eastman committed
2843
2844
2845
2846
        self.direct11Scale = direct11Scale 
        self.direct12Scale = direct12Scale 
        self.direct13Scale = direct13Scale 
        self.direct14Scale = direct14Scale 
2847

Peter Eastman's avatar
Peter Eastman committed
2848
2849
2850
2851
        self.mpole12Scale = mpole12Scale 
        self.mpole13Scale = mpole13Scale 
        self.mpole14Scale = mpole14Scale 
        self.mpole15Scale = mpole15Scale 
2852

Peter Eastman's avatar
Peter Eastman committed
2853
2854
2855
2856
        self.mutual11Scale = mutual11Scale 
        self.mutual12Scale = mutual12Scale 
        self.mutual13Scale = mutual13Scale 
        self.mutual14Scale = mutual14Scale 
2857

Peter Eastman's avatar
Peter Eastman committed
2858
2859
2860
2861
        self.polar12Scale = polar12Scale 
        self.polar13Scale = polar13Scale 
        self.polar14Scale = polar14Scale 
        self.polar15Scale = polar15Scale 
2862

Peter Eastman's avatar
Peter Eastman committed
2863
        self.typeMap = {}
2864
2865
2866
2867
2868
2869

    #=============================================================================================
    # Set axis type
    #=============================================================================================

    @staticmethod
Peter Eastman's avatar
Peter Eastman committed
2870
    def setAxisType(kIndices):
2871
2872
2873

                # set axis type

Peter Eastman's avatar
Peter Eastman committed
2874
2875
2876
                kIndicesLen = len(kIndices)
                if (kIndicesLen > 3):
                    ky = kIndices[3]
2877
                else:
Peter Eastman's avatar
Peter Eastman committed
2878
                    ky = 0
2879
   
Peter Eastman's avatar
Peter Eastman committed
2880
2881
                if (kIndicesLen > 2):
                    kx = kIndices[2]
2882
                else:
Peter Eastman's avatar
Peter Eastman committed
2883
                    kx = 0
2884
   
Peter Eastman's avatar
Peter Eastman committed
2885
2886
                if (kIndicesLen > 1):
                    kz = kIndices[1]
2887
                else:
Peter Eastman's avatar
Peter Eastman committed
2888
                    kz = 0
2889

Peter Eastman's avatar
Peter Eastman committed
2890
2891
                while(len(kIndices) < 4):
                    kIndices.append(0)
2892
2893

                axisType = mm.AmoebaMultipoleForce.ZThenX
Peter Eastman's avatar
Peter Eastman committed
2894
                if (kz == 0):
2895
                    axisType = mm.AmoebaMultipoleForce.NoAxisType
Peter Eastman's avatar
Peter Eastman committed
2896
                if (kz != 0 and kx == 0):
2897
                    axisType = mm.AmoebaMultipoleForce.ZOnly
Peter Eastman's avatar
Peter Eastman committed
2898
                if (kz < 0 or kx < 0):
2899
                    axisType = mm.AmoebaMultipoleForce.Bisector
Peter Eastman's avatar
Peter Eastman committed
2900
                if (kx < 0 and ky < 0):
2901
                    axisType = mm.AmoebaMultipoleForce.ZBisect
Peter Eastman's avatar
Peter Eastman committed
2902
                if (kz < 0 and kx < 0 and ky  < 0):
2903
2904
                    axisType = mm.AmoebaMultipoleForce.ThreeFold

Peter Eastman's avatar
Peter Eastman committed
2905
2906
2907
                kIndices[1] = abs(kz)   
                kIndices[2] = abs(kx)   
                kIndices[3] = abs(ky)   
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919

                return axisType

    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

        #   <AmoebaMultipoleForce  direct11Scale="0.0"  direct12Scale="1.0"  direct13Scale="1.0"  direct14Scale="1.0"  mpole12Scale="0.0"  mpole13Scale="0.0"  mpole14Scale="0.4"  mpole15Scale="0.8"  mutual11Scale="1.0"  mutual12Scale="1.0"  mutual13Scale="1.0"  mutual14Scale="1.0"  polar12Scale="0.0"  polar13Scale="0.0"  polar14Intra="0.5"  polar14Scale="1.0"  polar15Scale="1.0"  > 
        # <Multipole class="1"    kz="2"    kx="4"    c0="-0.22620" d1="0.08214" d2="0.00000" d3="0.34883" q11="0.11775" q21="0.00000" q22="-1.02185" q31="-0.17555" q32="0.00000" q33="0.90410"  />
        # <Multipole class="2"    kz="1"    kx="3"    c0="-0.15245" d1="0.19517" d2="0.00000" d3="0.19687" q11="-0.20677" q21="0.00000" q22="-0.48084" q31="-0.01672" q32="0.00000" q33="0.68761"  />

Peter Eastman's avatar
Peter Eastman committed
2920
        generator = AmoebaMultipoleGenerator(forceField,
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
                                              element.attrib['direct11Scale'],
                                              element.attrib['direct12Scale'],
                                              element.attrib['direct13Scale'],
                                              element.attrib['direct14Scale'],

                                              element.attrib['mpole12Scale'],
                                              element.attrib['mpole13Scale'],
                                              element.attrib['mpole14Scale'],
                                              element.attrib['mpole15Scale'],

                                              element.attrib['mutual11Scale'],
                                              element.attrib['mutual12Scale'],
                                              element.attrib['mutual13Scale'],
                                              element.attrib['mutual14Scale'],

                                              element.attrib['polar12Scale'],
                                              element.attrib['polar13Scale'],
                                              element.attrib['polar14Scale'],
Peter Eastman's avatar
Peter Eastman committed
2939
                                              element.attrib['polar15Scale'])
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957



        forceField._forces.append(generator)

        # set type map: [ kIndices, multipoles, AMOEBA/OpenMM axis type]

        for atom in element.findall('Multipole'):
            types = forceField._findAtomTypes(atom, 1)
            if types is not None:

                # k-indices not provided default to 0

                kIndices = [int(atom.attrib['type'])]

                kStrings = [ 'kz', 'kx', 'ky' ]
                for kString in kStrings:
                    try:
Peter Eastman's avatar
Peter Eastman committed
2958
2959
                        if (atom.attrib[kString]):
                             kIndices.append(int(atom.attrib[kString]))
2960
2961
2962
2963
2964
                    except: 
                        pass

                # set axis type based on k-Indices 

Peter Eastman's avatar
Peter Eastman committed
2965
                axisType = AmoebaMultipoleGenerator.setAxisType(kIndices)
2966
2967
2968

                # set multipole

Peter Eastman's avatar
Peter Eastman committed
2969
                charge = float(atom.attrib['c0'])
2970
 
Peter Eastman's avatar
Peter Eastman committed
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
                conversion = 1.0
                dipole = [ conversion*float(atom.attrib['d1']), conversion*float(atom.attrib['d2']), conversion*float(atom.attrib['d3'])]

                quadrupole = []
                quadrupole.append(conversion*float(atom.attrib['q11']))
                quadrupole.append(conversion*float(atom.attrib['q21']))
                quadrupole.append(conversion*float(atom.attrib['q31']))
                quadrupole.append(conversion*float(atom.attrib['q21']))
                quadrupole.append(conversion*float(atom.attrib['q22']))
                quadrupole.append(conversion*float(atom.attrib['q32']))
                quadrupole.append(conversion*float(atom.attrib['q31']))
                quadrupole.append(conversion*float(atom.attrib['q32']))
                quadrupole.append(conversion*float(atom.attrib['q33']))
2984
2985

                for t in types[0]:
Peter Eastman's avatar
Peter Eastman committed
2986
                    if (t not in generator.typeMap):
2987
2988
                        generator.typeMap[t] = []

Peter Eastman's avatar
Peter Eastman committed
2989
2990
2991
2992
2993
2994
2995
2996
                    valueMap = dict()
                    valueMap['classIndex'] = atom.attrib['type']
                    valueMap['kIndices'] = kIndices
                    valueMap['charge'] = charge 
                    valueMap['dipole'] = dipole
                    valueMap['quadrupole'] = quadrupole
                    valueMap['axisType'] = axisType
                    generator.typeMap[t].append(valueMap)
2997
2998
    
            else:
Peter Eastman's avatar
Peter Eastman committed
2999
3000
                outputString = "AmoebaMultipoleGenerator: error getting type for multipole: %s" % (atom.attrib['class'])
                raise ValueError(outputString) 
3001
3002
3003
3004
3005
3006
3007
    
        # polarization parameters
 
        for atom in element.findall('Polarize'):
            types = forceField._findAtomTypes(atom, 1)
            if types is not None:

Peter Eastman's avatar
Peter Eastman committed
3008
3009
3010
3011
                classIndex = atom.attrib['type']
                polarizability = float(atom.attrib['polarizability'])
                thole = float(atom.attrib['thole'])
                if (thole == 0):
3012
3013
                    pdamp = 0
                else:
Peter Eastman's avatar
Peter Eastman committed
3014
                    pdamp = pow(polarizability, 1.0/6.0)
3015

Peter Eastman's avatar
Peter Eastman committed
3016
3017
                pgrpMap = dict()
                for index in range(1, 7):
3018
                    pgrp = 'pgrp' + str(index)
Peter Eastman's avatar
Peter Eastman committed
3019
                    if (pgrp in atom.attrib):
3020
3021
3022
                        pgrpMap[int(atom.attrib[pgrp])] = -1

                for t in types[0]:
Peter Eastman's avatar
Peter Eastman committed
3023
3024
3025
                    if (t not in generator.typeMap):
                        outputString = "AmoebaMultipoleGenerator: polarize type not present: %s" % (atom.attrib['type'])
                        raise ValueError(outputString) 
3026
3027
                    else:
                        typeMapList = generator.typeMap[t]
Peter Eastman's avatar
Peter Eastman committed
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
                        hit = 0
                        for (ii, typeMap) in enumerate(typeMapList):

                            if (typeMap['classIndex'] == classIndex):
                                typeMap['polarizability'] = polarizability
                                typeMap['thole'] = thole
                                typeMap['pdamp'] = pdamp
                                typeMap['pgrpMap'] = pgrpMap 
                                typeMapList[ii] = typeMap
                                hit = 1

                        if (hit == 0):
                            outputString = "AmoebaMultipoleGenerator: error getting type for polarize: class index=%s not in multipole list?" % (atom.attrib['class'])
                            raise ValueError(outputString) 
3042
3043
    
            else:
Peter Eastman's avatar
Peter Eastman committed
3044
3045
                outputString = "AmoebaMultipoleGenerator: error getting type for polarize: %s" % (atom.attrib['class'])
                raise ValueError(outputString) 
3046
3047
3048
    
    #=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
3049
    def setPolarGroups(self, data, bonded12ParticleSets, force):
3050
3051
3052
3053
3054

        for (atomIndex, atom) in enumerate(data.atoms):

            # assign multipole parameters via only 1-2 connected atoms

Peter Eastman's avatar
Peter Eastman committed
3055
3056
3057
3058
            multipoleDict = atom.multipoleDict
            pgrpMap = multipoleDict['pgrpMap']
            bondedAtomIndices = bonded12ParticleSets[atomIndex]
            atom.stage = -1
3059
3060
3061
3062
            atom.polarizationGroupSet = list()
            atom.polarizationGroups[atomIndex] = 1
            for bondedAtomIndex in bondedAtomIndices:
                bondedAtomType = int(data.atomType[data.atoms[bondedAtomIndex]])
Peter Eastman's avatar
Peter Eastman committed
3063
3064
                bondedAtom = data.atoms[bondedAtomIndex]
                if (bondedAtomType in pgrpMap):
3065
3066
3067
3068
3069
3070
3071
                    atom.polarizationGroups[bondedAtomIndex] = 1
                    bondedAtom.polarizationGroups[atomIndex] = 1
                    
        # pgrp11

        for (atomIndex, atom) in enumerate(data.atoms):

Peter Eastman's avatar
Peter Eastman committed
3072
            if (len( data.atoms[atomIndex].polarizationGroupSet) > 0):
3073
3074
                continue

Peter Eastman's avatar
Peter Eastman committed
3075
3076
            group = set()
            visited = set()
3077
3078
            notVisited = set()
            for pgrpAtomIndex in atom.polarizationGroups:
Peter Eastman's avatar
Peter Eastman committed
3079
3080
3081
3082
                group.add(pgrpAtomIndex)
                notVisited.add(pgrpAtomIndex)
            visited.add(atomIndex)
            while(len(notVisited) > 0):
3083
                nextAtom = notVisited.pop()
Peter Eastman's avatar
Peter Eastman committed
3084
3085
                if (nextAtom not in visited):
                   visited.add(nextAtom)
3086
                   for ii in data.atoms[nextAtom].polarizationGroups:
Peter Eastman's avatar
Peter Eastman committed
3087
3088
3089
                       group.add(ii)
                       if (ii not in visited):
                           notVisited.add(ii)
3090
3091
3092

            pGroup = group
            for pgrpAtomIndex in group:
Peter Eastman's avatar
Peter Eastman committed
3093
                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pGroup)
3094
3095

        for (atomIndex, atom) in enumerate(data.atoms):
Peter Eastman's avatar
Peter Eastman committed
3096
3097
            atom.polarizationGroupSet[0] = sorted(atom.polarizationGroupSet[0])
            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent11, atom.polarizationGroupSet[0])
3098
3099
3100
3101
3102

        # pgrp12

        for (atomIndex, atom) in enumerate(data.atoms):

Peter Eastman's avatar
Peter Eastman committed
3103
            if (len( data.atoms[atomIndex].polarizationGroupSet) > 1):
3104
3105
                continue

Peter Eastman's avatar
Peter Eastman committed
3106
            pgrp11 = set(atom.polarizationGroupSet[0])
3107
3108
3109
            pgrp12 = set()
            for pgrpAtomIndex in pgrp11:
                for bonded12 in bonded12ParticleSets[pgrpAtomIndex]:
Peter Eastman's avatar
Peter Eastman committed
3110
                    pgrp12 = pgrp12.union(data.atoms[bonded12].polarizationGroupSet[0])
3111
3112
            pgrp12 = pgrp12 - pgrp11
            for pgrpAtomIndex in pgrp11:
Peter Eastman's avatar
Peter Eastman committed
3113
                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pgrp12)
3114
3115
                
        for (atomIndex, atom) in enumerate(data.atoms):
Peter Eastman's avatar
Peter Eastman committed
3116
3117
            atom.polarizationGroupSet[1] = sorted(atom.polarizationGroupSet[1])
            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent12, atom.polarizationGroupSet[1])
3118
3119
3120
3121
3122

        # pgrp13

        for (atomIndex, atom) in enumerate(data.atoms):

Peter Eastman's avatar
Peter Eastman committed
3123
            if (len(data.atoms[atomIndex].polarizationGroupSet) > 2):
3124
3125
                continue

Peter Eastman's avatar
Peter Eastman committed
3126
3127
            pgrp11 = set(atom.polarizationGroupSet[0])
            pgrp12 = set(atom.polarizationGroupSet[1])
3128
3129
3130
            pgrp13 = set()
            for pgrpAtomIndex in pgrp12:
                for bonded12 in bonded12ParticleSets[pgrpAtomIndex]:
Peter Eastman's avatar
Peter Eastman committed
3131
                    pgrp13 = pgrp13.union(data.atoms[bonded12].polarizationGroupSet[0])
3132
            pgrp13 = pgrp13 - pgrp12
Peter Eastman's avatar
Peter Eastman committed
3133
            pgrp13 = pgrp13 - set(pgrp11)
3134
            for pgrpAtomIndex in pgrp11:
Peter Eastman's avatar
Peter Eastman committed
3135
                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pgrp13)
3136
3137
                
        for (atomIndex, atom) in enumerate(data.atoms):
Peter Eastman's avatar
Peter Eastman committed
3138
3139
            atom.polarizationGroupSet[2] = sorted(atom.polarizationGroupSet[2])
            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent13, atom.polarizationGroupSet[2])
3140
3141
3142
3143
3144

        # pgrp14

        for (atomIndex, atom) in enumerate(data.atoms):

Peter Eastman's avatar
Peter Eastman committed
3145
            if (len(data.atoms[atomIndex].polarizationGroupSet) > 3):
3146
3147
                continue

Peter Eastman's avatar
Peter Eastman committed
3148
3149
3150
            pgrp11 = set(atom.polarizationGroupSet[0])
            pgrp12 = set(atom.polarizationGroupSet[1])
            pgrp13 = set(atom.polarizationGroupSet[2])
3151
3152
3153
            pgrp14 = set()
            for pgrpAtomIndex in pgrp13:
                for bonded12 in bonded12ParticleSets[pgrpAtomIndex]:
Peter Eastman's avatar
Peter Eastman committed
3154
                    pgrp14 = pgrp14.union(data.atoms[bonded12].polarizationGroupSet[0])
3155
3156
3157

            pgrp14 = pgrp14 - pgrp13
            pgrp14 = pgrp14 - pgrp12
Peter Eastman's avatar
Peter Eastman committed
3158
            pgrp14 = pgrp14 - set(pgrp11)
3159
3160

            for pgrpAtomIndex in pgrp11:
Peter Eastman's avatar
Peter Eastman committed
3161
                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pgrp14)
3162
3163
                
        for (atomIndex, atom) in enumerate(data.atoms):
Peter Eastman's avatar
Peter Eastman committed
3164
3165
            atom.polarizationGroupSet[3] = sorted(atom.polarizationGroupSet[3])
            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent14, atom.polarizationGroupSet[3])
3166
3167
3168

    #=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
3169
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180

        methodMap = {NoCutoff:mm.AmoebaMultipoleForce.NoCutoff,
                     PME:mm.AmoebaMultipoleForce.PME}

        # get or create force depending on whether it has already been added to the system

        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
        existing = [f for f in existing if type(f) == mm.AmoebaMultipoleForce]
        if len(existing) == 0:
            force = mm.AmoebaMultipoleForce()
            sys.addForce(force)
Peter Eastman's avatar
Peter Eastman committed
3181
            if (nonbondedMethod not in methodMap): 
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3182
                raise ValueError( "AmoebaMultipoleForce: input cutoff method not available." )
3183
            else:
Peter Eastman's avatar
Peter Eastman committed
3184
                force.setNonbondedMethod(methodMap[nonbondedMethod])
3185
3186
            force.setCutoffDistance(nonbondedCutoff)

Peter Eastman's avatar
Peter Eastman committed
3187
            if ('ewaldErrorTolerance' in args):
3188
3189
                force.setEwaldErrorTolerance(float(args['ewaldErrorTolerance']))

Peter Eastman's avatar
Peter Eastman committed
3190
            if ('polarization' in args):
3191
                polarizationType = args['polarization']
Peter Eastman's avatar
Peter Eastman committed
3192
                if (polarizationType.lower() == 'direct'):
3193
3194
3195
3196
                    force.setPolarizationType(mm.AmoebaMultipoleForce.Direct)
                else:
                    force.setPolarizationType(mm.AmoebaMultipoleForce.Mutual)

Peter Eastman's avatar
Peter Eastman committed
3197
3198
            if ('aEwald' in args):
                force.setAEwald(float(args['aEwald']))
3199

Peter Eastman's avatar
Peter Eastman committed
3200
            if ('pmeGridDimensions' in args):
3201
3202
                force.setPmeGridDimensions(args['pmeGridDimensions'])

Peter Eastman's avatar
Peter Eastman committed
3203
3204
            if ('mutualInducedMaxIterations' in args):
                force.setMutualInducedMaxIterations(int(args['mutualInducedMaxIterations']))
3205

Peter Eastman's avatar
Peter Eastman committed
3206
            if ('mutualInducedTargetEpsilon' in args):
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
                force.setMutualInducedTargetEpsilon(float(args['mutualInducedTargetEpsilon']))

        else:
            force = existing[0]

        # add particles to force
        # throw error if particle type not available 

        # get 1-2, 1-3, 1-4, 1-5 bonded sets

        # 1-2

        bonded12ParticleSets = []
        for i in range(len(data.atoms)):
Peter Eastman's avatar
Peter Eastman committed
3221
3222
3223
            bonded12ParticleSet = AmoebaVdwGenerator.getBondedParticleSet(i, data)
            bonded12ParticleSet = set(sorted(bonded12ParticleSet))
            bonded12ParticleSets.append(bonded12ParticleSet)
3224
3225
3226
3227
3228

        # 1-3

        bonded13ParticleSets = []
        for i in range(len(data.atoms)):
Peter Eastman's avatar
Peter Eastman committed
3229
            bonded13Set = set()
3230
3231
            bonded12ParticleSet = bonded12ParticleSets[i]
            for j in bonded12ParticleSet: 
Peter Eastman's avatar
Peter Eastman committed
3232
                bonded13Set = bonded13Set.union(bonded12ParticleSets[j])
3233
3234
3235
3236

            # remove 1-2 and self from set

            bonded13Set = bonded13Set - bonded12ParticleSet
Peter Eastman's avatar
Peter Eastman committed
3237
            selfSet = set()
3238
3239
            selfSet.add(i)
            bonded13Set = bonded13Set - selfSet
Peter Eastman's avatar
Peter Eastman committed
3240
3241
            bonded13Set = set(sorted(bonded13Set))
            bonded13ParticleSets.append(bonded13Set)
3242
3243
3244
3245
3246

        # 1-4

        bonded14ParticleSets = []
        for i in range(len(data.atoms)):
Peter Eastman's avatar
Peter Eastman committed
3247
3248
            bonded14Set = set()
            bonded13ParticleSet = bonded13ParticleSets[i]
3249
            for j in bonded13ParticleSet: 
Peter Eastman's avatar
Peter Eastman committed
3250
                bonded14Set = bonded14Set.union(bonded12ParticleSets[j])
3251
3252
3253
3254
3255
           
            # remove 1-3, 1-2 and self from set

            bonded14Set = bonded14Set - bonded12ParticleSets[i]
            bonded14Set = bonded14Set - bonded13ParticleSet
Peter Eastman's avatar
Peter Eastman committed
3256
            selfSet = set()
3257
3258
            selfSet.add(i)
            bonded14Set = bonded14Set - selfSet
Peter Eastman's avatar
Peter Eastman committed
3259
3260
            bonded14Set = set(sorted(bonded14Set))
            bonded14ParticleSets.append(bonded14Set)
3261
3262
3263
3264
3265

        # 1-5

        bonded15ParticleSets = []
        for i in range(len(data.atoms)):
Peter Eastman's avatar
Peter Eastman committed
3266
3267
            bonded15Set = set()
            bonded14ParticleSet = bonded14ParticleSets[i]
3268
            for j in bonded14ParticleSet: 
Peter Eastman's avatar
Peter Eastman committed
3269
                bonded15Set = bonded15Set.union(bonded12ParticleSets[j])
3270
3271
3272
3273
3274
3275

            # remove 1-4, 1-3, 1-2 and self from set

            bonded15Set = bonded15Set - bonded12ParticleSets[i]
            bonded15Set = bonded15Set - bonded13ParticleSets[i]
            bonded15Set = bonded15Set - bonded14ParticleSet
Peter Eastman's avatar
Peter Eastman committed
3276
            selfSet = set()
3277
3278
            selfSet.add(i)
            bonded15Set = bonded15Set - selfSet
Peter Eastman's avatar
Peter Eastman committed
3279
3280
            bonded15Set = set(sorted(bonded15Set))
            bonded15ParticleSets.append(bonded15Set)
3281
3282
3283
3284
3285

        for (atomIndex, atom) in enumerate(data.atoms):
            t = data.atomType[atom]
            if t in self.typeMap:

Peter Eastman's avatar
Peter Eastman committed
3286
3287
                multipoleList = self.typeMap[t]
                hit = 0
3288
3289
3290
3291
3292
3293
                savedMultipoleDict = 0

                # assign multipole parameters via only 1-2 connected atoms

                for multipoleDict in multipoleList:

Peter Eastman's avatar
Peter Eastman committed
3294
                    if (hit != 0):
3295
3296
                        break

Peter Eastman's avatar
Peter Eastman committed
3297
                    kIndices = multipoleDict['kIndices']
3298
    
Peter Eastman's avatar
Peter Eastman committed
3299
3300
3301
                    kz = kIndices[1]   
                    kx = kIndices[2]
                    ky = kIndices[3]
3302
3303
3304
3305
3306
3307

                    # assign multipole parameters
                    #    (1) get bonded partners
                    #    (2) match parameter types
    
                    bondedAtomIndices = bonded12ParticleSets[atomIndex]
Peter Eastman's avatar
Peter Eastman committed
3308
3309
3310
                    zaxis = -1
                    xaxis = -1
                    yaxis = -1
3311
3312
                    for bondedAtomZIndex in bondedAtomIndices:

Peter Eastman's avatar
Peter Eastman committed
3313
                       if (hit != 0):
3314
3315
3316
                           break

                       bondedAtomZType = int(data.atomType[data.atoms[bondedAtomZIndex]])
Peter Eastman's avatar
Peter Eastman committed
3317
3318
                       bondedAtomZ = data.atoms[bondedAtomZIndex]
                       if (bondedAtomZType == kz):
3319
                          for bondedAtomXIndex in bondedAtomIndices:
Peter Eastman's avatar
Peter Eastman committed
3320
                              if (bondedAtomXIndex == bondedAtomZIndex or hit != 0):
3321
3322
                                  continue
                              bondedAtomXType = int(data.atomType[data.atoms[bondedAtomXIndex]])
Peter Eastman's avatar
Peter Eastman committed
3323
3324
3325
3326
                              if (bondedAtomXType == kx):
                                  if (ky == 0):
                                      zaxis = bondedAtomZIndex
                                      xaxis = bondedAtomXIndex
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
                                      if( bondedAtomXType == bondedAtomZType and xaxis < zaxis ):
                                          swapI = zaxis
                                          zaxis = xaxis
                                          xaxis = swapI
                                      else:
                                          for bondedAtomXIndex in bondedAtomIndices:
                                              bondedAtomX1Type = int(data.atomType[data.atoms[bondedAtomXIndex]])
                                              if( bondedAtomX1Type == kx and bondedAtomXIndex != bondedAtomZIndex and bondedAtomXIndex < xaxis ):
                                                  xaxis = bondedAtomXIndex

3337
                                      savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
3338
                                      hit = 1
3339
3340
                                  else:
                                      for bondedAtomYIndex in bondedAtomIndices:
Peter Eastman's avatar
Peter Eastman committed
3341
                                          if (bondedAtomYIndex == bondedAtomZIndex or bondedAtomYIndex == bondedAtomXIndex or hit != 0):
3342
3343
                                              continue
                                          bondedAtomYType = int(data.atomType[data.atoms[bondedAtomYIndex]])
Peter Eastman's avatar
Peter Eastman committed
3344
3345
3346
3347
                                          if (bondedAtomYType == ky):
                                              zaxis = bondedAtomZIndex
                                              xaxis = bondedAtomXIndex
                                              yaxis = bondedAtomYIndex
3348
                                              savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
3349
                                              hit = 2
3350
3351
3352
3353
3354
                                         
                # assign multipole parameters via 1-2 and 1-3 connected atoms

                for multipoleDict in multipoleList:

Peter Eastman's avatar
Peter Eastman committed
3355
                    if (hit != 0):
3356
3357
                        break

Peter Eastman's avatar
Peter Eastman committed
3358
                    kIndices = multipoleDict['kIndices']
3359
    
Peter Eastman's avatar
Peter Eastman committed
3360
3361
3362
                    kz = kIndices[1]   
                    kx = kIndices[2]
                    ky = kIndices[3]
3363
3364
3365
3366
3367
3368
3369
3370
    
                    # assign multipole parameters
                    #    (1) get bonded partners
                    #    (2) match parameter types
    
                    bondedAtom12Indices = bonded12ParticleSets[atomIndex]
                    bondedAtom13Indices = bonded13ParticleSets[atomIndex]

Peter Eastman's avatar
Peter Eastman committed
3371
3372
3373
                    zaxis = -1
                    xaxis = -1
                    yaxis = -1
3374
3375
3376

                    for bondedAtomZIndex in bondedAtom12Indices:

Peter Eastman's avatar
Peter Eastman committed
3377
                       if (hit != 0):
3378
3379
3380
                           break

                       bondedAtomZType = int(data.atomType[data.atoms[bondedAtomZIndex]])
Peter Eastman's avatar
Peter Eastman committed
3381
                       bondedAtomZ = data.atoms[bondedAtomZIndex]
3382

Peter Eastman's avatar
Peter Eastman committed
3383
                       if (bondedAtomZType == kz):
3384
3385
                          for bondedAtomXIndex in bondedAtom13Indices:

Peter Eastman's avatar
Peter Eastman committed
3386
                              if (bondedAtomXIndex == bondedAtomZIndex or hit != 0):
3387
3388
                                  continue
                              bondedAtomXType = int(data.atomType[data.atoms[bondedAtomXIndex]])
Peter Eastman's avatar
Peter Eastman committed
3389
3390
3391
3392
                              if (bondedAtomXType == kx and bondedAtomZIndex in bonded12ParticleSets[bondedAtomXIndex]):
                                  if (ky == 0):
                                      zaxis = bondedAtomZIndex
                                      xaxis = bondedAtomXIndex
3393
3394
3395
3396
3397
3398
3399
3400

                                      # select xaxis w/ smallest index

                                      for bondedAtomXIndex in bondedAtom13Indices:
                                          bondedAtomX1Type = int(data.atomType[data.atoms[bondedAtomXIndex]])
                                          if( bondedAtomX1Type == kx and bondedAtomXIndex != bondedAtomZIndex and bondedAtomZIndex in bonded12ParticleSets[bondedAtomXIndex] and bondedAtomXIndex < xaxis ):
                                              xaxis = bondedAtomXIndex

3401
                                      savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
3402
                                      hit = 3
3403
3404
                                  else:
                                      for bondedAtomYIndex in bondedAtom13Indices:
Peter Eastman's avatar
Peter Eastman committed
3405
                                          if (bondedAtomYIndex == bondedAtomZIndex or bondedAtomYIndex == bondedAtomXIndex or hit != 0):
3406
3407
                                              continue
                                          bondedAtomYType = int(data.atomType[data.atoms[bondedAtomYIndex]])
Peter Eastman's avatar
Peter Eastman committed
3408
3409
3410
3411
                                          if (bondedAtomYType == ky and bondedAtomZIndex in bonded12ParticleSets[bondedAtomYIndex]):
                                              zaxis = bondedAtomZIndex
                                              xaxis = bondedAtomXIndex
                                              yaxis = bondedAtomYIndex
3412
                                              savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
3413
                                              hit = 4
3414
3415
3416
3417
3418
                                         
                # assign multipole parameters via only a z-defining atom

                for multipoleDict in multipoleList:

Peter Eastman's avatar
Peter Eastman committed
3419
                    if (hit != 0):
3420
3421
                        break

Peter Eastman's avatar
Peter Eastman committed
3422
                    kIndices = multipoleDict['kIndices']
3423
    
Peter Eastman's avatar
Peter Eastman committed
3424
3425
                    kz = kIndices[1]   
                    kx = kIndices[2]   
3426
    
Peter Eastman's avatar
Peter Eastman committed
3427
3428
3429
                    zaxis = -1
                    xaxis = -1
                    yaxis = -1
3430
3431
3432

                    for bondedAtomZIndex in bondedAtom12Indices:

Peter Eastman's avatar
Peter Eastman committed
3433
                        if (hit != 0):
3434
3435
3436
                            break

                        bondedAtomZType = int(data.atomType[data.atoms[bondedAtomZIndex]])
Peter Eastman's avatar
Peter Eastman committed
3437
                        bondedAtomZ = data.atoms[bondedAtomZIndex]
3438

Peter Eastman's avatar
Peter Eastman committed
3439
3440
                        if (kx == 0 and kz == bondedAtomZType):
                            kz = bondedAtomZIndex
3441
                            savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
3442
                            hit = 5
3443
3444
3445
3446
3447

                # assign multipole parameters via no connected atoms

                for multipoleDict in multipoleList:

Peter Eastman's avatar
Peter Eastman committed
3448
                    if (hit != 0):
3449
3450
                        break

Peter Eastman's avatar
Peter Eastman committed
3451
                    kIndices = multipoleDict['kIndices']
3452
    
Peter Eastman's avatar
Peter Eastman committed
3453
                    kz = kIndices[1]   
3454
    
Peter Eastman's avatar
Peter Eastman committed
3455
3456
3457
                    zaxis = -1
                    xaxis = -1
                    yaxis = -1
3458

Peter Eastman's avatar
Peter Eastman committed
3459
                    if (kz == 0):
3460
                        savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
3461
                        hit = 6
3462
3463
3464
                
                # add particle if there was a hit

Peter Eastman's avatar
Peter Eastman committed
3465
                if (hit != 0):
3466

Peter Eastman's avatar
Peter Eastman committed
3467
                    atom.multipoleDict = savedMultipoleDict
3468
                    atom.polarizationGroups = dict()
3469
                    newIndex = force.addMultipole(savedMultipoleDict['charge'], savedMultipoleDict['dipole'], savedMultipoleDict['quadrupole'], savedMultipoleDict['axisType'],
3470
                                                                 zaxis, xaxis, yaxis, savedMultipoleDict['thole'], savedMultipoleDict['pdamp'], savedMultipoleDict['polarizability'])
Peter Eastman's avatar
Peter Eastman committed
3471
3472
3473
3474
3475
                    if (atomIndex == newIndex):
                        force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.Covalent12, bonded12ParticleSets[atomIndex])
                        force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.Covalent13, bonded13ParticleSets[atomIndex])
                        force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.Covalent14, bonded14ParticleSets[atomIndex])
                        force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.Covalent15, bonded15ParticleSets[atomIndex])
3476
                    else:
Peter Eastman's avatar
Peter Eastman committed
3477
                        raise ValueError("Atom %s of %s %d is out of synch!." %(atom.name, atom.residue.name, atom.residue.index))
3478
                else:
Peter Eastman's avatar
Peter Eastman committed
3479
                    raise ValueError("Atom %s of %s %d was not assigned." %(atom.name, atom.residue.name, atom.residue.index))
3480
            else:
Peter Eastman's avatar
Peter Eastman committed
3481
                raise ValueError('No multipole type for atom %s %s %d' % (atom.name, atom.residue.name, atom.residue.index))
3482
3483
3484

        # set polar groups

Peter Eastman's avatar
Peter Eastman committed
3485
        self.setPolarGroups(data, bonded12ParticleSets, force)
3486
3487
3488
3489
3490

parsers["AmoebaMultipoleForce"] = AmoebaMultipoleGenerator.parseElement

#=============================================================================================

3491
## @private
3492
3493
3494
3495
3496
3497
class AmoebaWcaDispersionGenerator:

    """A AmoebaWcaDispersionGenerator constructs a AmoebaWcaDispersionForce."""
    
    #=========================================================================================

Peter Eastman's avatar
Peter Eastman committed
3498
    def __init__(self, epso, epsh, rmino, rminh, awater, slevy, dispoff, shctd):
3499

Peter Eastman's avatar
Peter Eastman committed
3500
3501
3502
3503
3504
3505
3506
3507
        self.epso = epso 
        self.epsh = epsh 
        self.rmino = rmino
        self.rminh = rminh
        self.awater = awater
        self.slevy = slevy
        self.dispoff = dispoff
        self.shctd = shctd 
3508

Peter Eastman's avatar
Peter Eastman committed
3509
        self.typeMap = {}
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519

    #=========================================================================================

    @staticmethod
    def parseElement(element, forceField):

        #  <AmoebaWcaDispersionForce epso="0.46024" epsh="0.056484" rmino="0.17025" rminh="0.13275" awater="33.428" slevy="1.0"  dispoff="0.026" shctd="0.81" >
        #   <WcaDispersion class="1" radius="0.1855" epsilon="0.46024" />
        #   <WcaDispersion class="2" radius="0.191" epsilon="0.422584" />
      
Peter Eastman's avatar
Peter Eastman committed
3520
        generator = AmoebaWcaDispersionGenerator(element.attrib['epso'],
3521
3522
3523
3524
3525
3526
                                                  element.attrib['epsh'],
                                                  element.attrib['rmino'],
                                                  element.attrib['rminh'],
                                                  element.attrib['awater'], 
                                                  element.attrib['slevy'],
                                                  element.attrib['dispoff'],
Peter Eastman's avatar
Peter Eastman committed
3527
                                                  element.attrib['shctd']) 
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
        forceField._forces.append(generator)

        # typeMap[] = [ radius, epsilon ]

        for atom in element.findall('WcaDispersion'):
            types = forceField._findAtomTypes(atom, 1)
            if types is not None:

                values = [float(atom.attrib['radius']), float(atom.attrib['epsilon'])]
                for t in types[0]:
                    generator.typeMap[t] = values
            else:
Peter Eastman's avatar
Peter Eastman committed
3540
3541
                outputString = "AmoebaWcaDispersionGenerator: error getting type: %s" % (atom.attrib['class'])
                raise ValueError(outputString) 
3542
3543
3544
    
    #=========================================================================================
    
Peter Eastman's avatar
Peter Eastman committed
3545
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559

        # get or create force depending on whether it has already been added to the system

        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
        existing = [f for f in existing if type(f) == mm.AmoebaWcaDispersionForce]
        if len(existing) == 0:
            force = mm.AmoebaWcaDispersionForce()
            sys.addForce(force)
        else:
            force = existing[0]

        # add particles to force
        # throw error if particle type not available 

Peter Eastman's avatar
Peter Eastman committed
3560
3561
3562
3563
3564
3565
3566
3567
        force.setEpso(   float(self.epso   ))
        force.setEpsh(   float(self.epsh   ))
        force.setRmino(  float(self.rmino  ))
        force.setRminh(  float(self.rminh  ))
        force.setDispoff(float(self.dispoff))
        force.setSlevy(  float(self.slevy  ))
        force.setAwater( float(self.awater ))
        force.setShctd(  float(self.shctd  ))
3568
3569
3570
3571
3572

        for (i, atom) in enumerate(data.atoms):
            t = data.atomType[atom]
            if t in self.typeMap:

Peter Eastman's avatar
Peter Eastman committed
3573
3574
                values = self.typeMap[t]
                force.addParticle(values[0], values[1])
3575
3576
3577
3578
3579
3580
3581
            else:
                raise ValueError('No WcaDispersion type for atom %s of %s %d' % (atom.name, atom.residue.name, atom.residue.index))

parsers["AmoebaWcaDispersionForce"] = AmoebaWcaDispersionGenerator.parseElement

#=============================================================================================

3582
## @private
3583
3584
3585
3586
3587
3588
class AmoebaGeneralizedKirkwoodGenerator:

    """A AmoebaGeneralizedKirkwoodGenerator constructs a AmoebaGeneralizedKirkwoodForce."""
    
    #=========================================================================================

Peter Eastman's avatar
Peter Eastman committed
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
    def __init__(self, forceField, solventDielectric, soluteDielectric, includeCavityTerm, probeRadius, surfaceAreaFactor):

        self.forceField = forceField
        self.solventDielectric = solventDielectric
        self.soluteDielectric = soluteDielectric
        self.includeCavityTerm = includeCavityTerm
        self.probeRadius = probeRadius
        self.surfaceAreaFactor = surfaceAreaFactor

        self.radiusTypeMap = {}
        self.radiusTypeMap['Bondi'] = {}
        bondiMap = self.radiusTypeMap['Bondi'] 
        rscale = 1.03

        bondiMap[0] = 0.00
        bondiMap[1] = 0.12*rscale
        bondiMap[2] = 0.14*rscale
        bondiMap[5] = 0.18*rscale

        bondiMap[6] = 0.170*rscale
        bondiMap[7] = 0.155*rscale
        bondiMap[8] = 0.152*rscale
        bondiMap[9] = 0.147*rscale

        bondiMap[10] = 0.154*rscale
        bondiMap[14] = 0.210*rscale
        bondiMap[15] = 0.180*rscale
        bondiMap[16] = 0.180*rscale

        bondiMap[17] = 0.175 *rscale
        bondiMap[18] = 0.188*rscale
        bondiMap[34] = 0.190*rscale
        bondiMap[35] = 0.185*rscale

        bondiMap[36] = 0.202*rscale
        bondiMap[53] = 0.198*rscale
        bondiMap[54] = 0.216*rscale
3626
3627
3628

    #=========================================================================================

Peter Eastman's avatar
Peter Eastman committed
3629
    def getObcShct(self, data, atomIndex):
3630

Peter Eastman's avatar
Peter Eastman committed
3631
        atom = data.atoms[atomIndex]
3632
        atomicNumber = atom.element.atomic_number
Peter Eastman's avatar
Peter Eastman committed
3633
        shct = -1.0
3634
3635
3636

        # shct
 
Peter Eastman's avatar
Peter Eastman committed
3637
        if (atomicNumber == 1):                 # H(1)
3638
            shct = 0.85       
Peter Eastman's avatar
Peter Eastman committed
3639
        elif (atomicNumber == 6):               # C(6)
3640
            shct = 0.72         
Peter Eastman's avatar
Peter Eastman committed
3641
        elif (atomicNumber == 7):               # N(7)
3642
            shct = 0.79        
Peter Eastman's avatar
Peter Eastman committed
3643
        elif (atomicNumber == 8):               # O(8)
3644
            shct = 0.85       
Peter Eastman's avatar
Peter Eastman committed
3645
        elif (atomicNumber == 9):               # F(9)
3646
            shct = 0.88    
Peter Eastman's avatar
Peter Eastman committed
3647
        elif (atomicNumber == 15):              # P(15)              
3648
            shct = 0.86 
Peter Eastman's avatar
Peter Eastman committed
3649
        elif (atomicNumber == 16):              # S(16)
3650
            shct = 0.96
Peter Eastman's avatar
Peter Eastman committed
3651
        elif (atomicNumber == 26):              # Fe(26)
3652
3653
            shct = 0.88

Peter Eastman's avatar
Peter Eastman committed
3654
        if (shct < 0.0): 
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3655
            raise ValueError( "getObcShct: no GK overlap scale factor for atom %s of %s %d" % (atom.name, atom.residue.name, atom.residue.index) )
3656
3657
3658
3659
3660
 
        return shct 

    #=========================================================================================

Peter Eastman's avatar
Peter Eastman committed
3661
    def getAmoebaTypeRadius(self, data, bondedAtomIndices, atomIndex):
3662

Peter Eastman's avatar
Peter Eastman committed
3663
        atom = data.atoms[atomIndex]
3664
        atomicNumber = atom.element.atomic_number
Peter Eastman's avatar
Peter Eastman committed
3665
        radius = -1.0
3666

Peter Eastman's avatar
Peter Eastman committed
3667
        if (atomicNumber == 1):                  # H(1)
3668
 
Peter Eastman's avatar
Peter Eastman committed
3669
            radius = 0.132
3670
 
Peter Eastman's avatar
Peter Eastman committed
3671
            if (len(bondedAtomIndices) < 1):
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3672
                 raise ValueError( "AmoebaGeneralizedKirkwoodGenerator: error getting atom bonded to %s of %s %d " % (atom.name, atom.residue.name, atom.residue.index) )
3673
3674
 
            for bondedAtomIndex in bondedAtomIndices:
Peter Eastman's avatar
Peter Eastman committed
3675
                bondedAtomAtomicNumber = data.atoms[bondedAtomIndex].element.atomic_number
3676

Peter Eastman's avatar
Peter Eastman committed
3677
            if (bondedAtomAtomicNumber == 7):
3678
                radius = 0.11
Peter Eastman's avatar
Peter Eastman committed
3679
            if (bondedAtomAtomicNumber == 8):
3680
3681
                radius = 0.105
 
Peter Eastman's avatar
Peter Eastman committed
3682
        elif (atomicNumber == 3):               # Li(3)
3683
            radius = 0.15
Peter Eastman's avatar
Peter Eastman committed
3684
        elif (atomicNumber == 6):               # C(6)
3685
3686
            
            radius = 0.20
Peter Eastman's avatar
Peter Eastman committed
3687
            if (len(bondedAtomIndices) == 3):
3688
3689
                radius = 0.205

Peter Eastman's avatar
Peter Eastman committed
3690
            elif (len(bondedAtomIndices) == 4):
3691
3692
                for bondedAtomIndex in bondedAtomIndices:
                   bondedAtomAtomicNumber = data.atoms[bondedAtomIndex].element.atomic_number
Peter Eastman's avatar
Peter Eastman committed
3693
                   if (bondedAtomAtomicNumber == 7 or bondedAtomAtomicNumber == 8):
3694
3695
                       radius = 0.175

Peter Eastman's avatar
Peter Eastman committed
3696
        elif (atomicNumber == 7):               # N(7)
3697
            radius = 0.16
Peter Eastman's avatar
Peter Eastman committed
3698
        elif (atomicNumber == 8):               # O(8)
3699
            radius = 0.155
Peter Eastman's avatar
Peter Eastman committed
3700
            if (len(bondedAtomIndices) == 2):
3701
                radius = 0.145
Peter Eastman's avatar
Peter Eastman committed
3702
        elif (atomicNumber == 9):               # F(9)
3703
            radius = 0.154
Peter Eastman's avatar
Peter Eastman committed
3704
        elif (atomicNumber == 10):              
3705
            radius = 0.146
Peter Eastman's avatar
Peter Eastman committed
3706
        elif (atomicNumber == 11):              
3707
            radius = 0.209
Peter Eastman's avatar
Peter Eastman committed
3708
        elif (atomicNumber == 12):              
3709
            radius = 0.179
Peter Eastman's avatar
Peter Eastman committed
3710
        elif (atomicNumber == 14):              
3711
            radius = 0.189
Peter Eastman's avatar
Peter Eastman committed
3712
        elif (atomicNumber == 15):              # P(15)              
3713
            radius = 0.196
Peter Eastman's avatar
Peter Eastman committed
3714
        elif (atomicNumber == 16):              # S(16)
3715
            radius = 0.186
Peter Eastman's avatar
Peter Eastman committed
3716
        elif (atomicNumber == 17):              
3717
            radius = 0.182
Peter Eastman's avatar
Peter Eastman committed
3718
        elif (atomicNumber == 18):              
3719
            radius = 0.179
Peter Eastman's avatar
Peter Eastman committed
3720
        elif (atomicNumber == 19):              
3721
            radius = 0.223
Peter Eastman's avatar
Peter Eastman committed
3722
        elif (atomicNumber == 20):              
3723
            radius = 0.191
Peter Eastman's avatar
Peter Eastman committed
3724
        elif (atomicNumber == 35):         
3725
            radius = 2.00
Peter Eastman's avatar
Peter Eastman committed
3726
        elif (atomicNumber == 36):   
3727
            radius = 0.190
Peter Eastman's avatar
Peter Eastman committed
3728
        elif (atomicNumber == 37):              
3729
            radius = 0.226
Peter Eastman's avatar
Peter Eastman committed
3730
        elif (atomicNumber == 53):              
3731
            radius = 0.237
Peter Eastman's avatar
Peter Eastman committed
3732
        elif (atomicNumber == 54):              
3733
            radius = 0.207
Peter Eastman's avatar
Peter Eastman committed
3734
        elif (atomicNumber == 55):              
3735
            radius = 0.263
Peter Eastman's avatar
Peter Eastman committed
3736
        elif (atomicNumber == 56):         
3737
3738
            radius = 0.230

Peter Eastman's avatar
Peter Eastman committed
3739
        if (radius < 0.0): 
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3740
3741
            outputString = "No GK radius for atom %s of %s %d" % (atom.name, atom.residue.name, atom.residue.index)
            raise ValueError( outputString )
3742
3743
3744
3745
3746
 
        return radius

    #=========================================================================================

Peter Eastman's avatar
Peter Eastman committed
3747
    def getBondiTypeRadius(self, data, bondedAtomIndices, atomIndex):
3748

Peter Eastman's avatar
Peter Eastman committed
3749
3750
        bondiMap = self.radiusTypeMap['Bondi'] 
        atom = data.atoms[atomIndex]
3751
        atomicNumber = atom.element.atomic_number
Peter Eastman's avatar
Peter Eastman committed
3752
        if (atomicNumber in bondiMap): 
3753
3754
            radius = bondiMap[atomicNumber]
        else:
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3755
3756
            outputString = "Warning no Bondi radius for atom %s of %s %d using default value=%f" % (atom.name, atom.residue.name, atom.residue.index, radius)
            raise ValueError( outputString )
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
 
        return radius

    #=========================================================================================

    @staticmethod
    def parseElement(element, forceField):

        #  <AmoebaGeneralizedKirkwoodForce solventDielectric="78.3" soluteDielectric="1.0" includeCavityTerm="1" probeRadius="0.14" surfaceAreaFactor="-170.351730663">
        #   <GeneralizedKirkwood type="1" charge="-0.22620" shct="0.79"  />
        #   <GeneralizedKirkwood type="2" charge="-0.15245" shct="0.72"  />
        
Peter Eastman's avatar
Peter Eastman committed
3769
        generator = AmoebaGeneralizedKirkwoodGenerator(forceField, element.attrib['solventDielectric'], element.attrib['soluteDielectric'],
3770
                                                        element.attrib['includeCavityTerm'], 
Peter Eastman's avatar
Peter Eastman committed
3771
                                                        element.attrib['probeRadius'], element.attrib['surfaceAreaFactor']) 
3772
3773
3774
3775
        forceField._forces.append(generator)

    #=========================================================================================
    
Peter Eastman's avatar
Peter Eastman committed
3776
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
3777

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3778
3779
3780
        if( nonbondedMethod != NoCutoff ):
            raise ValueError( "Only the nonbondedMethod=NoCutoff option is available for implicit solvent simulations." )

3781
3782
3783
        # check if AmoebaMultipoleForce exists since charges needed
        # if it has not been created, raise an error

Peter Eastman's avatar
Peter Eastman committed
3784
        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
3785
        amoebaMultipoleForceList = [f for f in existing if type(f) == mm.AmoebaMultipoleForce]
Peter Eastman's avatar
Peter Eastman committed
3786
        if (len(amoebaMultipoleForceList) > 0):
3787
3788
3789
3790
3791
            amoebaMultipoleForce = amoebaMultipoleForceList[0]
        else:
            # call AmoebaMultipoleForceGenerator.createForce() to ensure charges have been set

            for force in self.forceField._forces:
Peter Eastman's avatar
Peter Eastman committed
3792
3793
                if (force.__class__.__name__ == 'AmoebaMultipoleGenerator'): 
                    force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3794
          
3795
3796
3797
3798
3799
3800
3801
3802
        # get or create force depending on whether it has already been added to the system

        existing = [f for f in existing if type(f) == mm.AmoebaGeneralizedKirkwoodForce]
        if len(existing) == 0:

            force = mm.AmoebaGeneralizedKirkwoodForce()
            sys.addForce(force)
 
Peter Eastman's avatar
Peter Eastman committed
3803
3804
            if ('solventDielectric' in args):
                force.setSolventDielectric(float(args['solventDielectric']))
3805
            else:
Peter Eastman's avatar
Peter Eastman committed
3806
                force.setSolventDielectric(   float(self.solventDielectric))
3807

Peter Eastman's avatar
Peter Eastman committed
3808
3809
            if ('soluteDielectric' in args):
                force.setSoluteDielectric(float(args['soluteDielectric']))
3810
            else:
Peter Eastman's avatar
Peter Eastman committed
3811
                force.setSoluteDielectric(    float(self.soluteDielectric))
3812

Peter Eastman's avatar
Peter Eastman committed
3813
3814
            if ('includeCavityTerm' in args):
                force.setIncludeCavityTerm(int(args['includeCavityTerm']))
3815
            else:
Peter Eastman's avatar
Peter Eastman committed
3816
               force.setIncludeCavityTerm(   int(self.includeCavityTerm))
3817
3818
3819
3820
3821
3822
3823

        else:
            force = existing[0]

        # add particles to force
        # throw error if particle type not available 

Peter Eastman's avatar
Peter Eastman committed
3824
3825
        force.setProbeRadius(         float(self.probeRadius))
        force.setSurfaceAreaFactor(   float(self.surfaceAreaFactor))
3826
3827
3828
3829
3830

        # 1-2

        bonded12ParticleSets = []
        for i in range(len(data.atoms)):
Peter Eastman's avatar
Peter Eastman committed
3831
3832
3833
            bonded12ParticleSet = AmoebaVdwGenerator.getBondedParticleSet(i, data)
            bonded12ParticleSet = set(sorted(bonded12ParticleSet))
            bonded12ParticleSets.append(bonded12ParticleSet)
3834
3835

        radiusType = 'Bondi'
Peter Eastman's avatar
Peter Eastman committed
3836
3837
3838
3839
        for atomIndex in range(0, amoebaMultipoleForce.getNumMultipoles()):
            multipoleParameters = amoebaMultipoleForce.getMultipoleParameters(atomIndex)
            if (radiusType == 'Amoeba'):
                radius = self.getAmoebaTypeRadius(data, bonded12ParticleSets[atomIndex], atomIndex)
3840
            else:
Peter Eastman's avatar
Peter Eastman committed
3841
                radius = self.getBondiTypeRadius(data, bonded12ParticleSets[atomIndex], atomIndex)
3842
3843
            #shct = self.getObcShct(data, atomIndex)
            shct = 0.69
Peter Eastman's avatar
Peter Eastman committed
3844
            force.addParticle(multipoleParameters[0], radius, shct)
3845
3846
3847
3848
3849

parsers["AmoebaGeneralizedKirkwoodForce"] = AmoebaGeneralizedKirkwoodGenerator.parseElement

#=============================================================================================

3850
## @private
3851
3852
3853
3854
3855
3856
class AmoebaUreyBradleyGenerator:

    #=============================================================================================
    """An AmoebaUreyBradleyGenerator constructs a AmoebaUreyBradleyForce."""
    #=============================================================================================
    
3857
    def __init__(self):
3858

Peter Eastman's avatar
Peter Eastman committed
3859
3860
3861
        self.types1 = []
        self.types2 = []
        self.types3 = []
3862

Peter Eastman's avatar
Peter Eastman committed
3863
3864
        self.length = []
        self.k = []
3865
3866
3867
3868
3869
3870

    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

3871
        #  <AmoebaUreyBradleyForce>
3872
3873
        #   <UreyBradley class1="74" class2="73" class3="74" k="16003.8" d="0.15537" /> 

3874
        generator = AmoebaUreyBradleyGenerator()
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
        forceField._forces.append(generator)
        for bond in element.findall('UreyBradley'):
            types = forceField._findAtomTypes(bond, 3)
            if types is not None:

                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.types3.append(types[2])

                generator.length.append(float(bond.attrib['d']))
                generator.k.append(float(bond.attrib['k']))

            else:
                outputString = "AmoebaUreyBradleyGenerator: error getting types: %s %s %s" % (
Peter Eastman's avatar
Peter Eastman committed
3889
3890
                                    bond.attrib['class1'], bond.attrib['class2'], bond.attrib['class3'])
                raise ValueError(outputString) 
3891
3892
3893
    
    #=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
3894
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
3895

Peter Eastman's avatar
Peter Eastman committed
3896
        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
3897
        existing = [f for f in existing if type(f) == mm.HarmonicBondForce]
3898
3899

        if len(existing) == 0:
3900
            force = mm.HarmonicBondForce()
3901
3902
3903
3904
3905
            sys.addForce(force)
        else:
            force = existing[0]

        for (angle, isConstrained) in zip(data.angles, data.isAngleConstrained):
Peter Eastman's avatar
Peter Eastman committed
3906
            if (isConstrained):
3907
3908
3909
3910
3911
3912
3913
3914
                continue
            type1 = data.atomType[data.atoms[angle[0]]]
            type2 = data.atomType[data.atoms[angle[1]]]
            type3 = data.atomType[data.atoms[angle[2]]]
            for i in range(len(self.types1)):
                types1 = self.types1[i]
                types2 = self.types2[i]
                types3 = self.types3[i]
Peter Eastman's avatar
Peter Eastman committed
3915
                if ((type1 in types1 and type2 in types2 and type3 in types3) or (type3 in types1 and type2 in types2 and type1 in types3)):
3916
                    force.addBond(angle[0], angle[2], self.length[i], 2*self.k[i])
3917
3918
3919
3920
3921
                    break

parsers["AmoebaUreyBradleyForce"] = AmoebaUreyBradleyGenerator.parseElement

#=============================================================================================