forcefield.py 214 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

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.

9
Portions copyright (c) 2012-2015 Stanford University and the Authors.
10
11
12
Authors: Peter Eastman, Mark Friedrichs
Contributors:

Justin MacCallum's avatar
Justin MacCallum committed
13
Permission is hereby granted, free of charge, to any person obtaining a
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
from __future__ import absolute_import, print_function

33
34
35
36
37
38
__author__ = "Peter Eastman"
__version__ = "1.0"

import os
import itertools
import xml.etree.ElementTree as etree
39
import math
40
41
42
from math import sqrt, cos
import simtk.openmm as mm
import simtk.unit as unit
43
from . import element as elem
44
45
from simtk.openmm.app import Topology

46
47
def _convertParameterToNumber(param):
    if unit.is_quantity(param):
48
49
50
        if param.unit.is_compatible(unit.bar):
            return param / unit.bar
        return param.value_in_unit_system(unit.md_unit_system)
51
52
    return float(param)

53
54
# Enumerated values for nonbonded method

55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class NoCutoff(object):
    def __repr__(self):
        return 'NoCutoff'
NoCutoff = NoCutoff()

class CutoffNonPeriodic(object):
    def __repr__(self):
        return 'CutoffNonPeriodic'
CutoffNonPeriodic = CutoffNonPeriodic()

class CutoffPeriodic(object):
    def __repr__(self):
        return 'CutoffPeriodic'
CutoffPeriodic = CutoffPeriodic()

class Ewald(object):
    def __repr__(self):
        return 'Ewald'
Ewald = Ewald()

class PME(object):
    def __repr__(self):
        return 'PME'
PME = PME()
79
80
81

# Enumerated values for constraint type

82
83
84
85
86
87
88
89
90
91
92
93
94
95
class HBonds(object):
    def __repr__(self):
        return 'HBonds'
HBonds = HBonds()

class AllBonds(object):
    def __repr__(self):
        return 'AllBonds'
AllBonds = AllBonds()

class HAngles(object):
    def __repr__(self):
        return 'HAngles'
HAngles = HAngles()
96
97
98
99
100
101
102
103
104
105

# 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.
Justin MacCallum's avatar
Justin MacCallum committed
106

Robert McGibbon's avatar
Robert McGibbon committed
107
108
109
110
111
112
113
114
        Parameters
        ----------
        files : list
            A list of XML files defining the force field.  Each entry may
            be an absolute file path, a path relative to the current working
            directory, a path relative to this module's data subdirectory
            (for built in force fields), or an open file-like object with a
            read() method from which the forcefield XML data can be loaded.
115
116
117
        """
        self._atomTypes = {}
        self._templates = {}
118
        self._templateSignatures = {None:[]}
119
        self._atomClasses = {'':set()}
120
        self._forces = []
121
        self._scripts = []
122
        self._templateGenerators = []
123
        self.loadFile(files)
124

125
    def loadFile(self, files):
126
        """Load an XML file and add the definitions from it to this ForceField.
127

Robert McGibbon's avatar
Robert McGibbon committed
128
129
        Parameters
        ----------
130
131
132
        files : string or file or tuple
            An XML file or tuple of XML files containing force field definitions.
            Each entry may be either an absolute file path, a path relative to the current working
Robert McGibbon's avatar
Robert McGibbon committed
133
134
135
            directory, a path relative to this module's data subdirectory (for
            built in force fields), or an open file-like object with a read()
            method from which the forcefield XML data can be loaded.
peastman's avatar
peastman committed
136
        """
137

138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
        if not isinstance(files, tuple):
            files = (files,)

        trees = []

        for file in files:
            try:
                # this handles either filenames or open file-like objects
                tree = etree.parse(file)
            except IOError:
                tree = etree.parse(os.path.join(os.path.dirname(__file__), 'data', file))
            except Exception as e:
                # Fail with an error message about which file could not be read.
                # TODO: Also handle case where fallback to 'data' directory encounters problems,
                # but this is much less worrisome because we control those files.
                msg  = str(e) + '\n'
                if hasattr(file, 'name'):
                    filename = file.name
                else:
                    filename = str(file)
                msg += "ForceField.loadFile() encountered an error reading file '%s'\n" % filename
                raise Exception(msg)

            trees.append(tree)

peastman's avatar
peastman committed
163
164
165

        # Load the atom types.

166
167
168
169
        for tree in trees:
            if tree.getroot().find('AtomTypes') is not None:
                for type in tree.getroot().find('AtomTypes').findall('Type'):
                    self.registerAtomType(type.attrib)
peastman's avatar
peastman committed
170
171
172

        # Load the residue templates.

173
174
175
176
177
        for tree in trees:
            if tree.getroot().find('Residues') is not None:
                for residue in tree.getroot().find('Residues').findall('Residue'):
                    resName = residue.attrib['name']
                    template = ForceField._TemplateData(resName)
178
179
                    if 'overload' in residue.attrib:
                        template.overloadLevel = int(residue.attrib['overload'])
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
                    atomIndices = {}
                    for atom in residue.findall('Atom'):
                        params = {}
                        for key in atom.attrib:
                            if key not in ('name', 'type'):
                                params[key] = _convertParameterToNumber(atom.attrib[key])
                        atomName = atom.attrib['name']
                        if atomName in atomIndices:
                            raise ValueError('Residue '+resName+' contains multiple atoms named '+atomName)
                        atomIndices[atomName] = len(template.atoms)
                        typeName = atom.attrib['type']
                        template.atoms.append(ForceField._TemplateAtomData(atomName, typeName, self._atomTypes[typeName].element, params))
                    for site in residue.findall('VirtualSite'):
                        template.virtualSites.append(ForceField._VirtualSiteData(site, atomIndices))
                    for bond in residue.findall('Bond'):
                        if 'atomName1' in bond.attrib:
                            template.addBondByName(bond.attrib['atomName1'], bond.attrib['atomName2'])
                        else:
                            template.addBond(int(bond.attrib['from']), int(bond.attrib['to']))
                    for bond in residue.findall('ExternalBond'):
                        if 'atomName' in bond.attrib:
                            template.addExternalBondByName(bond.attrib['atomName'])
                        else:
                            template.addExternalBond(int(bond.attrib['from']))
                    self.registerResidueTemplate(template)
peastman's avatar
peastman committed
205
206
207

        # Load force definitions

208
209
210
211
        for tree in trees:
            for child in tree.getroot():
                if child.tag in parsers:
                    parsers[child.tag](child, self)
peastman's avatar
peastman committed
212
213
214

        # Load scripts

215
216
217
        for tree in trees:
            for node in tree.getroot().findall('Script'):
                self.registerScript(node.text)
218

219
220
221
    def getGenerators(self):
        """Get the list of all registered generators."""
        return self._forces
222

223
224
225
    def registerGenerator(self, generator):
        """Register a new generator."""
        self._forces.append(generator)
226

227
228
229
230
231
232
233
234
235
236
237
238
    def registerAtomType(self, parameters):
        """Register a new atom type."""
        name = parameters['name']
        if name in self._atomTypes:
            raise ValueError('Found multiple definitions for atom type: '+name)
        atomClass = parameters['class']
        mass = _convertParameterToNumber(parameters['mass'])
        element = None
        if 'element' in parameters:
            element = parameters['element']
            if not isinstance(element, elem.Element):
                element = elem.get_by_symbol(element)
239
        self._atomTypes[name] = ForceField._AtomType(name, atomClass, mass, element)
240
241
242
243
244
245
246
        if atomClass in self._atomClasses:
            typeSet = self._atomClasses[atomClass]
        else:
            typeSet = set()
            self._atomClasses[atomClass] = typeSet
        typeSet.add(name)
        self._atomClasses[''].add(name)
247

248
249
250
251
252
    def registerResidueTemplate(self, template):
        """Register a new residue template."""
        self._templates[template.name] = template
        signature = _createResidueSignature([atom.element for atom in template.atoms])
        if signature in self._templateSignatures:
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
            registered = False
            for regtemplate in self._templateSignatures[signature]:
                if regtemplate.name == template.name:
                    if regtemplate.overloadLevel > template.overloadLevel:
                        # ok to break - this is done every time a template is
                        # registered so there can only be one already existing
                        # with same name at a time
                        registered = True
                        break
                    elif regtemplate.overloadLevel < template.overloadLevel:
                        self._templateSignatures[signature].remove(regtemplate)
                        self._templateSignatures[signature].append(template)
                        registered = True
                    else:
                        raise Exception('Residue template %s with the same overloadLevel %d already exists.' %
                                         (template.name, template.overloadLevel)
                                         )
            if not registered:
                self._templateSignatures[signature].append(template)
272
273
        else:
            self._templateSignatures[signature] = [template]
274

275
276
277
    def registerScript(self, script):
        """Register a new script to be executed after building the System."""
        self._scripts.append(script)
278

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
279
    def registerTemplateGenerator(self, generator):
280
281
282
283
        """Register a residue template generator that can be used to parameterize residues that do not match existing forcefield templates.

        This functionality can be used to add handlers to parameterize small molecules or unnatural/modified residues.

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
284
285
        .. CAUTION:: This method is experimental, and its API is subject to change.

286
287
        Parameters
        ----------
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
288
        generator : function
289
290
            A function that will be called when a residue is encountered that does not match an existing forcefield template.

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
291
        When a residue without a template is encountered, the `generator` function is called with:
292

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
293
294
        ::
           success = generator(forcefield, residue)
295
296
        ```

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
297
298
299
300
301
302
303
304
305
306
        where `forcefield` is the calling `ForceField` object and `residue` is a simtk.openmm.app.topology.Residue object.

        `generator` must conform to the following API:
        ::
          Parameters
           ----------
           forcefield : simtk.openmm.app.ForceField
               The ForceField object to which residue templates and/or parameters are to be added.
           residue : simtk.openmm.app.Topology.Residue
               The residue topology for which a template is to be generated.
307

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
308
309
310
311
312
           Returns
           -------
           success : bool
               If the generator is able to successfully parameterize the residue, `True` is returned.
               If the generator cannot parameterize the residue, it should return `False` and not modify `forcefield`.
313

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
314
315
316
317
318
           The generator should either register a residue template directly with `forcefield.registerResidueTemplate(template)`
           or it should call `forcefield.loadFile(file)` to load residue definitions from an ffxml file.

           It can also use the `ForceField` programmatic API to add additional atom types (via `forcefield.registerAtomType(parameters)`)
           or additional parameters.
319
320

        """
321
        self._templateGenerators.append(generator)
322

323
    def _findAtomTypes(self, attrib, num):
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
        """Parse the attributes on an XML tag to find the set of atom types for each atom it involves.

        Parameters
        ----------
        attrib : dict of attributes
            The dictionary of attributes for an XML parameter tag.
        num : int
            The number of atom specifiers (e.g. 'class1' through 'class4') to extract.

        Returns
        -------
        types : list
            A list of atom types that match.

        """
339
340
341
342
343
344
345
        types = []
        for i in range(num):
            if num == 1:
                suffix = ''
            else:
                suffix = str(i+1)
            classAttrib = 'class'+suffix
346
            typeAttrib = 'type'+suffix
347
            if classAttrib in attrib:
348
                if typeAttrib in attrib:
349
                    raise ValueError('Specified both a type and a class for the same atom: '+str(attrib))
350
                if attrib[classAttrib] not in self._atomClasses:
peastman's avatar
peastman committed
351
352
353
                    types.append(None) # Unknown atom class
                else:
                    types.append(self._atomClasses[attrib[classAttrib]])
354
355
            elif typeAttrib in attrib:
                if attrib[typeAttrib] == '':
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
356
                    types.append(self._atomClasses[''])
357
                elif attrib[typeAttrib] not in self._atomTypes:
peastman's avatar
peastman committed
358
359
360
                    types.append(None) # Unknown atom type
                else:
                    types.append([attrib[typeAttrib]])
361
362
            else:
                types.append(None) # Unknown atom type
363
364
        return types

365
    def _parseTorsion(self, attrib):
366
        """Parse the node defining a torsion."""
367
        types = self._findAtomTypes(attrib, 4)
peastman's avatar
peastman committed
368
        if None in types:
369
370
371
372
373
            return None
        torsion = PeriodicTorsion(types)
        index = 1
        while 'phase%d'%index in attrib:
            torsion.periodicity.append(int(attrib['periodicity%d'%index]))
374
375
            torsion.phase.append(_convertParameterToNumber(attrib['phase%d'%index]))
            torsion.k.append(_convertParameterToNumber(attrib['k%d'%index]))
376
            index += 1
Justin MacCallum's avatar
Justin MacCallum committed
377
378
        return torsion

379
    class _SystemData(object):
380
381
382
        """Inner class used to encapsulate data about the system being created."""
        def __init__(self):
            self.atomType = {}
383
            self.atomParameters = {}
384
            self.atoms = []
385
            self.excludeAtomWith = []
386
            self.virtualSites = {}
387
388
389
390
391
392
            self.bonds = []
            self.angles = []
            self.propers = []
            self.impropers = []
            self.atomBonds = []
            self.isAngleConstrained = []
393
394
395
396
397
398
399
400
401
402
403
            self.constraints = {}

        def addConstraint(self, system, atom1, atom2, distance):
            """Add a constraint to the system, avoiding duplicate constraints."""
            key = (min(atom1, atom2), max(atom1, atom2))
            if key in self.constraints:
                if self.constraints(key) != distance:
                    raise ValueError('Two constraints were specified between atoms %d and %d with different distances' % (atom1, atom2))
            else:
                self.constraints[key] = distance
                system.addConstraint(atom1, atom2, distance)
404

405
    class _TemplateData(object):
406
407
408
409
        """Inner class used to encapsulate data about a residue template definition."""
        def __init__(self, name):
            self.name = name
            self.atoms = []
410
            self.virtualSites = []
411
412
            self.bonds = []
            self.externalBonds = []
413
            self.overloadLevel = 0
414

415
416
417
418
419
420
421
        def getAtomIndexByName(self, atom_name):
            """Look up an atom index by atom name, providing a helpful error message if not found."""
            for (index, atom) in enumerate(self.atoms):
                if atom.name == atom_name:
                    return index

            # Provide a helpful error message if atom name not found.
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
422
423
            msg =  "Atom name '%s' not found in residue template '%s'.\n" % (atom_name, self.name)
            msg += "Possible atom names are: %s" % str(atomIndices.keys())
424
425
            raise ValueError(msg)

426
        def addBond(self, atom1, atom2):
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
427
            """Add a bond between two atoms in a template given their indices in the template."""
428
429
430
            self.bonds.append((atom1, atom2))
            self.atoms[atom1].bondedTo.append(atom2)
            self.atoms[atom2].bondedTo.append(atom1)
431

432
        def addBondByName(self, atom1_name, atom2_name):
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
433
            """Add a bond between two atoms in a template given their atom names."""
434
435
436
437
438
            atom1 = self.getAtomIndexByName(atom1_name)
            atom2 = self.getAtomIndexByName(atom2_name)
            self.addBond(atom1, atom2)

        def addExternalBond(self, atom_index):
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
439
            """Designate that an atom in a residue template has an external bond, using atom index within template."""
440
441
442
443
            self.externalBonds.append(atom_index)
            self.atoms[atom_index].externalBonds += 1

        def addExternalBondByName(self, atom_name):
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
444
            """Designate that an atom in a residue template has an external bond, using atom name within template."""
445
446
447
            atom = self.getAtomIndexByName(atom_name)
            self.addExternalBond(atom)

448
    class _TemplateAtomData(object):
449
        """Inner class used to encapsulate data about an atom in a residue template definition."""
450
        def __init__(self, name, type, element, parameters={}):
451
452
453
            self.name = name
            self.type = type
            self.element = element
454
            self.parameters = parameters
455
456
457
            self.bondedTo = []
            self.externalBonds = 0

458
    class _BondData(object):
459
460
461
462
463
464
        """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
Justin MacCallum's avatar
Justin MacCallum committed
465

466
    class _VirtualSiteData(object):
467
        """Inner class used to encapsulate data about a virtual site."""
468
        def __init__(self, node, atomIndices):
469
470
471
            attrib = node.attrib
            self.type = attrib['type']
            if self.type == 'average2':
472
                numAtoms = 2
473
474
                self.weights = [float(attrib['weight1']), float(attrib['weight2'])]
            elif self.type == 'average3':
475
                numAtoms = 3
476
477
                self.weights = [float(attrib['weight1']), float(attrib['weight2']), float(attrib['weight3'])]
            elif self.type == 'outOfPlane':
478
                numAtoms = 3
479
                self.weights = [float(attrib['weight12']), float(attrib['weight13']), float(attrib['weightCross'])]
480
            elif self.type == 'localCoords':
481
                numAtoms = 3
482
483
484
485
                self.originWeights = [float(attrib['wo1']), float(attrib['wo2']), float(attrib['wo3'])]
                self.xWeights = [float(attrib['wx1']), float(attrib['wx2']), float(attrib['wx3'])]
                self.yWeights = [float(attrib['wy1']), float(attrib['wy2']), float(attrib['wy3'])]
                self.localPos = [float(attrib['p1']), float(attrib['p2']), float(attrib['p3'])]
486
487
            else:
                raise ValueError('Unknown virtual site type: %s' % self.type)
488
489
490
491
492
493
            if 'siteName' in attrib:
                self.index = atomIndices[attrib['siteName']]
                self.atoms = [atomIndices[attrib['atomName%d'%(i+1)]] for i in range(numAtoms)]
            else:
                self.index = int(attrib['index'])
                self.atoms = [int(attrib['atom%d'%(i+1)]) for i in range(numAtoms)]
494
495
496
497
            if 'excludeWith' in attrib:
                self.excludeWith = int(attrib['excludeWith'])
            else:
                self.excludeWith = self.atoms[0]
498

499
    class _AtomType(object):
500
501
502
503
504
505
506
        """Inner class used to record atom types and associated properties."""
        def __init__(self, name, atomClass, mass, element):
            self.name = name
            self.atomClass = atomClass
            self.mass = mass
            self.element = element

507
    class _AtomTypeParameters(object):
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
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
        """Inner class used to record parameter values for atom types."""
        def __init__(self, forcefield, forceName, atomTag, paramNames):
            self.ff = forcefield
            self.forceName = forceName
            self.atomTag = atomTag
            self.paramNames = paramNames
            self.paramsForType = {}
            self.extraParamsForType = {}

        def registerAtom(self, parameters, expectedParams=None):
            if expectedParams is None:
                expectedParams = self.paramNames
            types = self.ff._findAtomTypes(parameters, 1)
            if None not in types:
                values = {}
                extraValues = {}
                for key in parameters:
                    if key in expectedParams:
                        values[key] = _convertParameterToNumber(parameters[key])
                    else:
                        extraValues[key] = parameters[key]
                if len(values) < len(expectedParams):
                    for key in expectedParams:
                        if key not in values:
                            raise ValueError('%s: No value specified for "%s"' % (self.forceName, key))
                for t in types[0]:
                    self.paramsForType[t] = values
                    self.extraParamsForType[t] = extraValues

        def parseDefinitions(self, element):
            """"Load the definitions from an XML element."""
            expectedParams = list(self.paramNames)
            excludedParams = [node.attrib['name'] for node in element.findall('UseAttributeFromResidue')]
            for param in excludedParams:
                if param not in expectedParams:
                    raise ValueError('%s: <UseAttributeFromResidue> specified an invalid attribute: %s' % (self.forceName, param))
                expectedParams.remove(param)
            for atom in element.findall(self.atomTag):
                for param in excludedParams:
                    if param in atom.attrib:
                        raise ValueError('%s: The attribute "%s" appeared in both <%s> and <UseAttributeFromResidue> tags' % (self.forceName, param, self.atomTag))
                self.registerAtom(atom.attrib, expectedParams)

        def getAtomParameters(self, atom, data):
            """Get the parameter values for a particular atom."""
            t = data.atomType[atom]
            p = data.atomParameters[atom]
            if t in self.paramsForType:
                values = self.paramsForType[t]
                result = [None]*len(self.paramNames)
                for i, name in enumerate(self.paramNames):
                    if name in values:
                        result[i] = values[name]
                    elif name in p:
                        result[i] = p[name]
                    else:
                        raise ValueError('%s: No value specified for "%s"' % (self.forceName, name))
                return result
            else:
                raise ValueError('%s: No parameters defined for atom type %s' % (self.forceName, t))

        def getExtraParameters(self, atom, data):
            """Get extra parameter values for an atom that appeared in the <Atom> tag but were not included in paramNames."""
            t = data.atomType[atom]
            if t in self.paramsForType:
                return self.extraParamsForType[t]
            else:
                raise ValueError('%s: No parameters defined for atom type %s' % (self.forceName, t))


578
    def _getResidueTemplateMatches(self, res, bondedToAtom):
579
580
581
582
583
584
        """Return the residue template matches, or None if none are found.

        Parameters
        ----------
        res : Topology.Residue
            The residue for which template matches are to be retrieved.
585
586
        bondedToAtom : list of set of int
            bondedToAtom[i] is the set of atoms bonded to atom index i
587
588
589
590
591
592
593
594
595
596
597
598
599
600

        Returns
        -------
        template : _ForceFieldTemplate
            The matching forcefield residue template, or None if no matches are found.
        matches : list
            a list specifying which atom of the template each atom of the residue
            corresponds to, or None if it does not match the template

        """
        template = None
        matches = None
        signature = _createResidueSignature([atom.element for atom in res.atoms()])
        if signature in self._templateSignatures:
601
            allMatches = []
602
            for t in self._templateSignatures[signature]:
603
604
605
606
607
608
609
610
                match = _matchResidue(res, t, bondedToAtom)
                if match is not None:
                    allMatches.append((t, match))
            if len(allMatches) == 1:
                template = allMatches[0][0]
                matches = allMatches[0][1]
            elif len(allMatches) > 1:
                raise Exception('Multiple matching templates found for residue %d (%s).' % (res.index+1, res.name))
611
612
        return [template, matches]

613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
    def _buildBondedToAtomList(self, topology):
        """Build a list of which atom indices are bonded to each atom.

        Parameters
        ----------
        topology : Topology
            The Topology whose bonds are to be indexed.

        Returns
        -------
        bondedToAtom : list of set of int
            bondedToAtom[index] is the set of atom indices bonded to atom `index`

        """
        bondedToAtom = []
        for atom in topology.atoms():
            bondedToAtom.append(set())
630
631
632
        for (atom1, atom2) in topology.bonds():
            bondedToAtom[atom1.index].add(atom2.index)
            bondedToAtom[atom2.index].add(atom1.index)
633
        return bondedToAtom
634

635
636
637
    def getUnmatchedResidues(self, topology):
        """Return a list of Residue objects from specified topology for which no forcefield templates are available.

638
639
        .. CAUTION:: This method is experimental, and its API is subject to change.

640
641
642
        Parameters
        ----------
        topology : Topology
643
            The Topology whose residues are to be checked against the forcefield residue templates.
644
645
646
647

        Returns
        -------
        unmatched_residues : list of Residue
648
            List of Residue objects from `topology` for which no forcefield residue templates are available.
649
650
651
652
653
            Note that multiple instances of the same residue appearing at different points in the topology may be returned.

        This method may be of use in generating missing residue templates or diagnosing parameterization failures.
        """
        # Find the template matching each residue, compiling a list of residues for which no templates are available.
654
        bondedToAtom = self._buildBondedToAtomList(topology)
655
        unmatched_residues = list() # list of unmatched residues
656
657
658
659
660
661
        for res in topology.residues():
            # Attempt to match one of the existing templates.
            [template, matches] = self._getResidueTemplateMatches(res, bondedToAtom)
            if matches is None:
                # No existing templates match.
                unmatched_residues.append(res)
662
663
664

        return unmatched_residues

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
    def getMatchingTemplates(self, topology):
        """Return a list of forcefield residue templates matching residues in the specified topology.

        .. CAUTION:: This method is experimental, and its API is subject to change.

        Parameters
        ----------
        topology : Topology
            The Topology whose residues are to be checked against the forcefield residue templates.

        Returns
        -------
        templates : list of _TemplateData
            List of forcefield residue templates corresponding to residues in the topology.
            templates[index] is template corresponding to residue `index` in topology.residues()

        This method may be of use in debugging issues related to parameter assignment.
        """
        # Find the template matching each residue, compiling a list of residues for which no templates are available.
        bondedToAtom = self._buildBondedToAtomList(topology)
        templates = list() # list of templates matching the corresponding residues
        for res in topology.residues():
            # Attempt to match one of the existing templates.
            [template, matches] = self._getResidueTemplateMatches(res, bondedToAtom)
            # Raise an exception if we have found no templates that match.
            if matches is None:
                raise ValueError('No template found for residue %d (%s).  %s' % (res.index+1, res.name, _findMatchErrors(self, res)))
            else:
                templates.append(template)

        return templates

697
698
    def generateTemplatesForUnmatchedResidues(self, topology):
        """Generate forcefield residue templates for residues in specified topology for which no forcefield templates are available.
699

700
701
        .. CAUTION:: This method is experimental, and its API is subject to change.

702
703
704
        Parameters
        ----------
        topology : Topology
705
            The Topology whose residues are to be checked against the forcefield residue templates.
706
707
708

        Returns
        -------
709
710
711
712
713
714
        templates : list of _TemplateData
            List of forcefield residue templates corresponding to residues in `topology` for which no forcefield templates are currently available.
            Atom types will be set to `None`, but template name, atom names, elements, and connectivity will be taken from corresponding Residue objects.
        residues : list of Residue
            List of Residue objects that were used to generate the templates.
            `residues[index]` is the Residue that was used to generate the template `templates[index]`
715
716
717
718
719

        """
        # Get a non-unique list of unmatched residues.
        unmatched_residues = self.getUnmatchedResidues(topology)
        # Generate a unique list of unmatched residues by comparing fingerprints.
720
        bondedToAtom = self._buildBondedToAtomList(topology)
721
722
        unique_unmatched_residues = list() # list of unique unmatched Residue objects from topology
        templates = list() # corresponding _TemplateData templates
723
724
725
        signatures = set()
        for residue in unmatched_residues:
            signature = _createResidueSignature([ atom.element for atom in residue.atoms() ])
726
            template = _createResidueTemplate(residue)
727
728
729
730
731
732
733
734
735
736
737
            is_unique = True
            if signature in signatures:
                # Signature is the same as an existing residue; check connectivity.
                for check_residue in unique_unmatched_residues:
                    matches = _matchResidue(check_residue, template, bondedToAtom)
                    if matches is not None:
                        is_unique = False
            if is_unique:
                # Residue is unique.
                unique_unmatched_residues.append(residue)
                signatures.add(signature)
738
                templates.append(template)
739

740
        return [templates, unique_unmatched_residues]
741

742
    def createSystem(self, topology, nonbondedMethod=NoCutoff, nonbondedCutoff=1.0*unit.nanometer,
743
                     constraints=None, rigidWater=True, removeCMMotion=True, hydrogenMass=None, residueTemplates=dict(), **args):
744
        """Construct an OpenMM System representing a Topology with this force field.
Justin MacCallum's avatar
Justin MacCallum committed
745

Robert McGibbon's avatar
Robert McGibbon committed
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
        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
        constraints : object=None
            Specifies which bonds and angles should be implemented with constraints.
            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
        removeCMMotion : boolean=True
            If true, a CMMotionRemover will be added to the System
        hydrogenMass : mass=None
            The mass to use for hydrogen atoms bound to heavy atoms.  Any mass
            added to a hydrogen is subtracted from the heavy atom to keep
            their total mass the same.
767
768
769
770
771
772
773
        residueTemplates : dict=dict()
           Key: Topology Residue object
           Value: string, name of _TemplateData residue template object to use for
                  (Key) residue
           This allows user to specify which template to apply to particular Residues
           in the event that multiple matching templates are available (e.g Fe2+ and Fe3+
           templates in the ForceField for a monoatomic iron ion in the topology).
Robert McGibbon's avatar
Robert McGibbon committed
774
775
776
777
778
779
780
781
782
        args
             Arbitrary additional keyword arguments may also be specified.
             This allows extra parameters to be specified that are specific to
             particular force fields.

        Returns
        -------
        system
            the newly created System
783
784
        """
        data = ForceField._SystemData()
785
        data.atoms = list(topology.atoms())
786
787
        for atom in data.atoms:
            data.excludeAtomWith.append([])
788
789

        # Make a list of all bonds
Justin MacCallum's avatar
Justin MacCallum committed
790

791
        for bond in topology.bonds():
792
            data.bonds.append(ForceField._BondData(bond[0].index, bond[1].index))
793
794

        # Record which atoms are bonded to each other atom
Justin MacCallum's avatar
Justin MacCallum committed
795

796
797
798
799
800
801
802
803
804
805
806
807
        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.
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
808
        # If no templates are found, attempt to use residue template generators to create new templates (and potentially atom types/parameters).
Justin MacCallum's avatar
Justin MacCallum committed
809

810
811
        for chain in topology.chains():
            for res in chain.residues():
812
813
814
815
816
817
818
819
820
                if res in residueTemplates:
                    tname = residueTemplates[res]
                    template = self._templates[tname]
                    matches = _matchResidue(res, template, bondedToAtom)
                    if matches is None:
                        raise Exception('User-supplied template %s does not match the residue %d (%s)' % (tname, res.index+1, res.name))
                else:
                    # Attempt to match one of the existing templates.
                    [template, matches] = self._getResidueTemplateMatches(res, bondedToAtom)
821
822
                if matches is None:
                    # No existing templates match.  Try any registered residue template generators.
823
                    for generator in self._templateGenerators:
824
                        if generator(self, res):
825
                            # This generator has registered a new residue template that should match.
826
                            [template, matches] = self._getResidueTemplateMatches(res, bondedToAtom)
827
828
829
830
831
832
833
834
                            if matches is None:
                                # Something went wrong because the generated template does not match the residue signature.
                                raise Exception('The residue handler %s indicated it had correctly parameterized residue %s, but the generated template did not match the residue signature.' % (generator.__class__.__name__, str(res)))
                            else:
                                # We successfully generated a residue template.  Break out of the for loop.
                                break

                # Raise an exception if we have found no templates that match.
835
                if matches is None:
836
                    raise ValueError('No template found for residue %d (%s).  %s' % (res.index+1, res.name, _findMatchErrors(self, res)))
837
838

                # Store parameters for the matched residue template.
839
                matchAtoms = dict(zip(matches, res.atoms()))
840
841
                for atom, match in zip(res.atoms(), matches):
                    data.atomType[atom] = template.atoms[match].type
842
                    data.atomParameters[atom] = template.atoms[match].parameters
843
844
                    for site in template.virtualSites:
                        if match == site.index:
845
                            data.virtualSites[atom] = (site, [matchAtoms[i].index for i in site.atoms], matchAtoms[site.excludeWith].index)
846
847

        # Create the System and add atoms
Justin MacCallum's avatar
Justin MacCallum committed
848

849
850
        sys = mm.System()
        for atom in topology.atoms():
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
851
            # Look up the atom type name, returning a helpful error message if it cannot be found.
852
853
854
855
            if atom not in data.atomType:
                raise Exception("Could not identify atom type for atom '%s'." % str(atom))
            typename = data.atomType[atom]

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
856
            # Look up the type name in the list of registered atom types, returning a helpful error message if it cannot be found.
857
858
859
860
            if typename not in self._atomTypes:
                msg  = "Could not find typename '%s' for atom '%s' in list of known atom types.\n" % (typename, str(atom))
                msg += "Known atom types are: %s" % str(self._atomTypes.keys())
                raise Exception(msg)
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
861
862

            # Add the particle to the OpenMM system.
863
            mass = self._atomTypes[typename].mass
864
            sys.addParticle(mass)
865

866
        # Adjust hydrogen masses if requested.
867

868
        if hydrogenMass is not None:
869
870
            if not unit.is_quantity(hydrogenMass):
                hydrogenMass *= unit.dalton
871
872
873
874
875
876
877
            for atom1, atom2 in topology.bonds():
                if atom1.element == elem.hydrogen:
                    (atom1, atom2) = (atom2, atom1)
                if atom2.element == elem.hydrogen and atom1.element not in (elem.hydrogen, None):
                    transferMass = hydrogenMass-sys.getParticleMass(atom2.index)
                    sys.setParticleMass(atom2.index, hydrogenMass)
                    sys.setParticleMass(atom1.index, sys.getParticleMass(atom1.index)-transferMass)
Justin MacCallum's avatar
Justin MacCallum committed
878

879
        # Set periodic boundary conditions.
Justin MacCallum's avatar
Justin MacCallum committed
880

881
882
883
        boxVectors = topology.getPeriodicBoxVectors()
        if boxVectors is not None:
            sys.setDefaultPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2])
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
884
        elif nonbondedMethod not in [NoCutoff, CutoffNonPeriodic]:
885
886
887
            raise ValueError('Requested periodic boundary conditions for a Topology that does not specify periodic box dimensions')

        # Make a list of all unique angles
Justin MacCallum's avatar
Justin MacCallum committed
888

889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
        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))
Justin MacCallum's avatar
Justin MacCallum committed
904

905
        # Make a list of all unique proper torsions
Justin MacCallum's avatar
Justin MacCallum committed
906

907
908
909
        uniquePropers = set()
        for angle in data.angles:
            for atom in bondedToAtom[angle[0]]:
pgrinaway's avatar
pgrinaway committed
910
                if atom not in angle:
911
912
913
914
915
                    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]]:
pgrinaway's avatar
pgrinaway committed
916
                if atom not in angle:
917
918
919
920
921
                    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))
Justin MacCallum's avatar
Justin MacCallum committed
922

923
        # Make a list of all unique improper torsions
Justin MacCallum's avatar
Justin MacCallum committed
924

925
926
927
928
929
        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]))
Justin MacCallum's avatar
Justin MacCallum committed
930

931
        # Identify bonds that should be implemented with constraints
Justin MacCallum's avatar
Justin MacCallum committed
932

933
934
935
936
937
938
939
940
941
942
943
944
945
946
        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
Justin MacCallum's avatar
Justin MacCallum committed
947

948
        # Identify angles that should be implemented with constraints
Justin MacCallum's avatar
Justin MacCallum committed
949

950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
        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
Justin MacCallum's avatar
Justin MacCallum committed
971

972
        # Add virtual sites
Justin MacCallum's avatar
Justin MacCallum committed
973

974
        for atom in data.virtualSites:
975
            (site, atoms, excludeWith) = data.virtualSites[atom]
976
            index = atom.index
977
            data.excludeAtomWith[excludeWith].append(index)
978
            if site.type == 'average2':
979
                sys.setVirtualSite(index, mm.TwoParticleAverageSite(atoms[0], atoms[1], site.weights[0], site.weights[1]))
980
            elif site.type == 'average3':
981
                sys.setVirtualSite(index, mm.ThreeParticleAverageSite(atoms[0], atoms[1], atoms[2], site.weights[0], site.weights[1], site.weights[2]))
982
            elif site.type == 'outOfPlane':
983
984
985
986
987
988
989
                sys.setVirtualSite(index, mm.OutOfPlaneSite(atoms[0], atoms[1], atoms[2], site.weights[0], site.weights[1], site.weights[2]))
            elif site.type == 'localCoords':
                sys.setVirtualSite(index, mm.LocalCoordinatesSite(atoms[0], atoms[1], atoms[2],
                                                                  mm.Vec3(site.originWeights[0], site.originWeights[1], site.originWeights[2]),
                                                                  mm.Vec3(site.xWeights[0], site.xWeights[1], site.xWeights[2]),
                                                                  mm.Vec3(site.yWeights[0], site.yWeights[1], site.yWeights[2]),
                                                                  mm.Vec3(site.localPos[0], site.localPos[1], site.localPos[2])))
Justin MacCallum's avatar
Justin MacCallum committed
990

991
        # Add forces to the System
Justin MacCallum's avatar
Justin MacCallum committed
992

993
994
        for force in self._forces:
            force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
995
996
        if removeCMMotion:
            sys.addForce(mm.CMMotionRemover())
Justin MacCallum's avatar
Justin MacCallum committed
997

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
998
        # Let force generators do postprocessing
Justin MacCallum's avatar
Justin MacCallum committed
999

peastman's avatar
peastman committed
1000
1001
1002
        for force in self._forces:
            if 'postprocessSystem' in dir(force):
                force.postprocessSystem(sys, data, args)
Justin MacCallum's avatar
Justin MacCallum committed
1003

1004
        # Execute scripts found in the XML files.
Justin MacCallum's avatar
Justin MacCallum committed
1005

1006
        for script in self._scripts:
1007
            exec(script, locals())
1008
1009
1010
        return sys


1011
1012
def _countResidueAtoms(elements):
    """Count the number of atoms of each element in a residue."""
1013
1014
    counts = {}
    for element in elements:
1015
        if element in counts:
1016
1017
1018
            counts[element] += 1
        else:
            counts[element] = 1
1019
1020
1021
1022
1023
1024
    return counts


def _createResidueSignature(elements):
    """Create a signature for a residue based on the elements of the atoms it contains."""
    counts = _countResidueAtoms(elements)
1025
1026
    sig = []
    for c in counts:
1027
1028
        if c is not None:
            sig.append((c, counts[c]))
1029
    sig.sort(key=lambda x: -x[0].mass)
Justin MacCallum's avatar
Justin MacCallum committed
1030

1031
    # Convert it to a string.
1032
1033

    s = ''
1034
    for element, count in sig:
1035
1036
1037
        s += element.symbol+str(count)
    return s

1038
def _matchResidue(res, template, bondedToAtom):
1039
    """Determine whether a residue matches a template and return a list of corresponding atoms.
Justin MacCallum's avatar
Justin MacCallum committed
1040

Robert McGibbon's avatar
Robert McGibbon committed
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
    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

    Returns
    -------
1052
1053
1054
    list
        a list specifying which atom of the template each atom of the residue
        corresponds to, or None if it does not match the template
1055
1056
    """
    atoms = list(res.atoms())
1057
1058
    if len(atoms) != len(template.atoms):
        return None
1059
1060
    matches = len(atoms)*[0]
    hasMatch = len(atoms)*[False]
Justin MacCallum's avatar
Justin MacCallum committed
1061

1062
    # Translate from global to local atom indices, and record the bonds for each atom.
Justin MacCallum's avatar
Justin MacCallum committed
1063

1064
1065
    renumberAtoms = {}
    for i in range(len(atoms)):
1066
        renumberAtoms[atoms[i].index] = i
1067
1068
1069
    bondedTo = []
    externalBonds = []
    for atom in atoms:
1070
        bonds = [renumberAtoms[x] for x in bondedToAtom[atom.index] if x in renumberAtoms]
1071
        bondedTo.append(bonds)
1072
        externalBonds.append(len([x for x in bondedToAtom[atom.index] if x not in renumberAtoms]))
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093

    # For each unique combination of element and number of bonds, make sure the residue and
    # template have the same number of atoms.

    residueTypeCount = {}
    for i, atom in enumerate(atoms):
        key = (atom.element, len(bondedTo[i]), externalBonds[i])
        if key not in residueTypeCount:
            residueTypeCount[key] = 1
        residueTypeCount[key] += 1
    templateTypeCount = {}
    for i, atom in enumerate(template.atoms):
        key = (atom.element, len(atom.bondedTo), atom.externalBonds)
        if key not in templateTypeCount:
            templateTypeCount[key] = 1
        templateTypeCount[key] += 1
    if residueTypeCount != templateTypeCount:
        return None

    # Recursively match atoms.

1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
    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
peastman's avatar
peastman committed
1104
    name = atoms[position].name
1105
1106
    for i in range(len(atoms)):
        atom = template.atoms[i]
1107
        if ((atom.element is not None and atom.element == elem) or (atom.element is None and atom.name == name)) and not hasMatch[i] and len(atom.bondedTo) == len(bondedTo[position]) and atom.externalBonds == externalBonds[position]:
1108
            # See if the bonds for this identification are consistent
Justin MacCallum's avatar
Justin MacCallum committed
1109

1110
1111
1112
            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.
Justin MacCallum's avatar
Justin MacCallum committed
1113

1114
1115
1116
1117
1118
1119
1120
1121
                matches[position] = i
                hasMatch[i] = True
                if _findAtomMatches(atoms, template, bondedTo, externalBonds, matches, hasMatch, position+1):
                    return True
                hasMatch[i] = False
    return False


1122
1123
1124
def _findMatchErrors(forcefield, res):
    """Try to guess why a residue failed to match any template and return an error message."""
    residueCounts = _countResidueAtoms([atom.element for atom in res.atoms()])
1125
    numResidueAtoms = sum(residueCounts.values())
1126
    numResidueHeavyAtoms = sum(residueCounts[element] for element in residueCounts if element not in (None, elem.hydrogen))
1127

1128
    # Loop over templates and see how closely each one might match.
1129

1130
1131
1132
1133
1134
1135
    bestMatchName = None
    numBestMatchAtoms = 3*numResidueAtoms
    numBestMatchHeavyAtoms = 2*numResidueHeavyAtoms
    for templateName in forcefield._templates:
        template = forcefield._templates[templateName]
        templateCounts = _countResidueAtoms([atom.element for atom in template.atoms])
1136

1137
        # Does the residue have any atoms that clearly aren't in the template?
1138

1139
1140
        if any(element not in templateCounts or templateCounts[element] < residueCounts[element] for element in residueCounts):
            continue
1141

1142
        # If there are too many missing atoms, discard this template.
1143

1144
        numTemplateAtoms = sum(templateCounts.values())
1145
        numTemplateHeavyAtoms = sum(templateCounts[element] for element in templateCounts if element not in (None, elem.hydrogen))
1146
1147
1148
1149
        if numTemplateAtoms > numBestMatchAtoms:
            continue
        if numTemplateHeavyAtoms > numBestMatchHeavyAtoms:
            continue
1150

1151
1152
        # If this template has the same number of missing atoms as our previous best one, look at the name
        # to decide which one to use.
1153

1154
1155
1156
        if numTemplateAtoms == numBestMatchAtoms:
            if bestMatchName == res.name or res.name not in templateName:
                continue
1157

1158
        # Accept this as our new best match.
1159

1160
1161
1162
        bestMatchName = templateName
        numBestMatchAtoms = numTemplateAtoms
        numBestMatchHeavyAtoms = numTemplateHeavyAtoms
1163
        numBestMatchExtraParticles = len([atom for atom in template.atoms if atom.element is None])
1164

1165
    # Return an appropriate error message.
1166

1167
    if numBestMatchAtoms == numResidueAtoms:
1168
1169
        chainResidues = list(res.chain.residues())
        if len(chainResidues) > 1 and (res == chainResidues[0] or res == chainResidues[-1]):
1170
1171
1172
1173
            return 'The set of atoms matches %s, but the bonds are different.  Perhaps the chain is missing a terminal group?' % bestMatchName
        return 'The set of atoms matches %s, but the bonds are different.' % bestMatchName
    if bestMatchName is not None:
        if numBestMatchHeavyAtoms == numResidueHeavyAtoms:
1174
1175
1176
1177
1178
            numResidueExtraParticles = len([atom for atom in res.atoms() if atom.element is None])
            if numResidueExtraParticles == 0 and numBestMatchExtraParticles == 0:
                return 'The set of atoms is similar to %s, but it is missing %d hydrogen atoms.' % (bestMatchName, numBestMatchAtoms-numResidueAtoms)
            if numBestMatchExtraParticles-numResidueExtraParticles == numBestMatchAtoms-numResidueAtoms:
                return 'The set of atoms is similar to %s, but it is missing %d extra particles.  You can add them with Modeller.addExtraParticles().' % (bestMatchName, numBestMatchAtoms-numResidueAtoms)
1179
1180
1181
        return 'The set of atoms is similar to %s, but it is missing %d atoms.' % (bestMatchName, numBestMatchAtoms-numResidueAtoms)
    return 'This might mean your input topology is missing some atoms or bonds, or possibly that you are using the wrong force field.'

1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
def _createResidueTemplate(residue):
    """Create a _TemplateData template from a Residue object.

    Parameters
    ----------
    residue : Residue
        The Residue from which the template is to be constructed.

    Returns
    -------
    template : _TemplateData
        The residue template, with atom types set to None.

    This method may be useful in creating new residue templates for residues without templates defined by the ForceField.

    """
    template = ForceField._TemplateData(residue.name)
    for atom in residue.atoms():
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
1200
        template.atoms.append(ForceField._TemplateAtomData(atom.name, None, atom.element))
1201
1202
1203
1204
1205
1206
1207
1208
1209
    for (atom1,atom2) in residue.internal_bonds():
        template.addBondByName(atom1.name, atom2.name)
    residue_atoms = [ atom for atom in residue.atoms() ]
    for (atom1,atom2) in residue.external_bonds():
        if atom1 in residue_atoms:
            template.addExternalBondByName(atom1.name)
        elif atom2 in residue_atoms:
            template.addExternalBondByName(atom2.name)
    return template
1210

1211
1212
1213
1214
1215
# 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.

1216
## @private
1217
class HarmonicBondGenerator(object):
1218
    """A HarmonicBondGenerator constructs a HarmonicBondForce."""
Justin MacCallum's avatar
Justin MacCallum committed
1219

1220
1221
    def __init__(self, forcefield):
        self.ff = forcefield
1222
1223
1224
1225
        self.types1 = []
        self.types2 = []
        self.length = []
        self.k = []
1226

1227
1228
1229
1230
1231
1232
1233
    def registerBond(self, parameters):
        types = self.ff._findAtomTypes(parameters, 2)
        if None not in types:
            self.types1.append(types[0])
            self.types2.append(types[1])
            self.length.append(_convertParameterToNumber(parameters['length']))
            self.k.append(_convertParameterToNumber(parameters['k']))
Justin MacCallum's avatar
Justin MacCallum committed
1234

1235
1236
    @staticmethod
    def parseElement(element, ff):
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1237
1238
1239
1240
1241
1242
        existing = [f for f in ff._forces if isinstance(f, HarmonicBondGenerator)]
        if len(existing) == 0:
            generator = HarmonicBondGenerator(ff)
            ff.registerGenerator(generator)
        else:
            generator = existing[0]
1243
        for bond in element.findall('Bond'):
1244
            generator.registerBond(bond.attrib)
Justin MacCallum's avatar
Justin MacCallum committed
1245

1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
    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:
1263
                        data.addConstraint(sys, bond.atom1, bond.atom2, self.length[i])
1264
1265
1266
1267
1268
1269
1270
                    elif self.k[i] != 0:
                        force.addBond(bond.atom1, bond.atom2, self.length[i], self.k[i])
                    break

parsers["HarmonicBondForce"] = HarmonicBondGenerator.parseElement


1271
## @private
1272
class HarmonicAngleGenerator(object):
1273
    """A HarmonicAngleGenerator constructs a HarmonicAngleForce."""
Justin MacCallum's avatar
Justin MacCallum committed
1274

1275
1276
    def __init__(self, forcefield):
        self.ff = forcefield
1277
1278
1279
1280
1281
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.angle = []
        self.k = []
Justin MacCallum's avatar
Justin MacCallum committed
1282

1283
1284
1285
1286
1287
1288
1289
1290
1291
    def registerAngle(self, parameters):
        types = self.ff._findAtomTypes(parameters, 3)
        if None not in types:
            self.types1.append(types[0])
            self.types2.append(types[1])
            self.types3.append(types[2])
            self.angle.append(_convertParameterToNumber(parameters['angle']))
            self.k.append(_convertParameterToNumber(parameters['k']))

1292
1293
    @staticmethod
    def parseElement(element, ff):
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1294
1295
1296
1297
1298
1299
        existing = [f for f in ff._forces if isinstance(f, HarmonicAngleGenerator)]
        if len(existing) == 0:
            generator = HarmonicAngleGenerator(ff)
            ff.registerGenerator(generator)
        else:
            generator = existing[0]
1300
        for angle in element.findall('Angle'):
1301
            generator.registerAngle(angle.attrib)
Justin MacCallum's avatar
Justin MacCallum committed
1302

1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
    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.
Justin MacCallum's avatar
Justin MacCallum committed
1322

1323
1324
1325
1326
1327
1328
1329
1330
1331
                        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
Justin MacCallum's avatar
Justin MacCallum committed
1332

1333
                        # Compute the distance between atoms and add a constraint
Justin MacCallum's avatar
Justin MacCallum committed
1334

1335
1336
1337
1338
1339
                        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]))
1340
                                data.addConstraint(sys, angle[0], angle[2], length)
1341
1342
1343
1344
1345
1346
1347
                    elif self.k[i] != 0:
                        force.addAngle(angle[0], angle[1], angle[2], self.angle[i], self.k[i])
                    break

parsers["HarmonicAngleForce"] = HarmonicAngleGenerator.parseElement


1348
## @private
1349
class PeriodicTorsion(object):
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
    """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 = []

1361
## @private
1362
class PeriodicTorsionGenerator(object):
1363
    """A PeriodicTorsionGenerator constructs a PeriodicTorsionForce."""
Justin MacCallum's avatar
Justin MacCallum committed
1364

1365
1366
    def __init__(self, forcefield):
        self.ff = forcefield
1367
1368
        self.proper = []
        self.improper = []
Justin MacCallum's avatar
Justin MacCallum committed
1369

1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
    def registerProperTorsion(self, parameters):
        torsion = self.ff._parseTorsion(parameters)
        if torsion is not None:
            self.proper.append(torsion)

    def registerImproperTorsion(self, parameters):
        torsion = self.ff._parseTorsion(parameters)
        if torsion is not None:
            self.improper.append(torsion)

1380
1381
    @staticmethod
    def parseElement(element, ff):
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1382
1383
1384
1385
1386
1387
        existing = [f for f in ff._forces if isinstance(f, PeriodicTorsionGenerator)]
        if len(existing) == 0:
            generator = PeriodicTorsionGenerator(ff)
            ff.registerGenerator(generator)
        else:
            generator = existing[0]
1388
        for torsion in element.findall('Proper'):
1389
            generator.registerProperTorsion(torsion.attrib)
1390
        for torsion in element.findall('Improper'):
1391
            generator.registerImproperTorsion(torsion.attrib)
Justin MacCallum's avatar
Justin MacCallum committed
1392

1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
    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]]]
1428
            match = None
1429
1430
1431
1432
1433
            for tordef in self.improper:
                types1 = tordef.types1
                types2 = tordef.types2
                types3 = tordef.types3
                types4 = tordef.types4
1434
1435
1436
1437
                hasWildcard = (wildcard in (types1, types2, types3, types4))
                if match is not None and hasWildcard:
                    # Prefer specific definitions over ones with wildcards
                    continue
1438
1439
1440
                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:
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
                            # Workaround to be more consistent with AMBER.  It uses wildcards to define most of its
                            # impropers, which leaves the ordering ambiguous.  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)
1452
                            match = (a1, a2, torsion[0], torsion[t4[1]], tordef)
1453
                            break
1454
1455
1456
1457
1458
            if match is not None:
                (a1, a2, a3, a4, tordef) = match
                for i in range(len(tordef.phase)):
                    if tordef.k[i] != 0:
                        force.addTorsion(a1, a2, a3, a4, tordef.periodicity[i], tordef.phase[i], tordef.k[i])
1459
1460
1461
1462

parsers["PeriodicTorsionForce"] = PeriodicTorsionGenerator.parseElement


1463
## @private
1464
class RBTorsion(object):
1465
1466
1467
1468
1469
1470
1471
1472
1473
    """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

1474
## @private
1475
class RBTorsionGenerator(object):
1476
    """An RBTorsionGenerator constructs an RBTorsionForce."""
Justin MacCallum's avatar
Justin MacCallum committed
1477

1478
1479
    def __init__(self, forcefield):
        self.ff = forcefield
1480
1481
        self.proper = []
        self.improper = []
Justin MacCallum's avatar
Justin MacCallum committed
1482

1483
1484
    @staticmethod
    def parseElement(element, ff):
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1485
1486
1487
1488
1489
1490
        existing = [f for f in ff._forces if isinstance(f, RBTorsionGenerator)]
        if len(existing) == 0:
            generator = RBTorsionGenerator(ff)
            ff.registerGenerator(generator)
        else:
            generator = existing[0]
1491
        for torsion in element.findall('Proper'):
1492
            types = ff._findAtomTypes(torsion.attrib, 4)
peastman's avatar
peastman committed
1493
            if None not in types:
1494
1495
                generator.proper.append(RBTorsion(types, [float(torsion.attrib['c'+str(i)]) for i in range(6)]))
        for torsion in element.findall('Improper'):
1496
            types = ff._findAtomTypes(torsion.attrib, 4)
peastman's avatar
peastman committed
1497
            if None not in types:
1498
                generator.improper.append(RBTorsion(types, [float(torsion.attrib['c'+str(i)]) for i in range(6)]))
Justin MacCallum's avatar
Justin MacCallum committed
1499

1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
    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]]]
1533
            match = None
1534
1535
1536
1537
1538
            for tordef in self.improper:
                types1 = tordef.types1
                types2 = tordef.types2
                types3 = tordef.types3
                types4 = tordef.types4
1539
1540
1541
1542
                hasWildcard = (wildcard in (types1, types2, types3, types4))
                if match is not None and hasWildcard:
                    # Prefer specific definitions over ones with wildcards
                    continue
1543
1544
1545
                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:
1546
                            if hasWildcard:
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
                                # Workaround to be more consistent with AMBER.  It uses wildcards to define most of its
                                # impropers, which leaves the ordering ambiguous.  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)
1558
                                match = (a1, a2, torsion[0], torsion[t4[1]], tordef)
1559
1560
                            else:
                                # There are no wildcards, so the order is unambiguous.
1561
                                match = (torsion[0], torsion[t2[1]], torsion[t3[1]], torsion[t4[1]], tordef)
1562
                            break
1563
1564
1565
            if match is not None:
                (a1, a2, a3, a4, tordef) = match
                force.addTorsion(a1, a2, a3, a4, tordef.c[0], tordef.c[1], tordef.c[2], tordef.c[3], tordef.c[4], tordef.c[5])
1566
1567
1568
1569

parsers["RBTorsionForce"] = RBTorsionGenerator.parseElement


1570
## @private
1571
class CMAPTorsion(object):
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
    """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

1582
## @private
1583
class CMAPTorsionGenerator(object):
1584
    """A CMAPTorsionGenerator constructs a CMAPTorsionForce."""
Justin MacCallum's avatar
Justin MacCallum committed
1585

1586
1587
    def __init__(self, forcefield):
        self.ff = forcefield
1588
1589
        self.torsions = []
        self.maps = []
Justin MacCallum's avatar
Justin MacCallum committed
1590

1591
1592
    @staticmethod
    def parseElement(element, ff):
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1593
1594
1595
1596
1597
1598
        existing = [f for f in ff._forces if isinstance(f, CMAPTorsionGenerator)]
        if len(existing) == 0:
            generator = CMAPTorsionGenerator(ff)
            ff.registerGenerator(generator)
        else:
            generator = existing[0]
1599
1600
1601
1602
1603
1604
1605
        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'):
1606
            types = ff._findAtomTypes(torsion.attrib, 5)
peastman's avatar
peastman committed
1607
            if None not in types:
1608
                generator.torsions.append(CMAPTorsion(types, int(torsion.attrib['map'])))
Justin MacCallum's avatar
Justin MacCallum committed
1609

1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
    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)
Justin MacCallum's avatar
Justin MacCallum committed
1620

1621
        # Find all chains of length 5
Justin MacCallum's avatar
Justin MacCallum committed
1622

1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
        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


1666
## @private
1667
class NonbondedGenerator(object):
1668
    """A NonbondedGenerator constructs a NonbondedForce."""
Justin MacCallum's avatar
Justin MacCallum committed
1669

1670
1671
    SCALETOL = 1e-5

1672
1673
    def __init__(self, forcefield, coulomb14scale, lj14scale):
        self.ff = forcefield
1674
1675
        self.coulomb14scale = coulomb14scale
        self.lj14scale = lj14scale
1676
        self.params = ForceField._AtomTypeParameters(forcefield, 'NonbondedForce', 'Atom', ('charge', 'sigma', 'epsilon'))
1677

1678
    def registerAtom(self, parameters):
1679
        self.params.registerAtom(parameters)
1680

1681
1682
1683
1684
    @staticmethod
    def parseElement(element, ff):
        existing = [f for f in ff._forces if isinstance(f, NonbondedGenerator)]
        if len(existing) == 0:
1685
1686
            generator = NonbondedGenerator(ff, float(element.attrib['coulomb14scale']), float(element.attrib['lj14scale']))
            ff.registerGenerator(generator)
1687
1688
1689
        else:
            # Multiple <NonbondedForce> tags were found, probably in different files.  Simply add more types to the existing one.
            generator = existing[0]
1690
1691
            if abs(generator.coulomb14scale - float(element.attrib['coulomb14scale'])) > NonbondedGenerator.SCALETOL or \
                    abs(generator.lj14scale - float(element.attrib['lj14scale'])) > NonbondedGenerator.SCALETOL:
Justin MacCallum's avatar
Justin MacCallum committed
1692
                raise ValueError('Found multiple NonbondedForce tags with different 1-4 scales')
1693
        generator.params.parseDefinitions(element)
Justin MacCallum's avatar
Justin MacCallum committed
1694

1695
1696
1697
1698
1699
1700
1701
    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:
Justin MacCallum's avatar
Justin MacCallum committed
1702
            raise ValueError('Illegal nonbonded method for NonbondedForce')
1703
1704
        force = mm.NonbondedForce()
        for atom in data.atoms:
1705
1706
            values = self.params.getAtomParameters(atom, data)
            force.addParticle(values[0], values[1], values[2])
peastman's avatar
peastman committed
1707
1708
1709
1710
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
        if 'ewaldErrorTolerance' in args:
            force.setEwaldErrorTolerance(args['ewaldErrorTolerance'])
1711
1712
        if 'useDispersionCorrection' in args:
            force.setUseDispersionCorrection(bool(args['useDispersionCorrection']))
peastman's avatar
peastman committed
1713
        sys.addForce(force)
Justin MacCallum's avatar
Justin MacCallum committed
1714

peastman's avatar
peastman committed
1715
    def postprocessSystem(self, sys, data, args):
1716
        # Create exceptions based on bonds.
1717

1718
1719
1720
        bondIndices = []
        for bond in data.bonds:
            bondIndices.append((bond.atom1, bond.atom2))
1721
1722
1723

        # If a virtual site does *not* share exclusions with another atom, add a bond between it and its first parent atom.

1724
1725
        for i in range(sys.getNumParticles()):
            if sys.isVirtualSite(i):
1726
1727
1728
                (site, atoms, excludeWith) = data.virtualSites[data.atoms[i]]
                if excludeWith is None:
                    bondIndices.append((i, site.getParticle(0)))
1729

1730
1731
        # Certain particles, such as lone pairs and Drude particles, share exclusions with a parent atom.
        # If the parent atom does not interact with an atom, the child particle does not either.
1732

1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
        for atom1, atom2 in bondIndices:
            for child1 in data.excludeAtomWith[atom1]:
                bondIndices.append((child1, atom2))
                for child2 in data.excludeAtomWith[atom2]:
                    bondIndices.append((child1, child2))
            for child2 in data.excludeAtomWith[atom2]:
                bondIndices.append((atom1, child2))

        # Create the exceptions.

peastman's avatar
peastman committed
1743
        nonbonded = [f for f in sys.getForces() if isinstance(f, mm.NonbondedForce)][0]
Justin MacCallum's avatar
Justin MacCallum committed
1744
        nonbonded.createExceptionsFromBonds(bondIndices, self.coulomb14scale, self.lj14scale)
1745
1746
1747

parsers["NonbondedForce"] = NonbondedGenerator.parseElement

ChayaSt's avatar
ChayaSt committed
1748
class LennardJonesGenerator(object):
ChayaSt's avatar
ChayaSt committed
1749
1750
    """A NBFix generator to construct the L-J force with NBFIX implemented as a lookup table"""

ChayaSt's avatar
ChayaSt committed
1751
    def __init__(self, forcefield, lj14scale):
ChayaSt's avatar
ChayaSt committed
1752
        self.ff = forcefield
1753
        self.nbfix_types = {}
ChayaSt's avatar
ChayaSt committed
1754
1755
        self.lj14scale = lj14scale
        self.lj_types = ForceField._AtomTypeParameters(forcefield, 'LennardJonesForce', 'Atom', ('sigma', 'epsilon'))
ChayaSt's avatar
ChayaSt committed
1756

ChayaSt's avatar
ChayaSt committed
1757
    def registerNBFIX(self, parameters):
ChayaSt's avatar
ChayaSt committed
1758
1759
        types = self.ff._findAtomTypes(parameters, 2)
        if None not in types:
1760
1761
1762
1763
1764
1765
1766
            type1 = types[0][0]
            type2 = types[1][0]
            emin = _convertParameterToNumber(parameters['emin'])
            rmin = _convertParameterToNumber(parameters['rmin'])
            self.nbfix_types[(type1, type2)] = [emin, rmin]
            self.nbfix_types[(type2, type1)] = [emin, rmin]

ChayaSt's avatar
ChayaSt committed
1767
1768
1769
    def registerLennardJones(self, parameters):
        self.lj_types.registerAtom(parameters)

ChayaSt's avatar
ChayaSt committed
1770
1771
1772

    @staticmethod
    def parseElement(element, ff):
ChayaSt's avatar
ChayaSt committed
1773
        existing = [f for f in ff._forces if isinstance(f, LennardJonesGenerator)]
ChayaSt's avatar
ChayaSt committed
1774
        if len(existing) == 0:
ChayaSt's avatar
ChayaSt committed
1775
            generator = LennardJonesGenerator(ff, float(element.attrib['lj14scale']))
ChayaSt's avatar
ChayaSt committed
1776
1777
            ff.registerGenerator(generator)
        else:
ChayaSt's avatar
ChayaSt committed
1778
            # Multiple <LennardJonesForce> tags were found, probably in different files
ChayaSt's avatar
ChayaSt committed
1779
1780
            generator = existing[0]

ChayaSt's avatar
ChayaSt committed
1781
1782
        for LJ in element.findall('Atom'):
            generator.registerLennardJones(LJ.attrib)
ChayaSt's avatar
ChayaSt committed
1783
        for Nbfix in element.findall('NBFixPair'):
ChayaSt's avatar
ChayaSt committed
1784
            generator.registerNBFIX(Nbfix.attrib)
ChayaSt's avatar
ChayaSt committed
1785

ChayaSt's avatar
ChayaSt committed
1786
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
1787

ChayaSt's avatar
cleanup  
ChayaSt committed
1788
        # Ewald and PME will be interpreted as CutoffPeriodic for the CustomNonbondedForce
ChayaSt's avatar
ChayaSt committed
1789

ChayaSt's avatar
ChayaSt committed
1790
        # We need a CustomNonbondedForce to implement the NBFIX functionality.
ChayaSt's avatar
cleanup  
ChayaSt committed
1791
        nbfix_type_set = set().union(*self.nbfix_types)
ChayaSt's avatar
ChayaSt committed
1792
        # First derive the lookup tables
ChayaSt's avatar
cleanup  
ChayaSt committed
1793
1794
        lj_indx_list = [None for atom in data.atoms]
        num_lj_types = 0
ChayaSt's avatar
ChayaSt committed
1795
        lj_type_list = []
1796
        type_map = {}
ChayaSt's avatar
ChayaSt committed
1797
        for i, atom in enumerate(data.atoms):
ChayaSt's avatar
ChayaSt committed
1798
            atype = data.atomType[atom]
ChayaSt's avatar
cleanup  
ChayaSt committed
1799
1800
1801
            values = (self.lj_types.paramsForType[atype]['sigma'], self.lj_types.paramsForType[atype]['epsilon'])
            if lj_indx_list[i] is not None: continue # ljtype has been assigned an index
            if values in type_map and atype not in nbfix_type_set:
1802
                # only non NBFIX types can be compressed
ChayaSt's avatar
cleanup  
ChayaSt committed
1803
                lj_indx_list[i] = type_map[values]
1804
            else:
ChayaSt's avatar
cleanup  
ChayaSt committed
1805
1806
1807
                type_map[values] = num_lj_types
                lj_indx_list[i] = num_lj_types
                num_lj_types += 1
1808
                lj_type_list.append(atype)
ChayaSt's avatar
cleanup  
ChayaSt committed
1809
1810
1811
        reverse_map = [0 for type_values in range(len(type_map))]
        for type_value in type_map:
            reverse_map[type_map[type_value]] = type_value
1812

ChayaSt's avatar
ChayaSt committed
1813
1814
1815
        # Now everything is assigned. Create the A- and B-coefficient arrays
        acoef = [0 for i in range(num_lj_types*num_lj_types)]
        bcoef = acoef[:]
ChayaSt's avatar
ChayaSt committed
1816
1817
        for m in range(num_lj_types):
            for n in range(num_lj_types):
1818
                pair = (lj_type_list[m], lj_type_list[n])
ChayaSt's avatar
cleanup  
ChayaSt committed
1819
1820
1821
1822
1823
1824
1825
                if pair in self.nbfix_types:
                    wdij = self.nbfix_types[pair][0]
                    rij = self.nbfix_types[pair][1]
                    rij6 = rij**6
                    acoef[m+num_lj_types*n] = math.sqrt(wdij) * rij6
                    bcoef[m+num_lj_types*n] = 2 * wdij * rij6
                    continue
ChayaSt's avatar
ChayaSt committed
1826
                else:
ChayaSt's avatar
cleanup  
ChayaSt committed
1827
                    rij = (reverse_map[m][0] + reverse_map[n][0]) * 2**(1.0/6) / 2
ChayaSt's avatar
ChayaSt committed
1828
                    rij6 = rij**6
ChayaSt's avatar
cleanup  
ChayaSt committed
1829
                    wdij = math.sqrt(reverse_map[m][-1] * reverse_map[n][-1])
ChayaSt's avatar
ChayaSt committed
1830
1831
                    acoef[m+num_lj_types*n] = math.sqrt(wdij) * rij6
                    bcoef[m+num_lj_types*n] = 2 * wdij * rij6
ChayaSt's avatar
cleanup  
ChayaSt committed
1832
1833
1834

        self.force = mm.CustomNonbondedForce('a^2/r^12-b/r6; r6=r2*r2*r2; r2=r^2; '
                                'a=acoef(type1, type2);'
ChayaSt's avatar
ChayaSt committed
1835
                                'b=bcoef(type1, type2)')
ChayaSt's avatar
ChayaSt committed
1836
        self.force.addTabulatedFunction('acoef',
ChayaSt's avatar
ChayaSt committed
1837
                mm.Discrete2DFunction(num_lj_types, num_lj_types, acoef))
ChayaSt's avatar
ChayaSt committed
1838
        self.force.addTabulatedFunction('bcoef',
ChayaSt's avatar
ChayaSt committed
1839
                mm.Discrete2DFunction(num_lj_types, num_lj_types, bcoef))
ChayaSt's avatar
ChayaSt committed
1840
        self.force.addPerParticleParameter('type')
ChayaSt's avatar
ChayaSt committed
1841
1842
        if (nonbondedMethod is PME or nonbondedMethod is Ewald or
                nonbondedMethod is CutoffPeriodic):
ChayaSt's avatar
ChayaSt committed
1843
            self.force.setNonbondedMethod(mm.CustomNonbondedForce.CutoffPeriodic)
ChayaSt's avatar
ChayaSt committed
1844
        elif nonbondedMethod is NoCutoff:
ChayaSt's avatar
ChayaSt committed
1845
            self.force.setNonbondedMethod(mm.CustomNonbondedForce.NoCutoff)
ChayaSt's avatar
ChayaSt committed
1846
        elif nonbondedMethod is CutoffNonPeriodic:
ChayaSt's avatar
ChayaSt committed
1847
            self.force.setNonbondedMethod(mm.CustomNonbondedForce.CutoffNonPeriodic)
ChayaSt's avatar
ChayaSt committed
1848
1849
1850
1851
1852
        else:
            raise AssertionError('Unrecognized nonbonded method [%s]' %
                                 nonbondedMethod)
        # Add the particles
        for i in lj_indx_list:
ChayaSt's avatar
cleanup  
ChayaSt committed
1853
            self.force.addParticle((i,))
ChayaSt's avatar
ChayaSt committed
1854
1855
1856
        self.force.setUseLongRangeCorrection(True)
        self.force.setCutoffDistance(nonbondedCutoff)

ChayaSt's avatar
ChayaSt committed
1857
1858
1859
1860
        sys.addForce(self.force)

    def postprocessSystem(self, sys, data, args):

ChayaSt's avatar
ChayaSt committed
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
        bondIndices = []
        for bond in data.bonds:
            bondIndices.append((bond.atom1, bond.atom2))

        # If a virtual site does *not* share exclusions with another atom, add a bond between it and its first parent
        # atom.
        for i in range(sys.getNumParticles()):
            if sys.isVirtualSite(i):
                (site, atoms, excludeWith) = data.virtualSites[data.atoms[i]]
                if excludeWith is None:
                    bondIndices.append((i, site.getParticle(0)))

        # Certain particles, such as lone pairs and Drude particles, share exclusions with a parent atom.
        # If the parent atom does not interact with an atom, the child particle does not either.

        for atom1, atom2 in bondIndices:
            for child1 in data.excludeAtomWith[atom1]:
                bondIndices.append((child1, atom2))
                for child2 in data.excludeAtomWith[atom2]:
                    bondIndices.append((child1, child2))
            for child2 in data.excludeAtomWith[atom2]:
                bondIndices.append((atom1, child2))

        # Create the exceptions.
ChayaSt's avatar
ChayaSt committed
1885
        self.force.createExclusionsFromBonds(bondIndices, 3)
ChayaSt's avatar
ChayaSt committed
1886

ChayaSt's avatar
ChayaSt committed
1887
parsers["LennardJonesForce"] = LennardJonesGenerator.parseElement
1888

1889
## @private
1890
class GBSAOBCGenerator(object):
1891
    """A GBSAOBCGenerator constructs a GBSAOBCForce."""
Justin MacCallum's avatar
Justin MacCallum committed
1892

1893
1894
    def __init__(self, forcefield):
        self.ff = forcefield
1895
        self.params = ForceField._AtomTypeParameters(forcefield, 'GBSAOBCForce', 'Atom', ('charge', 'radius', 'scale'))
1896

1897
    def registerAtom(self, parameters):
1898
        self.params.registerAtom(parameters)
1899

1900
1901
    @staticmethod
    def parseElement(element, ff):
1902
1903
        existing = [f for f in ff._forces if isinstance(f, GBSAOBCGenerator)]
        if len(existing) == 0:
1904
1905
            generator = GBSAOBCGenerator(ff)
            ff.registerGenerator(generator)
1906
1907
1908
        else:
            # Multiple <GBSAOBCForce> tags were found, probably in different files.  Simply add more types to the existing one.
            generator = existing[0]
1909
        generator.params.parseDefinitions(element)
Justin MacCallum's avatar
Justin MacCallum committed
1910

1911
1912
1913
1914
1915
    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:
Justin MacCallum's avatar
Justin MacCallum committed
1916
            raise ValueError('Illegal nonbonded method for GBSAOBCForce')
1917
1918
        force = mm.GBSAOBCForce()
        for atom in data.atoms:
1919
1920
            values = self.params.getAtomParameters(atom, data)
            force.addParticle(values[0], values[1], values[2])
1921
1922
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
1923
1924
1925
1926
        if 'soluteDielectric' in args:
            force.setSoluteDielectric(float(args['soluteDielectric']))
        if 'solventDielectric' in args:
            force.setSolventDielectric(float(args['solventDielectric']))
1927
1928
        sys.addForce(force)

1929
1930
    def postprocessSystem(self, sys, data, args):
        # Disable the reaction field approximation, since it produces bad results when combined with GB.
Justin MacCallum's avatar
Justin MacCallum committed
1931

1932
1933
1934
1935
        for force in sys.getForces():
            if isinstance(force, mm.NonbondedForce):
                force.setReactionFieldDielectric(1.0)

1936
1937
1938
parsers["GBSAOBCForce"] = GBSAOBCGenerator.parseElement


1939
## @private
1940
class CustomBondGenerator(object):
1941
    """A CustomBondGenerator constructs a CustomBondForce."""
Justin MacCallum's avatar
Justin MacCallum committed
1942

1943
1944
    def __init__(self, forcefield):
        self.ff = forcefield
1945
1946
1947
1948
1949
        self.types1 = []
        self.types2 = []
        self.globalParams = {}
        self.perBondParams = []
        self.paramValues = []
Justin MacCallum's avatar
Justin MacCallum committed
1950

1951
1952
    @staticmethod
    def parseElement(element, ff):
1953
1954
        generator = CustomBondGenerator(ff)
        ff.registerGenerator(generator)
1955
1956
1957
1958
1959
1960
        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'):
1961
            types = ff._findAtomTypes(bond.attrib, 2)
peastman's avatar
peastman committed
1962
            if None not in types:
1963
1964
1965
                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.paramValues.append([float(bond.attrib[param]) for param in generator.perBondParams])
Justin MacCallum's avatar
Justin MacCallum committed
1966

1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
    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


1987
## @private
1988
class CustomAngleGenerator(object):
1989
    """A CustomAngleGenerator constructs a CustomAngleForce."""
Justin MacCallum's avatar
Justin MacCallum committed
1990

1991
1992
    def __init__(self, forcefield):
        self.ff = forcefield
1993
1994
1995
1996
1997
1998
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.globalParams = {}
        self.perAngleParams = []
        self.paramValues = []
Justin MacCallum's avatar
Justin MacCallum committed
1999

2000
2001
    @staticmethod
    def parseElement(element, ff):
2002
2003
        generator = CustomAngleGenerator(ff)
        ff.registerGenerator(generator)
2004
2005
2006
2007
2008
2009
        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'):
2010
            types = ff._findAtomTypes(angle.attrib, 3)
peastman's avatar
peastman committed
2011
            if None not in types:
2012
2013
2014
2015
                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])
Justin MacCallum's avatar
Justin MacCallum committed
2016

2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
    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


2039
## @private
2040
class CustomTorsion(object):
2041
2042
2043
2044
2045
2046
2047
2048
2049
    """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

2050
## @private
2051
class CustomTorsionGenerator(object):
2052
    """A CustomTorsionGenerator constructs a CustomTorsionForce."""
Justin MacCallum's avatar
Justin MacCallum committed
2053

2054
2055
    def __init__(self, forcefield):
        self.ff = forcefield
2056
2057
2058
2059
        self.proper = []
        self.improper = []
        self.globalParams = {}
        self.perTorsionParams = []
Justin MacCallum's avatar
Justin MacCallum committed
2060

2061
2062
    @staticmethod
    def parseElement(element, ff):
2063
2064
        generator = CustomTorsionGenerator(ff)
        ff.registerGenerator(generator)
2065
2066
2067
2068
2069
2070
        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'):
2071
            types = ff._findAtomTypes(torsion.attrib, 4)
peastman's avatar
peastman committed
2072
            if None not in types:
2073
2074
                generator.proper.append(CustomTorsion(types, [float(torsion.attrib[param]) for param in generator.perTorsionParams]))
        for torsion in element.findall('Improper'):
2075
            types = ff._findAtomTypes(torsion.attrib, 4)
peastman's avatar
peastman committed
2076
            if None not in types:
2077
                generator.improper.append(CustomTorsion(types, [float(torsion.attrib[param]) for param in generator.perTorsionParams]))
Justin MacCallum's avatar
Justin MacCallum committed
2078

2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
    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]]]
2111
            match = None
2112
2113
2114
2115
2116
            for tordef in self.improper:
                types1 = tordef.types1
                types2 = tordef.types2
                types3 = tordef.types3
                types4 = tordef.types4
2117
2118
2119
2120
                hasWildcard = (wildcard in (types1, types2, types3, types4))
                if match is not None and hasWildcard:
                    # Prefer specific definitions over ones with wildcards
                    continue
2121
2122
2123
                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:
2124
                            if hasWildcard:
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
                                # Workaround to be more consistent with AMBER.  It uses wildcards to define most of its
                                # impropers, which leaves the ordering ambiguous.  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)
2136
                                match = (a1, a2, torsion[0], torsion[t4[1]], tordef)
2137
2138
                            else:
                                # There are no wildcards, so the order is unambiguous.
2139
                                match = (torsion[0], torsion[t2[1]], torsion[t3[1]], torsion[t4[1]], tordef)
2140
                            break
2141
2142
2143
            if match is not None:
                (a1, a2, a3, a4, tordef) = match
                force.addTorsion(a1, a2, a3, a4, tordef.paramValues)
2144
2145
2146
2147

parsers["CustomTorsionForce"] = CustomTorsionGenerator.parseElement


2148
## @private
2149
class CustomNonbondedGenerator(object):
2150
2151
    """A CustomNonbondedGenerator constructs a CustomNonbondedForce."""

2152
2153
    def __init__(self, forcefield, energy, bondCutoff):
        self.ff = forcefield
2154
2155
2156
2157
2158
2159
2160
2161
        self.energy = energy
        self.bondCutoff = bondCutoff
        self.globalParams = {}
        self.perParticleParams = []
        self.functions = []

    @staticmethod
    def parseElement(element, ff):
2162
2163
        generator = CustomNonbondedGenerator(ff, element.attrib['energy'], int(element.attrib['bondCutoff']))
        ff.registerGenerator(generator)
2164
2165
2166
2167
        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'])
2168
2169
        generator.params = ForceField._AtomTypeParameters(ff, 'CustomNonbondedForce', 'Atom', generator.perParticleParams)
        generator.params.parseDefinitions(element)
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195

    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        methodMap = {NoCutoff:mm.CustomNonbondedForce.NoCutoff,
                     CutoffNonPeriodic:mm.CustomNonbondedForce.CutoffNonPeriodic,
                     CutoffPeriodic:mm.CustomNonbondedForce.CutoffPeriodic}
        if nonbondedMethod not in methodMap:
            raise ValueError('Illegal nonbonded method for CustomNonbondedForce')
        force = mm.CustomNonbondedForce(self.energy)
        for param in self.globalParams:
            force.addGlobalParameter(param, self.globalParams[param])
        for param in self.perParticleParams:
            force.addPerParticleParameter(param)
        for (name, type, values, params) in self.functions:
            if type == 'Continuous1D':
                force.addTabulatedFunction(name, mm.Continuous1DFunction(values, params['min'], params['max']))
            elif type == 'Continuous2D':
                force.addTabulatedFunction(name, mm.Continuous2DFunction(params['xsize'], params['ysize'], values, params['xmin'], params['xmax'], params['ymin'], params['ymax']))
            elif type == 'Continuous3D':
                force.addTabulatedFunction(name, mm.Continuous2DFunction(params['xsize'], params['ysize'], params['zsize'], values, params['xmin'], params['xmax'], params['ymin'], params['ymax'], params['zmin'], params['zmax']))
            elif type == 'Discrete1D':
                force.addTabulatedFunction(name, mm.Discrete1DFunction(values))
            elif type == 'Discrete2D':
                force.addTabulatedFunction(name, mm.Discrete2DFunction(params['xsize'], params['ysize'], values))
            elif type == 'Discrete3D':
                force.addTabulatedFunction(name, mm.Discrete2DFunction(params['xsize'], params['ysize'], params['zsize'], values))
        for atom in data.atoms:
2196
2197
            values = self.params.getAtomParameters(atom, data)
            force.addParticle(values)
2198
2199
2200
2201
2202
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
        sys.addForce(force)

    def postprocessSystem(self, sys, data, args):
2203
        # Create exclusions based on bonds.
2204

2205
2206
2207
        bondIndices = []
        for bond in data.bonds:
            bondIndices.append((bond.atom1, bond.atom2))
2208
2209
2210

        # If a virtual site does *not* share exclusions with another atom, add a bond between it and its first parent atom.

2211
2212
        for i in range(sys.getNumParticles()):
            if sys.isVirtualSite(i):
2213
2214
2215
                (site, atoms, excludeWith) = data.virtualSites[data.atoms[i]]
                if excludeWith is None:
                    bondIndices.append((i, site.getParticle(0)))
2216

2217
2218
        # Certain particles, such as lone pairs and Drude particles, share exclusions with a parent atom.
        # If the parent atom does not interact with an atom, the child particle does not either.
2219

2220
2221
2222
2223
2224
2225
2226
2227
2228
        for atom1, atom2 in bondIndices:
            for child1 in data.excludeAtomWith[atom1]:
                bondIndices.append((child1, atom2))
                for child2 in data.excludeAtomWith[atom2]:
                    bondIndices.append((child1, child2))
            for child2 in data.excludeAtomWith[atom2]:
                bondIndices.append((atom1, child2))

        # Create the exclusions.
2229

2230
2231
2232
2233
2234
2235
        nonbonded = [f for f in sys.getForces() if isinstance(f, mm.CustomNonbondedForce)][0]
        nonbonded.createExclusionsFromBonds(bondIndices, self.bondCutoff)

parsers["CustomNonbondedForce"] = CustomNonbondedGenerator.parseElement


2236
## @private
2237
class CustomGBGenerator(object):
2238
    """A CustomGBGenerator constructs a CustomGBForce."""
Justin MacCallum's avatar
Justin MacCallum committed
2239

2240
2241
    def __init__(self, forcefield):
        self.ff = forcefield
2242
2243
2244
2245
2246
2247
2248
2249
        self.globalParams = {}
        self.perParticleParams = []
        self.computedValues = []
        self.energyTerms = []
        self.functions = []

    @staticmethod
    def parseElement(element, ff):
2250
2251
        generator = CustomGBGenerator(ff)
        ff.registerGenerator(generator)
2252
2253
2254
2255
        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'])
2256
2257
        generator.params = ForceField._AtomTypeParameters(ff, 'CustomGBForce', 'Atom', generator.perParticleParams)
        generator.params.parseDefinitions(element)
2258
2259
2260
2261
2262
2263
2264
2265
2266
        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()]
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
            if 'type' in function.attrib:
                type = function.attrib['type']
            else:
                type = 'Continuous1D'
            params = {}
            for key in function.attrib:
                if key.endswith('size'):
                    params[key] = int(function.attrib[key])
                elif key.endswith('min') or key.endswith('max'):
                    params[key] = float(function.attrib[key])
            generator.functions.append((function.attrib['name'], type, values, params))
Justin MacCallum's avatar
Justin MacCallum committed
2278

2279
2280
2281
2282
2283
    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:
Justin MacCallum's avatar
Justin MacCallum committed
2284
            raise ValueError('Illegal nonbonded method for CustomGBForce')
2285
2286
2287
2288
2289
2290
2291
2292
2293
        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])
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
        for (name, type, values, params) in self.functions:
            if type == 'Continuous1D':
                force.addTabulatedFunction(name, mm.Continuous1DFunction(values, params['min'], params['max']))
            elif type == 'Continuous2D':
                force.addTabulatedFunction(name, mm.Continuous2DFunction(params['xsize'], params['ysize'], values, params['xmin'], params['xmax'], params['ymin'], params['ymax']))
            elif type == 'Continuous3D':
                force.addTabulatedFunction(name, mm.Continuous2DFunction(params['xsize'], params['ysize'], params['zsize'], values, params['xmin'], params['xmax'], params['ymin'], params['ymax'], params['zmin'], params['zmax']))
            elif type == 'Discrete1D':
                force.addTabulatedFunction(name, mm.Discrete1DFunction(values))
            elif type == 'Discrete2D':
                force.addTabulatedFunction(name, mm.Discrete2DFunction(params['xsize'], params['ysize'], values))
            elif type == 'Discrete3D':
                force.addTabulatedFunction(name, mm.Discrete2DFunction(params['xsize'], params['ysize'], params['zsize'], values))
2307
        for atom in data.atoms:
2308
2309
            values = self.params.getAtomParameters(atom, data)
            force.addParticle(values)
2310
2311
2312
2313
2314
2315
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
        sys.addForce(force)

parsers["CustomGBForce"] = CustomGBGenerator.parseElement

2316
2317

## @private
2318
class CustomManyParticleGenerator(object):
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
    """A CustomManyParticleGenerator constructs a CustomManyParticleForce."""

    def __init__(self, forcefield, particlesPerSet, energy, permutationMode, bondCutoff):
        self.ff = forcefield
        self.particlesPerSet = particlesPerSet
        self.energy = energy
        self.permutationMode = permutationMode
        self.bondCutoff = bondCutoff
        self.globalParams = {}
        self.perParticleParams = []
        self.functions = []
        self.typeFilters = []
2331

2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
    @staticmethod
    def parseElement(element, ff):
        permutationMap = {"SinglePermutation" : mm.CustomManyParticleForce.SinglePermutation,
                          "UniqueCentralParticle" : mm.CustomManyParticleForce.UniqueCentralParticle}
        generator = CustomManyParticleGenerator(ff, int(element.attrib['particlesPerSet']), element.attrib['energy'], permutationMap[element.attrib['permutationMode']], int(element.attrib['bondCutoff']))
        ff.registerGenerator(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 param in element.findall('TypeFilter'):
            generator.typeFilters.append((int(param.attrib['index']), [int(x) for x in param.attrib['types'].split(',')]))
2344
2345
        generator.params = ForceField._AtomTypeParameters(ff, 'CustomManyParticleForce', 'Atom', generator.perParticleParams)
        generator.params.parseDefinitions(element)
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374

    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        methodMap = {NoCutoff:mm.CustomManyParticleForce.NoCutoff,
                     CutoffNonPeriodic:mm.CustomManyParticleForce.CutoffNonPeriodic,
                     CutoffPeriodic:mm.CustomManyParticleForce.CutoffPeriodic}
        if nonbondedMethod not in methodMap:
            raise ValueError('Illegal nonbonded method for CustomManyParticleForce')
        force = mm.CustomManyParticleForce(self.particlesPerSet, self.energy)
        force.setPermutationMode(self.permutationMode)
        for param in self.globalParams:
            force.addGlobalParameter(param, self.globalParams[param])
        for param in self.perParticleParams:
            force.addPerParticleParameter(param)
        for index, types in self.typeFilters:
            force.setTypeFilter(index, types)
        for (name, type, values, params) in self.functions:
            if type == 'Continuous1D':
                force.addTabulatedFunction(name, mm.Continuous1DFunction(values, params['min'], params['max']))
            elif type == 'Continuous2D':
                force.addTabulatedFunction(name, mm.Continuous2DFunction(params['xsize'], params['ysize'], values, params['xmin'], params['xmax'], params['ymin'], params['ymax']))
            elif type == 'Continuous3D':
                force.addTabulatedFunction(name, mm.Continuous2DFunction(params['xsize'], params['ysize'], params['zsize'], values, params['xmin'], params['xmax'], params['ymin'], params['ymax'], params['zmin'], params['zmax']))
            elif type == 'Discrete1D':
                force.addTabulatedFunction(name, mm.Discrete1DFunction(values))
            elif type == 'Discrete2D':
                force.addTabulatedFunction(name, mm.Discrete2DFunction(params['xsize'], params['ysize'], values))
            elif type == 'Discrete3D':
                force.addTabulatedFunction(name, mm.Discrete2DFunction(params['xsize'], params['ysize'], params['zsize'], values))
        for atom in data.atoms:
2375
2376
2377
            values = self.params.getAtomParameters(atom, data)
            type = int(self.params.getExtraParameters(atom, data)['filterType'])
            force.addParticle(values, type)
2378
2379
2380
2381
2382
2383
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
        sys.addForce(force)

    def postprocessSystem(self, sys, data, args):
        # Create exclusions based on bonds.
2384

2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
        bondIndices = []
        for bond in data.bonds:
            bondIndices.append((bond.atom1, bond.atom2))

        # If a virtual site does *not* share exclusions with another atom, add a bond between it and its first parent atom.

        for i in range(sys.getNumParticles()):
            if sys.isVirtualSite(i):
                (site, atoms, excludeWith) = data.virtualSites[data.atoms[i]]
                if excludeWith is None:
                    bondIndices.append((i, site.getParticle(0)))
2396

2397
2398
        # Certain particles, such as lone pairs and Drude particles, share exclusions with a parent atom.
        # If the parent atom does not interact with an atom, the child particle does not either.
2399

2400
2401
2402
2403
2404
2405
2406
2407
2408
        for atom1, atom2 in bondIndices:
            for child1 in data.excludeAtomWith[atom1]:
                bondIndices.append((child1, atom2))
                for child2 in data.excludeAtomWith[atom2]:
                    bondIndices.append((child1, child2))
            for child2 in data.excludeAtomWith[atom2]:
                bondIndices.append((atom1, child2))

        # Create the exclusions.
2409

2410
2411
2412
2413
2414
        nonbonded = [f for f in sys.getForces() if isinstance(f, mm.CustomManyParticleForce)][0]
        nonbonded.createExclusionsFromBonds(bondIndices, self.bondCutoff)

parsers["CustomManyParticleForce"] = CustomManyParticleGenerator.parseElement

Peter Eastman's avatar
Peter Eastman committed
2415
def getAtomPrint(data, atomIndex):
2416

Peter Eastman's avatar
Peter Eastman committed
2417
2418
2419
    if (atomIndex < len(data.atoms)):
        atom = data.atoms[atomIndex]
        returnString = "%4s %4s %5d" % (atom.name, atom.residue.name, atom.residue.index)
2420
    else:
Peter Eastman's avatar
Peter Eastman committed
2421
        returnString = "NA"
2422
2423
2424
2425
2426

    return returnString

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

Peter Eastman's avatar
Peter Eastman committed
2427
def countConstraint(data):
2428

Peter Eastman's avatar
Peter Eastman committed
2429
    bondCount = 0
2430
2431
2432
2433
2434
2435
2436
    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
2437
        if (isConstrained):
2438
            angleCount += 1
Justin MacCallum's avatar
Justin MacCallum committed
2439

2440
    print("Constraints bond=%d angle=%d  total=%d" % (bondCount, angleCount, (bondCount+angleCount)))
2441

2442
## @private
2443
class AmoebaBondGenerator(object):
2444
2445
2446

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

2447
    """An AmoebaBondGenerator constructs a AmoebaBondForce."""
2448
2449

    #=============================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
2450

2451
2452
    def __init__(self, cubic, quartic):

Peter Eastman's avatar
Peter Eastman committed
2453
2454
2455
2456
2457
2458
        self.cubic = cubic
        self.quartic = quartic
        self.types1 = []
        self.types2 = []
        self.length = []
        self.k = []
Justin MacCallum's avatar
Justin MacCallum committed
2459

2460
2461
2462
2463
2464
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

2465
        # <AmoebaBondForce bond-cubic="-25.5" bond-quartic="379.3125">
2466
        # <Bond class1="1" class2="2" length="0.1437" k="156900.0"/>
Justin MacCallum's avatar
Justin MacCallum committed
2467

2468
        generator = AmoebaBondGenerator(float(element.attrib['bond-cubic']), float(element.attrib['bond-quartic']))
2469
2470
        forceField._forces.append(generator)
        for bond in element.findall('Bond'):
2471
            types = forceField._findAtomTypes(bond.attrib, 2)
peastman's avatar
peastman committed
2472
            if None not in types:
2473
2474
2475
2476
2477
                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:
2478
                outputString = "AmoebaBondGenerator: error getting types: %s %s" % (
2479
                                    bond.attrib['class1'],
Peter Eastman's avatar
Peter Eastman committed
2480
                                    bond.attrib['class2'])
Justin MacCallum's avatar
Justin MacCallum committed
2481
2482
                raise ValueError(outputString)

2483
2484
    #=============================================================================================

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

Mark Friedrichs's avatar
Mark Friedrichs committed
2487
        #countConstraint(data)
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2488

Peter Eastman's avatar
Peter Eastman committed
2489
        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
2490
        existing = [f for f in existing if type(f) == mm.AmoebaBondForce]
2491
        if len(existing) == 0:
2492
            force = mm.AmoebaBondForce()
2493
2494
2495
2496
            sys.addForce(force)
        else:
            force = existing[0]

2497
2498
        force.setAmoebaGlobalBondCubic(self.cubic)
        force.setAmoebaGlobalBondQuartic(self.quartic)
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508

        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:
2509
                        data.addConstraint(sys, bond.atom1, bond.atom2, self.length[i])
2510
2511
2512
2513
                    elif self.k[i] != 0:
                        force.addBond(bond.atom1, bond.atom2, self.length[i], self.k[i])
                    break

2514
parsers["AmoebaBondForce"] = AmoebaBondGenerator.parseElement
2515
2516
2517
2518

#=============================================================================================
# Add angle constraint
#=============================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
2519

Peter Eastman's avatar
Peter Eastman committed
2520
def addAngleConstraint(angle, idealAngle, data, sys):
2521
2522

    # Find the two bonds that make this angle.
Justin MacCallum's avatar
Justin MacCallum committed
2523

Peter Eastman's avatar
Peter Eastman committed
2524
2525
    bond1 = None
    bond2 = None
2526
2527
2528
2529
2530
2531
2532
    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
Justin MacCallum's avatar
Justin MacCallum committed
2533

2534
        # Compute the distance between atoms and add a constraint
Justin MacCallum's avatar
Justin MacCallum committed
2535

2536
2537
2538
2539
        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
2540
                length = sqrt(l1*l1 + l2*l2 - 2*l1*l2*cos(idealAngle))
2541
                data.addConstraint(sys, angle[0], angle[2], length)
2542
2543
2544
                return

#=============================================================================================
2545
## @private
2546
class AmoebaAngleGenerator(object):
2547
2548

    #=============================================================================================
2549
    """An AmoebaAngleGenerator constructs a AmoebaAngleForce."""
2550
    #=============================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
2551

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

Peter Eastman's avatar
Peter Eastman committed
2554
2555
2556
2557
2558
        self.forceField = forceField
        self.cubic = cubic
        self.quartic = quartic
        self.pentic = pentic
        self.sextic = sextic
2559

Peter Eastman's avatar
Peter Eastman committed
2560
2561
2562
        self.types1 = []
        self.types2 = []
        self.types3 = []
2563

Peter Eastman's avatar
Peter Eastman committed
2564
2565
        self.angle = []
        self.k = []
Justin MacCallum's avatar
Justin MacCallum committed
2566

2567
2568
2569
2570
2571
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

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

2575
        generator = AmoebaAngleGenerator(forceField, float(element.attrib['angle-cubic']), float(element.attrib['angle-quartic']),  float(element.attrib['angle-pentic']), float(element.attrib['angle-sextic']))
2576
2577
        forceField._forces.append(generator)
        for angle in element.findall('Angle'):
2578
            types = forceField._findAtomTypes(angle.attrib, 3)
peastman's avatar
peastman committed
2579
            if None not in types:
2580
2581
2582
2583
2584
2585

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

                angleList = []
Peter Eastman's avatar
Peter Eastman committed
2586
                angleList.append(float(angle.attrib['angle1']))
2587
2588

                try:
Peter Eastman's avatar
Peter Eastman committed
2589
                    angleList.append(float(angle.attrib['angle2']))
2590
                    try:
Peter Eastman's avatar
Peter Eastman committed
2591
                        angleList.append(float(angle.attrib['angle3']))
2592
2593
2594
2595
2596
2597
2598
                    except:
                        pass
                except:
                    pass
                generator.angle.append(angleList)
                generator.k.append(float(angle.attrib['k']))
            else:
2599
                outputString = "AmoebaAngleGenerator: error getting types: %s %s %s" % (
2600
2601
                                    angle.attrib['class1'],
                                    angle.attrib['class2'],
Peter Eastman's avatar
Peter Eastman committed
2602
                                    angle.attrib['class3'])
Justin MacCallum's avatar
Justin MacCallum committed
2603
2604
                raise ValueError(outputString)

2605
2606
2607
2608
    #=============================================================================================
    # createForce is bypassed here since the AmoebaOutOfPlaneBendForce generator must first execute
    # and partition angles into in-plane and non-in-plane angles
    #=============================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
2609

Peter Eastman's avatar
Peter Eastman committed
2610
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
2611
2612
2613
2614
2615
2616
        pass

    #=============================================================================================
    # createForcePostOpBendAngle is called by AmoebaOutOfPlaneBendForce with the list of
    # non-in-plane angles
    #=============================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
2617

Peter Eastman's avatar
Peter Eastman committed
2618
    def createForcePostOpBendAngle(self, sys, data, nonbondedMethod, nonbondedCutoff, angleList, args):
2619
2620
2621
2622

        # get force

        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
2623
        existing = [f for f in existing if type(f) == mm.AmoebaAngleForce]
2624
2625

        if len(existing) == 0:
2626
            force = mm.AmoebaAngleForce()
2627
2628
2629
2630
            sys.addForce(force)
        else:
            force = existing[0]

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2631
        # set scalars
2632

2633
2634
2635
2636
        force.setAmoebaGlobalAngleCubic(self.cubic)
        force.setAmoebaGlobalAngleQuartic(self.quartic)
        force.setAmoebaGlobalAnglePentic(self.pentic)
        force.setAmoebaGlobalAngleSextic(self.sextic)
2637
2638

        for angleDict in angleList:
Peter Eastman's avatar
Peter Eastman committed
2639
2640
            angle = angleDict['angle']
            isConstrained = angleDict['isConstrained']
2641

Peter Eastman's avatar
Peter Eastman committed
2642
2643
2644
            type1 = data.atomType[data.atoms[angle[0]]]
            type2 = data.atomType[data.atoms[angle[1]]]
            type3 = data.atomType[data.atoms[angle[2]]]
2645
2646
2647
2648
2649
2650
2651
            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 and self.k[i] != 0.0:
                        angleDict['idealAngle'] = self.angle[i][0]
2652
                        addAngleConstraint(angle, self.angle[i][0]*math.pi/180.0, data, sys)
2653
                    elif self.k[i] != 0:
Peter Eastman's avatar
Peter Eastman committed
2654
2655
                        lenAngle = len(self.angle[i])
                        if (lenAngle > 1):
2656
2657
2658
2659
2660
2661
                            # 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
2662
                                if (atom1 == angle[1] and atom2 != angle[0] and atom2 != angle[2] and (sys.getParticleMass(atom2)/unit.dalton) < 1.90):
2663
                                    numberOfHydrogens += 1
Peter Eastman's avatar
Peter Eastman committed
2664
                                if (atom2 == angle[1] and atom1 != angle[0] and atom1 != angle[2] and (sys.getParticleMass(atom1)/unit.dalton) < 1.90):
2665
                                    numberOfHydrogens += 1
Peter Eastman's avatar
Peter Eastman committed
2666
                            if (numberOfHydrogens < lenAngle):
2667
2668
                                angleValue =  self.angle[i][numberOfHydrogens]
                            else:
2669
                                outputString = "AmoebaAngleGenerator angle index=%d is out of range: [0, %5d] " % (numberOfHydrogens, lenAngle)
Justin MacCallum's avatar
Justin MacCallum committed
2670
                                raise ValueError(outputString)
2671
2672
                        else:
                            angleValue =  self.angle[i][0]
Justin MacCallum's avatar
Justin MacCallum committed
2673

2674
                        angleDict['idealAngle'] = angleValue
Peter Eastman's avatar
Peter Eastman committed
2675
                        force.addAngle(angle[0], angle[1], angle[2], angleValue, self.k[i])
2676
2677
2678
2679
2680
2681
                    break

    #=============================================================================================
    # createForcePostOpBendInPlaneAngle is called by AmoebaOutOfPlaneBendForce with the list of
    # in-plane angles
    #=============================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
2682

Peter Eastman's avatar
Peter Eastman committed
2683
    def createForcePostOpBendInPlaneAngle(self, sys, data, nonbondedMethod, nonbondedCutoff, angleList, args):
2684
2685
2686
2687

        # get force

        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
2688
        existing = [f for f in existing if type(f) == mm.AmoebaInPlaneAngleForce]
2689
2690

        if len(existing) == 0:
2691
            force = mm.AmoebaInPlaneAngleForce()
2692
2693
2694
2695
2696
2697
            sys.addForce(force)
        else:
            force = existing[0]

        # scalars

2698
2699
2700
2701
        force.setAmoebaGlobalInPlaneAngleCubic(self.cubic)
        force.setAmoebaGlobalInPlaneAngleQuartic(self.quartic)
        force.setAmoebaGlobalInPlaneAnglePentic(self.pentic)
        force.setAmoebaGlobalInPlaneAngleSextic(self.sextic)
2702
2703

        for angleDict in angleList:
Justin MacCallum's avatar
Justin MacCallum committed
2704

Peter Eastman's avatar
Peter Eastman committed
2705
2706
            angle = angleDict['angle']
            isConstrained = angleDict['isConstrained']
2707

Peter Eastman's avatar
Peter Eastman committed
2708
2709
2710
            type1 = data.atomType[data.atoms[angle[0]]]
            type2 = data.atomType[data.atoms[angle[1]]]
            type3 = data.atomType[data.atoms[angle[2]]]
2711
2712
2713
2714
2715
2716
2717
2718
2719

            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):
                    angleDict['idealAngle'] = self.angle[i][0]
Peter Eastman's avatar
Peter Eastman committed
2720
                    if (isConstrained and self.k[i] != 0.0):
2721
                        addAngleConstraint(angle, self.angle[i][0]*math.pi/180.0, data, sys)
2722
2723
2724
2725
                    else:
                        force.addAngle(angle[0], angle[1], angle[2], angle[3], self.angle[i][0], self.k[i])
                    break

2726
parsers["AmoebaAngleForce"] = AmoebaAngleGenerator.parseElement
2727
2728
2729

#=============================================================================================
# Generator for the AmoebaOutOfPlaneBend covalent force; also calls methods in the
2730
2731
# AmoebaAngleGenerator to generate the AmoebaAngleForce and
# AmoebaInPlaneAngleForce
2732
2733
#=============================================================================================

2734
## @private
2735
class AmoebaOutOfPlaneBendGenerator(object):
2736
2737
2738
2739

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

    """An AmoebaOutOfPlaneBendGenerator constructs a AmoebaOutOfPlaneBendForce."""
Justin MacCallum's avatar
Justin MacCallum committed
2740

2741
2742
2743
2744
    #=============================================================================================

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

Peter Eastman's avatar
Peter Eastman committed
2745
2746
2747
2748
2749
2750
        self.forceField = forceField
        self.type = type
        self.cubic = cubic
        self.quartic = quartic
        self.pentic = pentic
        self.sextic = sextic
2751

Peter Eastman's avatar
Peter Eastman committed
2752
2753
2754
2755
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.types4 = []
2756

Peter Eastman's avatar
Peter Eastman committed
2757
        self.ks = []
2758
2759
2760
2761
2762

    #=============================================================================================
    # Local version of findAtomTypes needed since class indices are 0 (i.e., not recognized)
    # for types3 and 4
    #=============================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
2763

2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
    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"/>
Justin MacCallum's avatar
Justin MacCallum committed
2789

2790
2791
        # get global scalar parameters

Peter Eastman's avatar
Peter Eastman committed
2792
        generator = AmoebaOutOfPlaneBendGenerator(forceField, element.attrib['type'],
2793
2794
2795
                                                   float(element.attrib['opbend-cubic']),
                                                   float(element.attrib['opbend-quartic']),
                                                   float(element.attrib['opbend-pentic']),
Peter Eastman's avatar
Peter Eastman committed
2796
                                                   float(element.attrib['opbend-sextic']))
2797
2798
2799
2800

        forceField._forces.append(generator)

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

Peter Eastman's avatar
Peter Eastman committed
2804
2805
2806
2807
                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.types3.append(types[2])
                generator.types4.append(types[3])
2808

Peter Eastman's avatar
Peter Eastman committed
2809
                generator.ks.append(float(angle.attrib['k']))
2810
2811

            else:
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2812
2813
                outputString = "AmoebaOutOfPlaneBendGenerator error getting types: %s %s %s %s." % (
                               angle.attrib['class1'], angle.attrib['class2'], angle.attrib['class3'], angle.attrib['class4'])
Justin MacCallum's avatar
Justin MacCallum committed
2814
2815
                raise ValueError(outputString)

2816
2817
2818
2819
2820
2821
    #=============================================================================================
    # 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
    #=============================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
2822

Peter Eastman's avatar
Peter Eastman committed
2823
    def getMiddleAtom(self, angle, data):
2824
2825
2826

        # find atom shared by both bonds making up the angle

Peter Eastman's avatar
Peter Eastman committed
2827
        middleAtom = -1
Justin MacCallum's avatar
Justin MacCallum committed
2828
        for atomIndex in angle:
Peter Eastman's avatar
Peter Eastman committed
2829
            isMiddle = 0
2830
2831
2832
            for bond in data.atomBonds[atomIndex]:
                atom1 = data.bonds[bond].atom1
                atom2 = data.bonds[bond].atom2
Peter Eastman's avatar
Peter Eastman committed
2833
                if (atom1 != atomIndex):
2834
2835
2836
                    partner = atom1
                else:
                    partner = atom2
Justin MacCallum's avatar
Justin MacCallum committed
2837
                if (partner == angle[0] or partner == angle[1] or partner == angle[2]):
2838
2839
                    isMiddle += 1

Peter Eastman's avatar
Peter Eastman committed
2840
            if (isMiddle == 2):
2841
2842
2843
2844
2845
                return atomIndex
        return -1

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

Peter Eastman's avatar
Peter Eastman committed
2846
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859

        # 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
2860
2861
2862
2863
        force.setAmoebaGlobalOutOfPlaneBendCubic(  self.cubic)
        force.setAmoebaGlobalOutOfPlaneBendQuartic(self.quartic)
        force.setAmoebaGlobalOutOfPlaneBendPentic( self.pentic)
        force.setAmoebaGlobalOutOfPlaneBendSextic( self.sextic)
2864
2865
2866
2867

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

Peter Eastman's avatar
Peter Eastman committed
2868
        skipAtoms = dict()
2869
2870
2871
2872

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

Peter Eastman's avatar
Peter Eastman committed
2873
2874
        inPlaneAngles = []
        nonInPlaneAngles = []
2875
        nonInPlaneAnglesConstrained = []
Peter Eastman's avatar
Peter Eastman committed
2876
        idealAngles = []*len(data.angles)
2877
2878
2879

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

Peter Eastman's avatar
Peter Eastman committed
2880
2881
2882
            middleAtom = self.getMiddleAtom(angle, data)
            if (middleAtom > -1):
                middleType = data.atomType[data.atoms[middleAtom]]
2883
2884
                middleCovalency = len(data.atomBonds[middleAtom])
            else:
Peter Eastman's avatar
Peter Eastman committed
2885
                middleType = -1
2886
2887
                middleCovalency = -1

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

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

Peter Eastman's avatar
Peter Eastman committed
2896
2897
2898
2899
                partners = []
                partnerSet = set()
                partnerTypes = []
                partnerK = []
2900
2901
2902
2903

                for bond in data.atomBonds[middleAtom]:
                    atom1 = data.bonds[bond].atom1
                    atom2 = data.bonds[bond].atom2
Peter Eastman's avatar
Peter Eastman committed
2904
                    if (atom1 != middleAtom):
2905
2906
2907
2908
2909
2910
2911
2912
                        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
2913
2914
2915
2916
2917
                        if (middleType in types2 and partnerType in types1):
                            partners.append(partner)
                            partnerSet.add(partner)
                            partnerTypes.append(partnerType)
                            partnerK.append(self.ks[i])
Justin MacCallum's avatar
Justin MacCallum committed
2918

Peter Eastman's avatar
Peter Eastman committed
2919
                if (len(partners) == 3):
2920

Peter Eastman's avatar
Peter Eastman committed
2921
2922
2923
                    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])
2924

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

2927
                    skipAtoms[middleAtom] = set()
Peter Eastman's avatar
Peter Eastman committed
2928
2929
2930
2931
                    skipAtoms[middleAtom].add(partners[0])
                    skipAtoms[middleAtom].add(partners[1])
                    skipAtoms[middleAtom].add(partners[2])

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
2932
2933
                    # in-plane angle

Peter Eastman's avatar
Peter Eastman committed
2934
2935
2936
2937
2938
                    angleDict = {}
                    angleList = []
                    angleList.append(angle[0])
                    angleList.append(angle[1])
                    angleList.append(angle[2])
2939
2940
                    angleDict['angle'] = angleList

Peter Eastman's avatar
Peter Eastman committed
2941
                    angleDict['isConstrained'] = 0
2942

Peter Eastman's avatar
Peter Eastman committed
2943
2944
2945
2946
                    angleSet = set()
                    angleSet.add(angle[0])
                    angleSet.add(angle[1])
                    angleSet.add(angle[2])
2947
2948

                    for atomIndex in partnerSet:
Peter Eastman's avatar
Peter Eastman committed
2949
2950
                        if (atomIndex not in angleSet):
                            angleList.append(atomIndex)
2951

Peter Eastman's avatar
Peter Eastman committed
2952
                    inPlaneAngles.append(angleDict)
2953
2954

                else:
Peter Eastman's avatar
Peter Eastman committed
2955
2956
2957
2958
                    angleDict = {}
                    angleDict['angle'] = angle
                    angleDict['isConstrained'] = isConstrained
                    nonInPlaneAngles.append(angleDict)
2959
            else:
Peter Eastman's avatar
Peter Eastman committed
2960
                if (middleAtom > -1 and middleCovalency == 3 and middleAtom in skipAtoms):
2961

Peter Eastman's avatar
Peter Eastman committed
2962
                    partnerSet = skipAtoms[middleAtom]
Justin MacCallum's avatar
Justin MacCallum committed
2963

Peter Eastman's avatar
Peter Eastman committed
2964
                    angleDict = {}
2965

Peter Eastman's avatar
Peter Eastman committed
2966
2967
2968
2969
2970
                    angleList = []
                    angleList.append(angle[0])
                    angleList.append(angle[1])
                    angleList.append(angle[2])
                    angleDict['angle'] = angleList
2971

Peter Eastman's avatar
Peter Eastman committed
2972
                    angleDict['isConstrained'] = isConstrained
2973

Peter Eastman's avatar
Peter Eastman committed
2974
2975
2976
2977
                    angleSet = set()
                    angleSet.add(angle[0])
                    angleSet.add(angle[1])
                    angleSet.add(angle[2])
2978
2979

                    for atomIndex in partnerSet:
Peter Eastman's avatar
Peter Eastman committed
2980
2981
                        if (atomIndex not in angleSet):
                            angleList.append(atomIndex)
2982

Peter Eastman's avatar
Peter Eastman committed
2983
                    inPlaneAngles.append(angleDict)
2984
2985

                else:
Peter Eastman's avatar
Peter Eastman committed
2986
2987
                    angleDict = {}
                    angleDict['angle'] = angle
2988
                    angleDict['isConstrained'] = isConstrained
Peter Eastman's avatar
Peter Eastman committed
2989
                    nonInPlaneAngles.append(angleDict)
2990

2991
        # get AmoebaAngleGenerator and add AmoebaAngle and AmoebaInPlaneAngle forces
2992
2993

        for force in self.forceField._forces:
Justin MacCallum's avatar
Justin MacCallum committed
2994
            if (force.__class__.__name__ == 'AmoebaAngleGenerator'):
Peter Eastman's avatar
Peter Eastman committed
2995
2996
                force.createForcePostOpBendAngle(sys, data, nonbondedMethod, nonbondedCutoff, nonInPlaneAngles, args)
                force.createForcePostOpBendInPlaneAngle(sys, data, nonbondedMethod, nonbondedCutoff, inPlaneAngles, args)
2997
2998

        for force in self.forceField._forces:
Justin MacCallum's avatar
Justin MacCallum committed
2999
            if (force.__class__.__name__ == 'AmoebaStretchBendGenerator'):
3000
                for angleDict in inPlaneAngles:
Peter Eastman's avatar
Peter Eastman committed
3001
                    nonInPlaneAngles.append(angleDict)
3002
                force.createForcePostAmoebaBondForce(sys, data, nonbondedMethod, nonbondedCutoff, nonInPlaneAngles, args)
3003
3004
3005
3006
3007

parsers["AmoebaOutOfPlaneBendForce"] = AmoebaOutOfPlaneBendGenerator.parseElement

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

3008
## @private
3009
class AmoebaTorsionGenerator(object):
3010
3011
3012
3013
3014
3015
3016

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

    def __init__(self, torsionUnit):

Peter Eastman's avatar
Peter Eastman committed
3017
        self.torsionUnit = torsionUnit
3018

Peter Eastman's avatar
Peter Eastman committed
3019
3020
3021
3022
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.types4 = []
3023

Peter Eastman's avatar
Peter Eastman committed
3024
3025
3026
        self.t1 = []
        self.t2 = []
        self.t3 = []
Justin MacCallum's avatar
Justin MacCallum committed
3027

3028
3029
3030
3031
3032
3033
3034
3035
    #=============================================================================================

    @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" />
Justin MacCallum's avatar
Justin MacCallum committed
3036

Peter Eastman's avatar
Peter Eastman committed
3037
        generator = AmoebaTorsionGenerator(float(element.attrib['torsionUnit']))
3038
3039
3040
3041
3042
3043
        forceField._forces.append(generator)

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

        for torsion in element.findall('Torsion'):
3044
            types = forceField._findAtomTypes(torsion.attrib, 4)
peastman's avatar
peastman committed
3045
            if None not in types:
3046
3047
3048
3049
3050
3051
3052

                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
3053
3054
                    tInfo = []
                    suffix = str(ii)
3055
3056
3057
3058
3059
3060
                    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
3061
3062
3063
3064
3065
3066
                    if (ii == 1):
                        generator.t1.append(tInfo)
                    elif (ii == 2):
                        generator.t2.append(tInfo)
                    elif (ii == 3):
                        generator.t3.append(tInfo)
3067
3068
3069

            else:
                outputString = "AmoebaTorsionGenerator: error getting types: %s %s %s %s" % (
3070
3071
3072
3073
                                    torsion.attrib['class1'],
                                    torsion.attrib['class2'],
                                    torsion.attrib['class3'],
                                    torsion.attrib['class4'])
Justin MacCallum's avatar
Justin MacCallum committed
3074
3075
                raise ValueError(outputString)

3076
3077
3078
3079
3080
    #=============================================================================================

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

        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
3081
        existing = [f for f in existing if type(f) == mm.PeriodicTorsionForce]
3082
        if len(existing) == 0:
3083
            force = mm.PeriodicTorsionForce()
3084
3085
3086
            sys.addForce(force)
        else:
            force = existing[0]
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3087

3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
        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]]]

            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
3104
                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):
3105
3106
3107
3108
3109
3110
                    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])
3111
3112
3113
3114
3115
3116
                    break

parsers["AmoebaTorsionForce"] = AmoebaTorsionGenerator.parseElement

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

3117
## @private
3118
class AmoebaPiTorsionGenerator(object):
3119
3120
3121
3122
3123
3124

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

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

    #=============================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
3125

3126
    def __init__(self, piTorsionUnit):
Justin MacCallum's avatar
Justin MacCallum committed
3127
        self.piTorsionUnit = piTorsionUnit
Peter Eastman's avatar
Peter Eastman committed
3128
3129
3130
        self.types1 = []
        self.types2 = []
        self.k = []
Justin MacCallum's avatar
Justin MacCallum committed
3131

3132
3133
3134
3135
3136
3137
3138
3139
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

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

Peter Eastman's avatar
Peter Eastman committed
3140
        generator = AmoebaPiTorsionGenerator(float(element.attrib['piTorsionUnit']))
3141
3142
3143
        forceField._forces.append(generator)

        for piTorsion in element.findall('PiTorsion'):
3144
            types = forceField._findAtomTypes(piTorsion.attrib, 2)
peastman's avatar
peastman committed
3145
            if None not in types:
3146
3147
3148
3149
3150
3151
                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
3152
                                    piTorsion.attrib['class2'])
Justin MacCallum's avatar
Justin MacCallum committed
3153
3154
                raise ValueError(outputString)

3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
    #=============================================================================================

    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
Justin MacCallum's avatar
Justin MacCallum committed
3171

3172
3173
            atom1 = bond.atom1
            atom2 = bond.atom2
Justin MacCallum's avatar
Justin MacCallum committed
3174

3175
            if (len(data.atomBonds[atom1]) == 3 and len(data.atomBonds[atom2]) == 3):
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186

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

Justin MacCallum's avatar
Justin MacCallum committed
3187
3188
                       # piTorsionAtom1, piTorsionAtom2 are the atoms bonded to atom1, excluding atom2
                       # piTorsionAtom5, piTorsionAtom6 are the atoms bonded to atom2, excluding atom1
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200

                       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
3201
                           if (bondedAtom1 != atom1):
3202
3203
3204
                               b1 = bondedAtom1
                           else:
                               b1 = bondedAtom2
Peter Eastman's avatar
Peter Eastman committed
3205
3206
                           if (b1 != atom2):
                               if (piTorsionAtom1 == -1):
Justin MacCallum's avatar
Justin MacCallum committed
3207
                                   piTorsionAtom1 = b1
3208
3209
3210
3211
3212
3213
                               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
3214
                           if (bondedAtom1 != atom2):
3215
3216
3217
3218
                               b1 = bondedAtom1
                           else:
                               b1 = bondedAtom2

Peter Eastman's avatar
Peter Eastman committed
3219
3220
                           if (b1 != atom1):
                               if (piTorsionAtom5 == -1):
Justin MacCallum's avatar
Justin MacCallum committed
3221
                                   piTorsionAtom5 = b1
3222
3223
                               else:
                                   piTorsionAtom6 = b1
Justin MacCallum's avatar
Justin MacCallum committed
3224

Peter Eastman's avatar
Peter Eastman committed
3225
                       force.addPiTorsion(piTorsionAtom1, piTorsionAtom2, piTorsionAtom3, piTorsionAtom4, piTorsionAtom5, piTorsionAtom6, self.k[i])
3226
3227
3228
3229
3230

parsers["AmoebaPiTorsionForce"] = AmoebaPiTorsionGenerator.parseElement

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

3231
## @private
3232
class AmoebaTorsionTorsionGenerator(object):
3233
3234
3235
3236
3237

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

Peter Eastman's avatar
Peter Eastman committed
3238
    def __init__(self):
3239

Peter Eastman's avatar
Peter Eastman committed
3240
3241
3242
3243
3244
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.types4 = []
        self.types5 = []
3245

Peter Eastman's avatar
Peter Eastman committed
3246
        self.gridIndex = []
3247

Peter Eastman's avatar
Peter Eastman committed
3248
        self.grids = []
Justin MacCallum's avatar
Justin MacCallum committed
3249

3250
3251
3252
3253
3254
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

Peter Eastman's avatar
Peter Eastman committed
3255
        generator = AmoebaTorsionTorsionGenerator()
3256
3257
3258
3259
3260
3261
3262
        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'):
3263
            types = forceField._findAtomTypes(torsionTorsion.attrib, 5)
peastman's avatar
peastman committed
3264
            if None not in types:
3265
3266
3267
3268
3269
3270
3271

                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
3272
3273
                gridIndex = int(torsionTorsion.attrib['grid'])
                if (gridIndex > maxGridIndex):
3274
3275
3276
3277
3278
3279
3280
3281
3282
                    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
3283
                                    torsionTorsion.attrib['class5'] )
Justin MacCallum's avatar
Justin MacCallum committed
3284
3285
                raise ValueError(outputString)

3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
        # 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:

Justin MacCallum's avatar
Justin MacCallum committed
3296
3297
3298
3299
3300
3301
        #     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
3302
3303

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

Peter Eastman's avatar
Peter Eastman committed
3307
3308
3309
            gridIndex = int(torsionTorsionGrid.attrib[ "grid"])
            nx = int(torsionTorsionGrid.attrib[ "nx"])
            ny = int(torsionTorsionGrid.attrib[ "ny"])
3310

Peter Eastman's avatar
Peter Eastman committed
3311
3312
            grid = []
            gridCol = []
3313
3314
3315
3316
3317

            gridColIndex = 0

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

Peter Eastman's avatar
Peter Eastman committed
3318
3319
3320
3321
                gridRow = []
                gridRow.append(float(gridEntry.attrib['angle1']))
                gridRow.append(float(gridEntry.attrib['angle2']))
                gridRow.append(float(gridEntry.attrib['f']))
3322
                if 'fx' in gridEntry.attrib:
3323
3324
3325
                    gridRow.append(float(gridEntry.attrib['fx']))
                    gridRow.append(float(gridEntry.attrib['fy']))
                    gridRow.append(float(gridEntry.attrib['fxy']))
Peter Eastman's avatar
Peter Eastman committed
3326
                gridCol.append(gridRow)
3327
3328

                gridColIndex  += 1
Peter Eastman's avatar
Peter Eastman committed
3329
3330
3331
                if (gridColIndex == nx):
                    grid.append(gridCol)
                    gridCol = []
3332
3333
                    gridColIndex = 0

Justin MacCallum's avatar
Justin MacCallum committed
3334

Peter Eastman's avatar
Peter Eastman committed
3335
3336
            if (gridIndex == len(generator.grids)):
                generator.grids.append(grid)
3337
            else:
Peter Eastman's avatar
Peter Eastman committed
3338
3339
                while(len(generator.grids) < gridIndex):
                    generator.grids.append([])
3340
3341
3342
3343
                generator.grids[gridIndex] = grid

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

Peter Eastman's avatar
Peter Eastman committed
3344
    def getChiralAtomIndex(self, data, sys, atomB, atomC, atomD):
3345
3346
3347
3348
3349
3350
3351
3352

        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
3353
        if (len(data.atomBonds[atomC]) == 4):
3354
3355
3356
3357
3358
            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
3359
3360
                hit = -1
                if (  bondedAtom1 == atomC and bondedAtom2 != atomB and bondedAtom2 != atomD):
3361
                    hit = bondedAtom2
Peter Eastman's avatar
Peter Eastman committed
3362
                elif (bondedAtom2 == atomC and bondedAtom1 != atomB and bondedAtom1 != atomD):
3363
3364
                    hit = bondedAtom1

Peter Eastman's avatar
Peter Eastman committed
3365
3366
                if (hit > -1):
                    if (atomE == -1):
3367
3368
3369
                        atomE = hit
                    else:
                        atomF = hit
Justin MacCallum's avatar
Justin MacCallum committed
3370

3371
3372
            # raise error if atoms E or F not found

Peter Eastman's avatar
Peter Eastman committed
3373
3374
            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,)
Justin MacCallum's avatar
Justin MacCallum committed
3375
                raise ValueError(outputString)
3376
3377
3378
3379
3380

            # 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
3381
            if (typeE > typeF):
Justin MacCallum's avatar
Justin MacCallum committed
3382
                chiralAtomIndex = atomE
Peter Eastman's avatar
Peter Eastman committed
3383
            if (typeF > typeE):
Justin MacCallum's avatar
Justin MacCallum committed
3384
                chiralAtomIndex = atomF
3385

Peter Eastman's avatar
Peter Eastman committed
3386
3387
3388
            massE = sys.getParticleMass(atomE)/unit.dalton
            massF = sys.getParticleMass(atomE)/unit.dalton
            if (massE > massF):
Justin MacCallum's avatar
Justin MacCallum committed
3389
                chiralAtomIndex = massE
Peter Eastman's avatar
Peter Eastman committed
3390
            if (massF > massE):
Justin MacCallum's avatar
Justin MacCallum committed
3391
                chiralAtomIndex = massF
3392
3393
3394
3395

        return chiralAtomIndex

    #=============================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
3396

3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
    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:

Justin MacCallum's avatar
Justin MacCallum committed
3410
3411
            # search for bitorsions; based on TINKER subroutine bitors()

3412
3413
3414
3415
3416
3417
3418
            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
3419
                if (bondedAtom1 != ib):
3420
3421
3422
3423
                    ia = bondedAtom1
                else:
                    ia = bondedAtom2

Peter Eastman's avatar
Peter Eastman committed
3424
                if (ia != ic and ia != id):
3425
3426
3427
                    for bondIndex in data.atomBonds[id]:
                        bondedAtom1 = data.bonds[bondIndex].atom1
                        bondedAtom2 = data.bonds[bondIndex].atom2
Peter Eastman's avatar
Peter Eastman committed
3428
                        if (bondedAtom1 != id):
3429
3430
3431
3432
                            ie = bondedAtom1
                        else:
                            ie = bondedAtom2

Peter Eastman's avatar
Peter Eastman committed
3433
                        if (ie != ic and ie != ib and ie != ia):
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453

                            # 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
3454
3455
3456
                                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])
3457
3458
3459

                                # match in reverse order

3460
                                elif (type5 in types1 and type4 in types2 and type3 in types3 and type2 in types4 and type1 in types5):
Peter Eastman's avatar
Peter Eastman committed
3461
3462
                                    chiralAtomIndex = self.getChiralAtomIndex(data, sys, ib, ic, id)
                                    force.addTorsionTorsion(ie, id, ic, ib, ia, chiralAtomIndex, self.gridIndex[i])
3463
3464
3465
3466

        # set grids

        for (index, grid) in enumerate(self.grids):
Peter Eastman's avatar
Peter Eastman committed
3467
            force.setTorsionTorsionGrid(index, grid)
Justin MacCallum's avatar
Justin MacCallum committed
3468

3469
3470
3471
3472
parsers["AmoebaTorsionTorsionForce"] = AmoebaTorsionTorsionGenerator.parseElement

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

3473
## @private
3474
class AmoebaStretchBendGenerator(object):
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3475
3476

    #=============================================================================================
3477
3478
3479
3480
3481
    """An AmoebaStretchBendGenerator constructs a AmoebaStretchBendForce."""
    #=============================================================================================

    def __init__(self):

Peter Eastman's avatar
Peter Eastman committed
3482
3483
3484
        self.types1 = []
        self.types2 = []
        self.types3 = []
3485

Peter Eastman's avatar
Peter Eastman committed
3486
3487
        self.k1 = []
        self.k2 = []
Justin MacCallum's avatar
Justin MacCallum committed
3488

3489
3490
3491
3492
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):
Peter Eastman's avatar
Peter Eastman committed
3493
        generator = AmoebaStretchBendGenerator()
3494
3495
3496
3497
3498
3499
3500
        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'):
3501
            types = forceField._findAtomTypes(stretchBend.attrib, 3)
peastman's avatar
peastman committed
3502
            if None not in types:
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514

                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
3515
                                    stretchBend.attrib['class3'])
Justin MacCallum's avatar
Justin MacCallum committed
3516
3517
                raise ValueError(outputString)

3518
3519
    #=============================================================================================

Justin MacCallum's avatar
Justin MacCallum committed
3520
    # The setup of this force is dependent on AmoebaBondForce and AmoebaAngleForce
3521
3522
    # 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
Justin MacCallum's avatar
Justin MacCallum committed
3523
3524
    # AmoebaBondForce and AmoebaAngleForce have been called prior to AmoebaStretchBendGenerator().
    # Instead, createForcePostAmoebaBondForce() is called
3525
    # after the generators for AmoebaBondForce and AmoebaAngleForce have been called
3526
3527
3528

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

Peter Eastman's avatar
Peter Eastman committed
3529
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
3530
3531
3532
3533
3534
3535
3536
3537
        pass

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

    # Note: request for constrained bonds is ignored.

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

3538
    def createForcePostAmoebaBondForce(self, sys, data, nonbondedMethod, nonbondedCutoff, angleList, args):
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550

        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
3551
            if ('isConstrained' in angleDict):
3552
3553
3554
3555
3556
3557
3558
3559
                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
3560
            radian = 57.2957795130
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
            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

Justin MacCallum's avatar
Justin MacCallum committed
3571
                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
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
                    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
Justin MacCallum's avatar
Justin MacCallum committed
3587

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3588
                    # check that ideal angle and bonds are set
3589

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3590
                    if ('idealAngle' not in angleDict):
3591

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3592
3593
3594
3595
3596
                       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] )
Justin MacCallum's avatar
Justin MacCallum committed
3597
                       raise ValueError(outputString)
3598

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3599
3600
3601
3602
3603
3604
3605
                    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] )
Justin MacCallum's avatar
Justin MacCallum committed
3606
                       raise ValueError(outputString)
3607

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

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3611
                    break
3612
3613
3614
3615
3616

parsers["AmoebaStretchBendForce"] = AmoebaStretchBendGenerator.parseElement

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

3617
## @private
3618
class AmoebaVdwGenerator(object):
3619
3620

    """A AmoebaVdwGenerator constructs a AmoebaVdwForce."""
Justin MacCallum's avatar
Justin MacCallum committed
3621

3622
3623
    #=============================================================================================

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

Justin MacCallum's avatar
Justin MacCallum committed
3626
        self.type = type
3627

Peter Eastman's avatar
Peter Eastman committed
3628
3629
3630
        self.radiusrule = radiusrule
        self.radiustype = radiustype
        self.radiussize = radiussize
3631

Peter Eastman's avatar
Peter Eastman committed
3632
        self.epsilonrule = epsilonrule
3633

Peter Eastman's avatar
Peter Eastman committed
3634
3635
3636
        self.vdw13Scale = vdw13Scale
        self.vdw14Scale = vdw14Scale
        self.vdw15Scale = vdw15Scale
3637
3638
3639
3640
3641
3642
3643

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

    @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" >
Justin MacCallum's avatar
Justin MacCallum committed
3644
3645
3646
3647
3648
        #   <Vdw class="1" sigma="0.371" epsilon="0.46024" reduction="1.0" />
        #   <Vdw class="2" sigma="0.382" epsilon="0.422584" reduction="1.0" />

        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']))
3649
        forceField._forces.append(generator)
3650
3651
        generator.params = ForceField._AtomTypeParameters(forceField, 'AmoebaVdwForce', 'Vdw', ('sigma', 'epsilon', 'reduction'))
        generator.params.parseDefinitions(element)
3652
3653
3654
3655
3656
3657
3658
3659
3660
        two_six = 1.122462048309372

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

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

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

    @staticmethod
Peter Eastman's avatar
Peter Eastman committed
3661
    def getBondedParticleSet(particleIndex, data):
3662
3663
3664
3665
3666
3667

        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
3668
3669
            if (atom1 != particleIndex):
                bondedParticleSet.add(atom1)
3670
            else:
Peter Eastman's avatar
Peter Eastman committed
3671
                bondedParticleSet.add(atom2)
3672
3673

        return bondedParticleSet
Justin MacCallum's avatar
Justin MacCallum committed
3674

3675
3676
    #=============================================================================================

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

Peter Eastman's avatar
Peter Eastman committed
3679
        sigmaMap = {'ARITHMETIC':1, 'GEOMETRIC':1, 'CUBIC-MEAN':1}
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
        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
3692
            if ('sigmaCombiningRule' in args):
3693
                sigmaRule = args['sigmaCombiningRule'].upper()
Peter Eastman's avatar
Peter Eastman committed
3694
3695
                if (sigmaRule.upper() in sigmaMap):
                    force.setSigmaCombiningRule(sigmaRule.upper())
3696
                else:
Peter Eastman's avatar
Peter Eastman committed
3697
                    stringList = ' ' . join(str(x) for x in sigmaMap.keys())
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3698
                    raise ValueError( "AmoebaVdwGenerator: sigma combining rule %s not recognized; valid values are %s; using default." % (sigmaRule, stringList) )
3699
            else:
Peter Eastman's avatar
Peter Eastman committed
3700
                force.setSigmaCombiningRule(self.radiusrule)
3701

Peter Eastman's avatar
Peter Eastman committed
3702
            if ('epsilonCombiningRule' in args):
3703
                epsilonRule = args['epsilonCombiningRule'].upper()
Peter Eastman's avatar
Peter Eastman committed
3704
3705
                if (epsilonRule.upper() in epsilonMap):
                    force.setEpsilonCombiningRule(epsilonRule.upper())
3706
                else:
Peter Eastman's avatar
Peter Eastman committed
3707
                    stringList = ' ' . join(str(x) for x in epsilonMap.keys())
Justin MacCallum's avatar
Justin MacCallum committed
3708
                    raise ValueError( "AmoebaVdwGenerator: epsilon combining rule %s not recognized; valid values are %s; using default." % (epsilonRule, stringList) )
3709
            else:
Peter Eastman's avatar
Peter Eastman committed
3710
                force.setEpsilonCombiningRule(self.epsilonrule)
Justin MacCallum's avatar
Justin MacCallum committed
3711

3712
3713
            # cutoff

Peter Eastman's avatar
Peter Eastman committed
3714
            if ('vdwCutoff' in args):
3715
                force.setCutoff(args['vdwCutoff'])
3716
            else:
Peter Eastman's avatar
Peter Eastman committed
3717
                force.setCutoff(nonbondedCutoff)
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3718

3719
3720
3721
            # dispersion correction

            if ('useDispersionCorrection' in args):
3722
                force.setUseDispersionCorrection(bool(args['useDispersionCorrection']))
3723

Peter Eastman's avatar
Peter Eastman committed
3724
            if (nonbondedMethod == PME):
3725
                force.setNonbondedMethod(mm.AmoebaVdwForce.CutoffPeriodic)
Justin MacCallum's avatar
Justin MacCallum committed
3726

3727
3728
3729
3730
3731
        else:
            force = existing[0]

        # add particles to force

3732
3733
3734
3735
3736
        sigmaScale = 1
        if self.radiustype == 'SIGMA':
            sigmaScale = 1.122462048309372
        if self.radiussize == 'DIAMETER':
            sigmaScale = 0.5
3737
        for (i, atom) in enumerate(data.atoms):
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
            values = self.params.getAtomParameters(atom, data)
            # ivIndex = index of bonded partner for hydrogens; otherwise ivIndex = particle index

            ivIndex = i
            if atom.element == elem.hydrogen and len(data.atomBonds[i]) == 1:
                bondIndex = data.atomBonds[i][0]
                if (data.bonds[bondIndex].atom1 == i):
                    ivIndex = data.bonds[bondIndex].atom2
                else:
                    ivIndex = data.bonds[bondIndex].atom1
3748

3749
            force.addParticle(ivIndex, values[0]*sigmaScale, values[1], values[2])
3750
3751
3752
3753
3754
3755
3756
3757
3758

        # 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
3759
            bondedParticleSets.append(AmoebaVdwGenerator.getBondedParticleSet(i, data))
3760
3761

        for (i,atom) in enumerate(data.atoms):
Justin MacCallum's avatar
Justin MacCallum committed
3762

3763
3764
3765
3766
3767
3768
            # 1-2 partners

            exclusionSet = bondedParticleSets[i].copy()

            # 1-3 partners

Peter Eastman's avatar
Peter Eastman committed
3769
            if (self.vdw13Scale == 0.0):
3770
                for bondedParticle in bondedParticleSets[i]:
Peter Eastman's avatar
Peter Eastman committed
3771
                    exclusionSet = exclusionSet.union(bondedParticleSets[bondedParticle])
3772
3773
3774
3775
3776

            # self

            exclusionSet.add(i)

3777
            force.setParticleExclusions(i, tuple(exclusionSet))
3778
3779
3780
3781
3782

parsers["AmoebaVdwForce"] = AmoebaVdwGenerator.parseElement

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

3783
## @private
3784
class AmoebaMultipoleGenerator(object):
3785
3786
3787
3788

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

    """A AmoebaMultipoleGenerator constructs a AmoebaMultipoleForce."""
Justin MacCallum's avatar
Justin MacCallum committed
3789

3790
3791
3792
3793
3794
3795
    #=============================================================================================

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

Peter Eastman's avatar
Peter Eastman committed
3798
        self.forceField = forceField
3799

Justin MacCallum's avatar
Justin MacCallum committed
3800
3801
3802
3803
        self.direct11Scale = direct11Scale
        self.direct12Scale = direct12Scale
        self.direct13Scale = direct13Scale
        self.direct14Scale = direct14Scale
3804

Justin MacCallum's avatar
Justin MacCallum committed
3805
3806
3807
3808
        self.mpole12Scale = mpole12Scale
        self.mpole13Scale = mpole13Scale
        self.mpole14Scale = mpole14Scale
        self.mpole15Scale = mpole15Scale
3809

Justin MacCallum's avatar
Justin MacCallum committed
3810
3811
3812
3813
        self.mutual11Scale = mutual11Scale
        self.mutual12Scale = mutual12Scale
        self.mutual13Scale = mutual13Scale
        self.mutual14Scale = mutual14Scale
3814

Justin MacCallum's avatar
Justin MacCallum committed
3815
3816
3817
3818
        self.polar12Scale = polar12Scale
        self.polar13Scale = polar13Scale
        self.polar14Scale = polar14Scale
        self.polar15Scale = polar15Scale
3819

Peter Eastman's avatar
Peter Eastman committed
3820
        self.typeMap = {}
3821
3822
3823
3824
3825
3826

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

    @staticmethod
Peter Eastman's avatar
Peter Eastman committed
3827
    def setAxisType(kIndices):
3828
3829
3830

                # set axis type

Peter Eastman's avatar
Peter Eastman committed
3831
3832
3833
                kIndicesLen = len(kIndices)
                if (kIndicesLen > 3):
                    ky = kIndices[3]
3834
                else:
Peter Eastman's avatar
Peter Eastman committed
3835
                    ky = 0
Justin MacCallum's avatar
Justin MacCallum committed
3836

Peter Eastman's avatar
Peter Eastman committed
3837
3838
                if (kIndicesLen > 2):
                    kx = kIndices[2]
3839
                else:
Peter Eastman's avatar
Peter Eastman committed
3840
                    kx = 0
Justin MacCallum's avatar
Justin MacCallum committed
3841

Peter Eastman's avatar
Peter Eastman committed
3842
3843
                if (kIndicesLen > 1):
                    kz = kIndices[1]
3844
                else:
Peter Eastman's avatar
Peter Eastman committed
3845
                    kz = 0
3846

Peter Eastman's avatar
Peter Eastman committed
3847
3848
                while(len(kIndices) < 4):
                    kIndices.append(0)
3849
3850

                axisType = mm.AmoebaMultipoleForce.ZThenX
Peter Eastman's avatar
Peter Eastman committed
3851
                if (kz == 0):
3852
                    axisType = mm.AmoebaMultipoleForce.NoAxisType
Peter Eastman's avatar
Peter Eastman committed
3853
                if (kz != 0 and kx == 0):
3854
                    axisType = mm.AmoebaMultipoleForce.ZOnly
Peter Eastman's avatar
Peter Eastman committed
3855
                if (kz < 0 or kx < 0):
3856
                    axisType = mm.AmoebaMultipoleForce.Bisector
Peter Eastman's avatar
Peter Eastman committed
3857
                if (kx < 0 and ky < 0):
3858
                    axisType = mm.AmoebaMultipoleForce.ZBisect
Peter Eastman's avatar
Peter Eastman committed
3859
                if (kz < 0 and kx < 0 and ky  < 0):
3860
3861
                    axisType = mm.AmoebaMultipoleForce.ThreeFold

Justin MacCallum's avatar
Justin MacCallum committed
3862
3863
3864
                kIndices[1] = abs(kz)
                kIndices[2] = abs(kx)
                kIndices[3] = abs(ky)
3865
3866
3867
3868
3869
3870
3871
3872

                return axisType

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

    @staticmethod
    def parseElement(element, forceField):

Justin MacCallum's avatar
Justin MacCallum committed
3873
        #   <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"  >
3874
3875
3876
        # <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
3877
        generator = AmoebaMultipoleGenerator(forceField,
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
                                              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
3896
                                              element.attrib['polar15Scale'])
3897
3898
3899
3900
3901
3902
3903
3904



        forceField._forces.append(generator)

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

        for atom in element.findall('Multipole'):
3905
            types = forceField._findAtomTypes(atom.attrib, 1)
peastman's avatar
peastman committed
3906
            if None not in types:
3907
3908
3909
3910
3911
3912
3913
3914

                # 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
3915
3916
                        if (atom.attrib[kString]):
                             kIndices.append(int(atom.attrib[kString]))
Justin MacCallum's avatar
Justin MacCallum committed
3917
                    except:
3918
3919
                        pass

Justin MacCallum's avatar
Justin MacCallum committed
3920
                # set axis type based on k-Indices
3921

Peter Eastman's avatar
Peter Eastman committed
3922
                axisType = AmoebaMultipoleGenerator.setAxisType(kIndices)
3923
3924
3925

                # set multipole

Peter Eastman's avatar
Peter Eastman committed
3926
                charge = float(atom.attrib['c0'])
Justin MacCallum's avatar
Justin MacCallum committed
3927

Peter Eastman's avatar
Peter Eastman committed
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
                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']))
3941
3942

                for t in types[0]:
Peter Eastman's avatar
Peter Eastman committed
3943
                    if (t not in generator.typeMap):
3944
3945
                        generator.typeMap[t] = []

Peter Eastman's avatar
Peter Eastman committed
3946
3947
3948
                    valueMap = dict()
                    valueMap['classIndex'] = atom.attrib['type']
                    valueMap['kIndices'] = kIndices
Justin MacCallum's avatar
Justin MacCallum committed
3949
                    valueMap['charge'] = charge
Peter Eastman's avatar
Peter Eastman committed
3950
3951
3952
3953
                    valueMap['dipole'] = dipole
                    valueMap['quadrupole'] = quadrupole
                    valueMap['axisType'] = axisType
                    generator.typeMap[t].append(valueMap)
Justin MacCallum's avatar
Justin MacCallum committed
3954

3955
            else:
Peter Eastman's avatar
Peter Eastman committed
3956
                outputString = "AmoebaMultipoleGenerator: error getting type for multipole: %s" % (atom.attrib['class'])
Justin MacCallum's avatar
Justin MacCallum committed
3957
3958
                raise ValueError(outputString)

3959
        # polarization parameters
Justin MacCallum's avatar
Justin MacCallum committed
3960

3961
        for atom in element.findall('Polarize'):
3962
            types = forceField._findAtomTypes(atom.attrib, 1)
peastman's avatar
peastman committed
3963
            if None not in types:
3964

Peter Eastman's avatar
Peter Eastman committed
3965
3966
3967
3968
                classIndex = atom.attrib['type']
                polarizability = float(atom.attrib['polarizability'])
                thole = float(atom.attrib['thole'])
                if (thole == 0):
3969
3970
                    pdamp = 0
                else:
Peter Eastman's avatar
Peter Eastman committed
3971
                    pdamp = pow(polarizability, 1.0/6.0)
3972

Peter Eastman's avatar
Peter Eastman committed
3973
3974
                pgrpMap = dict()
                for index in range(1, 7):
3975
                    pgrp = 'pgrp' + str(index)
Peter Eastman's avatar
Peter Eastman committed
3976
                    if (pgrp in atom.attrib):
3977
3978
3979
                        pgrpMap[int(atom.attrib[pgrp])] = -1

                for t in types[0]:
Peter Eastman's avatar
Peter Eastman committed
3980
3981
                    if (t not in generator.typeMap):
                        outputString = "AmoebaMultipoleGenerator: polarize type not present: %s" % (atom.attrib['type'])
Justin MacCallum's avatar
Justin MacCallum committed
3982
                        raise ValueError(outputString)
3983
3984
                    else:
                        typeMapList = generator.typeMap[t]
Peter Eastman's avatar
Peter Eastman committed
3985
3986
3987
3988
3989
3990
3991
                        hit = 0
                        for (ii, typeMap) in enumerate(typeMapList):

                            if (typeMap['classIndex'] == classIndex):
                                typeMap['polarizability'] = polarizability
                                typeMap['thole'] = thole
                                typeMap['pdamp'] = pdamp
Justin MacCallum's avatar
Justin MacCallum committed
3992
                                typeMap['pgrpMap'] = pgrpMap
Peter Eastman's avatar
Peter Eastman committed
3993
3994
3995
3996
3997
                                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'])
Justin MacCallum's avatar
Justin MacCallum committed
3998
3999
                            raise ValueError(outputString)

4000
            else:
Peter Eastman's avatar
Peter Eastman committed
4001
                outputString = "AmoebaMultipoleGenerator: error getting type for polarize: %s" % (atom.attrib['class'])
Justin MacCallum's avatar
Justin MacCallum committed
4002
4003
                raise ValueError(outputString)

4004
4005
    #=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
4006
    def setPolarGroups(self, data, bonded12ParticleSets, force):
4007
4008
4009
4010
4011

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

            # assign multipole parameters via only 1-2 connected atoms

Peter Eastman's avatar
Peter Eastman committed
4012
4013
4014
4015
            multipoleDict = atom.multipoleDict
            pgrpMap = multipoleDict['pgrpMap']
            bondedAtomIndices = bonded12ParticleSets[atomIndex]
            atom.stage = -1
4016
4017
4018
4019
            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
4020
4021
                bondedAtom = data.atoms[bondedAtomIndex]
                if (bondedAtomType in pgrpMap):
4022
4023
                    atom.polarizationGroups[bondedAtomIndex] = 1
                    bondedAtom.polarizationGroups[atomIndex] = 1
Justin MacCallum's avatar
Justin MacCallum committed
4024

4025
4026
4027
4028
        # pgrp11

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

Peter Eastman's avatar
Peter Eastman committed
4029
            if (len( data.atoms[atomIndex].polarizationGroupSet) > 0):
4030
4031
                continue

Peter Eastman's avatar
Peter Eastman committed
4032
4033
            group = set()
            visited = set()
4034
4035
            notVisited = set()
            for pgrpAtomIndex in atom.polarizationGroups:
Peter Eastman's avatar
Peter Eastman committed
4036
4037
4038
4039
                group.add(pgrpAtomIndex)
                notVisited.add(pgrpAtomIndex)
            visited.add(atomIndex)
            while(len(notVisited) > 0):
4040
                nextAtom = notVisited.pop()
Peter Eastman's avatar
Peter Eastman committed
4041
4042
                if (nextAtom not in visited):
                   visited.add(nextAtom)
4043
                   for ii in data.atoms[nextAtom].polarizationGroups:
Peter Eastman's avatar
Peter Eastman committed
4044
4045
4046
                       group.add(ii)
                       if (ii not in visited):
                           notVisited.add(ii)
4047
4048
4049

            pGroup = group
            for pgrpAtomIndex in group:
Peter Eastman's avatar
Peter Eastman committed
4050
                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pGroup)
4051
4052

        for (atomIndex, atom) in enumerate(data.atoms):
Peter Eastman's avatar
Peter Eastman committed
4053
4054
            atom.polarizationGroupSet[0] = sorted(atom.polarizationGroupSet[0])
            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent11, atom.polarizationGroupSet[0])
4055
4056
4057
4058
4059

        # pgrp12

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

Peter Eastman's avatar
Peter Eastman committed
4060
            if (len( data.atoms[atomIndex].polarizationGroupSet) > 1):
4061
4062
                continue

Peter Eastman's avatar
Peter Eastman committed
4063
            pgrp11 = set(atom.polarizationGroupSet[0])
4064
4065
4066
            pgrp12 = set()
            for pgrpAtomIndex in pgrp11:
                for bonded12 in bonded12ParticleSets[pgrpAtomIndex]:
Peter Eastman's avatar
Peter Eastman committed
4067
                    pgrp12 = pgrp12.union(data.atoms[bonded12].polarizationGroupSet[0])
4068
4069
            pgrp12 = pgrp12 - pgrp11
            for pgrpAtomIndex in pgrp11:
Peter Eastman's avatar
Peter Eastman committed
4070
                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pgrp12)
Justin MacCallum's avatar
Justin MacCallum committed
4071

4072
        for (atomIndex, atom) in enumerate(data.atoms):
Peter Eastman's avatar
Peter Eastman committed
4073
4074
            atom.polarizationGroupSet[1] = sorted(atom.polarizationGroupSet[1])
            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent12, atom.polarizationGroupSet[1])
4075
4076
4077
4078
4079

        # pgrp13

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

Peter Eastman's avatar
Peter Eastman committed
4080
            if (len(data.atoms[atomIndex].polarizationGroupSet) > 2):
4081
4082
                continue

Peter Eastman's avatar
Peter Eastman committed
4083
4084
            pgrp11 = set(atom.polarizationGroupSet[0])
            pgrp12 = set(atom.polarizationGroupSet[1])
4085
4086
4087
            pgrp13 = set()
            for pgrpAtomIndex in pgrp12:
                for bonded12 in bonded12ParticleSets[pgrpAtomIndex]:
Peter Eastman's avatar
Peter Eastman committed
4088
                    pgrp13 = pgrp13.union(data.atoms[bonded12].polarizationGroupSet[0])
4089
            pgrp13 = pgrp13 - pgrp12
Peter Eastman's avatar
Peter Eastman committed
4090
            pgrp13 = pgrp13 - set(pgrp11)
4091
            for pgrpAtomIndex in pgrp11:
Peter Eastman's avatar
Peter Eastman committed
4092
                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pgrp13)
Justin MacCallum's avatar
Justin MacCallum committed
4093

4094
        for (atomIndex, atom) in enumerate(data.atoms):
Peter Eastman's avatar
Peter Eastman committed
4095
4096
            atom.polarizationGroupSet[2] = sorted(atom.polarizationGroupSet[2])
            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent13, atom.polarizationGroupSet[2])
4097
4098
4099
4100
4101

        # pgrp14

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

Peter Eastman's avatar
Peter Eastman committed
4102
            if (len(data.atoms[atomIndex].polarizationGroupSet) > 3):
4103
4104
                continue

Peter Eastman's avatar
Peter Eastman committed
4105
4106
4107
            pgrp11 = set(atom.polarizationGroupSet[0])
            pgrp12 = set(atom.polarizationGroupSet[1])
            pgrp13 = set(atom.polarizationGroupSet[2])
4108
4109
4110
            pgrp14 = set()
            for pgrpAtomIndex in pgrp13:
                for bonded12 in bonded12ParticleSets[pgrpAtomIndex]:
Peter Eastman's avatar
Peter Eastman committed
4111
                    pgrp14 = pgrp14.union(data.atoms[bonded12].polarizationGroupSet[0])
4112
4113
4114

            pgrp14 = pgrp14 - pgrp13
            pgrp14 = pgrp14 - pgrp12
Peter Eastman's avatar
Peter Eastman committed
4115
            pgrp14 = pgrp14 - set(pgrp11)
4116
4117

            for pgrpAtomIndex in pgrp11:
Peter Eastman's avatar
Peter Eastman committed
4118
                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pgrp14)
Justin MacCallum's avatar
Justin MacCallum committed
4119

4120
        for (atomIndex, atom) in enumerate(data.atoms):
Peter Eastman's avatar
Peter Eastman committed
4121
4122
            atom.polarizationGroupSet[3] = sorted(atom.polarizationGroupSet[3])
            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent14, atom.polarizationGroupSet[3])
4123
4124
4125

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

Peter Eastman's avatar
Peter Eastman committed
4126
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137

        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)
Justin MacCallum's avatar
Justin MacCallum committed
4138
            if (nonbondedMethod not in methodMap):
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
4139
                raise ValueError( "AmoebaMultipoleForce: input cutoff method not available." )
4140
            else:
Peter Eastman's avatar
Peter Eastman committed
4141
                force.setNonbondedMethod(methodMap[nonbondedMethod])
4142
4143
            force.setCutoffDistance(nonbondedCutoff)

Peter Eastman's avatar
Peter Eastman committed
4144
            if ('ewaldErrorTolerance' in args):
4145
4146
                force.setEwaldErrorTolerance(float(args['ewaldErrorTolerance']))

Peter Eastman's avatar
Peter Eastman committed
4147
            if ('polarization' in args):
4148
                polarizationType = args['polarization']
Peter Eastman's avatar
Peter Eastman committed
4149
                if (polarizationType.lower() == 'direct'):
4150
                    force.setPolarizationType(mm.AmoebaMultipoleForce.Direct)
4151
4152
                elif (polarizationType.lower() == 'extrapolated'):
                    force.setPolarizationType(mm.AmoebaMultipoleForce.Extrapolated)
4153
4154
4155
                else:
                    force.setPolarizationType(mm.AmoebaMultipoleForce.Mutual)

Peter Eastman's avatar
Peter Eastman committed
4156
4157
            if ('aEwald' in args):
                force.setAEwald(float(args['aEwald']))
4158

Peter Eastman's avatar
Peter Eastman committed
4159
            if ('pmeGridDimensions' in args):
4160
4161
                force.setPmeGridDimensions(args['pmeGridDimensions'])

Peter Eastman's avatar
Peter Eastman committed
4162
4163
            if ('mutualInducedMaxIterations' in args):
                force.setMutualInducedMaxIterations(int(args['mutualInducedMaxIterations']))
4164

Peter Eastman's avatar
Peter Eastman committed
4165
            if ('mutualInducedTargetEpsilon' in args):
4166
4167
4168
4169
4170
4171
                force.setMutualInducedTargetEpsilon(float(args['mutualInducedTargetEpsilon']))

        else:
            force = existing[0]

        # add particles to force
Justin MacCallum's avatar
Justin MacCallum committed
4172
        # throw error if particle type not available
4173
4174
4175
4176
4177
4178
4179

        # 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
4180
4181
4182
            bonded12ParticleSet = AmoebaVdwGenerator.getBondedParticleSet(i, data)
            bonded12ParticleSet = set(sorted(bonded12ParticleSet))
            bonded12ParticleSets.append(bonded12ParticleSet)
4183
4184
4185
4186
4187

        # 1-3

        bonded13ParticleSets = []
        for i in range(len(data.atoms)):
Peter Eastman's avatar
Peter Eastman committed
4188
            bonded13Set = set()
4189
            bonded12ParticleSet = bonded12ParticleSets[i]
Justin MacCallum's avatar
Justin MacCallum committed
4190
            for j in bonded12ParticleSet:
Peter Eastman's avatar
Peter Eastman committed
4191
                bonded13Set = bonded13Set.union(bonded12ParticleSets[j])
4192
4193
4194
4195

            # remove 1-2 and self from set

            bonded13Set = bonded13Set - bonded12ParticleSet
Peter Eastman's avatar
Peter Eastman committed
4196
            selfSet = set()
4197
4198
            selfSet.add(i)
            bonded13Set = bonded13Set - selfSet
Peter Eastman's avatar
Peter Eastman committed
4199
4200
            bonded13Set = set(sorted(bonded13Set))
            bonded13ParticleSets.append(bonded13Set)
4201
4202
4203
4204
4205

        # 1-4

        bonded14ParticleSets = []
        for i in range(len(data.atoms)):
Peter Eastman's avatar
Peter Eastman committed
4206
4207
            bonded14Set = set()
            bonded13ParticleSet = bonded13ParticleSets[i]
Justin MacCallum's avatar
Justin MacCallum committed
4208
            for j in bonded13ParticleSet:
Peter Eastman's avatar
Peter Eastman committed
4209
                bonded14Set = bonded14Set.union(bonded12ParticleSets[j])
Justin MacCallum's avatar
Justin MacCallum committed
4210

4211
4212
4213
4214
            # remove 1-3, 1-2 and self from set

            bonded14Set = bonded14Set - bonded12ParticleSets[i]
            bonded14Set = bonded14Set - bonded13ParticleSet
Peter Eastman's avatar
Peter Eastman committed
4215
            selfSet = set()
4216
4217
            selfSet.add(i)
            bonded14Set = bonded14Set - selfSet
Peter Eastman's avatar
Peter Eastman committed
4218
4219
            bonded14Set = set(sorted(bonded14Set))
            bonded14ParticleSets.append(bonded14Set)
4220
4221
4222
4223
4224

        # 1-5

        bonded15ParticleSets = []
        for i in range(len(data.atoms)):
Peter Eastman's avatar
Peter Eastman committed
4225
4226
            bonded15Set = set()
            bonded14ParticleSet = bonded14ParticleSets[i]
Justin MacCallum's avatar
Justin MacCallum committed
4227
            for j in bonded14ParticleSet:
Peter Eastman's avatar
Peter Eastman committed
4228
                bonded15Set = bonded15Set.union(bonded12ParticleSets[j])
4229
4230
4231
4232
4233
4234

            # 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
4235
            selfSet = set()
4236
4237
            selfSet.add(i)
            bonded15Set = bonded15Set - selfSet
Peter Eastman's avatar
Peter Eastman committed
4238
4239
            bonded15Set = set(sorted(bonded15Set))
            bonded15ParticleSets.append(bonded15Set)
4240
4241
4242
4243
4244

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

Peter Eastman's avatar
Peter Eastman committed
4245
4246
                multipoleList = self.typeMap[t]
                hit = 0
4247
4248
4249
4250
4251
4252
                savedMultipoleDict = 0

                # assign multipole parameters via only 1-2 connected atoms

                for multipoleDict in multipoleList:

Peter Eastman's avatar
Peter Eastman committed
4253
                    if (hit != 0):
4254
4255
                        break

Peter Eastman's avatar
Peter Eastman committed
4256
                    kIndices = multipoleDict['kIndices']
Justin MacCallum's avatar
Justin MacCallum committed
4257
4258

                    kz = kIndices[1]
Peter Eastman's avatar
Peter Eastman committed
4259
4260
                    kx = kIndices[2]
                    ky = kIndices[3]
4261
4262
4263
4264

                    # assign multipole parameters
                    #    (1) get bonded partners
                    #    (2) match parameter types
Justin MacCallum's avatar
Justin MacCallum committed
4265

4266
                    bondedAtomIndices = bonded12ParticleSets[atomIndex]
Peter Eastman's avatar
Peter Eastman committed
4267
4268
4269
                    zaxis = -1
                    xaxis = -1
                    yaxis = -1
4270
4271
                    for bondedAtomZIndex in bondedAtomIndices:

Peter Eastman's avatar
Peter Eastman committed
4272
                       if (hit != 0):
4273
4274
4275
                           break

                       bondedAtomZType = int(data.atomType[data.atoms[bondedAtomZIndex]])
Peter Eastman's avatar
Peter Eastman committed
4276
4277
                       bondedAtomZ = data.atoms[bondedAtomZIndex]
                       if (bondedAtomZType == kz):
4278
                          for bondedAtomXIndex in bondedAtomIndices:
Peter Eastman's avatar
Peter Eastman committed
4279
                              if (bondedAtomXIndex == bondedAtomZIndex or hit != 0):
4280
4281
                                  continue
                              bondedAtomXType = int(data.atomType[data.atoms[bondedAtomXIndex]])
Peter Eastman's avatar
Peter Eastman committed
4282
4283
4284
4285
                              if (bondedAtomXType == kx):
                                  if (ky == 0):
                                      zaxis = bondedAtomZIndex
                                      xaxis = bondedAtomXIndex
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
                                      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

4296
                                      savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
4297
                                      hit = 1
4298
4299
                                  else:
                                      for bondedAtomYIndex in bondedAtomIndices:
Peter Eastman's avatar
Peter Eastman committed
4300
                                          if (bondedAtomYIndex == bondedAtomZIndex or bondedAtomYIndex == bondedAtomXIndex or hit != 0):
4301
4302
                                              continue
                                          bondedAtomYType = int(data.atomType[data.atoms[bondedAtomYIndex]])
Peter Eastman's avatar
Peter Eastman committed
4303
4304
4305
4306
                                          if (bondedAtomYType == ky):
                                              zaxis = bondedAtomZIndex
                                              xaxis = bondedAtomXIndex
                                              yaxis = bondedAtomYIndex
4307
                                              savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
4308
                                              hit = 2
Justin MacCallum's avatar
Justin MacCallum committed
4309

4310
4311
4312
4313
                # assign multipole parameters via 1-2 and 1-3 connected atoms

                for multipoleDict in multipoleList:

Peter Eastman's avatar
Peter Eastman committed
4314
                    if (hit != 0):
4315
4316
                        break

Peter Eastman's avatar
Peter Eastman committed
4317
                    kIndices = multipoleDict['kIndices']
Justin MacCallum's avatar
Justin MacCallum committed
4318
4319

                    kz = kIndices[1]
Peter Eastman's avatar
Peter Eastman committed
4320
4321
                    kx = kIndices[2]
                    ky = kIndices[3]
Justin MacCallum's avatar
Justin MacCallum committed
4322

4323
4324
4325
                    # assign multipole parameters
                    #    (1) get bonded partners
                    #    (2) match parameter types
Justin MacCallum's avatar
Justin MacCallum committed
4326

4327
4328
4329
                    bondedAtom12Indices = bonded12ParticleSets[atomIndex]
                    bondedAtom13Indices = bonded13ParticleSets[atomIndex]

Peter Eastman's avatar
Peter Eastman committed
4330
4331
4332
                    zaxis = -1
                    xaxis = -1
                    yaxis = -1
4333
4334
4335

                    for bondedAtomZIndex in bondedAtom12Indices:

Peter Eastman's avatar
Peter Eastman committed
4336
                       if (hit != 0):
4337
4338
4339
                           break

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

Peter Eastman's avatar
Peter Eastman committed
4342
                       if (bondedAtomZType == kz):
4343
4344
                          for bondedAtomXIndex in bondedAtom13Indices:

Peter Eastman's avatar
Peter Eastman committed
4345
                              if (bondedAtomXIndex == bondedAtomZIndex or hit != 0):
4346
4347
                                  continue
                              bondedAtomXType = int(data.atomType[data.atoms[bondedAtomXIndex]])
Peter Eastman's avatar
Peter Eastman committed
4348
4349
4350
4351
                              if (bondedAtomXType == kx and bondedAtomZIndex in bonded12ParticleSets[bondedAtomXIndex]):
                                  if (ky == 0):
                                      zaxis = bondedAtomZIndex
                                      xaxis = bondedAtomXIndex
4352
4353
4354
4355
4356
4357
4358
4359

                                      # 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

4360
                                      savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
4361
                                      hit = 3
4362
4363
                                  else:
                                      for bondedAtomYIndex in bondedAtom13Indices:
Peter Eastman's avatar
Peter Eastman committed
4364
                                          if (bondedAtomYIndex == bondedAtomZIndex or bondedAtomYIndex == bondedAtomXIndex or hit != 0):
4365
4366
                                              continue
                                          bondedAtomYType = int(data.atomType[data.atoms[bondedAtomYIndex]])
Peter Eastman's avatar
Peter Eastman committed
4367
4368
4369
4370
                                          if (bondedAtomYType == ky and bondedAtomZIndex in bonded12ParticleSets[bondedAtomYIndex]):
                                              zaxis = bondedAtomZIndex
                                              xaxis = bondedAtomXIndex
                                              yaxis = bondedAtomYIndex
4371
                                              savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
4372
                                              hit = 4
Justin MacCallum's avatar
Justin MacCallum committed
4373

4374
4375
4376
4377
                # assign multipole parameters via only a z-defining atom

                for multipoleDict in multipoleList:

Peter Eastman's avatar
Peter Eastman committed
4378
                    if (hit != 0):
4379
4380
                        break

Peter Eastman's avatar
Peter Eastman committed
4381
                    kIndices = multipoleDict['kIndices']
Justin MacCallum's avatar
Justin MacCallum committed
4382
4383
4384
4385

                    kz = kIndices[1]
                    kx = kIndices[2]

Peter Eastman's avatar
Peter Eastman committed
4386
4387
4388
                    zaxis = -1
                    xaxis = -1
                    yaxis = -1
4389
4390
4391

                    for bondedAtomZIndex in bondedAtom12Indices:

Peter Eastman's avatar
Peter Eastman committed
4392
                        if (hit != 0):
4393
4394
4395
                            break

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

Peter Eastman's avatar
Peter Eastman committed
4398
4399
                        if (kx == 0 and kz == bondedAtomZType):
                            kz = bondedAtomZIndex
4400
                            savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
4401
                            hit = 5
4402
4403
4404
4405
4406

                # assign multipole parameters via no connected atoms

                for multipoleDict in multipoleList:

Peter Eastman's avatar
Peter Eastman committed
4407
                    if (hit != 0):
4408
4409
                        break

Peter Eastman's avatar
Peter Eastman committed
4410
                    kIndices = multipoleDict['kIndices']
Justin MacCallum's avatar
Justin MacCallum committed
4411
4412
4413

                    kz = kIndices[1]

Peter Eastman's avatar
Peter Eastman committed
4414
4415
4416
                    zaxis = -1
                    xaxis = -1
                    yaxis = -1
4417

Peter Eastman's avatar
Peter Eastman committed
4418
                    if (kz == 0):
4419
                        savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
4420
                        hit = 6
Justin MacCallum's avatar
Justin MacCallum committed
4421

4422
4423
                # add particle if there was a hit

Peter Eastman's avatar
Peter Eastman committed
4424
                if (hit != 0):
4425

Peter Eastman's avatar
Peter Eastman committed
4426
                    atom.multipoleDict = savedMultipoleDict
4427
                    atom.polarizationGroups = dict()
4428
                    newIndex = force.addMultipole(savedMultipoleDict['charge'], savedMultipoleDict['dipole'], savedMultipoleDict['quadrupole'], savedMultipoleDict['axisType'],
4429
                                                                 zaxis, xaxis, yaxis, savedMultipoleDict['thole'], savedMultipoleDict['pdamp'], savedMultipoleDict['polarizability'])
Peter Eastman's avatar
Peter Eastman committed
4430
                    if (atomIndex == newIndex):
4431
4432
4433
4434
                        force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.Covalent12, tuple(bonded12ParticleSets[atomIndex]))
                        force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.Covalent13, tuple(bonded13ParticleSets[atomIndex]))
                        force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.Covalent14, tuple(bonded14ParticleSets[atomIndex]))
                        force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.Covalent15, tuple(bonded15ParticleSets[atomIndex]))
4435
                    else:
4436
                        raise ValueError("Atom %s of %s %d is out of sync!." %(atom.name, atom.residue.name, atom.residue.index))
4437
                else:
Peter Eastman's avatar
Peter Eastman committed
4438
                    raise ValueError("Atom %s of %s %d was not assigned." %(atom.name, atom.residue.name, atom.residue.index))
4439
            else:
Peter Eastman's avatar
Peter Eastman committed
4440
                raise ValueError('No multipole type for atom %s %s %d' % (atom.name, atom.residue.name, atom.residue.index))
4441
4442
4443

        # set polar groups

Peter Eastman's avatar
Peter Eastman committed
4444
        self.setPolarGroups(data, bonded12ParticleSets, force)
4445
4446
4447
4448
4449

parsers["AmoebaMultipoleForce"] = AmoebaMultipoleGenerator.parseElement

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

4450
## @private
4451
class AmoebaWcaDispersionGenerator(object):
4452
4453

    """A AmoebaWcaDispersionGenerator constructs a AmoebaWcaDispersionForce."""
Justin MacCallum's avatar
Justin MacCallum committed
4454

4455
4456
    #=========================================================================================

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

Justin MacCallum's avatar
Justin MacCallum committed
4459
4460
        self.epso = epso
        self.epsh = epsh
Peter Eastman's avatar
Peter Eastman committed
4461
4462
4463
4464
4465
        self.rmino = rmino
        self.rminh = rminh
        self.awater = awater
        self.slevy = slevy
        self.dispoff = dispoff
Justin MacCallum's avatar
Justin MacCallum committed
4466
        self.shctd = shctd
4467
4468
4469
4470
4471
4472
4473
4474
4475

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

    @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" />
Justin MacCallum's avatar
Justin MacCallum committed
4476

Peter Eastman's avatar
Peter Eastman committed
4477
        generator = AmoebaWcaDispersionGenerator(element.attrib['epso'],
4478
4479
4480
                                                  element.attrib['epsh'],
                                                  element.attrib['rmino'],
                                                  element.attrib['rminh'],
Justin MacCallum's avatar
Justin MacCallum committed
4481
                                                  element.attrib['awater'],
4482
4483
                                                  element.attrib['slevy'],
                                                  element.attrib['dispoff'],
Justin MacCallum's avatar
Justin MacCallum committed
4484
                                                  element.attrib['shctd'])
4485
        forceField._forces.append(generator)
4486
4487
        generator.params = ForceField._AtomTypeParameters(forceField, 'AmoebaWcaDispersionForce', 'WcaDispersion', ('radius', 'epsilon'))
        generator.params.parseDefinitions(element)
Justin MacCallum's avatar
Justin MacCallum committed
4488

4489
    #=========================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
4490

Peter Eastman's avatar
Peter Eastman committed
4491
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503

        # 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
Justin MacCallum's avatar
Justin MacCallum committed
4504
        # throw error if particle type not available
4505

Peter Eastman's avatar
Peter Eastman committed
4506
4507
4508
4509
4510
4511
4512
4513
        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  ))
4514

4515
4516
4517
        for atom in data.atoms:
            values = self.params.getAtomParameters(atom, data)
            force.addParticle(values[0], values[1])
4518
4519
4520
4521
4522

parsers["AmoebaWcaDispersionForce"] = AmoebaWcaDispersionGenerator.parseElement

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

4523
## @private
4524
class AmoebaGeneralizedKirkwoodGenerator(object):
4525
4526

    """A AmoebaGeneralizedKirkwoodGenerator constructs a AmoebaGeneralizedKirkwoodForce."""
Justin MacCallum's avatar
Justin MacCallum committed
4527

4528
4529
    #=========================================================================================

Peter Eastman's avatar
Peter Eastman committed
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
    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'] = {}
Justin MacCallum's avatar
Justin MacCallum committed
4541
        bondiMap = self.radiusTypeMap['Bondi']
Peter Eastman's avatar
Peter Eastman committed
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
        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
4567
4568
4569

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

Peter Eastman's avatar
Peter Eastman committed
4570
    def getObcShct(self, data, atomIndex):
4571

Peter Eastman's avatar
Peter Eastman committed
4572
        atom = data.atoms[atomIndex]
4573
        atomicNumber = atom.element.atomic_number
Peter Eastman's avatar
Peter Eastman committed
4574
        shct = -1.0
4575
4576

        # shct
Justin MacCallum's avatar
Justin MacCallum committed
4577

Peter Eastman's avatar
Peter Eastman committed
4578
        if (atomicNumber == 1):                 # H(1)
Justin MacCallum's avatar
Justin MacCallum committed
4579
            shct = 0.85
Peter Eastman's avatar
Peter Eastman committed
4580
        elif (atomicNumber == 6):               # C(6)
Justin MacCallum's avatar
Justin MacCallum committed
4581
            shct = 0.72
Peter Eastman's avatar
Peter Eastman committed
4582
        elif (atomicNumber == 7):               # N(7)
Justin MacCallum's avatar
Justin MacCallum committed
4583
            shct = 0.79
Peter Eastman's avatar
Peter Eastman committed
4584
        elif (atomicNumber == 8):               # O(8)
Justin MacCallum's avatar
Justin MacCallum committed
4585
            shct = 0.85
Peter Eastman's avatar
Peter Eastman committed
4586
        elif (atomicNumber == 9):               # F(9)
Justin MacCallum's avatar
Justin MacCallum committed
4587
4588
4589
            shct = 0.88
        elif (atomicNumber == 15):              # P(15)
            shct = 0.86
Peter Eastman's avatar
Peter Eastman committed
4590
        elif (atomicNumber == 16):              # S(16)
4591
            shct = 0.96
Peter Eastman's avatar
Peter Eastman committed
4592
        elif (atomicNumber == 26):              # Fe(26)
4593
4594
            shct = 0.88

Justin MacCallum's avatar
Justin MacCallum committed
4595
        if (shct < 0.0):
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
4596
            raise ValueError( "getObcShct: no GK overlap scale factor for atom %s of %s %d" % (atom.name, atom.residue.name, atom.residue.index) )
Justin MacCallum's avatar
Justin MacCallum committed
4597
4598

        return shct
4599
4600
4601

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

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

Peter Eastman's avatar
Peter Eastman committed
4604
        atom = data.atoms[atomIndex]
4605
        atomicNumber = atom.element.atomic_number
Peter Eastman's avatar
Peter Eastman committed
4606
        radius = -1.0
4607

Peter Eastman's avatar
Peter Eastman committed
4608
        if (atomicNumber == 1):                  # H(1)
Justin MacCallum's avatar
Justin MacCallum committed
4609

Peter Eastman's avatar
Peter Eastman committed
4610
            radius = 0.132
Justin MacCallum's avatar
Justin MacCallum committed
4611

Peter Eastman's avatar
Peter Eastman committed
4612
            if (len(bondedAtomIndices) < 1):
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
4613
                 raise ValueError( "AmoebaGeneralizedKirkwoodGenerator: error getting atom bonded to %s of %s %d " % (atom.name, atom.residue.name, atom.residue.index) )
Justin MacCallum's avatar
Justin MacCallum committed
4614

4615
            for bondedAtomIndex in bondedAtomIndices:
Peter Eastman's avatar
Peter Eastman committed
4616
                bondedAtomAtomicNumber = data.atoms[bondedAtomIndex].element.atomic_number
4617

Peter Eastman's avatar
Peter Eastman committed
4618
            if (bondedAtomAtomicNumber == 7):
4619
                radius = 0.11
Peter Eastman's avatar
Peter Eastman committed
4620
            if (bondedAtomAtomicNumber == 8):
4621
                radius = 0.105
Justin MacCallum's avatar
Justin MacCallum committed
4622

Peter Eastman's avatar
Peter Eastman committed
4623
        elif (atomicNumber == 3):               # Li(3)
4624
            radius = 0.15
Peter Eastman's avatar
Peter Eastman committed
4625
        elif (atomicNumber == 6):               # C(6)
Justin MacCallum's avatar
Justin MacCallum committed
4626

4627
            radius = 0.20
Peter Eastman's avatar
Peter Eastman committed
4628
            if (len(bondedAtomIndices) == 3):
4629
4630
                radius = 0.205

Peter Eastman's avatar
Peter Eastman committed
4631
            elif (len(bondedAtomIndices) == 4):
4632
4633
                for bondedAtomIndex in bondedAtomIndices:
                   bondedAtomAtomicNumber = data.atoms[bondedAtomIndex].element.atomic_number
Peter Eastman's avatar
Peter Eastman committed
4634
                   if (bondedAtomAtomicNumber == 7 or bondedAtomAtomicNumber == 8):
4635
4636
                       radius = 0.175

Peter Eastman's avatar
Peter Eastman committed
4637
        elif (atomicNumber == 7):               # N(7)
4638
            radius = 0.16
Peter Eastman's avatar
Peter Eastman committed
4639
        elif (atomicNumber == 8):               # O(8)
4640
            radius = 0.155
Peter Eastman's avatar
Peter Eastman committed
4641
            if (len(bondedAtomIndices) == 2):
4642
                radius = 0.145
Peter Eastman's avatar
Peter Eastman committed
4643
        elif (atomicNumber == 9):               # F(9)
4644
            radius = 0.154
Justin MacCallum's avatar
Justin MacCallum committed
4645
        elif (atomicNumber == 10):
4646
            radius = 0.146
Justin MacCallum's avatar
Justin MacCallum committed
4647
        elif (atomicNumber == 11):
4648
            radius = 0.209
Justin MacCallum's avatar
Justin MacCallum committed
4649
        elif (atomicNumber == 12):
4650
            radius = 0.179
Justin MacCallum's avatar
Justin MacCallum committed
4651
        elif (atomicNumber == 14):
4652
            radius = 0.189
Justin MacCallum's avatar
Justin MacCallum committed
4653
        elif (atomicNumber == 15):              # P(15)
4654
            radius = 0.196
Peter Eastman's avatar
Peter Eastman committed
4655
        elif (atomicNumber == 16):              # S(16)
4656
            radius = 0.186
Justin MacCallum's avatar
Justin MacCallum committed
4657
        elif (atomicNumber == 17):
4658
            radius = 0.182
Justin MacCallum's avatar
Justin MacCallum committed
4659
        elif (atomicNumber == 18):
4660
            radius = 0.179
Justin MacCallum's avatar
Justin MacCallum committed
4661
        elif (atomicNumber == 19):
4662
            radius = 0.223
Justin MacCallum's avatar
Justin MacCallum committed
4663
        elif (atomicNumber == 20):
4664
            radius = 0.191
Justin MacCallum's avatar
Justin MacCallum committed
4665
        elif (atomicNumber == 35):
4666
            radius = 2.00
Justin MacCallum's avatar
Justin MacCallum committed
4667
        elif (atomicNumber == 36):
4668
            radius = 0.190
Justin MacCallum's avatar
Justin MacCallum committed
4669
        elif (atomicNumber == 37):
4670
            radius = 0.226
Justin MacCallum's avatar
Justin MacCallum committed
4671
        elif (atomicNumber == 53):
4672
            radius = 0.237
Justin MacCallum's avatar
Justin MacCallum committed
4673
        elif (atomicNumber == 54):
4674
            radius = 0.207
Justin MacCallum's avatar
Justin MacCallum committed
4675
        elif (atomicNumber == 55):
4676
            radius = 0.263
Justin MacCallum's avatar
Justin MacCallum committed
4677
        elif (atomicNumber == 56):
4678
4679
            radius = 0.230

Justin MacCallum's avatar
Justin MacCallum committed
4680
        if (radius < 0.0):
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
4681
4682
            outputString = "No GK radius for atom %s of %s %d" % (atom.name, atom.residue.name, atom.residue.index)
            raise ValueError( outputString )
Justin MacCallum's avatar
Justin MacCallum committed
4683

4684
4685
4686
4687
        return radius

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

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

Justin MacCallum's avatar
Justin MacCallum committed
4690
        bondiMap = self.radiusTypeMap['Bondi']
Peter Eastman's avatar
Peter Eastman committed
4691
        atom = data.atoms[atomIndex]
4692
        atomicNumber = atom.element.atomic_number
Justin MacCallum's avatar
Justin MacCallum committed
4693
        if (atomicNumber in bondiMap):
4694
4695
            radius = bondiMap[atomicNumber]
        else:
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
4696
4697
            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 )
Justin MacCallum's avatar
Justin MacCallum committed
4698

4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
        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"  />
Justin MacCallum's avatar
Justin MacCallum committed
4709

Peter Eastman's avatar
Peter Eastman committed
4710
        generator = AmoebaGeneralizedKirkwoodGenerator(forceField, element.attrib['solventDielectric'], element.attrib['soluteDielectric'],
Justin MacCallum's avatar
Justin MacCallum committed
4711
4712
                                                        element.attrib['includeCavityTerm'],
                                                        element.attrib['probeRadius'], element.attrib['surfaceAreaFactor'])
4713
4714
4715
        forceField._forces.append(generator)

    #=========================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
4716

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

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

4722
4723
4724
        # check if AmoebaMultipoleForce exists since charges needed
        # if it has not been created, raise an error

Peter Eastman's avatar
Peter Eastman committed
4725
        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
4726
        amoebaMultipoleForceList = [f for f in existing if type(f) == mm.AmoebaMultipoleForce]
Peter Eastman's avatar
Peter Eastman committed
4727
        if (len(amoebaMultipoleForceList) > 0):
4728
4729
4730
4731
4732
            amoebaMultipoleForce = amoebaMultipoleForceList[0]
        else:
            # call AmoebaMultipoleForceGenerator.createForce() to ensure charges have been set

            for force in self.forceField._forces:
Justin MacCallum's avatar
Justin MacCallum committed
4733
                if (force.__class__.__name__ == 'AmoebaMultipoleGenerator'):
Peter Eastman's avatar
Peter Eastman committed
4734
                    force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
Justin MacCallum's avatar
Justin MacCallum committed
4735

4736
4737
4738
4739
4740
4741
4742
        # 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)
Justin MacCallum's avatar
Justin MacCallum committed
4743

Peter Eastman's avatar
Peter Eastman committed
4744
4745
            if ('solventDielectric' in args):
                force.setSolventDielectric(float(args['solventDielectric']))
4746
            else:
Peter Eastman's avatar
Peter Eastman committed
4747
                force.setSolventDielectric(   float(self.solventDielectric))
4748

Peter Eastman's avatar
Peter Eastman committed
4749
4750
            if ('soluteDielectric' in args):
                force.setSoluteDielectric(float(args['soluteDielectric']))
4751
            else:
Peter Eastman's avatar
Peter Eastman committed
4752
                force.setSoluteDielectric(    float(self.soluteDielectric))
4753

Peter Eastman's avatar
Peter Eastman committed
4754
4755
            if ('includeCavityTerm' in args):
                force.setIncludeCavityTerm(int(args['includeCavityTerm']))
4756
            else:
Peter Eastman's avatar
Peter Eastman committed
4757
               force.setIncludeCavityTerm(   int(self.includeCavityTerm))
4758
4759
4760
4761
4762

        else:
            force = existing[0]

        # add particles to force
Justin MacCallum's avatar
Justin MacCallum committed
4763
        # throw error if particle type not available
4764

Peter Eastman's avatar
Peter Eastman committed
4765
4766
        force.setProbeRadius(         float(self.probeRadius))
        force.setSurfaceAreaFactor(   float(self.surfaceAreaFactor))
4767
4768
4769
4770
4771

        # 1-2

        bonded12ParticleSets = []
        for i in range(len(data.atoms)):
Peter Eastman's avatar
Peter Eastman committed
4772
4773
4774
            bonded12ParticleSet = AmoebaVdwGenerator.getBondedParticleSet(i, data)
            bonded12ParticleSet = set(sorted(bonded12ParticleSet))
            bonded12ParticleSets.append(bonded12ParticleSet)
4775
4776

        radiusType = 'Bondi'
Peter Eastman's avatar
Peter Eastman committed
4777
4778
4779
4780
        for atomIndex in range(0, amoebaMultipoleForce.getNumMultipoles()):
            multipoleParameters = amoebaMultipoleForce.getMultipoleParameters(atomIndex)
            if (radiusType == 'Amoeba'):
                radius = self.getAmoebaTypeRadius(data, bonded12ParticleSets[atomIndex], atomIndex)
4781
            else:
Peter Eastman's avatar
Peter Eastman committed
4782
                radius = self.getBondiTypeRadius(data, bonded12ParticleSets[atomIndex], atomIndex)
4783
4784
            #shct = self.getObcShct(data, atomIndex)
            shct = 0.69
Peter Eastman's avatar
Peter Eastman committed
4785
            force.addParticle(multipoleParameters[0], radius, shct)
4786
4787
4788
4789
4790

parsers["AmoebaGeneralizedKirkwoodForce"] = AmoebaGeneralizedKirkwoodGenerator.parseElement

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

4791
## @private
4792
class AmoebaUreyBradleyGenerator(object):
4793
4794
4795
4796

    #=============================================================================================
    """An AmoebaUreyBradleyGenerator constructs a AmoebaUreyBradleyForce."""
    #=============================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
4797

4798
    def __init__(self):
4799

Peter Eastman's avatar
Peter Eastman committed
4800
4801
4802
        self.types1 = []
        self.types2 = []
        self.types3 = []
4803

Peter Eastman's avatar
Peter Eastman committed
4804
4805
        self.length = []
        self.k = []
4806
4807
4808
4809
4810
4811

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

    @staticmethod
    def parseElement(element, forceField):

4812
        #  <AmoebaUreyBradleyForce>
Justin MacCallum's avatar
Justin MacCallum committed
4813
        #   <UreyBradley class1="74" class2="73" class3="74" k="16003.8" d="0.15537" />
4814

4815
        generator = AmoebaUreyBradleyGenerator()
4816
4817
        forceField._forces.append(generator)
        for bond in element.findall('UreyBradley'):
4818
            types = forceField._findAtomTypes(bond.attrib, 3)
peastman's avatar
peastman committed
4819
            if None not in types:
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829

                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
4830
                                    bond.attrib['class1'], bond.attrib['class2'], bond.attrib['class3'])
Justin MacCallum's avatar
Justin MacCallum committed
4831
4832
                raise ValueError(outputString)

4833
4834
    #=============================================================================================

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

Peter Eastman's avatar
Peter Eastman committed
4837
        existing = [sys.getForce(i) for i in range(sys.getNumForces())]
4838
        existing = [f for f in existing if type(f) == mm.HarmonicBondForce]
4839
4840

        if len(existing) == 0:
4841
            force = mm.HarmonicBondForce()
4842
4843
4844
4845
4846
            sys.addForce(force)
        else:
            force = existing[0]

        for (angle, isConstrained) in zip(data.angles, data.isAngleConstrained):
Peter Eastman's avatar
Peter Eastman committed
4847
            if (isConstrained):
4848
4849
4850
4851
4852
4853
4854
4855
                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
4856
                if ((type1 in types1 and type2 in types2 and type3 in types3) or (type3 in types1 and type2 in types2 and type1 in types3)):
4857
                    force.addBond(angle[0], angle[2], self.length[i], 2*self.k[i])
4858
4859
4860
4861
4862
                    break

parsers["AmoebaUreyBradleyForce"] = AmoebaUreyBradleyGenerator.parseElement

#=============================================================================================
peastman's avatar
peastman committed
4863
4864
4865


## @private
4866
class DrudeGenerator(object):
peastman's avatar
peastman committed
4867
    """A DrudeGenerator constructs a DrudeForce."""
Justin MacCallum's avatar
Justin MacCallum committed
4868

4869
4870
    def __init__(self, forcefield):
        self.ff = forcefield
peastman's avatar
peastman committed
4871
4872
4873
4874
4875
4876
        self.typeMap = {}

    @staticmethod
    def parseElement(element, ff):
        existing = [f for f in ff._forces if isinstance(f, DrudeGenerator)]
        if len(existing) == 0:
4877
4878
            generator = DrudeGenerator(ff)
            ff.registerGenerator(generator)
peastman's avatar
peastman committed
4879
4880
4881
4882
        else:
            # Multiple <DrudeForce> tags were found, probably in different files.  Simply add more types to the existing one.
            generator = existing[0]
        for particle in element.findall('Particle'):
4883
            types = ff._findAtomTypes(particle.attrib, 5)
peastman's avatar
peastman committed
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
            if None not in types[:2]:
                aniso12 = 0.0
                aniso34 = 0.0
                if 'aniso12' in particle.attrib:
                    aniso12 = float(particle.attrib['aniso12'])
                if 'aniso34' in particle.attrib:
                    aniso34 = float(particle.attrib['aniso34'])
                values = (types[1], types[2], types[3], types[4], float(particle.attrib['charge']), float(particle.attrib['polarizability']), aniso12, aniso34, float(particle.attrib['thole']))
                for t in types[0]:
                    generator.typeMap[t] = values
Justin MacCallum's avatar
Justin MacCallum committed
4894

peastman's avatar
peastman committed
4895
4896
4897
4898
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        force = mm.DrudeForce()
        if not any(isinstance(f, mm.NonbondedForce) for f in sys.getForces()):
            raise ValueError('<DrudeForce> must come after <NonbondedForce> in XML file')
Justin MacCallum's avatar
Justin MacCallum committed
4899

peastman's avatar
peastman committed
4900
        # Add Drude particles.
Justin MacCallum's avatar
Justin MacCallum committed
4901

peastman's avatar
peastman committed
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
        for atom in data.atoms:
            t = data.atomType[atom]
            if t in self.typeMap:
                # Find other atoms in the residue that affect the Drude particle.
                p = [-1, -1, -1, -1]
                values = self.typeMap[t]
                for atom2 in atom.residue.atoms():
                    type2 = data.atomType[atom2]
                    if type2 in values[0]:
                        p[0] = atom2.index
                    elif values[1] is not None and type2 in values[1]:
                        p[1] = atom2.index
                    elif values[2] is not None and type2 in values[2]:
                        p[2] = atom2.index
                    elif values[3] is not None and type2 in values[3]:
                        p[3] = atom2.index
4918
4919
                force.addParticle(atom.index, p[0], p[1], p[2], p[3], values[4], values[5], values[6], values[7])
                data.excludeAtomWith[p[0]].append(atom.index)
peastman's avatar
peastman committed
4920
        sys.addForce(force)
Justin MacCallum's avatar
Justin MacCallum committed
4921

peastman's avatar
peastman committed
4922
4923
    def postprocessSystem(self, sys, data, args):
        # For every nonbonded exclusion between Drude particles, add a screened pair.
Justin MacCallum's avatar
Justin MacCallum committed
4924

peastman's avatar
peastman committed
4925
4926
4927
4928
4929
4930
4931
        drude = [f for f in sys.getForces() if isinstance(f, mm.DrudeForce)][0]
        nonbonded = [f for f in sys.getForces() if isinstance(f, mm.NonbondedForce)][0]
        particleMap = {}
        for i in range(drude.getNumParticles()):
            particleMap[drude.getParticleParameters(i)[0]] = i
        for i in range(nonbonded.getNumExceptions()):
            (particle1, particle2, charge, sigma, epsilon) = nonbonded.getExceptionParameters(i)
4932
            if charge._value == 0 and epsilon._value == 0:
peastman's avatar
peastman committed
4933
4934
4935
4936
4937
                # This is an exclusion.
                if particle1 in particleMap and particle2 in particleMap:
                    # It connects two Drude particles, so add a screened pair.
                    drude1 = particleMap[particle1]
                    drude2 = particleMap[particle2]
4938
4939
                    type1 = data.atomType[data.atoms[particle1]]
                    type2 = data.atomType[data.atoms[particle2]]
peastman's avatar
peastman committed
4940
4941
4942
4943
                    thole1 = self.typeMap[type1][8]
                    thole2 = self.typeMap[type2][8]
                    drude.addScreenedPair(drude1, drude2, thole1+thole2)

Justin MacCallum's avatar
Justin MacCallum committed
4944
parsers["DrudeForce"] = DrudeGenerator.parseElement
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
4945
4946

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