forcefield.py 281 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-2024 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
import warnings
41
from math import sqrt, cos
42
from copy import deepcopy
peastman's avatar
peastman committed
43
from collections import defaultdict
44
45
import openmm as mm
import openmm.unit as unit
46
from . import element as elem
47
48
from openmm.app.internal.singleton import Singleton
from openmm.app.internal import compiled
49
from openmm.app.internal.argtracker import ArgTracker
50

51
52
# Directories from which to load built in force fields.

53
54
55
56
57
58
59
_dataDirectories = None

def _getDataDirectories():
    global _dataDirectories
    if _dataDirectories is None:
        _dataDirectories = [os.path.join(os.path.dirname(__file__), 'data')]
        try:
60
61
            from importlib_metadata import entry_points
            for entry in entry_points().select(group='openmm.forcefielddir'):
62
63
                _dataDirectories.append(entry.load()())
        except:
64
            pass # importlib_metadata is not installed
65
    return _dataDirectories
66

67
68
def _convertParameterToNumber(param):
    if unit.is_quantity(param):
69
70
71
        if param.unit.is_compatible(unit.bar):
            return param / unit.bar
        return param.value_in_unit_system(unit.md_unit_system)
72
73
    return float(param)

74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def _parseFunctions(element):
    """Parse the attributes on an XML tag to find any tabulated functions it defines."""
    functions = []
    for function in element.findall('Function'):
        values = [float(x) for x in function.text.split()]
        if 'type' in function.attrib:
            functionType = function.attrib['type']
        else:
            functionType = '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])
89
        if functionType.startswith('Continuous'):
90
91
92
93
94
            periodicStr = function.attrib.get('periodic', 'false').lower()
            if periodicStr in ['true', 'false', 'yes', 'no', '1', '0']:
                params['periodic'] = periodicStr in ['true', 'yes', '1']
            else:
                raise ValueError('ForceField: non-boolean value for periodic attribute in tabulated function definition')
95
96
97
98
99
100
101
        functions.append((function.attrib['name'], functionType, values, params))
    return functions

def _createFunctions(force, functions):
    """Add TabulatedFunctions to a Force based on the information that was recorded by _parseFunctions()."""
    for (name, type, values, params) in functions:
        if type == 'Continuous1D':
102
103
104
105
            force.addTabulatedFunction(
                name,
                mm.Continuous1DFunction(values, params['min'], params['max'], params['periodic']),
            )
106
        elif type == 'Continuous2D':
107
108
109
110
111
112
113
114
115
116
            force.addTabulatedFunction(
                name,
                mm.Continuous2DFunction(
                    params['xsize'], params['ysize'],
                    values,
                    params['xmin'], params['xmax'],
                    params['ymin'], params['ymax'],
                    params['periodic'],
                ),
            )
117
        elif type == 'Continuous3D':
118
119
            force.addTabulatedFunction(
                name,
120
                mm.Continuous3DFunction(
121
122
123
124
125
126
127
128
                    params['xsize'], params['ysize'], params['zsize'],
                    values,
                    params['xmin'], params['xmax'],
                    params['ymin'], params['ymax'],
                    params['zmin'], params['zmax'],
                    params['periodic'],
                ),
            )
129
130
131
132
133
        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':
134
            force.addTabulatedFunction(name, mm.Discrete3DFunction(params['xsize'], params['ysize'], params['zsize'], values))
135

136
137
# Enumerated values for nonbonded method

138
class NoCutoff(Singleton):
139
140
141
142
    def __repr__(self):
        return 'NoCutoff'
NoCutoff = NoCutoff()

143
class CutoffNonPeriodic(Singleton):
144
145
146
147
    def __repr__(self):
        return 'CutoffNonPeriodic'
CutoffNonPeriodic = CutoffNonPeriodic()

148
class CutoffPeriodic(Singleton):
149
150
151
152
    def __repr__(self):
        return 'CutoffPeriodic'
CutoffPeriodic = CutoffPeriodic()

153
class Ewald(Singleton):
154
155
156
157
    def __repr__(self):
        return 'Ewald'
Ewald = Ewald()

158
class PME(Singleton):
159
160
161
    def __repr__(self):
        return 'PME'
PME = PME()
162

Peter Eastman's avatar
Peter Eastman committed
163
164
165
166
167
class LJPME(Singleton):
    def __repr__(self):
        return 'LJPME'
LJPME = LJPME()

168
169
# Enumerated values for constraint type

170
class HBonds(Singleton):
171
172
173
174
    def __repr__(self):
        return 'HBonds'
HBonds = HBonds()

175
class AllBonds(Singleton):
176
177
178
179
    def __repr__(self):
        return 'AllBonds'
AllBonds = AllBonds()

180
class HAngles(Singleton):
181
182
183
    def __repr__(self):
        return 'HAngles'
HAngles = HAngles()
184
185
186
187
188
189
190
191
192
193

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

Robert McGibbon's avatar
Robert McGibbon committed
195
196
197
198
199
200
201
202
        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.
203
204
205
        """
        self._atomTypes = {}
        self._templates = {}
206
207
        self._patches = {}
        self._templatePatches = {}
208
        self._templateSignatures = {None:[]}
209
        self._atomClasses = {'':set()}
210
        self._forces = []
211
        self._scripts = []
212
        self._templateMatchers = []
213
        self._templateGenerators = []
214
        self.loadFile(files)
215

216
    def loadFile(self, files, resname_prefix=''):
217
        """Load an XML file and add the definitions from it to this ForceField.
218

Robert McGibbon's avatar
Robert McGibbon committed
219
220
        Parameters
        ----------
221
222
223
        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
224
225
226
            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.
227
228
229
        prefix : string
            An optional string to be prepended to each residue name found in the
            loaded files.
peastman's avatar
peastman committed
230
        """
231

232
233
234
235
        if isinstance(files, tuple):
            files = list(files)
        else:
            files = [files]
236
237
238

        trees = []

239
240
241
        i = 0
        while i < len(files):
            file = files[i]
242
            tree = None
243
244
245
246
            try:
                # this handles either filenames or open file-like objects
                tree = etree.parse(file)
            except IOError:
247
                for dataDir in _getDataDirectories():
248
249
250
251
                    f = os.path.join(dataDir, file)
                    if os.path.isfile(f):
                        tree = etree.parse(f)
                        break
252
253
254
255
256
257
258
259
260
261
262
            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)
263
264
            if tree is None:
                raise ValueError('Could not locate file "%s"' % file)
265
266

            trees.append(tree)
267
            i += 1
268

269
            # Process includes in this file.
270

271
272
            if isinstance(file, str):
                parentDir = os.path.dirname(file)
peastman's avatar
peastman committed
273
274
            else:
                parentDir = ''
peastman's avatar
peastman committed
275
276
            for included in tree.getroot().findall('Include'):
                includeFile = included.attrib['file']
peastman's avatar
peastman committed
277
278
279
                joined = os.path.join(parentDir, includeFile)
                if os.path.isfile(joined):
                    includeFile = joined
280
281
                if includeFile not in files:
                    files.append(includeFile)
peastman's avatar
peastman committed
282
283
284

        # Load the atom types.

285
286
287
288
        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
289
290
291

        # Load the residue templates.

292
293
294
        for tree in trees:
            if tree.getroot().find('Residues') is not None:
                for residue in tree.getroot().find('Residues').findall('Residue'):
295
                    resName = resname_prefix+residue.attrib['name']
296
                    template = ForceField._TemplateData(resName)
297
298
                    if 'override' in residue.attrib:
                        template.overrideLevel = int(residue.attrib['override'])
299
300
                    if 'rigidWater' in residue.attrib:
                        template.rigidWater = (residue.attrib['rigidWater'].lower() == 'true')
301
302
                    for key in residue.attrib:
                        template.attributes[key] = residue.attrib[key]
303
304
                    atomIndices = template.atomIndices
                    for ia, atom in enumerate(residue.findall('Atom')):
305
                        params = {}
306
307
308
309
                        for key in atom.attrib:
                            if key not in ('name', 'type'):
                                params[key] = _convertParameterToNumber(atom.attrib[key])
                        atomName = atom.attrib['name']
310
311
                        if atomName in atomIndices:
                            raise ValueError('Residue '+resName+' contains multiple atoms named '+atomName)
312
                        typeName = atom.attrib['type']
313
                        atomIndices[atomName] = ia
314
315
316
317
318
319
320
321
322
323
324
325
326
                        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']))
327
                    for patch in residue.findall('AllowPatch'):
328
                        patchName = patch.attrib['name']
329
330
                        if ':' in patchName:
                            colonIndex = patchName.find(':')
331
332
333
                            self.registerTemplatePatch(resName, patchName[:colonIndex], int(patchName[colonIndex+1:])-1)
                        else:
                            self.registerTemplatePatch(resName, patchName, 0)
334
                    self.registerResidueTemplate(template)
peastman's avatar
peastman committed
335

336
        # Load the patch definitions.
337
338
339
340
341
342
343
344
345
346

        for tree in trees:
            if tree.getroot().find('Patches') is not None:
                for patch in tree.getroot().find('Patches').findall('Patch'):
                    patchName = patch.attrib['name']
                    if 'residues' in patch.attrib:
                        numResidues = int(patch.attrib['residues'])
                    else:
                        numResidues = 1
                    patchData = ForceField._PatchData(patchName, numResidues)
347
348
                    for key in patch.attrib:
                        patchData.attributes[key] = patch.attrib[key]
349
350
351
352
353
354
                    for atom in patch.findall('AddAtom'):
                        params = {}
                        for key in atom.attrib:
                            if key not in ('name', 'type'):
                                params[key] = _convertParameterToNumber(atom.attrib[key])
                        atomName = atom.attrib['name']
peastman's avatar
peastman committed
355
                        if atomName in patchData.allAtomNames:
356
                            raise ValueError('Patch '+patchName+' contains multiple atoms named '+atomName)
peastman's avatar
peastman committed
357
                        patchData.allAtomNames.add(atomName)
358
359
                        atomDescription = ForceField._PatchAtomData(atomName)
                        typeName = atom.attrib['type']
360
                        patchData.addedAtoms[atomDescription.residue].append(ForceField._TemplateAtomData(atomDescription.name, typeName, self._atomTypes[typeName].element, params))
361
362
363
364
365
366
                    for atom in patch.findall('ChangeAtom'):
                        params = {}
                        for key in atom.attrib:
                            if key not in ('name', 'type'):
                                params[key] = _convertParameterToNumber(atom.attrib[key])
                        atomName = atom.attrib['name']
peastman's avatar
peastman committed
367
                        if atomName in patchData.allAtomNames:
368
                            raise ValueError('Patch '+patchName+' contains multiple atoms named '+atomName)
peastman's avatar
peastman committed
369
                        patchData.allAtomNames.add(atomName)
370
371
                        atomDescription = ForceField._PatchAtomData(atomName)
                        typeName = atom.attrib['type']
372
                        patchData.changedAtoms[atomDescription.residue].append(ForceField._TemplateAtomData(atomDescription.name, typeName, self._atomTypes[typeName].element, params))
373
374
                    for atom in patch.findall('RemoveAtom'):
                        atomName = atom.attrib['name']
peastman's avatar
peastman committed
375
                        if atomName in patchData.allAtomNames:
376
                            raise ValueError('Patch '+patchName+' contains multiple atoms named '+atomName)
peastman's avatar
peastman committed
377
                        patchData.allAtomNames.add(atomName)
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
                        atomDescription = ForceField._PatchAtomData(atomName)
                        patchData.deletedAtoms.append(atomDescription)
                    for bond in patch.findall('AddBond'):
                        atom1 = ForceField._PatchAtomData(bond.attrib['atomName1'])
                        atom2 = ForceField._PatchAtomData(bond.attrib['atomName2'])
                        patchData.addedBonds.append((atom1, atom2))
                    for bond in patch.findall('RemoveBond'):
                        atom1 = ForceField._PatchAtomData(bond.attrib['atomName1'])
                        atom2 = ForceField._PatchAtomData(bond.attrib['atomName2'])
                        patchData.deletedBonds.append((atom1, atom2))
                    for bond in patch.findall('AddExternalBond'):
                        atom = ForceField._PatchAtomData(bond.attrib['atomName'])
                        patchData.addedExternalBonds.append(atom)
                    for bond in patch.findall('RemoveExternalBond'):
                        atom = ForceField._PatchAtomData(bond.attrib['atomName'])
                        patchData.deletedExternalBonds.append(atom)
394
395
396
                    # The following three lines are only correct for single residue patches.  Multi-residue patches with
                    # virtual sites currently don't work correctly.  See issue #2848.
                    atomIndices = dict((atom.name, i) for i, atom in enumerate(patchData.addedAtoms[0]+patchData.changedAtoms[0]))
peastman's avatar
peastman committed
397
                    for site in patch.findall('VirtualSite'):
398
                        patchData.virtualSites[0].append(ForceField._VirtualSiteData(site, atomIndices))
399
400
401
402
403
404
405
406
407
                    for residue in patch.findall('ApplyToResidue'):
                        name = residue.attrib['name']
                        if ':' in name:
                            colonIndex = name.find(':')
                            self.registerTemplatePatch(name[colonIndex+1:], patchName, int(name[:colonIndex])-1)
                        else:
                            self.registerTemplatePatch(name, patchName, 0)
                    self.registerPatch(patchData)

peastman's avatar
peastman committed
408
409
        # Load force definitions

410
411
412
413
        for tree in trees:
            for child in tree.getroot():
                if child.tag in parsers:
                    parsers[child.tag](child, self)
peastman's avatar
peastman committed
414
415
416

        # Load scripts

417
418
419
        for tree in trees:
            for node in tree.getroot().findall('Script'):
                self.registerScript(node.text)
420

421
422
423
424
425
426
        # Execute initialization scripts.

        for tree in trees:
            for node in tree.getroot().findall('InitializationScript'):
                exec(node.text, locals())

427
428
429
    def getGenerators(self):
        """Get the list of all registered generators."""
        return self._forces
430

431
432
433
    def registerGenerator(self, generator):
        """Register a new generator."""
        self._forces.append(generator)
434

435
436
437
438
439
440
441
442
443
444
445
446
    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)
447
        self._atomTypes[name] = ForceField._AtomType(name, atomClass, mass, element)
448
449
450
451
452
453
454
        if atomClass in self._atomClasses:
            typeSet = self._atomClasses[atomClass]
        else:
            typeSet = set()
            self._atomClasses[atomClass] = typeSet
        typeSet.add(name)
        self._atomClasses[''].add(name)
455

456
457
    def registerResidueTemplate(self, template):
        """Register a new residue template."""
458
459
        if template.name in self._templates:
            # There is already a template with this name, so check the override levels.
460

461
462
463
464
465
466
467
468
469
470
471
            existingTemplate = self._templates[template.name]
            if template.overrideLevel < existingTemplate.overrideLevel:
                # The existing one takes precedence, so just return.
                return
            if template.overrideLevel > existingTemplate.overrideLevel:
                # We need to delete the existing template.
                del self._templates[template.name]
                existingSignature = _createResidueSignature([atom.element for atom in existingTemplate.atoms])
                self._templateSignatures[existingSignature].remove(existingTemplate)
            else:
                raise ValueError('Residue template %s with the same override level %d already exists.' % (template.name, template.overrideLevel))
472

473
        # Register the template.
474

475
476
477
        self._templates[template.name] = template
        signature = _createResidueSignature([atom.element for atom in template.atoms])
        if signature in self._templateSignatures:
478
            self._templateSignatures[signature].append(template)
479
480
        else:
            self._templateSignatures[signature] = [template]
481

482
483
    def registerPatch(self, patch):
        """Register a new patch that can be applied to templates."""
484
        patch.index = len(self._patches)
485
        self._patches[patch.name] = patch
486

487
488
489
    def registerTemplatePatch(self, residue, patch, patchResidueIndex):
        """Register that a particular patch can be used with a particular residue."""
        if residue not in self._templatePatches:
490
491
            self._templatePatches[residue] = set()
        self._templatePatches[residue].add((patch, patchResidueIndex))
492

493
494
495
    def registerScript(self, script):
        """Register a new script to be executed after building the System."""
        self._scripts.append(script)
496

497
498
499
500
    def registerTemplateMatcher(self, matcher):
        """Register an object that can override the default logic for matching templates to residues.

        A template matcher is a callable object that can be invoked as::
501

Peter Eastman's avatar
Peter Eastman committed
502
            template = f(forcefield, residue, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)
503

Peter Eastman's avatar
Peter Eastman committed
504
505
506
507
508
        where ``forcefield`` is the ForceField invoking it, ``residue`` is an openmm.app.Residue object,
        ``bondedToAtom[i]`` is the set of atoms bonded to atom index i, and ``ignoreExternalBonds`` and
        ``ignoreExtraParticles`` indicate whether external bonds and extra particules should be considered
        in matching templates.

509
510
511
        It should return a _TemplateData object that matches the residue.  Alternatively it may return
        None, in which case the standard logic will be used to find a template for the residue.

512
        .. CAUTION:: This method is experimental, and its API is subject to change.
513
514
        """
        self._templateMatchers.append(matcher)
515

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
516
    def registerTemplateGenerator(self, generator):
517
518
519
520
        """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
521
522
        .. CAUTION:: This method is experimental, and its API is subject to change.

523
524
        Parameters
        ----------
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
525
        generator : function
526
527
            A function that will be called when a residue is encountered that does not match an existing forcefield template.

John Chodera's avatar
John Chodera committed
528
        When a residue without a template is encountered, the ``generator`` function is called with:
529

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
530
531
        ::
           success = generator(forcefield, residue)
532

533
        where ``forcefield`` is the calling ``ForceField`` object and ``residue`` is a openmm.app.topology.Residue object.
John Chodera's avatar
John Chodera committed
534
535

        ``generator`` must conform to the following API:
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
536
537

        ::
John Chodera's avatar
John Chodera committed
538
539
540
           generator API

           Parameters
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
541
           ----------
542
           forcefield : openmm.app.ForceField
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
543
               The ForceField object to which residue templates and/or parameters are to be added.
544
           residue : openmm.app.Topology.Residue
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
545
               The residue topology for which a template is to be generated.
546

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
547
548
549
550
551
           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`.
552

John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
553
554
555
556
557
           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.
558
559

        """
560
        self._templateGenerators.append(generator)
561

562
    def _findAtomTypes(self, attrib, num):
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
        """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.

        """
578
579
580
581
582
583
584
        types = []
        for i in range(num):
            if num == 1:
                suffix = ''
            else:
                suffix = str(i+1)
            classAttrib = 'class'+suffix
585
            typeAttrib = 'type'+suffix
586
            if classAttrib in attrib:
587
                if typeAttrib in attrib:
588
                    raise ValueError('Specified both a type and a class for the same atom: '+str(attrib))
589
                if attrib[classAttrib] not in self._atomClasses:
peastman's avatar
peastman committed
590
591
592
                    types.append(None) # Unknown atom class
                else:
                    types.append(self._atomClasses[attrib[classAttrib]])
593
594
            elif typeAttrib in attrib:
                if attrib[typeAttrib] == '':
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
595
                    types.append(self._atomClasses[''])
596
                elif attrib[typeAttrib] not in self._atomTypes:
peastman's avatar
peastman committed
597
598
599
                    types.append(None) # Unknown atom type
                else:
                    types.append([attrib[typeAttrib]])
600
601
            else:
                types.append(None) # Unknown atom type
602
603
        return types

604
    def _parseTorsion(self, attrib):
605
        """Parse the node defining a torsion."""
606
        types = self._findAtomTypes(attrib, 4)
peastman's avatar
peastman committed
607
        if None in types:
608
609
610
611
612
            return None
        torsion = PeriodicTorsion(types)
        index = 1
        while 'phase%d'%index in attrib:
            torsion.periodicity.append(int(attrib['periodicity%d'%index]))
613
614
            torsion.phase.append(_convertParameterToNumber(attrib['phase%d'%index]))
            torsion.k.append(_convertParameterToNumber(attrib['k%d'%index]))
615
            index += 1
Justin MacCallum's avatar
Justin MacCallum committed
616
617
        return torsion

618
    class _SystemData(object):
619
        """Inner class used to encapsulate data about the system being created."""
620
        def __init__(self, topology):
621
            self.atomType = {}
622
            self.atomParameters = {}
623
            self.atomTemplateIndexes = {}
624
            self.atoms = list(topology.atoms())
Peter Eastman's avatar
Peter Eastman committed
625
            self.excludeAtomWith = [[] for _ in self.atoms]
626
            self.virtualSites = {}
627
            self.bonds = [ForceField._BondData(bond[0].index, bond[1].index) for bond in topology.bonds()]
628
629
630
            self.angles = []
            self.propers = []
            self.impropers = []
Peter Eastman's avatar
Peter Eastman committed
631
            self.atomBonds = [[] for _ in self.atoms]
632
            self.isAngleConstrained = []
633
            self.constraints = {}
Peter Eastman's avatar
Peter Eastman committed
634
            self.bondedToAtom = [set() for _ in self.atoms]
635

636
            # Record which atoms are bonded to each other atom
637

638
639
640
641
642
643
            for i in range(len(self.bonds)):
                bond = self.bonds[i]
                self.bondedToAtom[bond.atom1].add(bond.atom2)
                self.bondedToAtom[bond.atom2].add(bond.atom1)
                self.atomBonds[bond.atom1].append(i)
                self.atomBonds[bond.atom2].append(i)
644
            self.bondedToAtom = [sorted(b) for b in self.bondedToAtom]
645
646
647
648
649

        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:
650
                if self.constraints[key] != distance:
651
652
653
654
                    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)
655

656
657
658
659
660
661
        def recordMatchedAtomParameters(self, residue, template, matches):
            """Record parameters for atoms based on having matched a residue to a template."""
            matchAtoms = dict(zip(matches, residue.atoms()))
            for atom, match in zip(residue.atoms(), matches):
                self.atomType[atom] = template.atoms[match].type
                self.atomParameters[atom] = template.atoms[match].parameters
662
                self.atomTemplateIndexes[atom] = match
663
664
665
                for site in template.virtualSites:
                    if match == site.index:
                        self.virtualSites[atom] = (site, [matchAtoms[i].index for i in site.atoms], matchAtoms[site.excludeWith].index)
666

667
    class _TemplateData(object):
668
669
670
671
        """Inner class used to encapsulate data about a residue template definition."""
        def __init__(self, name):
            self.name = name
            self.atoms = []
672
            self.atomIndices = {}
673
            self.virtualSites = []
674
675
            self.bonds = []
            self.externalBonds = []
676
            self.overrideLevel = 0
677
            self.rigidWater = True
678
            self.attributes = {}
679

680
681
        def getAtomIndexByName(self, atom_name):
            """Look up an atom index by atom name, providing a helpful error message if not found."""
682
683
684
            index = self.atomIndices.get(atom_name, None)
            if index is not None:
                return index
685
686

            # Provide a helpful error message if atom name not found.
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
687
            msg =  "Atom name '%s' not found in residue template '%s'.\n" % (atom_name, self.name)
688
            msg += "Possible atom names are: %s" % str(list(map(lambda x: x.name, self.atoms)))
689
690
            raise ValueError(msg)

691
692
        def addAtom(self, atom):
            self.atoms.append(atom)
693
            self.atomIndices[atom.name] = len(self.atoms)-1
694

695
        def addBond(self, atom1, atom2):
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
696
            """Add a bond between two atoms in a template given their indices in the template."""
697
698
699
            self.bonds.append((atom1, atom2))
            self.atoms[atom1].bondedTo.append(atom2)
            self.atoms[atom2].bondedTo.append(atom1)
700

701
        def addBondByName(self, atom1_name, atom2_name):
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
702
            """Add a bond between two atoms in a template given their atom names."""
703
704
705
706
707
            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
708
            """Designate that an atom in a residue template has an external bond, using atom index within template."""
709
710
711
712
            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
713
            """Designate that an atom in a residue template has an external bond, using atom name within template."""
714
715
716
            atom = self.getAtomIndexByName(atom_name)
            self.addExternalBond(atom)

peastman's avatar
peastman committed
717
718
        def areParametersIdentical(self, template2, matchingAtoms, matchingAtoms2):
            """Get whether this template and another one both assign identical atom types and parameters to all atoms.
John Chodera's avatar
John Chodera committed
719

peastman's avatar
peastman committed
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
            Parameters
            ----------
            template2: _TemplateData
                the template to compare this one to
            matchingAtoms: list
                the indices of atoms in this template that atoms of the residue are matched to
            matchingAtoms2: list
                the indices of atoms in template2 that atoms of the residue are matched to
            """
            atoms1 = [self.atoms[m] for m in matchingAtoms]
            atoms2 = [template2.atoms[m] for m in matchingAtoms2]
            if any(a1.type != a2.type or a1.parameters != a2.parameters for a1,a2 in zip(atoms1, atoms2)):
                return False
            # Properly comparing virtual sites really needs a much more complicated analysis.  This simple check
            # could easily fail for templates containing vsites, even if they're actually identical.  Since we
            # currently have no force fields that include both patches and vsites, I'm not going to worry about it now.
            if self.virtualSites != template2.virtualSites:
                return False
            return True

740
    class _TemplateAtomData(object):
741
        """Inner class used to encapsulate data about an atom in a residue template definition."""
742
        def __init__(self, name, type, element, parameters={}):
743
744
745
            self.name = name
            self.type = type
            self.element = element
746
            self.parameters = parameters
747
748
749
            self.bondedTo = []
            self.externalBonds = 0

750
    class _BondData(object):
751
752
753
754
755
756
        """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
757

758
    class _VirtualSiteData(object):
759
        """Inner class used to encapsulate data about a virtual site."""
760
        def __init__(self, node, atomIndices):
761
762
763
            attrib = node.attrib
            self.type = attrib['type']
            if self.type == 'average2':
764
                numAtoms = 2
765
766
                self.weights = [float(attrib['weight1']), float(attrib['weight2'])]
            elif self.type == 'average3':
767
                numAtoms = 3
768
769
                self.weights = [float(attrib['weight1']), float(attrib['weight2']), float(attrib['weight3'])]
            elif self.type == 'outOfPlane':
770
                numAtoms = 3
771
                self.weights = [float(attrib['weight12']), float(attrib['weight13']), float(attrib['weightCross'])]
772
            elif self.type == 'localCoords':
773
774
775
776
777
778
779
780
781
                numAtoms = 0
                self.originWeights = []
                self.xWeights = []
                self.yWeights = []
                while ('wo%d' % (numAtoms+1)) in attrib:
                    numAtoms += 1
                    self.originWeights.append(float(attrib['wo%d' % numAtoms]))
                    self.xWeights.append(float(attrib['wx%d' % numAtoms]))
                    self.yWeights.append(float(attrib['wy%d' % numAtoms]))
782
                self.localPos = [float(attrib['p1']), float(attrib['p2']), float(attrib['p3'])]
783
784
            else:
                raise ValueError('Unknown virtual site type: %s' % self.type)
785
786
787
788
789
790
            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)]
791
792
793
794
            if 'excludeWith' in attrib:
                self.excludeWith = int(attrib['excludeWith'])
            else:
                self.excludeWith = self.atoms[0]
795

796
797
798
799
800
801
802
803
804
805
806
        def __eq__(self, other):
            if not isinstance(other, ForceField._VirtualSiteData):
                return False
            if self.type != other.type or self.index != other.index or self.atoms != other.atoms or self.excludeWith != other.excludeWith:
                return False
            if self.type in ('average2', 'average3', 'outOfPlane'):
                return self.weights == other.weights
            elif self.type == 'localCoords':
                return self.originWeights == other.originWeights and self.xWeights == other.xWeights and self.yWeights == other.yWeights and self.localPos == other.localPos
            return False

807
808
809
810
811
    class _PatchData(object):
        """Inner class used to encapsulate data about a patch definition."""
        def __init__(self, name, numResidues):
            self.name = name
            self.numResidues = numResidues
812
813
            self.addedAtoms = [[] for i in range(numResidues)]
            self.changedAtoms = [[] for i in range(numResidues)]
814
815
816
817
818
            self.deletedAtoms = []
            self.addedBonds = []
            self.deletedBonds = []
            self.addedExternalBonds = []
            self.deletedExternalBonds = []
peastman's avatar
peastman committed
819
            self.allAtomNames = set()
peastman's avatar
peastman committed
820
            self.virtualSites = [[] for i in range(numResidues)]
821
            self.attributes = {}
822
823
824
825
            self.index = None

        def __lt__(self, other):
            return self.index < other.index
826

827
828
829
830
        def createPatchedTemplates(self, templates):
            """Apply this patch to a set of templates, creating new modified ones."""
            if len(templates) != self.numResidues:
                raise ValueError("Patch '%s' expected %d templates, received %d", (self.name, self.numResidues, len(templates)))
831

832
            # Construct a new version of each template.
833

834
835
836
837
            newTemplates = []
            for index, template in enumerate(templates):
                newTemplate = ForceField._TemplateData("%s-%s" % (template.name, self.name))
                newTemplates.append(newTemplate)
838

839
                # Build the list of atoms in it.
840

841
842
                for atom in template.atoms:
                    if not any(deleted.name == atom.name and deleted.residue == index for deleted in self.deletedAtoms):
843
                        newTemplate.addAtom(ForceField._TemplateAtomData(atom.name, atom.type, atom.element, atom.parameters))
844
                for atom in self.addedAtoms[index]:
845
846
                    if any(a.name == atom.name for a in newTemplate.atoms):
                        raise ValueError("Patch '%s' adds an atom with the same name as an existing atom: %s" % (self.name, atom.name))
847
                    newTemplate.addAtom(ForceField._TemplateAtomData(atom.name, atom.type, atom.element, atom.parameters))
848
849
850
851
852
                oldAtomIndex = dict([(atom.name, i) for i, atom in enumerate(template.atoms)])
                newAtomIndex = dict([(atom.name, i) for i, atom in enumerate(newTemplate.atoms)])
                for atom in self.changedAtoms[index]:
                    if atom.name not in newAtomIndex:
                        raise ValueError("Patch '%s' modifies nonexistent atom '%s' in template '%s'" % (self.name, atom.name, template.name))
853
                    newTemplate.atoms[newAtomIndex[atom.name]] = ForceField._TemplateAtomData(atom.name, atom.type, atom.element, atom.parameters)
854

855
                # Copy over the virtual sites, translating the atom indices.
856

857
858
859
860
861
862
863
                indexMap = dict([(oldAtomIndex[name], newAtomIndex[name]) for name in newAtomIndex if name in oldAtomIndex])
                for site in template.virtualSites:
                    if site.index in indexMap and all(i in indexMap for i in site.atoms):
                        newSite = deepcopy(site)
                        newSite.index = indexMap[site.index]
                        newSite.atoms = [indexMap[i] for i in site.atoms]
                        newTemplate.virtualSites.append(newSite)
864

865
                # Build the lists of bonds and external bonds.
866

867
868
869
870
871
                atomMap = dict([(template.atoms[i], indexMap[i]) for i in indexMap])
                deletedBonds = [(atom1.name, atom2.name) for atom1, atom2 in self.deletedBonds if atom1.residue == index and atom2.residue == index]
                for atom1, atom2 in template.bonds:
                    a1 = template.atoms[atom1]
                    a2 = template.atoms[atom2]
872
                    if a1 in atomMap and a2 in atomMap and (a1.name, a2.name) not in deletedBonds and (a2.name, a1.name) not in deletedBonds:
873
874
875
876
                        newTemplate.addBond(atomMap[a1], atomMap[a2])
                deletedExternalBonds = [atom.name for atom in self.deletedExternalBonds if atom.residue == index]
                for atom in template.externalBonds:
                    if template.atoms[atom].name not in deletedExternalBonds:
877
                        newTemplate.addExternalBond(indexMap[atom])
878
879
880
881
882
883
884
885
886
                for atom1, atom2 in self.addedBonds:
                    if atom1.residue == index and atom2.residue == index:
                        newTemplate.addBondByName(atom1.name, atom2.name)
                    elif atom1.residue == index:
                        newTemplate.addExternalBondByName(atom1.name)
                    elif atom2.residue == index:
                        newTemplate.addExternalBondByName(atom2.name)
                for atom in self.addedExternalBonds:
                    newTemplate.addExternalBondByName(atom.name)
peastman's avatar
peastman committed
887
888
889
890
891
892
893
894

                # Add new virtual sites.

                indexMap = dict((i, newAtomIndex[atom.name]) for i, atom in enumerate(self.addedAtoms[index]+self.changedAtoms[index]))
                for site in self.virtualSites[index]:
                    newSite = deepcopy(site)
                    newSite.index = indexMap[site.index]
                    newSite.atoms = [indexMap[i] for i in site.atoms]
895
                    newSite.excludeWith = indexMap[site.excludeWith]
peastman's avatar
peastman committed
896
897
                    newTemplate.virtualSites = [site for site in newTemplate.virtualSites if site.index != newSite.index]
                    newTemplate.virtualSites.append(newSite)
898
            return newTemplates
899

900
901
902
903
904
905
906
907
908
909
910
    class _PatchAtomData(object):
        """Inner class used to encapsulate data about an atom in a patch definition."""
        def __init__(self, description):
            if ':' in description:
                colonIndex = description.find(':')
                self.residue = int(description[:colonIndex])-1
                self.name = description[colonIndex+1:]
            else:
                self.residue = 0
                self.name = description

911
    class _AtomType(object):
912
913
914
915
916
917
918
        """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

919
    class _AtomTypeParameters(object):
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
        """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))


990
991
    def _getResidueTemplateMatches(self, res, bondedToAtom, templateSignatures=None, ignoreExternalBonds=False, ignoreExtraParticles=False):
        """Return the templates that match a residue, or None if none are found.
992
993
994
995
996

        Parameters
        ----------
        res : Topology.Residue
            The residue for which template matches are to be retrieved.
997
998
        bondedToAtom : list of set of int
            bondedToAtom[i] is the set of atoms bonded to atom index i
999
1000
1001

        Returns
        -------
peastman's avatar
peastman committed
1002
        template : _TemplateData
1003
1004
1005
1006
1007
1008
1009
1010
            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
1011
        for matcher in self._templateMatchers:
Peter Eastman's avatar
Peter Eastman committed
1012
            template = matcher(self, res, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)
1013
1014
1015
            if template is not None:
                match = compiled.matchResidueToTemplate(res, template, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)
                if match is None:
Peter Eastman's avatar
Peter Eastman committed
1016
                    raise ValueError('A custom template matcher returned a template for residue %d (%s), but it does not match the residue.' % (res.index, res.name))
1017
                return [template, match]
1018
1019
        if templateSignatures is None:
            templateSignatures = self._templateSignatures
1020
        signature = _createResidueSignature([atom.element for atom in res.atoms()])
1021
        if signature in templateSignatures:
1022
            allMatches = []
1023
            for t in templateSignatures[signature]:
1024
                match = compiled.matchResidueToTemplate(res, t, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)
1025
1026
1027
1028
1029
1030
                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:
1031
1032
1033
                # We found multiple matches.  This is OK if and only if they assign identical types and parameters to all atoms.
                t1, m1 = allMatches[0]
                for t2, m2 in allMatches[1:]:
peastman's avatar
peastman committed
1034
1035
                    if not t1.areParametersIdentical(t2, m1, m2):
                        raise Exception('Multiple non-identical matching templates found for residue %d (%s): %s.' % (res.index+1, res.name, ', '.join(match[0].name for match in allMatches)))
1036
1037
                template = allMatches[0][0]
                matches = allMatches[0][1]
1038
1039
        return [template, matches]

1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
    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
        -------
1050
1051
        bondedToAtom : list of list of int
            bondedToAtom[index] is the list of atom indices bonded to atom `index`
1052
1053

        """
Peter Eastman's avatar
Peter Eastman committed
1054
        bondedToAtom = [set() for _ in topology.atoms()]
1055
1056
1057
        for (atom1, atom2) in topology.bonds():
            bondedToAtom[atom1.index].add(atom2.index)
            bondedToAtom[atom2.index].add(atom1.index)
1058
        bondedToAtom = [sorted(b) for b in bondedToAtom]
1059
        return bondedToAtom
1060

1061
    def getUnmatchedResidues(self, topology, residueTemplates=dict()):
1062
1063
        """Return a list of Residue objects from specified topology for which no forcefield templates are available.

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

1066
1067
1068
        Parameters
        ----------
        topology : Topology
1069
            The Topology whose residues are to be checked against the forcefield residue templates.
1070
1071
1072
1073
1074
1075
        residueTemplates : dict=dict()
            Specifies which template to use for particular residues.  The keys should be Residue
            objects from the Topology, and the values should be the names of the templates to
            use for them.  This is useful when a ForceField contains multiple templates that
            can match the same residue (e.g Fe2+ and Fe3+ templates in the ForceField for a
            monoatomic iron ion in the Topology).
1076
1077
1078
1079

        Returns
        -------
        unmatched_residues : list of Residue
1080
            List of Residue objects from `topology` for which no forcefield residue templates are available.
1081
1082
1083
1084
1085
            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.
1086
        bondedToAtom = self._buildBondedToAtomList(topology)
1087
        unmatched_residues = list() # list of unmatched residues
1088
        for res in topology.residues():
1089
1090
1091
1092
1093
1094
1095
            if res in residueTemplates:
                # Make sure the specified template matches.
                template = self._templates[residueTemplates[res]]
                matches = compiled.matchResidueToTemplate(res, template, bondedToAtom, False, False)
            else:
                # Attempt to match one of the existing templates.
                [template, matches] = self._getResidueTemplateMatches(res, bondedToAtom)
1096
1097
1098
            if matches is None:
                # No existing templates match.
                unmatched_residues.append(res)
1099
1100
1101

        return unmatched_residues

1102
    def getMatchingTemplates(self, topology, ignoreExternalBonds=False):
1103
1104
1105
1106
1107
1108
1109
1110
        """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.
1111
1112
        ignoreExternalBonds : bool=False
            If true, ignore external bonds when matching residues to templates.
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
        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
1124
        for residue in topology.residues():
1125
            # Attempt to match one of the existing templates.
1126
            [template, matches] = self._getResidueTemplateMatches(residue, bondedToAtom, ignoreExternalBonds=ignoreExternalBonds)
1127
1128
            # Raise an exception if we have found no templates that match.
            if matches is None:
1129
                raise ValueError('No template found for chainid <%s> resid <%s> resname <%s> (residue index within topology %d).\n%s' % (residue.chain.id, residue.id, residue.name, residue.index, _findMatchErrors(self, residue)))
1130
1131
1132
1133
1134
            else:
                templates.append(template)

        return templates

1135
1136
    def generateTemplatesForUnmatchedResidues(self, topology):
        """Generate forcefield residue templates for residues in specified topology for which no forcefield templates are available.
1137

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

1140
1141
1142
        Parameters
        ----------
        topology : Topology
1143
            The Topology whose residues are to be checked against the forcefield residue templates.
1144
1145
1146

        Returns
        -------
1147
1148
1149
1150
1151
1152
        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]`
1153
1154
1155
1156
1157

        """
        # Get a non-unique list of unmatched residues.
        unmatched_residues = self.getUnmatchedResidues(topology)
        # Generate a unique list of unmatched residues by comparing fingerprints.
1158
        bondedToAtom = self._buildBondedToAtomList(topology)
1159
1160
        unique_unmatched_residues = list() # list of unique unmatched Residue objects from topology
        templates = list() # corresponding _TemplateData templates
1161
1162
1163
        signatures = set()
        for residue in unmatched_residues:
            signature = _createResidueSignature([ atom.element for atom in residue.atoms() ])
1164
            template = _createResidueTemplate(residue)
1165
1166
1167
1168
            is_unique = True
            if signature in signatures:
                # Signature is the same as an existing residue; check connectivity.
                for check_residue in unique_unmatched_residues:
peastman's avatar
peastman committed
1169
                    matches = compiled.matchResidueToTemplate(check_residue, template, bondedToAtom, False)
1170
1171
1172
1173
1174
1175
                    if matches is not None:
                        is_unique = False
            if is_unique:
                # Residue is unique.
                unique_unmatched_residues.append(residue)
                signatures.add(signature)
1176
                templates.append(template)
1177

1178
        return [templates, unique_unmatched_residues]
1179

1180
    def createSystem(self, topology, nonbondedMethod=NoCutoff, nonbondedCutoff=1.0*unit.nanometer,
1181
                     constraints=None, rigidWater=None, removeCMMotion=True, hydrogenMass=None, residueTemplates=dict(),
1182
                     ignoreExternalBonds=False, switchDistance=None, flexibleConstraints=False, drudeMass=0.4*unit.amu, **args):
1183
        """Construct an OpenMM System representing a Topology with this force field.
Justin MacCallum's avatar
Justin MacCallum committed
1184

Robert McGibbon's avatar
Robert McGibbon committed
1185
1186
1187
1188
1189
1190
        Parameters
        ----------
        topology : Topology
            The Topology for which to create a System
        nonbondedMethod : object=NoCutoff
            The method to use for nonbonded interactions.  Allowed values are
Peter Eastman's avatar
Peter Eastman committed
1191
            NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, PME, or LJPME.
Robert McGibbon's avatar
Robert McGibbon committed
1192
1193
1194
1195
1196
        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.
1197
        rigidWater : boolean=None
Robert McGibbon's avatar
Robert McGibbon committed
1198
            If true, water molecules will be fully rigid regardless of the value
1199
1200
            passed for the constraints argument.  If None (the default), it uses the
            default behavior for this force field's water model.
Robert McGibbon's avatar
Robert McGibbon committed
1201
1202
1203
1204
1205
        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
1206
1207
            their total mass the same.  If rigidWater is used to make water molecules
            rigid, then water hydrogens are not altered.
1208
        residueTemplates : dict=dict()
1209
1210
1211
1212
1213
            Specifies which template to use for particular residues.  The keys should be Residue
            objects from the Topology, and the values should be the names of the templates to
            use for them.  This is useful when a ForceField contains multiple templates that
            can match the same residue (e.g Fe2+ and Fe3+ templates in the ForceField for a
            monoatomic iron ion in the Topology).
1214
1215
1216
1217
1218
1219
        ignoreExternalBonds : boolean=False
            If true, ignore external bonds when matching residues to templates.  This is
            useful when the Topology represents one piece of a larger molecule, so chains are
            not terminated properly.  This option can create ambiguities where multiple
            templates match the same residue.  If that happens, use the residueTemplates
            argument to specify which one to use.
1220
1221
1222
        switchDistance : float=None
            The distance at which the potential energy switching function is turned on for
            Lennard-Jones interactions. If this is None, no switching function will be used.
1223
1224
        flexibleConstraints : boolean=False
            If True, parameters for constrained degrees of freedom will be added to the System
1225
        drudeMass : mass=0.4*amu
1226
1227
            The mass to use for Drude particles.  Any mass added to a Drude particle is
            subtracted from its parent atom to keep their total mass the same.
Robert McGibbon's avatar
Robert McGibbon committed
1228
        args
1229
1230
1231
            Arbitrary additional keyword arguments may also be specified.
            This allows extra parameters to be specified that are specific to
            particular force fields.
Robert McGibbon's avatar
Robert McGibbon committed
1232
1233
1234
1235
1236

        Returns
        -------
        system
            the newly created System
1237
        """
1238
1239
        args['switchDistance'] = switchDistance
        args['flexibleConstraints'] = flexibleConstraints
1240
        args['drudeMass'] = drudeMass
1241
        args = ArgTracker(args)
1242
        data = ForceField._SystemData(topology)
1243
        rigidResidue = [False]*topology.getNumResidues()
1244
1245

        # Find the template matching each residue and assign atom types.
Justin MacCallum's avatar
Justin MacCallum committed
1246

1247
1248
1249
1250
        templateForResidue = self._matchAllResiduesToTemplates(data, topology, residueTemplates, ignoreExternalBonds)
        for res in topology.residues():
            if res.name == 'HOH':
                # Determine whether this should be a rigid water.
1251

1252
1253
1254
1255
                if rigidWater is None:
                    rigidResidue[res.index] = templateForResidue[res.index].rigidWater
                elif rigidWater:
                    rigidResidue[res.index] = True
1256
1257

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

1259
1260
        sys = mm.System()
        for atom in topology.atoms():
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
1261
            # Look up the atom type name, returning a helpful error message if it cannot be found.
1262
1263
1264
1265
            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
1266
            # Look up the type name in the list of registered atom types, returning a helpful error message if it cannot be found.
1267
1268
1269
1270
            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
1271
1272

            # Add the particle to the OpenMM system.
1273
            mass = self._atomTypes[typename].mass
1274
            sys.addParticle(mass)
1275

1276
        # Adjust hydrogen masses if requested.
1277

1278
        if hydrogenMass is not None:
1279
1280
            if not unit.is_quantity(hydrogenMass):
                hydrogenMass *= unit.dalton
1281
            for atom1, atom2 in topology.bonds():
1282
                if atom1.element is elem.hydrogen:
1283
                    (atom1, atom2) = (atom2, atom1)
1284
                if atom2.element is elem.hydrogen and atom1.element not in (elem.hydrogen, None) and not rigidResidue[atom2.residue.index]:
1285
1286
1287
                    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
1288

1289
        # Set periodic boundary conditions.
Justin MacCallum's avatar
Justin MacCallum committed
1290

1291
1292
1293
        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
1294
        elif nonbondedMethod not in [NoCutoff, CutoffNonPeriodic]:
1295
1296
1297
            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
1298

1299
1300
        uniqueAngles = set()
        for bond in data.bonds:
1301
            for atom in data.bondedToAtom[bond.atom1]:
1302
1303
1304
1305
1306
                if atom != bond.atom2:
                    if atom < bond.atom2:
                        uniqueAngles.add((atom, bond.atom1, bond.atom2))
                    else:
                        uniqueAngles.add((bond.atom2, bond.atom1, atom))
1307
            for atom in data.bondedToAtom[bond.atom2]:
1308
1309
1310
1311
1312
1313
                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
1314

1315
        # Make a list of all unique proper torsions
Justin MacCallum's avatar
Justin MacCallum committed
1316

1317
1318
        uniquePropers = set()
        for angle in data.angles:
1319
            for atom in data.bondedToAtom[angle[0]]:
pgrinaway's avatar
pgrinaway committed
1320
                if atom not in angle:
1321
1322
1323
1324
                    if atom < angle[2]:
                        uniquePropers.add((atom, angle[0], angle[1], angle[2]))
                    else:
                        uniquePropers.add((angle[2], angle[1], angle[0], atom))
1325
            for atom in data.bondedToAtom[angle[2]]:
pgrinaway's avatar
pgrinaway committed
1326
                if atom not in angle:
1327
1328
1329
1330
1331
                    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
1332

1333
        # Make a list of all unique improper torsions
Justin MacCallum's avatar
Justin MacCallum committed
1334

1335
1336
        for atom in range(len(data.bondedToAtom)):
            bondedTo = data.bondedToAtom[atom]
1337
1338
1339
            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
1340

1341
        # Identify bonds that should be implemented with constraints
Justin MacCallum's avatar
Justin MacCallum committed
1342

1343
1344
1345
1346
1347
1348
1349
        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]
1350
                bond.isConstrained = atom1.element is elem.hydrogen or atom2.element is elem.hydrogen
1351
1352
1353
1354
1355
        for bond in data.bonds:
            atom1 = data.atoms[bond.atom1]
            atom2 = data.atoms[bond.atom2]
            if rigidResidue[atom1.residue.index] and rigidResidue[atom2.residue.index]:
                bond.isConstrained = True
Justin MacCallum's avatar
Justin MacCallum committed
1356

1357
        # Identify angles that should be implemented with constraints
Justin MacCallum's avatar
Justin MacCallum committed
1358

1359
1360
1361
1362
1363
1364
        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
1365
                if atom1.element is elem.hydrogen:
1366
                    numH += 1
1367
                if atom3.element is elem.hydrogen:
1368
                    numH += 1
1369
                data.isAngleConstrained.append(numH == 2 or (numH == 1 and atom2.element is elem.oxygen))
1370
1371
        else:
            data.isAngleConstrained = len(data.angles)*[False]
1372
1373
1374
1375
1376
1377
1378
        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 rigidResidue[atom1.residue.index] and rigidResidue[atom2.residue.index] and rigidResidue[atom3.residue.index]:
                data.isAngleConstrained[i] = True
Justin MacCallum's avatar
Justin MacCallum committed
1379

1380
        # Add virtual sites
Justin MacCallum's avatar
Justin MacCallum committed
1381

1382
        for atom in data.virtualSites:
1383
            (site, atoms, excludeWith) = data.virtualSites[atom]
1384
            index = atom.index
1385
            data.excludeAtomWith[excludeWith].append(index)
1386
            if site.type == 'average2':
1387
                sys.setVirtualSite(index, mm.TwoParticleAverageSite(atoms[0], atoms[1], site.weights[0], site.weights[1]))
1388
            elif site.type == 'average3':
1389
                sys.setVirtualSite(index, mm.ThreeParticleAverageSite(atoms[0], atoms[1], atoms[2], site.weights[0], site.weights[1], site.weights[2]))
1390
            elif site.type == 'outOfPlane':
1391
1392
                sys.setVirtualSite(index, mm.OutOfPlaneSite(atoms[0], atoms[1], atoms[2], site.weights[0], site.weights[1], site.weights[2]))
            elif site.type == 'localCoords':
1393
                sys.setVirtualSite(index, mm.LocalCoordinatesSite(atoms, site.originWeights, site.xWeights, site.yWeights, site.localPos))
Justin MacCallum's avatar
Justin MacCallum committed
1394

1395
        # Add forces to the System
Justin MacCallum's avatar
Justin MacCallum committed
1396

1397
1398
        for force in self._forces:
            force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
1399
1400
        if removeCMMotion:
            sys.addForce(mm.CMMotionRemover())
Justin MacCallum's avatar
Justin MacCallum committed
1401

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

peastman's avatar
peastman committed
1404
1405
1406
        for force in self._forces:
            if 'postprocessSystem' in dir(force):
                force.postprocessSystem(sys, data, args)
Justin MacCallum's avatar
Justin MacCallum committed
1407

1408
        # Execute scripts found in the XML files.
Justin MacCallum's avatar
Justin MacCallum committed
1409

1410
        for script in self._scripts:
1411
            exec(script, locals())
1412
        args.checkArgs(self.createSystem)
1413
1414
1415
        return sys


1416
    def _matchAllResiduesToTemplates(self, data, topology, residueTemplates, ignoreExternalBonds, ignoreExtraParticles=False, recordParameters=True):
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
        """Return a list of which template matches each residue in the topology, and assign atom types."""
        templateForResidue = [None]*topology.getNumResidues()
        unmatchedResidues = []
        for chain in topology.chains():
            for res in chain.residues():
                if res in residueTemplates:
                    tname = residueTemplates[res]
                    template = self._templates[tname]
                    matches = compiled.matchResidueToTemplate(res, template, data.bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)
                    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, data.bondedToAtom, ignoreExternalBonds=ignoreExternalBonds, ignoreExtraParticles=ignoreExtraParticles)
                if matches is None:
                    unmatchedResidues.append(res)
                else:
1434
1435
                    if recordParameters:
                        data.recordMatchedAtomParameters(res, template, matches)
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
                    templateForResidue[res.index] = template

        # Try to apply patches to find matches for any unmatched residues.

        if len(unmatchedResidues) > 0:
            unmatchedResidues = _applyPatchesToMatchResidues(self, data, unmatchedResidues, templateForResidue, data.bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)

        # If we still haven't found a match for a residue, attempt to use residue template generators to create
        # new templates (and potentially atom types/parameters).

        for res in unmatchedResidues:
            # A template might have been generated on an earlier iteration of this loop.
            [template, matches] = self._getResidueTemplateMatches(res, data.bondedToAtom, ignoreExternalBonds=ignoreExternalBonds, ignoreExtraParticles=ignoreExtraParticles)
            if matches is None:
                # Try all generators.
                for generator in self._templateGenerators:
                    if generator(self, res):
                        # This generator has registered a new residue template that should match.
                        [template, matches] = self._getResidueTemplateMatches(res, data.bondedToAtom, ignoreExternalBonds=ignoreExternalBonds, ignoreExtraParticles=ignoreExtraParticles)
                        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
            if matches is None:
1462
                raise ValueError('No template found for residue %d (%s).  %s  For more information, see https://github.com/openmm/openmm/wiki/Frequently-Asked-Questions#template' % (res.index+1, res.name, _findMatchErrors(self, res)))
1463
            else:
1464
1465
                if recordParameters:
                    data.recordMatchedAtomParameters(res, template, matches)
1466
1467
1468
1469
                templateForResidue[res.index] = template
        return templateForResidue


1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
def _findBondsForExclusions(data, sys):
    """Create a list of bonds to use when identifying exclusions."""
    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))
1494
1495
1496
    for atom in data.atoms:
        for child in data.excludeAtomWith[atom.index]:
            bondIndices.append((child, atom.index))
1497
1498
    return bondIndices

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
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
def _findExclusions(bondIndices, maxSeparation, numAtoms):
    """Identify pairs of atoms in the same molecule separated by no more than maxSeparation bonds."""
    bondedTo = [set() for i in range(numAtoms)]
    for i, j in bondIndices:
        bondedTo[i].add(j)
        bondedTo[j].add(i)

    # Identify all neighbors of each atom with each separation.

    bondedWithSeparation = [bondedTo]
    for i in range(maxSeparation-1):
        lastBonds = bondedWithSeparation[-1]
        newBonds = deepcopy(lastBonds)
        for atom in range(numAtoms):
            for a1 in lastBonds[atom]:
                for a2 in bondedTo[a1]:
                    newBonds[atom].add(a2)
        bondedWithSeparation.append(newBonds)

    # Build the list of pairs.

    pairs = []
    for atom in range(numAtoms):
        for otherAtom in bondedWithSeparation[-1][atom]:
            if otherAtom > atom:
                # Determine the minimum number of bonds between them.
                sep = maxSeparation
                for i in reversed(range(maxSeparation-1)):
                    if otherAtom in bondedWithSeparation[i][atom]:
                        sep -= 1
                    else:
                        break
                pairs.append((atom, otherAtom, sep))
    return pairs


def _findGroups(bondedTo):
    """Given bonds that connect atoms, identify the connected groups."""
    atomGroup = [None]*len(bondedTo)
    numGroups = 0
    for i in range(len(bondedTo)):
        if atomGroup[i] is None:
            # Start a new group.

            atomStack = [i]
            neighborStack = [0]
            group = numGroups
            numGroups += 1

            # Recursively tag all the bonded atoms.

            while len(atomStack) > 0:
                atom = atomStack[-1]
                atomGroup[atom] = group
                while neighborStack[-1] < len(bondedTo[atom]) and atomGroup[bondedTo[atom][neighborStack[-1]]] is not None:
                    neighborStack[-1] += 1
                if neighborStack[-1] < len(bondedTo[atom]):
                    atomStack.append(bondedTo[atom][neighborStack[-1]])
                    neighborStack.append(0)
                else:
                    atomStack.pop()
                    neighborStack.pop()
    return atomGroup

1563
1564
def _countResidueAtoms(elements):
    """Count the number of atoms of each element in a residue."""
1565
1566
    counts = {}
    for element in elements:
1567
        if element in counts:
1568
1569
1570
            counts[element] += 1
        else:
            counts[element] = 1
1571
1572
1573
1574
1575
1576
    return counts


def _createResidueSignature(elements):
    """Create a signature for a residue based on the elements of the atoms it contains."""
    counts = _countResidueAtoms(elements)
1577
1578
    sig = []
    for c in counts:
1579
1580
        if c is not None:
            sig.append((c, counts[c]))
1581
    sig.sort(key=lambda x: -x[0].mass)
Justin MacCallum's avatar
Justin MacCallum committed
1582

1583
    # Convert it to a string.
1584
1585

    s = ''
1586
    for element, count in sig:
1587
1588
1589
1590
        s += element.symbol+str(count)
    return s


1591
def _applyPatchesToMatchResidues(forcefield, data, residues, templateForResidue, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles):
1592
1593
1594
1595
    """Try to apply patches to find matches for residues."""
    # Start by creating all templates than can be created by applying a combination of one-residue patches
    # to a single template.  The number of these is usually not too large, and they often cover a large fraction
    # of residues.
1596

1597
1598
1599
1600
    patchedTemplateSignatures = {}
    patchedTemplates = {}
    for name, template in forcefield._templates.items():
        if name in forcefield._templatePatches:
1601
            patches = sorted([forcefield._patches[patchName] for patchName, patchResidueIndex in forcefield._templatePatches[name] if forcefield._patches[patchName].numResidues == 1])
1602
1603
1604
            if len(patches) > 0:
                newTemplates = []
                patchedTemplates[name] = newTemplates
peastman's avatar
peastman committed
1605
                _generatePatchedSingleResidueTemplates(template, patches, 0, newTemplates, set())
1606
1607
1608
1609
1610
1611
                for patchedTemplate in newTemplates:
                    signature = _createResidueSignature([atom.element for atom in patchedTemplate.atoms])
                    if signature in patchedTemplateSignatures:
                        patchedTemplateSignatures[signature].append(patchedTemplate)
                    else:
                        patchedTemplateSignatures[signature] = [patchedTemplate]
1612

1613
    # Now see if any of those templates matches any of the residues.
1614

1615
1616
    unmatchedResidues = []
    for res in residues:
1617
        [template, matches] = forcefield._getResidueTemplateMatches(res, bondedToAtom, patchedTemplateSignatures, ignoreExternalBonds, ignoreExtraParticles)
1618
1619
1620
1621
        if matches is None:
            unmatchedResidues.append(res)
        else:
            data.recordMatchedAtomParameters(res, template, matches)
1622
            templateForResidue[res.index] = template
1623
1624
    if len(unmatchedResidues) == 0:
        return []
1625

1626
1627
1628
    # We need to consider multi-residue patches.  This can easily lead to a combinatorial explosion, so we make a simplifying
    # assumption: that no residue is affected by more than one multi-residue patch (in addition to any number of single-residue
    # patches).  Record all multi-residue patches, and the templates they can be applied to.
1629

1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
    patches = {}
    maxPatchSize = 0
    for patch in forcefield._patches.values():
        if patch.numResidues > 1:
            patches[patch.name] = [[] for i in range(patch.numResidues)]
            maxPatchSize = max(maxPatchSize, patch.numResidues)
    if maxPatchSize == 0:
        return unmatchedResidues # There aren't any multi-residue patches
    for templateName in forcefield._templatePatches:
        for patchName, patchResidueIndex in forcefield._templatePatches[templateName]:
            if patchName in patches:
                # The patch should accept this template, *and* all patched versions of it generated above.
                patches[patchName][patchResidueIndex].append(forcefield._templates[templateName])
                if templateName in patchedTemplates:
                    patches[patchName][patchResidueIndex] += patchedTemplates[templateName]
1645

1646
    # Record which unmatched residues are bonded to each other.
1647

1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
    bonds = set()
    topology = residues[0].chain.topology
    for atom1, atom2 in topology.bonds():
        if atom1.residue != atom2.residue:
            res1 = atom1.residue
            res2 = atom2.residue
            if res1 in unmatchedResidues and res2 in unmatchedResidues:
                bond = tuple(sorted((res1, res2), key=lambda x: x.index))
                if bond not in bonds:
                    bonds.add(bond)
1658

1659
1660
    # Identify clusters of unmatched residues that are all bonded to each other.  These are the ones we'll
    # try to apply multi-residue patches to.
1661

1662
1663
1664
1665
    clusterSize = 2
    clusters = bonds
    while clusterSize <= maxPatchSize:
        # Try to apply patches to clusters of this size.
1666

1667
1668
1669
        for patchName in patches:
            patch = forcefield._patches[patchName]
            if patch.numResidues == clusterSize:
1670
                matchedClusters = _matchToMultiResiduePatchedTemplates(data, clusters, patch, patches[patchName], bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)
1671
1672
1673
1674
1675
1676
                for cluster in matchedClusters:
                    for residue in cluster:
                        unmatchedResidues.remove(residue)
                bonds = set(bond for bond in bonds if bond[0] in unmatchedResidues and bond[1] in unmatchedResidues)

        # Now extend the clusters to find ones of the next size up.
1677

1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
        largerClusters = set()
        for cluster in clusters:
            for bond in bonds:
                if bond[0] in cluster and bond[1] not in cluster:
                    newCluster = tuple(sorted(cluster+(bond[1],), key=lambda x: x.index))
                    largerClusters.add(newCluster)
                elif bond[1] in cluster and bond[0] not in cluster:
                    newCluster = tuple(sorted(cluster+(bond[0],), key=lambda x: x.index))
                    largerClusters.add(newCluster)
        if len(largerClusters) == 0:
            # There are no clusters of this size or larger
            break
        clusters = largerClusters
        clusterSize += 1

1693
1694
1695
    return unmatchedResidues


peastman's avatar
peastman committed
1696
def _generatePatchedSingleResidueTemplates(template, patches, index, newTemplates, alteredAtoms):
1697
1698
    """Apply all possible combinations of a set of single-residue patches to a template."""
    try:
peastman's avatar
peastman committed
1699
1700
1701
1702
1703
1704
1705
        if len(alteredAtoms.intersection(patches[index].allAtomNames)) > 0:
            # This patch would alter an atom that another patch has already altered,
            # so don't apply it.
            patchedTemplate = None
        else:
            patchedTemplate = patches[index].createPatchedTemplates([template])[0]
            newTemplates.append(patchedTemplate)
1706
1707
1708
1709
    except:
        # This probably means the patch is inconsistent with another one that has already been applied,
        # so just ignore it.
        patchedTemplate = None
1710

1711
    # Call this function recursively to generate combinations of patches.
1712

1713
    if index+1 < len(patches):
peastman's avatar
peastman committed
1714
        _generatePatchedSingleResidueTemplates(template, patches, index+1, newTemplates, alteredAtoms)
1715
        if patchedTemplate is not None:
peastman's avatar
peastman committed
1716
1717
            newAlteredAtoms = alteredAtoms.union(patches[index].allAtomNames)
            _generatePatchedSingleResidueTemplates(patchedTemplate, patches, index+1, newTemplates, newAlteredAtoms)
1718
1719


1720
def _matchToMultiResiduePatchedTemplates(data, clusters, patch, residueTemplates, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles):
1721
1722
1723
    """Apply a multi-residue patch to templates, then try to match them against clusters of residues."""
    matchedClusters = []
    selectedTemplates = [None]*patch.numResidues
1724
    _applyMultiResiduePatch(data, clusters, patch, residueTemplates, selectedTemplates, 0, matchedClusters, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)
1725
1726
1727
    return matchedClusters


1728
def _applyMultiResiduePatch(data, clusters, patch, candidateTemplates, selectedTemplates, index, matchedClusters, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles):
1729
1730
1731
1732
1733
    """This is called recursively to apply a multi-residue patch to all possible combinations of templates."""

    if index < patch.numResidues:
        for template in candidateTemplates[index]:
            selectedTemplates[index] = template
1734
            _applyMultiResiduePatch(data, clusters, patch, candidateTemplates, selectedTemplates, index+1, matchedClusters, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)
1735
1736
1737
    else:
        # We're at the deepest level of the recursion.  We've selected a template for each residue, so apply the patch,
        # then try to match it against clusters.
1738

1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
        try:
            patchedTemplates = patch.createPatchedTemplates(selectedTemplates)
        except:
            # This probably means the patch is inconsistent with another one that has already been applied,
            # so just ignore it.
            return
        newlyMatchedClusters = []
        for cluster in clusters:
            for residues in itertools.permutations(cluster):
                residueMatches = []
                for residue, template in zip(residues, patchedTemplates):
1750
                    matches = compiled.matchResidueToTemplate(residue, template, bondedToAtom, ignoreExternalBonds, ignoreExtraParticles)
1751
1752
1753
1754
1755
1756
                    if matches is None:
                        residueMatches = None
                        break
                    else:
                        residueMatches.append(matches)
                if residueMatches is not None:
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
                    # Each residue individually matches.  Now make sure they're bonded in the correct way.

                    bondsMatch = True
                    for a1, a2 in patch.addedBonds:
                        res1 = a1.residue
                        res2 = a2.residue
                        if res1 != res2:
                            # The patch adds a bond between residues.  Make sure that bond exists.

                            atoms1 = patchedTemplates[res1].atoms
                            atoms2 = patchedTemplates[res2].atoms
                            index1 = next(i for i in range(len(atoms1)) if atoms1[residueMatches[res1][i]].name == a1.name)
                            index2 = next(i for i in range(len(atoms2)) if atoms2[residueMatches[res2][i]].name == a2.name)
                            atom1 = list(residues[res1].atoms())[index1]
                            atom2 = list(residues[res2].atoms())[index2]
                            bondsMatch &= atom2.index in bondedToAtom[atom1.index]
                    if bondsMatch:
                        # We successfully matched the template to the residues.  Record the parameters.
1775

1776
1777
1778
1779
                        for i in range(patch.numResidues):
                            data.recordMatchedAtomParameters(residues[i], patchedTemplates[i], residueMatches[i])
                        newlyMatchedClusters.append(cluster)
                        break
1780

1781
        # Record which clusters were successfully matched.
1782

1783
1784
1785
        matchedClusters += newlyMatchedClusters
        for cluster in newlyMatchedClusters:
            clusters.remove(cluster)
1786

1787

1788
1789
1790
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()])
1791
    numResidueAtoms = sum(residueCounts.values())
1792
    numResidueHeavyAtoms = sum(residueCounts[element] for element in residueCounts if element not in (None, elem.hydrogen))
1793

1794
    # Loop over templates and see how closely each one might match.
1795

1796
1797
1798
1799
1800
1801
    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])
1802

1803
        # Does the residue have any atoms that clearly aren't in the template?
1804

1805
1806
        if any(element not in templateCounts or templateCounts[element] < residueCounts[element] for element in residueCounts):
            continue
1807

1808
        # If there are too many missing atoms, discard this template.
1809

1810
        numTemplateAtoms = sum(templateCounts.values())
1811
        numTemplateHeavyAtoms = sum(templateCounts[element] for element in templateCounts if element not in (None, elem.hydrogen))
1812
1813
1814
1815
        if numTemplateAtoms > numBestMatchAtoms:
            continue
        if numTemplateHeavyAtoms > numBestMatchHeavyAtoms:
            continue
1816

1817
1818
        # 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.
1819

1820
1821
1822
        if numTemplateAtoms == numBestMatchAtoms:
            if bestMatchName == res.name or res.name not in templateName:
                continue
1823

1824
        # Accept this as our new best match.
1825

1826
1827
1828
        bestMatchName = templateName
        numBestMatchAtoms = numTemplateAtoms
        numBestMatchHeavyAtoms = numTemplateHeavyAtoms
1829
        numBestMatchExtraParticles = len([atom for atom in template.atoms if atom.element is None])
1830

1831
    # Return an appropriate error message.
1832

1833
    if numBestMatchAtoms == numResidueAtoms:
1834
1835
        chainResidues = list(res.chain.residues())
        if len(chainResidues) > 1 and (res == chainResidues[0] or res == chainResidues[-1]):
1836
1837
1838
1839
            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:
1840
1841
1842
1843
1844
            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)
1845
1846
1847
        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.'

1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
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():
1866
        template.addAtom(ForceField._TemplateAtomData(atom.name, None, atom.element))
1867
1868
1869
1870
1871
1872
1873
1874
1875
    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
1876

1877
1878
1879
1880
1881
def _matchImproper(data, torsion, generator):
    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]]]
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1882
    wildcard = generator.ff._atomClasses['']
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
    match = None
    for tordef in generator.improper:
        types1 = tordef.types1
        types2 = tordef.types2
        types3 = tordef.types3
        types4 = tordef.types4
        hasWildcard = (wildcard in (types1, types2, types3, types4))
        if match is not None and hasWildcard:
            # Prefer specific definitions over ones with wildcards
            continue
        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:
                    if tordef.ordering == 'default':
                        # 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)
                        match = (a1, a2, torsion[0], torsion[t4[1]], tordef)
                        break
                    elif tordef.ordering == 'charmm':
                        if hasWildcard:
                            # 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)
                            match = (a1, a2, torsion[0], torsion[t4[1]], tordef)
                        else:
                            # There are no wildcards, so the order is unambiguous.
                            match = (torsion[0], torsion[t2[1]], torsion[t3[1]], torsion[t4[1]], tordef)
                        break
                    elif tordef.ordering == 'amber':
                        # topology atom indexes
                        a2 = torsion[t2[1]]
                        a3 = torsion[t3[1]]
                        a4 = torsion[t4[1]]
                        # residue indexes
                        r2 = data.atoms[a2].residue.index
                        r3 = data.atoms[a3].residue.index
                        r4 = data.atoms[a4].residue.index
                        # template atom indexes
                        ta2 = data.atomTemplateIndexes[data.atoms[a2]]
                        ta3 = data.atomTemplateIndexes[data.atoms[a3]]
                        ta4 = data.atomTemplateIndexes[data.atoms[a4]]
                        # elements
                        e2 = data.atoms[a2].element
                        e3 = data.atoms[a3].element
                        e4 = data.atoms[a4].element
                        if not hasWildcard:
                            if t2[0] == t4[0] and (r2 > r4 or (r2 == r4 and ta2 > ta4)):
                                (a2, a4) = (a4, a2)
                                r2 = data.atoms[a2].residue.index
                                r4 = data.atoms[a4].residue.index
                                ta2 = data.atomTemplateIndexes[data.atoms[a2]]
                                ta4 = data.atomTemplateIndexes[data.atoms[a4]]
                            if t3[0] == t4[0] and (r3 > r4 or (r3 == r4 and ta3 > ta4)):
                                (a3, a4) = (a4, a3)
                                r3 = data.atoms[a3].residue.index
                                r4 = data.atoms[a4].residue.index
                                ta3 = data.atomTemplateIndexes[data.atoms[a3]]
                                ta4 = data.atomTemplateIndexes[data.atoms[a4]]
                            if t2[0] == t3[0] and (r2 > r3 or (r2 == r3 and ta2 > ta3)):
                                (a2, a3) = (a3, a2)
                        else:
                            if e2 == e4 and (r2 > r4 or (r2 == r4 and ta2 > ta4)):
                                (a2, a4) = (a4, a2)
                                r2 = data.atoms[a2].residue.index
                                r4 = data.atoms[a4].residue.index
                                ta2 = data.atomTemplateIndexes[data.atoms[a2]]
                                ta4 = data.atomTemplateIndexes[data.atoms[a4]]
                            if e3 == e4 and (r3 > r4 or (r3 == r4 and ta3 > ta4)):
                                (a3, a4) = (a4, a3)
                                r3 = data.atoms[a3].residue.index
                                r4 = data.atoms[a4].residue.index
                                ta3 = data.atomTemplateIndexes[data.atoms[a3]]
                                ta4 = data.atomTemplateIndexes[data.atoms[a4]]
                            if r2 > r3 or (r2 == r3 and ta2 > ta3):
                                (a2, a3) = (a3, a2)
                        match = (a2, a3, torsion[0], a4, tordef)
                        break
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
                    elif tordef.ordering == 'smirnoff':
                        # topology atom indexes
                        a1 = torsion[0]
                        a2 = torsion[t2[1]]
                        a3 = torsion[t3[1]]
                        a4 = torsion[t4[1]]
                        # enforce exact match
                        match = (a1, a2, a3, a4, tordef)
                        break

Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
1987
    return match
1988

1989

1990
1991
1992
1993
1994
# 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.

1995
## @private
1996
class HarmonicBondGenerator(object):
1997
    """A HarmonicBondGenerator constructs a HarmonicBondForce."""
Justin MacCallum's avatar
Justin MacCallum committed
1998

1999
2000
    def __init__(self, forcefield):
        self.ff = forcefield
peastman's avatar
peastman committed
2001
        self.bondsForAtomType = defaultdict(set)
2002
2003
2004
2005
        self.types1 = []
        self.types2 = []
        self.length = []
        self.k = []
2006

2007
2008
2009
    def registerBond(self, parameters):
        types = self.ff._findAtomTypes(parameters, 2)
        if None not in types:
peastman's avatar
peastman committed
2010
            index = len(self.types1)
2011
2012
            self.types1.append(types[0])
            self.types2.append(types[1])
peastman's avatar
peastman committed
2013
2014
2015
2016
            for t in types[0]:
                self.bondsForAtomType[t].add(index)
            for t in types[1]:
                self.bondsForAtomType[t].add(index)
2017
2018
            self.length.append(_convertParameterToNumber(parameters['length']))
            self.k.append(_convertParameterToNumber(parameters['k']))
Justin MacCallum's avatar
Justin MacCallum committed
2019

2020
2021
    @staticmethod
    def parseElement(element, ff):
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
2022
2023
2024
2025
2026
2027
        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]
2028
        for bond in element.findall('Bond'):
2029
            generator.registerBond(bond.attrib)
Justin MacCallum's avatar
Justin MacCallum committed
2030

2031
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
2032
        existing = [f for f in sys.getForces() if type(f) == mm.HarmonicBondForce]
2033
2034
2035
2036
2037
2038
2039
2040
        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]]
peastman's avatar
peastman committed
2041
            for i in self.bondsForAtomType[type1]:
2042
2043
2044
2045
2046
                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:
2047
                        data.addConstraint(sys, bond.atom1, bond.atom2, self.length[i])
2048
2049
2050
2051
2052
                    if self.k[i] != 0:
                        # flexibleConstraints allows us to add parameters even if the DOF is
                        # constrained
                        if not bond.isConstrained or args.get('flexibleConstraints', False):
                            force.addBond(bond.atom1, bond.atom2, self.length[i], self.k[i])
2053
2054
2055
2056
2057
                    break

parsers["HarmonicBondForce"] = HarmonicBondGenerator.parseElement


2058
## @private
2059
class HarmonicAngleGenerator(object):
2060
    """A HarmonicAngleGenerator constructs a HarmonicAngleForce."""
Justin MacCallum's avatar
Justin MacCallum committed
2061

2062
2063
    def __init__(self, forcefield):
        self.ff = forcefield
peastman's avatar
peastman committed
2064
        self.anglesForAtom2Type = defaultdict(list)
2065
2066
2067
2068
2069
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.angle = []
        self.k = []
Justin MacCallum's avatar
Justin MacCallum committed
2070

2071
2072
2073
    def registerAngle(self, parameters):
        types = self.ff._findAtomTypes(parameters, 3)
        if None not in types:
peastman's avatar
peastman committed
2074
            index = len(self.types1)
2075
2076
2077
            self.types1.append(types[0])
            self.types2.append(types[1])
            self.types3.append(types[2])
peastman's avatar
peastman committed
2078
2079
            for t in types[1]:
                self.anglesForAtom2Type[t].append(index)
2080
2081
2082
            self.angle.append(_convertParameterToNumber(parameters['angle']))
            self.k.append(_convertParameterToNumber(parameters['k']))

2083
2084
    @staticmethod
    def parseElement(element, ff):
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
2085
2086
2087
2088
2089
2090
        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]
2091
        for angle in element.findall('Angle'):
2092
            generator.registerAngle(angle.attrib)
Justin MacCallum's avatar
Justin MacCallum committed
2093

2094
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
2095
2096
2097
2098
2099
        pass

    def postprocessSystem(self, sys, data, args):
        # We need to wait until after all bonds have been added so their lengths will be set correctly.

2100
        existing = [f for f in sys.getForces() if type(f) == mm.HarmonicAngleForce]
2101
2102
2103
2104
2105
2106
2107
2108
2109
        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]]]
peastman's avatar
peastman committed
2110
            for i in self.anglesForAtom2Type[type2]:
2111
2112
2113
2114
2115
2116
                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
2117

2118
2119
2120
2121
2122
2123
2124
2125
2126
                        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
2127

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

2130
2131
2132
2133
2134
                        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]))
2135
                                data.addConstraint(sys, angle[0], angle[2], length)
2136
2137
2138
                    if self.k[i] != 0:
                        if not isConstrained or args.get('flexibleConstraints', False):
                            force.addAngle(angle[0], angle[1], angle[2], self.angle[i], self.k[i])
2139
2140
2141
2142
2143
                    break

parsers["HarmonicAngleForce"] = HarmonicAngleGenerator.parseElement


2144
## @private
2145
class PeriodicTorsion(object):
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
    """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 = []
2156
        self.ordering = 'default'
2157

2158
## @private
2159
class PeriodicTorsionGenerator(object):
2160
    """A PeriodicTorsionGenerator constructs a PeriodicTorsionForce."""
Justin MacCallum's avatar
Justin MacCallum committed
2161

2162
2163
    def __init__(self, forcefield):
        self.ff = forcefield
2164
2165
        self.proper = []
        self.improper = []
2166
        self.propersForAtomType = defaultdict(set)
Justin MacCallum's avatar
Justin MacCallum committed
2167

2168
2169
2170
    def registerProperTorsion(self, parameters):
        torsion = self.ff._parseTorsion(parameters)
        if torsion is not None:
2171
            index = len(self.proper)
2172
            self.proper.append(torsion)
2173
2174
2175
2176
            for t in torsion.types2:
                self.propersForAtomType[t].add(index)
            for t in torsion.types3:
                self.propersForAtomType[t].add(index)
2177

2178
    def registerImproperTorsion(self, parameters, ordering='default'):
2179
2180
        torsion = self.ff._parseTorsion(parameters)
        if torsion is not None:
2181
            if ordering in ['default', 'charmm', 'amber', 'smirnoff']:
2182
2183
                torsion.ordering = ordering
            else:
2184
                raise ValueError('Illegal ordering type %s for improper torsion %s' % (ordering, torsion))
2185
2186
            self.improper.append(torsion)

2187
2188
    @staticmethod
    def parseElement(element, ff):
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
2189
2190
2191
2192
2193
2194
        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]
2195
        for torsion in element.findall('Proper'):
2196
            generator.registerProperTorsion(torsion.attrib)
2197
        for torsion in element.findall('Improper'):
2198
2199
2200
2201
            if 'ordering' in element.attrib:
                generator.registerImproperTorsion(torsion.attrib, element.attrib['ordering'])
            else:
                generator.registerImproperTorsion(torsion.attrib)
Justin MacCallum's avatar
Justin MacCallum committed
2202

2203
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
2204
        existing = [f for f in sys.getForces() if type(f) == mm.PeriodicTorsionForce]
2205
2206
2207
2208
2209
2210
        if len(existing) == 0:
            force = mm.PeriodicTorsionForce()
            sys.addForce(force)
        else:
            force = existing[0]
        wildcard = self.ff._atomClasses['']
tic20's avatar
tic20 committed
2211
        proper_cache = {}
2212
        for torsion in data.propers:
tic20's avatar
tic20 committed
2213
2214
            type1, type2, type3, type4 = [data.atomType[data.atoms[torsion[i]]] for i in range(4)]
            sig = (type1, type2, type3, type4)
2215
            sig = frozenset((sig, sig[::-1]))
tic20's avatar
tic20 committed
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
            match = proper_cache.get(sig, None)
            if match == -1:
                continue
            if match is None:
                for index in self.propersForAtomType[type2]:
                    tordef = self.proper[index]
                    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 None:
                    proper_cache[sig] = -1
                else:
                    proper_cache[sig] = match
2236
2237
2238
2239
            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])
2240
        impr_cache = {}
2241
        for torsion in data.impropers:
Peter Eastman's avatar
Peter Eastman committed
2242
            t1, t2, t3, t4 = [data.atomType[data.atoms[torsion[i]]] for i in range(4)]
2243
            sig = (t1, t2, t3, t4)
2244
2245
2246
2247
            match = impr_cache.get(sig, None)
            if match == -1:
                # Previously checked, and doesn't appear in the database
                continue
2248
2249
2250
2251
            elif match:
                i1, i2, i3, i4, tordef = match
                a1, a2, a3, a4 = (torsion[i] for i in (i1, i2, i3, i4))
                match = (a1, a2, a3, a4, tordef)
2252
2253
2254
            if match is None:
                match = _matchImproper(data, torsion, self)
                if match is not None:
2255
2256
2257
                    order = match[:4]
                    i1, i2, i3, i4 = tuple(torsion.index(a) for a in order)
                    impr_cache[sig] = (i1, i2, i3, i4, match[-1])
2258
2259
                else:
                    impr_cache[sig] = -1
2260
2261
2262
2263
            if match is not None:
                (a1, a2, a3, a4, tordef) = match
                for i in range(len(tordef.phase)):
                    if tordef.k[i] != 0:
2264
2265
2266
2267
2268
2269
2270
                        if tordef.ordering == 'smirnoff':
                            # Add all torsions in trefoil
                            force.addTorsion(a1, a2, a3, a4, tordef.periodicity[i], tordef.phase[i], tordef.k[i])
                            force.addTorsion(a1, a3, a4, a2, tordef.periodicity[i], tordef.phase[i], tordef.k[i])
                            force.addTorsion(a1, a4, a2, a3, tordef.periodicity[i], tordef.phase[i], tordef.k[i])
                        else:
                            force.addTorsion(a1, a2, a3, a4, tordef.periodicity[i], tordef.phase[i], tordef.k[i])
2271
2272
2273
parsers["PeriodicTorsionForce"] = PeriodicTorsionGenerator.parseElement


2274
## @private
2275
class RBTorsion(object):
2276
2277
    """An RBTorsion records the information for a Ryckaert-Bellemans torsion definition."""

2278
    def __init__(self, types, c, ordering='charmm'):
2279
2280
2281
2282
2283
        self.types1 = types[0]
        self.types2 = types[1]
        self.types3 = types[2]
        self.types4 = types[3]
        self.c = c
2284
        if ordering in ['default', 'charmm', 'amber']:
2285
2286
            self.ordering = ordering
        else:
2287
            raise ValueError('Illegal ordering type %s for RBTorsion (%s,%s,%s,%s)' % (ordering, types[0], types[1], types[2], types[3]))
2288

2289
## @private
2290
class RBTorsionGenerator(object):
2291
    """An RBTorsionGenerator constructs an RBTorsionForce."""
Justin MacCallum's avatar
Justin MacCallum committed
2292

2293
2294
    def __init__(self, forcefield):
        self.ff = forcefield
2295
2296
        self.proper = []
        self.improper = []
Justin MacCallum's avatar
Justin MacCallum committed
2297

2298
2299
    @staticmethod
    def parseElement(element, ff):
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
2300
2301
2302
2303
2304
2305
        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]
2306
        for torsion in element.findall('Proper'):
2307
            types = ff._findAtomTypes(torsion.attrib, 4)
peastman's avatar
peastman committed
2308
            if None not in types:
2309
2310
                generator.proper.append(RBTorsion(types, [float(torsion.attrib['c'+str(i)]) for i in range(6)]))
        for torsion in element.findall('Improper'):
2311
            types = ff._findAtomTypes(torsion.attrib, 4)
peastman's avatar
peastman committed
2312
            if None not in types:
2313
2314
2315
2316
                if 'ordering' in element.attrib:
                    generator.improper.append(RBTorsion(types, [float(torsion.attrib['c'+str(i)]) for i in range(6)], element.attrib['ordering']))
                else:
                    generator.improper.append(RBTorsion(types, [float(torsion.attrib['c'+str(i)]) for i in range(6)]))
Justin MacCallum's avatar
Justin MacCallum committed
2317

2318
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
2319
        existing = [f for f in sys.getForces() if type(f) == mm.RBTorsionForce]
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
        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:
2346
            match = _matchImproper(data, torsion, self)
2347
2348
2349
            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])
2350
2351
2352
2353

parsers["RBTorsionForce"] = RBTorsionGenerator.parseElement


2354
## @private
2355
class CMAPTorsion(object):
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
    """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

2366
## @private
2367
class CMAPTorsionGenerator(object):
2368
    """A CMAPTorsionGenerator constructs a CMAPTorsionForce."""
Justin MacCallum's avatar
Justin MacCallum committed
2369

2370
2371
    def __init__(self, forcefield):
        self.ff = forcefield
2372
2373
        self.torsions = []
        self.maps = []
Justin MacCallum's avatar
Justin MacCallum committed
2374

2375
2376
    @staticmethod
    def parseElement(element, ff):
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
2377
2378
2379
2380
2381
2382
        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]
2383
2384
2385
2386
2387
2388
2389
        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'):
2390
            types = ff._findAtomTypes(torsion.attrib, 5)
peastman's avatar
peastman committed
2391
            if None not in types:
2392
                generator.torsions.append(CMAPTorsion(types, int(torsion.attrib['map'])))
Justin MacCallum's avatar
Justin MacCallum committed
2393

2394
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
2395
        existing = [f for f in sys.getForces() if type(f) == mm.CMAPTorsionForce]
2396
2397
2398
2399
2400
2401
2402
        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
2403

2404
        # Find all chains of length 5
Justin MacCallum's avatar
Justin MacCallum committed
2405

2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
        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


2449
## @private
2450
class NonbondedGenerator(object):
2451
    """A NonbondedGenerator constructs a NonbondedForce."""
Justin MacCallum's avatar
Justin MacCallum committed
2452

2453
2454
    SCALETOL = 1e-5

2455
    def __init__(self, forcefield, coulomb14scale, lj14scale, useDispersionCorrection):
2456
        self.ff = forcefield
2457
2458
        self.coulomb14scale = coulomb14scale
        self.lj14scale = lj14scale
2459
        self.useDispersionCorrection = useDispersionCorrection
2460
        self.params = ForceField._AtomTypeParameters(forcefield, 'NonbondedForce', 'Atom', ('charge', 'sigma', 'epsilon'))
2461

2462
    def registerAtom(self, parameters):
2463
        self.params.registerAtom(parameters)
2464

2465
2466
2467
    @staticmethod
    def parseElement(element, ff):
        existing = [f for f in ff._forces if isinstance(f, NonbondedGenerator)]
2468
2469
2470
2471
        if 'useDispersionCorrection' in element.attrib:
            useDispersionCorrection = bool(eval(element.attrib.get('useDispersionCorrection')))
        else:
            useDispersionCorrection = None
2472
        if len(existing) == 0:
2473
2474
2475
2476
2477
2478
            generator = NonbondedGenerator(
                ff,
                float(element.attrib['coulomb14scale']),
                float(element.attrib['lj14scale']),
                useDispersionCorrection
            )
2479
            ff.registerGenerator(generator)
2480
2481
2482
        else:
            # Multiple <NonbondedForce> tags were found, probably in different files.  Simply add more types to the existing one.
            generator = existing[0]
2483
2484
2485
            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
2486
                raise ValueError('Found multiple NonbondedForce tags with different 1-4 scales')
2487
2488
2489
2490
2491
2492
            if (
                    generator.useDispersionCorrection is not None
                    and useDispersionCorrection is not None
                    and generator.useDispersionCorrection != useDispersionCorrection
            ):
                raise ValueError('Found multiple NonbondedForce tags with different useDispersionCorrection settings.')
2493
        generator.params.parseDefinitions(element)
Justin MacCallum's avatar
Justin MacCallum committed
2494

2495
2496
2497
2498
2499
    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,
Peter Eastman's avatar
Peter Eastman committed
2500
2501
                     PME:mm.NonbondedForce.PME,
                     LJPME:mm.NonbondedForce.LJPME}
2502
        if nonbondedMethod not in methodMap:
Justin MacCallum's avatar
Justin MacCallum committed
2503
            raise ValueError('Illegal nonbonded method for NonbondedForce')
2504
2505
        force = mm.NonbondedForce()
        for atom in data.atoms:
2506
2507
            values = self.params.getAtomParameters(atom, data)
            force.addParticle(values[0], values[1], values[2])
peastman's avatar
peastman committed
2508
2509
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
2510
2511
2512
        if args['switchDistance'] is not None:
            force.setUseSwitchingFunction(True)
            force.setSwitchingDistance(args['switchDistance'])
peastman's avatar
peastman committed
2513
2514
        if 'ewaldErrorTolerance' in args:
            force.setEwaldErrorTolerance(args['ewaldErrorTolerance'])
2515
        if 'useDispersionCorrection' in args:
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
            lrc_keyword = bool(args['useDispersionCorrection'])
            if self.useDispersionCorrection is not None and lrc_keyword != self.useDispersionCorrection:
                warnings.warn(
                    "Conflicting settings for useDispersionCorrection in createSystem() and forcefield file. "
                    "Using the one specified in createSystem()."
                )
            force.setUseDispersionCorrection(lrc_keyword)
        elif self.useDispersionCorrection is not None:
            force.setUseDispersionCorrection(self.useDispersionCorrection)
        else:
            # by default
            force.setUseDispersionCorrection(True)
peastman's avatar
peastman committed
2528
        sys.addForce(force)
Justin MacCallum's avatar
Justin MacCallum committed
2529

peastman's avatar
peastman committed
2530
    def postprocessSystem(self, sys, data, args):
2531
2532
        # Create the exceptions.

2533
        bondIndices = _findBondsForExclusions(data, sys)
peastman's avatar
peastman committed
2534
        nonbonded = [f for f in sys.getForces() if isinstance(f, mm.NonbondedForce)][0]
Justin MacCallum's avatar
Justin MacCallum committed
2535
        nonbonded.createExceptionsFromBonds(bondIndices, self.coulomb14scale, self.lj14scale)
2536
2537
2538

parsers["NonbondedForce"] = NonbondedGenerator.parseElement

2539
2540

## @private
ChayaSt's avatar
ChayaSt committed
2541
class LennardJonesGenerator(object):
ChayaSt's avatar
ChayaSt committed
2542
2543
    """A NBFix generator to construct the L-J force with NBFIX implemented as a lookup table"""

2544
    def __init__(self, forcefield, lj14scale, useDispersionCorrection):
ChayaSt's avatar
ChayaSt committed
2545
        self.ff = forcefield
2546
        self.nbfixTypes = {}
ChayaSt's avatar
ChayaSt committed
2547
        self.lj14scale = lj14scale
2548
        self.useDispersionCorrection = useDispersionCorrection
2549
        self.ljTypes = ForceField._AtomTypeParameters(forcefield, 'LennardJonesForce', 'Atom', ('sigma', 'epsilon'))
ChayaSt's avatar
ChayaSt committed
2550

ChayaSt's avatar
ChayaSt committed
2551
    def registerNBFIX(self, parameters):
ChayaSt's avatar
ChayaSt committed
2552
2553
        types = self.ff._findAtomTypes(parameters, 2)
        if None not in types:
2554
2555
2556
2557
2558
2559
            for type1 in types[0]:
                for type2 in types[1]:
                    epsilon = _convertParameterToNumber(parameters['epsilon'])
                    sigma = _convertParameterToNumber(parameters['sigma'])
                    self.nbfixTypes[(type1, type2)] = [sigma, epsilon]
                    self.nbfixTypes[(type2, type1)] = [sigma, epsilon]
2560

ChayaSt's avatar
ChayaSt committed
2561
    def registerLennardJones(self, parameters):
2562
        self.ljTypes.registerAtom(parameters)
ChayaSt's avatar
ChayaSt committed
2563
2564
2565

    @staticmethod
    def parseElement(element, ff):
ChayaSt's avatar
ChayaSt committed
2566
        existing = [f for f in ff._forces if isinstance(f, LennardJonesGenerator)]
2567
2568
2569
2570
        if 'useDispersionCorrection' in element.attrib:
            useDispersionCorrection = bool(eval(element.attrib.get('useDispersionCorrection')))
        else:
            useDispersionCorrection = None
ChayaSt's avatar
ChayaSt committed
2571
        if len(existing) == 0:
2572
2573
2574
2575
2576
            generator = LennardJonesGenerator(
                ff,
                float(element.attrib['lj14scale']),
                useDispersionCorrection=useDispersionCorrection
            )
ChayaSt's avatar
ChayaSt committed
2577
2578
            ff.registerGenerator(generator)
        else:
ChayaSt's avatar
ChayaSt committed
2579
            # Multiple <LennardJonesForce> tags were found, probably in different files
ChayaSt's avatar
ChayaSt committed
2580
            generator = existing[0]
2581
2582
            if abs(generator.lj14scale - float(element.attrib['lj14scale'])) > NonbondedGenerator.SCALETOL:
                raise ValueError('Found multiple LennardJonesForce tags with different 1-4 scales')
2583
2584
2585
2586
2587
2588
            if (
                    generator.useDispersionCorrection is not None
                    and useDispersionCorrection is not None
                    and generator.useDispersionCorrection != useDispersionCorrection
            ):
                raise ValueError('Found multiple LennardJonesForce tags with different useDispersionCorrection settings.')
ChayaSt's avatar
ChayaSt committed
2589
2590
        for LJ in element.findall('Atom'):
            generator.registerLennardJones(LJ.attrib)
ChayaSt's avatar
ChayaSt committed
2591
        for Nbfix in element.findall('NBFixPair'):
ChayaSt's avatar
ChayaSt committed
2592
            generator.registerNBFIX(Nbfix.attrib)
ChayaSt's avatar
ChayaSt committed
2593

ChayaSt's avatar
ChayaSt committed
2594
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
peastman's avatar
peastman committed
2595
2596
        # First derive the lookup tables.  We need to include entries for every type
        # that a) appears in the system and b) has unique parameters.
2597
2598

        nbfixTypeSet = set().union(*self.nbfixTypes)
peastman's avatar
peastman committed
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
        allTypes = set(data.atomType[atom] for atom in data.atoms)
        mergedTypes = []
        mergedTypeParams = []
        paramsToMergedType = {}
        typeToMergedType = {}
        for t in allTypes:
            typeParams = self.ljTypes.paramsForType[t]
            params = (typeParams['sigma'], typeParams['epsilon'])
            if t in nbfixTypeSet:
                # NBFIX types cannot be merged.
                typeToMergedType[t] = len(mergedTypes)
                mergedTypes.append(t)
                mergedTypeParams.append(params)
            elif params in paramsToMergedType:
                # We can merge this with another type.
                typeToMergedType[t] = paramsToMergedType[params]
2615
            else:
peastman's avatar
peastman committed
2616
2617
2618
2619
2620
                # This is a new type.
                typeToMergedType[t] = len(mergedTypes)
                paramsToMergedType[params] = len(mergedTypes)
                mergedTypes.append(t)
                mergedTypeParams.append(params)
2621

ChayaSt's avatar
ChayaSt committed
2622
        # Now everything is assigned. Create the A- and B-coefficient arrays
2623

peastman's avatar
peastman committed
2624
        numLjTypes = len(mergedTypes)
2625
        acoef = [0]*(numLjTypes*numLjTypes)
ChayaSt's avatar
ChayaSt committed
2626
        bcoef = acoef[:]
2627
2628
        for m in range(numLjTypes):
            for n in range(numLjTypes):
peastman's avatar
peastman committed
2629
                pair = (mergedTypes[m], mergedTypes[n])
2630
2631
2632
2633
2634
2635
                if pair in self.nbfixTypes:
                    epsilon = self.nbfixTypes[pair][1]
                    sigma = self.nbfixTypes[pair][0]
                    sigma6 = sigma**6
                    acoef[m+numLjTypes*n] = 4*epsilon*sigma6*sigma6
                    bcoef[m+numLjTypes*n] = 4*epsilon*sigma6
ChayaSt's avatar
cleanup  
ChayaSt committed
2636
                    continue
ChayaSt's avatar
ChayaSt committed
2637
                else:
peastman's avatar
peastman committed
2638
                    sigma = 0.5*(mergedTypeParams[m][0]+mergedTypeParams[n][0])
2639
                    sigma6 = sigma**6
peastman's avatar
peastman committed
2640
                    epsilon = math.sqrt(mergedTypeParams[m][1]*mergedTypeParams[n][1])
2641
2642
2643
2644
2645
2646
                    acoef[m+numLjTypes*n] = 4*epsilon*sigma6*sigma6
                    bcoef[m+numLjTypes*n] = 4*epsilon*sigma6

        self.force = mm.CustomNonbondedForce('acoef(type1, type2)/r^12 - bcoef(type1, type2)/r^6;')
        self.force.addTabulatedFunction('acoef', mm.Discrete2DFunction(numLjTypes, numLjTypes, acoef))
        self.force.addTabulatedFunction('bcoef', mm.Discrete2DFunction(numLjTypes, numLjTypes, bcoef))
ChayaSt's avatar
ChayaSt committed
2647
        self.force.addPerParticleParameter('type')
2648
        self.force.setName('LennardJones')
Peter Eastman's avatar
Peter Eastman committed
2649
        if nonbondedMethod in [CutoffPeriodic, Ewald, PME, LJPME]:
ChayaSt's avatar
ChayaSt committed
2650
            self.force.setNonbondedMethod(mm.CustomNonbondedForce.CutoffPeriodic)
ChayaSt's avatar
ChayaSt committed
2651
        elif nonbondedMethod is NoCutoff:
ChayaSt's avatar
ChayaSt committed
2652
            self.force.setNonbondedMethod(mm.CustomNonbondedForce.NoCutoff)
ChayaSt's avatar
ChayaSt committed
2653
        elif nonbondedMethod is CutoffNonPeriodic:
ChayaSt's avatar
ChayaSt committed
2654
            self.force.setNonbondedMethod(mm.CustomNonbondedForce.CutoffNonPeriodic)
ChayaSt's avatar
ChayaSt committed
2655
        else:
2656
            raise AssertionError('Unrecognized nonbonded method [%s]' % nonbondedMethod)
2657
        if args['switchDistance'] is not None:
2658
2659
            self.force.setUseSwitchingFunction(True)
            self.force.setSwitchingDistance(args['switchDistance'])
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
        if 'useDispersionCorrection' in args:
            lrc_keyword = bool(args['useDispersionCorrection'])
            if self.useDispersionCorrection is not None and lrc_keyword != self.useDispersionCorrection:
                warnings.warn(
                    "Conflicting settings for useDispersionCorrection in createSystem() and forcefield file. "
                    "Using the one specified in createSystem()."
                )
            self.force.setUseLongRangeCorrection(lrc_keyword)
        elif self.useDispersionCorrection is not None:
            self.force.setUseLongRangeCorrection(self.useDispersionCorrection)
        else:
            # by default
            self.force.setUseLongRangeCorrection(True)
2673

ChayaSt's avatar
ChayaSt committed
2674
        # Add the particles
2675

peastman's avatar
peastman committed
2676
2677
        for atom in data.atoms:
            self.force.addParticle((typeToMergedType[data.atomType[atom]],))
ChayaSt's avatar
ChayaSt committed
2678
        self.force.setCutoffDistance(nonbondedCutoff)
ChayaSt's avatar
ChayaSt committed
2679
2680
2681
        sys.addForce(self.force)

    def postprocessSystem(self, sys, data, args):
ChayaSt's avatar
ChayaSt committed
2682
        # Create the exceptions.
2683

2684
        bondIndices = _findBondsForExclusions(data, sys)
2685
2686
2687
2688
2689
2690
2691
2692
2693
        forceCopy = deepcopy(self.force)
        forceCopy.createExclusionsFromBonds(bondIndices, 2)
        self.force.createExclusionsFromBonds(bondIndices, 3)
        if self.force.getNumExclusions() > forceCopy.getNumExclusions() and self.lj14scale != 0:
            # We need to create a CustomBondForce and use it to implement the scaled 1-4 interactions.

            bonded = mm.CustomBondForce('%g*epsilon*((sigma/r)^12-(sigma/r)^6)' % (4*self.lj14scale))
            bonded.addPerBondParameter('sigma')
            bonded.addPerBondParameter('epsilon')
2694
            bonded.setName('LennardJones14')
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
            sys.addForce(bonded)
            skip = set(tuple(forceCopy.getExclusionParticles(i)) for i in range(forceCopy.getNumExclusions()))
            for i in range(self.force.getNumExclusions()):
                p1,p2 = self.force.getExclusionParticles(i)
                a1 = data.atoms[p1]
                a2 = data.atoms[p2]
                if (p1,p2) not in skip and (p2,p1) not in skip:
                    type1 = data.atomType[a1]
                    type2 = data.atomType[a2]
                    if (type1, type2) in self.nbfixTypes:
                        sigma, epsilon = self.nbfixTypes[(type1, type2)]
                    else:
                        values1 = self.ljTypes.getAtomParameters(a1, data)
                        values2 = self.ljTypes.getAtomParameters(a2, data)
2709
2710
2711
2712
2713
2714
2715
2716
                        extra1 = self.ljTypes.getExtraParameters(a1, data)
                        extra2 = self.ljTypes.getExtraParameters(a2, data)
                        sigma1 = float(extra1['sigma14']) if 'sigma14' in extra1 else values1[0]
                        sigma2 = float(extra2['sigma14']) if 'sigma14' in extra2 else values2[0]
                        epsilon1 = float(extra1['epsilon14']) if 'epsilon14' in extra1 else values1[1]
                        epsilon2 = float(extra2['epsilon14']) if 'epsilon14' in extra2 else values2[1]
                        sigma = 0.5*(sigma1+sigma2)
                        epsilon = sqrt(epsilon1*epsilon2)
2717
                    bonded.addBond(p1, p2, (sigma, epsilon))
ChayaSt's avatar
ChayaSt committed
2718

ChayaSt's avatar
ChayaSt committed
2719
parsers["LennardJonesForce"] = LennardJonesGenerator.parseElement
2720

2721

2722
## @private
2723
class GBSAOBCGenerator(object):
2724
    """A GBSAOBCGenerator constructs a GBSAOBCForce."""
Justin MacCallum's avatar
Justin MacCallum committed
2725

2726
2727
    def __init__(self, forcefield):
        self.ff = forcefield
2728
        self.params = ForceField._AtomTypeParameters(forcefield, 'GBSAOBCForce', 'Atom', ('charge', 'radius', 'scale'))
2729

2730
    def registerAtom(self, parameters):
2731
        self.params.registerAtom(parameters)
2732

2733
2734
    @staticmethod
    def parseElement(element, ff):
2735
2736
        existing = [f for f in ff._forces if isinstance(f, GBSAOBCGenerator)]
        if len(existing) == 0:
2737
2738
            generator = GBSAOBCGenerator(ff)
            ff.registerGenerator(generator)
2739
2740
2741
        else:
            # Multiple <GBSAOBCForce> tags were found, probably in different files.  Simply add more types to the existing one.
            generator = existing[0]
2742
        generator.params.parseDefinitions(element)
Justin MacCallum's avatar
Justin MacCallum committed
2743

2744
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
2745
2746
2747
2748
2749
2750
        methodMap = {NoCutoff:mm.GBSAOBCForce.NoCutoff,
                     CutoffNonPeriodic:mm.GBSAOBCForce.CutoffNonPeriodic,
                     CutoffPeriodic:mm.GBSAOBCForce.CutoffPeriodic,
                     Ewald:mm.GBSAOBCForce.CutoffPeriodic,
                     PME:mm.GBSAOBCForce.CutoffPeriodic,
                     LJPME:mm.GBSAOBCForce.CutoffPeriodic}
2751
        if nonbondedMethod not in methodMap:
Justin MacCallum's avatar
Justin MacCallum committed
2752
            raise ValueError('Illegal nonbonded method for GBSAOBCForce')
2753
2754
        force = mm.GBSAOBCForce()
        for atom in data.atoms:
2755
2756
            values = self.params.getAtomParameters(atom, data)
            force.addParticle(values[0], values[1], values[2])
2757
2758
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
2759
2760
2761
2762
        if 'soluteDielectric' in args:
            force.setSoluteDielectric(float(args['soluteDielectric']))
        if 'solventDielectric' in args:
            force.setSolventDielectric(float(args['solventDielectric']))
2763
2764
        sys.addForce(force)

2765
2766
    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
2767

2768
2769
2770
2771
        for force in sys.getForces():
            if isinstance(force, mm.NonbondedForce):
                force.setReactionFieldDielectric(1.0)

2772
2773
2774
parsers["GBSAOBCForce"] = GBSAOBCGenerator.parseElement


2775
## @private
2776
class CustomBondGenerator(object):
2777
    """A CustomBondGenerator constructs a CustomBondForce."""
Justin MacCallum's avatar
Justin MacCallum committed
2778

2779
2780
    def __init__(self, forcefield):
        self.ff = forcefield
2781
2782
2783
2784
2785
        self.types1 = []
        self.types2 = []
        self.globalParams = {}
        self.perBondParams = []
        self.paramValues = []
Justin MacCallum's avatar
Justin MacCallum committed
2786

2787
2788
    @staticmethod
    def parseElement(element, ff):
2789
2790
        generator = CustomBondGenerator(ff)
        ff.registerGenerator(generator)
2791
2792
2793
2794
2795
2796
        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'):
2797
            types = ff._findAtomTypes(bond.attrib, 2)
peastman's avatar
peastman committed
2798
            if None not in types:
2799
2800
2801
                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
2802

2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
    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


2823
## @private
2824
class CustomAngleGenerator(object):
2825
    """A CustomAngleGenerator constructs a CustomAngleForce."""
Justin MacCallum's avatar
Justin MacCallum committed
2826

2827
2828
    def __init__(self, forcefield):
        self.ff = forcefield
2829
2830
2831
2832
2833
2834
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.globalParams = {}
        self.perAngleParams = []
        self.paramValues = []
Justin MacCallum's avatar
Justin MacCallum committed
2835

2836
2837
    @staticmethod
    def parseElement(element, ff):
2838
2839
        generator = CustomAngleGenerator(ff)
        ff.registerGenerator(generator)
2840
2841
2842
2843
2844
2845
        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'):
2846
            types = ff._findAtomTypes(angle.attrib, 3)
peastman's avatar
peastman committed
2847
            if None not in types:
2848
2849
2850
2851
                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
2852

2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
    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


2875
## @private
2876
class CustomTorsion(object):
2877
2878
    """A CustomTorsion records the information for a custom torsion definition."""

2879
    def __init__(self, types, paramValues, ordering='charmm'):
2880
2881
2882
2883
2884
        self.types1 = types[0]
        self.types2 = types[1]
        self.types3 = types[2]
        self.types4 = types[3]
        self.paramValues = paramValues
2885
        if ordering in ['default', 'charmm', 'amber']:
2886
2887
            self.ordering = ordering
        else:
2888
            raise ValueError('Illegal ordering type %s for CustomTorsion (%s,%s,%s,%s)' % (ordering, types[0], types[1], types[2], types[3]))
2889

2890
## @private
2891
class CustomTorsionGenerator(object):
2892
    """A CustomTorsionGenerator constructs a CustomTorsionForce."""
Justin MacCallum's avatar
Justin MacCallum committed
2893

2894
2895
    def __init__(self, forcefield):
        self.ff = forcefield
2896
2897
2898
2899
        self.proper = []
        self.improper = []
        self.globalParams = {}
        self.perTorsionParams = []
Justin MacCallum's avatar
Justin MacCallum committed
2900

2901
2902
    @staticmethod
    def parseElement(element, ff):
2903
2904
        generator = CustomTorsionGenerator(ff)
        ff.registerGenerator(generator)
2905
2906
2907
2908
2909
2910
        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'):
2911
            types = ff._findAtomTypes(torsion.attrib, 4)
peastman's avatar
peastman committed
2912
            if None not in types:
2913
2914
                generator.proper.append(CustomTorsion(types, [float(torsion.attrib[param]) for param in generator.perTorsionParams]))
        for torsion in element.findall('Improper'):
2915
            types = ff._findAtomTypes(torsion.attrib, 4)
peastman's avatar
peastman committed
2916
            if None not in types:
2917
2918
2919
2920
                if 'ordering' in element.attrib:
                    generator.improper.append(CustomTorsion(types, [float(torsion.attrib[param]) for param in generator.perTorsionParams], element.attrib['ordering']))
                else:
                    generator.improper.append(CustomTorsion(types, [float(torsion.attrib[param]) for param in generator.perTorsionParams]))
Justin MacCallum's avatar
Justin MacCallum committed
2921

2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
    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:
2950
            match = _matchImproper(data, torsion, self)
2951
2952
2953
            if match is not None:
                (a1, a2, a3, a4, tordef) = match
                force.addTorsion(a1, a2, a3, a4, tordef.paramValues)
2954
2955
2956
2957

parsers["CustomTorsionForce"] = CustomTorsionGenerator.parseElement


2958
## @private
2959
class CustomNonbondedGenerator(object):
2960
2961
    """A CustomNonbondedGenerator constructs a CustomNonbondedForce."""

2962
2963
    def __init__(self, forcefield, energy, bondCutoff):
        self.ff = forcefield
2964
2965
2966
2967
        self.energy = energy
        self.bondCutoff = bondCutoff
        self.globalParams = {}
        self.perParticleParams = []
2968
        self.computedValues = {}
2969
2970
2971
2972
        self.functions = []

    @staticmethod
    def parseElement(element, ff):
2973
2974
        generator = CustomNonbondedGenerator(ff, element.attrib['energy'], int(element.attrib['bondCutoff']))
        ff.registerGenerator(generator)
2975
2976
2977
2978
        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'])
2979
2980
        for value in element.findall('ComputedValue'):
            generator.computedValues[value.attrib['name']] = value.attrib['expression']
2981
2982
        generator.params = ForceField._AtomTypeParameters(ff, 'CustomNonbondedForce', 'Atom', generator.perParticleParams)
        generator.params.parseDefinitions(element)
2983
        generator.functions += _parseFunctions(element)
2984
2985
2986
2987

    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        methodMap = {NoCutoff:mm.CustomNonbondedForce.NoCutoff,
                     CutoffNonPeriodic:mm.CustomNonbondedForce.CutoffNonPeriodic,
2988
2989
2990
2991
                     CutoffPeriodic:mm.CustomNonbondedForce.CutoffPeriodic,
                     Ewald:mm.CustomNonbondedForce.CutoffPeriodic,
                     PME:mm.CustomNonbondedForce.CutoffPeriodic,
                     LJPME:mm.CustomNonbondedForce.CutoffPeriodic}
2992
2993
2994
2995
2996
2997
2998
        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)
2999
3000
        for name in self.computedValues:
            force.addComputedValue(name, self.computedValues[name])
3001
        _createFunctions(force, self.functions)
3002
        for atom in data.atoms:
3003
3004
            values = self.params.getAtomParameters(atom, data)
            force.addParticle(values)
3005
3006
3007
3008
3009
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
        sys.addForce(force)

    def postprocessSystem(self, sys, data, args):
3010
        # Create the exclusions.
3011

3012
        bondIndices = _findBondsForExclusions(data, sys)
3013
3014
3015
        for f in sys.getForces():
            if isinstance(f, mm.CustomNonbondedForce) and f.getEnergyFunction() == self.energy:
                f.createExclusionsFromBonds(bondIndices, self.bondCutoff)
3016
3017
3018
3019

parsers["CustomNonbondedForce"] = CustomNonbondedGenerator.parseElement


3020
## @private
3021
class CustomGBGenerator(object):
3022
    """A CustomGBGenerator constructs a CustomGBForce."""
Justin MacCallum's avatar
Justin MacCallum committed
3023

3024
3025
    def __init__(self, forcefield):
        self.ff = forcefield
3026
3027
3028
3029
3030
3031
3032
3033
        self.globalParams = {}
        self.perParticleParams = []
        self.computedValues = []
        self.energyTerms = []
        self.functions = []

    @staticmethod
    def parseElement(element, ff):
3034
3035
        generator = CustomGBGenerator(ff)
        ff.registerGenerator(generator)
3036
3037
3038
3039
        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'])
3040
3041
        generator.params = ForceField._AtomTypeParameters(ff, 'CustomGBForce', 'Atom', generator.perParticleParams)
        generator.params.parseDefinitions(element)
3042
3043
3044
3045
3046
3047
3048
        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']]))
3049
        generator.functions += _parseFunctions(element)
Justin MacCallum's avatar
Justin MacCallum committed
3050

3051
3052
3053
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        methodMap = {NoCutoff:mm.CustomGBForce.NoCutoff,
                     CutoffNonPeriodic:mm.CustomGBForce.CutoffNonPeriodic,
3054
3055
3056
3057
                     CutoffPeriodic:mm.CustomGBForce.CutoffPeriodic,
                     Ewald:mm.CustomGBForce.CutoffPeriodic,
                     PME:mm.CustomGBForce.CutoffPeriodic,
                     LJPME:mm.CustomGBForce.CutoffPeriodic}
3058
        if nonbondedMethod not in methodMap:
Justin MacCallum's avatar
Justin MacCallum committed
3059
            raise ValueError('Illegal nonbonded method for CustomGBForce')
3060
3061
3062
3063
3064
3065
3066
3067
3068
        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])
3069
        _createFunctions(force, self.functions)
3070
        for atom in data.atoms:
3071
3072
            values = self.params.getAtomParameters(atom, data)
            force.addParticle(values)
3073
3074
3075
3076
3077
3078
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
        sys.addForce(force)

parsers["CustomGBForce"] = CustomGBGenerator.parseElement

3079

3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
## @private
class CustomHbondGenerator(object):
    """A CustomHbondGenerator constructs a CustomHbondForce."""

    def __init__(self, forcefield):
        self.ff = forcefield
        self.donorTypes1 = []
        self.donorTypes2 = []
        self.donorTypes3 = []
        self.acceptorTypes1 = []
        self.acceptorTypes2 = []
        self.acceptorTypes3 = []
        self.globalParams = {}
        self.perDonorParams = []
        self.perAcceptorParams = []
        self.donorParamValues = []
        self.acceptorParamValues = []
        self.functions = []

    @staticmethod
    def parseElement(element, ff):
        generator = CustomHbondGenerator(ff)
        ff.registerGenerator(generator)
        generator.energy = element.attrib['energy']
        generator.bondCutoff = int(element.attrib['bondCutoff'])
        generator.particlesPerDonor = int(element.attrib['particlesPerDonor'])
        generator.particlesPerAcceptor = int(element.attrib['particlesPerAcceptor'])
        if generator.particlesPerDonor < 1 or generator.particlesPerDonor > 3:
            raise ValueError('Illegal value for particlesPerDonor for CustomHbondForce')
        if generator.particlesPerAcceptor < 1 or generator.particlesPerAcceptor > 3:
            raise ValueError('Illegal value for particlesPerAcceptor for CustomHbondForce')
        for param in element.findall('GlobalParameter'):
            generator.globalParams[param.attrib['name']] = float(param.attrib['defaultValue'])
        for param in element.findall('PerDonorParameter'):
            generator.perDonorParams.append(param.attrib['name'])
        for param in element.findall('PerAcceptorParameter'):
            generator.perAcceptorParams.append(param.attrib['name'])
        for donor in element.findall('Donor'):
3118
            types = ff._findAtomTypes(donor.attrib, 3)[:generator.particlesPerDonor]
3119
3120
3121
3122
3123
3124
3125
3126
            if None not in types:
                generator.donorTypes1.append(types[0])
                if len(types) > 1:
                    generator.donorTypes2.append(types[1])
                if len(types) > 2:
                    generator.donorTypes3.append(types[2])
                generator.donorParamValues.append([float(donor.attrib[param]) for param in generator.perDonorParams])
        for acceptor in element.findall('Acceptor'):
3127
            types = ff._findAtomTypes(acceptor.attrib, 3)[:generator.particlesPerAcceptor]
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
            if None not in types:
                generator.acceptorTypes1.append(types[0])
                if len(types) > 1:
                    generator.acceptorTypes2.append(types[1])
                if len(types) > 2:
                    generator.acceptorTypes3.append(types[2])
                generator.acceptorParamValues.append([float(acceptor.attrib[param]) for param in generator.perAcceptorParams])
        generator.functions += _parseFunctions(element)

    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        methodMap = {NoCutoff:mm.CustomHbondForce.NoCutoff,
                     CutoffNonPeriodic:mm.CustomHbondForce.CutoffNonPeriodic,
3140
3141
3142
3143
                     CutoffPeriodic:mm.CustomHbondForce.CutoffPeriodic,
                     Ewald:mm.CustomHbondForce.CutoffPeriodic,
                     PME:mm.CustomHbondForce.CutoffPeriodic,
                     LJPME:mm.CustomHbondForce.CutoffPeriodic}
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
        if nonbondedMethod not in methodMap:
            raise ValueError('Illegal nonbonded method for CustomNonbondedForce')
        force = mm.CustomHbondForce(self.energy)
        sys.addForce(force)
        for param in self.globalParams:
            force.addGlobalParameter(param, self.globalParams[param])
        for param in self.perDonorParams:
            force.addPerDonorParameter(param)
        for param in self.perAcceptorParams:
            force.addPerAcceptorParameter(param)
        _createFunctions(force, self.functions)
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)

        # Add donors.

        if self.particlesPerDonor == 1:
            for atom in data.atoms:
                type1 = data.atomType[atom]
                for i in range(len(self.donorTypes1)):
                    types1 = self.donorTypes1[i]
Peter Eastman's avatar
Peter Eastman committed
3165
                    if type1 in types1:
3166
3167
3168
3169
3170
3171
3172
3173
                        force.addDonor(atom.index, -1, -1, self.donorParamValues[i])
        elif self.particlesPerDonor == 2:
            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.donorTypes1)):
                    types1 = self.donorTypes1[i]
                    types2 = self.donorTypes2[i]
3174
3175
3176
3177
                    if type1 in types1 and type2 in types2:
                        force.addDonor(bond.atom1, bond.atom2, -1, self.donorParamValues[i])
                    elif type1 in types2 and type2 in types1:
                        force.addDonor(bond.atom2, bond.atom1, -1, self.donorParamValues[i])
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
        else:
            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.donorTypes1)):
                    types1 = self.donorTypes1[i]
                    types2 = self.donorTypes2[i]
                    types3 = self.donorTypes3[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.addDonor(angle[0], angle[1], angle[2], self.donorParamValues[i])

        # Add acceptors.

        if self.particlesPerAcceptor == 1:
            for atom in data.atoms:
                type1 = data.atomType[atom]
                for i in range(len(self.acceptorTypes1)):
                    types1 = self.acceptorTypes1[i]
Peter Eastman's avatar
Peter Eastman committed
3197
                    if type1 in types1:
3198
3199
3200
3201
3202
3203
3204
3205
                        force.addAcceptor(atom.index, -1, -1, self.acceptorParamValues[i])
        elif self.particlesPerAcceptor == 2:
            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.acceptorTypes1)):
                    types1 = self.acceptorTypes1[i]
                    types2 = self.acceptorTypes2[i]
3206
                    if type1 in types1 and type2 in types2:
3207
                        force.addAcceptor(bond.atom1, bond.atom2, -1, self.acceptorParamValues[i])
3208
3209
                    elif type1 in types2 and type2 in types1:
                        force.addAcceptor(bond.atom2, bond.atom1, -1, self.acceptorParamValues[i])
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
        else:
            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.acceptorTypes1)):
                    types1 = self.acceptorTypes1[i]
                    types2 = self.acceptorTypes2[i]
                    types3 = self.acceptorTypes3[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.addAcceptor(angle[0], angle[1], angle[2], self.acceptorParamValues[i])

        # Add exclusions.

        for donor in range(force.getNumDonors()):
            (d1, d2, d3, params) = force.getDonorParameters(donor)
            outerAtoms = set((d1, d2, d3))
            if -1 in outerAtoms:
                outerAtoms.remove(-1)
            excludedAtoms = set(outerAtoms)
            for i in range(self.bondCutoff):
                newOuterAtoms = set()
                for atom in outerAtoms:
                    for bond in data.atomBonds[atom]:
                        b = data.bonds[bond]
                        bondedAtom = (b.atom2 if b.atom1 == atom else b.atom1)
                        if bondedAtom not in excludedAtoms:
                            newOuterAtoms.add(bondedAtom)
                            excludedAtoms.add(bondedAtom)
                outerAtoms = newOuterAtoms
            for acceptor in range(force.getNumAcceptors()):
                (a1, a2, a3, params) = force.getAcceptorParameters(acceptor)
                if a1 in excludedAtoms or a2 in excludedAtoms or a3 in excludedAtoms:
                    force.addExclusion(donor, acceptor)

parsers["CustomHbondForce"] = CustomHbondGenerator.parseElement


3248
## @private
3249
class CustomManyParticleGenerator(object):
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
    """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 = []
3262

3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
    @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(',')]))
3275
3276
        generator.params = ForceField._AtomTypeParameters(ff, 'CustomManyParticleForce', 'Atom', generator.perParticleParams)
        generator.params.parseDefinitions(element)
3277
3278
3279
3280

    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        methodMap = {NoCutoff:mm.CustomManyParticleForce.NoCutoff,
                     CutoffNonPeriodic:mm.CustomManyParticleForce.CutoffNonPeriodic,
3281
3282
3283
3284
                     CutoffPeriodic:mm.CustomManyParticleForce.CutoffPeriodic,
                     Ewald:mm.CustomManyParticleForce.CutoffPeriodic,
                     PME:mm.CustomManyParticleForce.CutoffPeriodic,
                     LJPME:mm.CustomManyParticleForce.CutoffPeriodic}
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
        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':
3297
                force.addTabulatedFunction(name, mm.Continuous1DFunction(values, params['min'], params['max'], params['periodic']))
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
            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:
3309
3310
3311
            values = self.params.getAtomParameters(atom, data)
            type = int(self.params.getExtraParameters(atom, data)['filterType'])
            force.addParticle(values, type)
3312
3313
3314
3315
3316
3317
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
        sys.addForce(force)

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

3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
        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)))
3330

3331
3332
        # 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.
3333

3334
3335
3336
3337
3338
3339
3340
3341
3342
        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.
3343

3344
3345
3346
3347
3348
        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
3349
def getAtomPrint(data, atomIndex):
3350

Peter Eastman's avatar
Peter Eastman committed
3351
3352
3353
    if (atomIndex < len(data.atoms)):
        atom = data.atoms[atomIndex]
        returnString = "%4s %4s %5d" % (atom.name, atom.residue.name, atom.residue.index)
3354
    else:
Peter Eastman's avatar
Peter Eastman committed
3355
        returnString = "NA"
3356
3357
3358
3359
3360

    return returnString

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

Peter Eastman's avatar
Peter Eastman committed
3361
def countConstraint(data):
3362

Peter Eastman's avatar
Peter Eastman committed
3363
    bondCount = 0
3364
3365
3366
3367
3368
3369
3370
    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
3371
        if (isConstrained):
3372
            angleCount += 1
Justin MacCallum's avatar
Justin MacCallum committed
3373

3374
    print("Constraints bond=%d angle=%d  total=%d" % (bondCount, angleCount, (bondCount+angleCount)))
3375

3376
## @private
3377
class AmoebaBondGenerator(object):
3378
3379
3380

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

3381
    """An AmoebaBondGenerator constructs a AmoebaBondForce."""
3382
3383

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

3385
3386
    def __init__(self, cubic, quartic):

Peter Eastman's avatar
Peter Eastman committed
3387
3388
3389
3390
3391
3392
        self.cubic = cubic
        self.quartic = quartic
        self.types1 = []
        self.types2 = []
        self.length = []
        self.k = []
Justin MacCallum's avatar
Justin MacCallum committed
3393

3394
3395
3396
3397
3398
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

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

3402
        generator = AmoebaBondGenerator(element.attrib['bond-cubic'], element.attrib['bond-quartic'])
3403
3404
        forceField._forces.append(generator)
        for bond in element.findall('Bond'):
3405
            types = forceField._findAtomTypes(bond.attrib, 2)
peastman's avatar
peastman committed
3406
            if None not in types:
3407
3408
3409
3410
3411
                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:
3412
                outputString = "AmoebaBondGenerator: error getting types: %s %s" % (
3413
                                    bond.attrib['class1'],
Peter Eastman's avatar
Peter Eastman committed
3414
                                    bond.attrib['class2'])
Justin MacCallum's avatar
Justin MacCallum committed
3415
3416
                raise ValueError(outputString)

3417
3418
    #=============================================================================================

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

3421
3422
        energy = "k*(d^2 + %s*d^3 + %s*d^4); d=r-r0" % (self.cubic, self.quartic)
        existing = [f for f in sys.getForces() if type(f) == mm.CustomBondForce and f.getEnergyFunction() == energy]
3423
        if len(existing) == 0:
3424
3425
3426
            force = mm.CustomBondForce(energy)
            force.addPerBondParameter('r0')
            force.addPerBondParameter('k')
3427
            force.setName('AmoebaBond')
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
            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:
3441
                        data.addConstraint(sys, bond.atom1, bond.atom2, self.length[i])
3442
3443
                    if self.k[i] != 0:
                        if not bond.isConstrained or args.get('flexibleConstraints', False):
3444
                            force.addBond(bond.atom1, bond.atom2, [self.length[i], self.k[i]])
3445
3446
                    break

3447
parsers["AmoebaBondForce"] = AmoebaBondGenerator.parseElement
3448
3449
3450
3451

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

Peter Eastman's avatar
Peter Eastman committed
3453
def addAngleConstraint(angle, idealAngle, data, sys):
3454
3455

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

Peter Eastman's avatar
Peter Eastman committed
3457
3458
    bond1 = None
    bond2 = None
3459
3460
3461
3462
3463
3464
3465
    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
3466

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

3469
3470
3471
3472
        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
3473
                length = sqrt(l1*l1 + l2*l2 - 2*l1*l2*cos(idealAngle))
3474
                data.addConstraint(sys, angle[0], angle[2], length)
3475
3476
3477
                return

#=============================================================================================
3478
## @private
3479
class AmoebaAngleGenerator(object):
3480
3481

    #=============================================================================================
3482
    """An AmoebaAngleGenerator constructs a AmoebaAngleForce."""
3483
    #=============================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
3484

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

Peter Eastman's avatar
Peter Eastman committed
3487
3488
3489
3490
3491
        self.forceField = forceField
        self.cubic = cubic
        self.quartic = quartic
        self.pentic = pentic
        self.sextic = sextic
3492

Peter Eastman's avatar
Peter Eastman committed
3493
3494
3495
        self.types1 = []
        self.types2 = []
        self.types3 = []
3496

Peter Eastman's avatar
Peter Eastman committed
3497
3498
        self.angle = []
        self.k = []
3499
        self.inPlane = []
Justin MacCallum's avatar
Justin MacCallum committed
3500

3501
3502
3503
3504
3505
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

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

3509
3510
3511
3512
3513
3514
3515
3516
        existing = [f for f in forceField._forces if isinstance(f, AmoebaAngleGenerator)]
        if len(existing) == 0:
            generator = AmoebaAngleGenerator(forceField, element.attrib['angle-cubic'], element.attrib['angle-quartic'],  element.attrib['angle-pentic'], element.attrib['angle-sextic'])
            forceField.registerGenerator(generator)
        else:
            generator = existing[0]
            if tuple(element.attrib[x] for x in ('angle-cubic', 'angle-quartic', 'angle-pentic', 'angle-sextic')) != (generator.cubic, generator.quartic, generator.pentic, generator.sextic):
                raise ValueError('All <AmoebaAngleForce> tags must use identical scale factors')
3517
        for angle in element.findall('Angle'):
3518
            types = forceField._findAtomTypes(angle.attrib, 3)
peastman's avatar
peastman committed
3519
            if None not in types:
3520
3521
3522
3523
3524
3525

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

                angleList = []
Peter Eastman's avatar
Peter Eastman committed
3526
                angleList.append(float(angle.attrib['angle1']))
3527

3528
                if 'angle2' in angle.attrib:
Peter Eastman's avatar
Peter Eastman committed
3529
                    angleList.append(float(angle.attrib['angle2']))
3530
3531
3532
                if 'angle3' in angle.attrib:
                    angleList.append(float(angle.attrib['angle3']))

3533
3534
                generator.angle.append(angleList)
                generator.k.append(float(angle.attrib['k']))
3535
3536
3537
3538
                if 'inPlane' in angle.attrib:
                    generator.inPlane.append(angle.attrib['inPlane'].lower() == 'true')
                else:
                    generator.inPlane.append(None) # for backward compatibility with older versions of AMOEBA
3539
            else:
3540
                outputString = "AmoebaAngleGenerator: error getting types: %s %s %s" % (
3541
3542
                                    angle.attrib['class1'],
                                    angle.attrib['class2'],
Peter Eastman's avatar
Peter Eastman committed
3543
                                    angle.attrib['class3'])
Justin MacCallum's avatar
Justin MacCallum committed
3544
3545
                raise ValueError(outputString)

3546
3547
3548
3549
    #=============================================================================================
    # 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
3550

Peter Eastman's avatar
Peter Eastman committed
3551
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
3552
3553
        if not any(isinstance(f, AmoebaOutOfPlaneBendGenerator) for f in self.forceField.getGenerators()):
            raise ValueError('A ForceField containing an <AmoebaAngleForce> must also contain an <AmoebaOutOfPlaneBendForce>')
3554
3555
3556
3557
3558

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

Peter Eastman's avatar
Peter Eastman committed
3560
    def createForcePostOpBendAngle(self, sys, data, nonbondedMethod, nonbondedCutoff, angleList, args):
3561
3562
3563

        # get force

3564
3565
        energy = "k*(d^2 + %s*d^3 + %s*d^4 + %s*d^5 + %s*d^6); d=%.15g*theta-theta0" % (self.cubic, self.quartic, self.pentic, self.sextic, 180/math.pi)
        existing = [f for f in sys.getForces() if type(f) == mm.CustomAngleForce and f.getEnergyFunction() == energy]
3566
3567

        if len(existing) == 0:
3568
3569
3570
            force = mm.CustomAngleForce(energy)
            force.addPerAngleParameter('theta0')
            force.addPerAngleParameter('k')
3571
            force.setName('AmoebaAngle')
3572
3573
3574
3575
            sys.addForce(force)
        else:
            force = existing[0]

3576
3577
        DEG_TO_RAD = math.pi / 180

3578
        for angleDict in angleList:
Peter Eastman's avatar
Peter Eastman committed
3579
3580
            angle = angleDict['angle']
            isConstrained = angleDict['isConstrained']
3581
            inPlane = angleDict['inPlane']
3582

Peter Eastman's avatar
Peter Eastman committed
3583
3584
3585
            type1 = data.atomType[data.atoms[angle[0]]]
            type2 = data.atomType[data.atoms[angle[1]]]
            type3 = data.atomType[data.atoms[angle[2]]]
3586
            for i in range(len(self.types1)):
3587
3588
3589
                # self.inPlane is used for modern force fields.  inPlane is used for legacy ones that don't specify it.
                if self.inPlane[i] or (self.inPlane[i] is None and inPlane):
                    continue
3590
3591
3592
3593
3594
3595
                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]
3596
3597
                        addAngleConstraint(angle, self.angle[i][0]*DEG_TO_RAD, data, sys)
                    if self.k[i] != 0 and (not isConstrained or args.get('flexibleConstraints', False)):
Peter Eastman's avatar
Peter Eastman committed
3598
3599
                        lenAngle = len(self.angle[i])
                        if (lenAngle > 1):
3600
3601
3602
3603
3604
3605
                            # 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
3606
                                if (atom1 == angle[1] and atom2 != angle[0] and atom2 != angle[2] and (sys.getParticleMass(atom2)/unit.dalton) < 1.90):
3607
                                    numberOfHydrogens += 1
Peter Eastman's avatar
Peter Eastman committed
3608
                                if (atom2 == angle[1] and atom1 != angle[0] and atom1 != angle[2] and (sys.getParticleMass(atom1)/unit.dalton) < 1.90):
3609
                                    numberOfHydrogens += 1
Peter Eastman's avatar
Peter Eastman committed
3610
                            if (numberOfHydrogens < lenAngle):
3611
3612
                                angleValue =  self.angle[i][numberOfHydrogens]
                            else:
3613
                                outputString = "AmoebaAngleGenerator angle index=%d is out of range: [0, %5d] " % (numberOfHydrogens, lenAngle)
Justin MacCallum's avatar
Justin MacCallum committed
3614
                                raise ValueError(outputString)
3615
3616
                        else:
                            angleValue =  self.angle[i][0]
Justin MacCallum's avatar
Justin MacCallum committed
3617

3618
                        angleDict['idealAngle'] = angleValue
3619
                        force.addAngle(angle[0], angle[1], angle[2], [angleValue, self.k[i]])
3620
3621
3622
3623
3624
3625
                    break

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

Peter Eastman's avatar
Peter Eastman committed
3627
    def createForcePostOpBendInPlaneAngle(self, sys, data, nonbondedMethod, nonbondedCutoff, angleList, args):
3628
3629
3630

        # get force

3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
        energy = """k*(d^2 + %s*d^3 + %s*d^4 + %s*d^5 + %s*d^6); d=theta-theta0;
                    theta = %.15g*pointangle(x1, y1, z1, projx, projy, projz, x3, y3, z3);
                    projx = x2-nx*dot; projy = y2-ny*dot; projz = z2-nz*dot;
                    dot = nx*(x2-x3) + ny*(y2-y3) + nz*(z2-z3);
                    nx = px/norm; ny = py/norm; nz = pz/norm;
                    norm = sqrt(px*px + py*py + pz*pz);
                    px = (d1y*d2z-d1z*d2y); py = (d1z*d2x-d1x*d2z); pz = (d1x*d2y-d1y*d2x);
                    d1x = x1-x4; d1y = y1-y4; d1z = z1-z4;
                    d2x = x3-x4; d2y = y3-y4; d2z = z3-z4""" % (self.cubic, self.quartic, self.pentic, self.sextic, 180/math.pi)
        existing = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getEnergyFunction() == energy]
3641
        if len(existing) == 0:
3642
3643
3644
            force = mm.CustomCompoundBondForce(4, energy)
            force.addPerBondParameter("theta0")
            force.addPerBondParameter("k")
3645
            force.setName('AmoebaInPlaneAngle')
3646
3647
3648
3649
3650
            sys.addForce(force)
        else:
            force = existing[0]

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

Peter Eastman's avatar
Peter Eastman committed
3652
3653
            angle = angleDict['angle']
            isConstrained = angleDict['isConstrained']
3654
            inPlane = angleDict['inPlane']
3655

Peter Eastman's avatar
Peter Eastman committed
3656
3657
3658
            type1 = data.atomType[data.atoms[angle[0]]]
            type2 = data.atomType[data.atoms[angle[1]]]
            type3 = data.atomType[data.atoms[angle[2]]]
3659
3660

            for i in range(len(self.types1)):
3661
3662
3663
                # self.inPlane is used for modern force fields.  inPlane is used for legacy ones that don't specify it.
                if self.inPlane[i] == False or (self.inPlane[i] is None and not inPlane):
                    continue
3664
3665
3666
3667
3668
3669
                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
3670
                    if (isConstrained and self.k[i] != 0.0):
3671
                        addAngleConstraint(angle, self.angle[i][0]*math.pi/180.0, data, sys)
3672
                    if self.k[i] != 0.0 and (not isConstrained or args.get('flexibleConstraints', False)):
3673
                        force.addBond((angle[0], angle[1], angle[2], angle[3]), (self.angle[i][0], self.k[i]))
3674
3675
                    break

3676
parsers["AmoebaAngleForce"] = AmoebaAngleGenerator.parseElement
3677
3678
3679

#=============================================================================================
# Generator for the AmoebaOutOfPlaneBend covalent force; also calls methods in the
3680
3681
# AmoebaAngleGenerator to generate the AmoebaAngleForce and
# AmoebaInPlaneAngleForce
3682
3683
#=============================================================================================

3684
## @private
3685
class AmoebaOutOfPlaneBendGenerator(object):
3686
3687
3688
3689

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

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

3691
3692
3693
3694
    #=============================================================================================

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

Peter Eastman's avatar
Peter Eastman committed
3695
3696
3697
3698
3699
3700
        self.forceField = forceField
        self.type = type
        self.cubic = cubic
        self.quartic = quartic
        self.pentic = pentic
        self.sextic = sextic
3701

Peter Eastman's avatar
Peter Eastman committed
3702
3703
3704
3705
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.types4 = []
3706

Peter Eastman's avatar
Peter Eastman committed
3707
        self.ks = []
3708
3709
3710
3711
3712

    #=============================================================================================
    # 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
3713

3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
    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
3739

3740
3741
        # get global scalar parameters

3742
3743
3744
3745
3746
3747
3748
3749
        existing = [f for f in forceField._forces if isinstance(f, AmoebaOutOfPlaneBendGenerator)]
        if len(existing) == 0:
            generator = AmoebaOutOfPlaneBendGenerator(forceField, element.attrib['type'], element.attrib['opbend-cubic'], element.attrib['opbend-quartic'],  element.attrib['opbend-pentic'], element.attrib['opbend-sextic'])
            forceField.registerGenerator(generator)
        else:
            generator = existing[0]
            if tuple(element.attrib[x] for x in ('type', 'opbend-cubic', 'opbend-quartic', 'opbend-pentic', 'opbend-sextic')) != (generator.type, generator.cubic, generator.quartic, generator.pentic, generator.sextic):
                raise ValueError('All <AmoebaOutOfPlaneBendForce> tags must use identical scale factors')
3750
3751

        for angle in element.findall('Angle'):
3752
3753
3754
3755
            if 'class3' in angle.attrib and 'class4' in angle.attrib and angle.attrib['class3'] == '0' and angle.attrib['class4'] == '0':
                # This is needed for backward compatibility with old AMOEBA force fields that specified wildcards in a nonstandard way.
                angle.attrib['class3'] = ''
                angle.attrib['class4'] = ''
Peter Eastman's avatar
Peter Eastman committed
3756
            types = generator.findAtomTypes(forceField, angle, 4)
3757
3758
            if types is not None:

Peter Eastman's avatar
Peter Eastman committed
3759
3760
3761
3762
                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.types3.append(types[2])
                generator.types4.append(types[3])
3763

Peter Eastman's avatar
Peter Eastman committed
3764
                generator.ks.append(float(angle.attrib['k']))
3765
3766

            else:
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3767
3768
                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
3769
3770
                raise ValueError(outputString)

3771
3772
    #=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
3773
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
3774
3775
        self._nonbondedMethod = nonbondedMethod
        self._nonbondedCutoff = nonbondedCutoff
3776

3777
3778
    def postprocessSystem(self, sys, data, args):
        # We need to wait until after all bonds have been added so their lengths will be set correctly.
3779

3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
        energy = """k*(theta^2 + %s*theta^3 + %s*theta^4 + %s*theta^5 + %s*theta^6);
                    theta = %.15g*pointangle(x2, y2, z2, x4, y4, z4, projx, projy, projz);
                    projx = x2-nx*dot; projy = y2-ny*dot; projz = z2-nz*dot;
                    dot = nx*(x2-x3) + ny*(y2-y3) + nz*(z2-z3);
                    nx = px/norm; ny = py/norm; nz = pz/norm;
                    norm = sqrt(px*px + py*py + pz*pz);
                    px = (d1y*d2z-d1z*d2y); py = (d1z*d2x-d1x*d2z); pz = (d1x*d2y-d1y*d2x);
                    d1x = x1-x4; d1y = y1-y4; d1z = z1-z4;
                    d2x = x3-x4; d2y = y3-y4; d2z = z3-z4""" % (self.cubic, self.quartic, self.pentic, self.sextic, 180/math.pi)
        existing = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getEnergyFunction() == energy]
3790
        if len(existing) == 0:
3791
3792
            force = mm.CustomCompoundBondForce(4, energy)
            force.addPerBondParameter("k")
3793
            force.setName('AmoebaOutOfPlaneBend')
3794
3795
3796
        else:
            force = existing[0]

3797
        # this hash is used to ensure the out-of-plane-bend bonds
3798
3799
        # are only added once

Peter Eastman's avatar
Peter Eastman committed
3800
        skipAtoms = dict()
3801
        angles = []
3802

3803
3804
3805
3806
3807
3808
3809
        def addBond(particles):
            types = [data.atomType[data.atoms[p]] for p in particles]
            for i in range(len(self.types1)):
                if types[1] in self.types2[i] and types[3] in self.types1[i]:
                    if (types[0] in self.types3[i] and types[2] in self.types4[i]) or (types[2] in self.types3[i] and types[0] in self.types4[i]):
                        force.addBond(particles, [self.ks[i]])
                        return
3810
3811
3812

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

3813
3814
3815
            middleAtom = angle[1]
            middleType = data.atomType[data.atoms[middleAtom]]
            middleCovalency = len(data.atomBonds[middleAtom])
3816

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

3823
            if middleCovalency == 3 and middleAtom not in skipAtoms:
3824

Peter Eastman's avatar
Peter Eastman committed
3825
                partners = []
3826
3827
3828
3829

                for bond in data.atomBonds[middleAtom]:
                    atom1 = data.bonds[bond].atom1
                    atom2 = data.bonds[bond].atom2
3830
                    if atom1 != middleAtom:
3831
3832
3833
3834
3835
3836
3837
3838
                        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]
3839
                        if middleType in types2 and partnerType in types1:
Peter Eastman's avatar
Peter Eastman committed
3840
                            partners.append(partner)
3841
                            break
Justin MacCallum's avatar
Justin MacCallum committed
3842

3843
                if len(partners) == 3:
3844

3845
3846
3847
                    addBond([partners[0], middleAtom, partners[1], partners[2]])
                    addBond([partners[2], middleAtom, partners[0], partners[1]])
                    addBond([partners[1], middleAtom, partners[2], partners[0]])
3848

3849
                    # skipAtoms is used to ensure angles are only included once
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3850

3851
                    skipAtoms[middleAtom] = set(partners[:3])
Peter Eastman's avatar
Peter Eastman committed
3852

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3853
3854
                    # in-plane angle

Peter Eastman's avatar
Peter Eastman committed
3855
                    angleDict = {}
3856
3857
3858
3859
                    angleList = list(angle[:3])
                    for atomIndex in partners:
                        if atomIndex not in angleList:
                            angleList.append(atomIndex)
3860
                    angleDict['angle'] = angleList
Peter Eastman's avatar
Peter Eastman committed
3861
                    angleDict['isConstrained'] = 0
3862
3863
                    angleDict['inPlane'] = True
                    angles.append(angleDict)
3864
3865

                else:
Peter Eastman's avatar
Peter Eastman committed
3866
                    angleDict = {}
3867
3868
3869
3870
                    angleList = list(angle[:3])
                    for atomIndex in partners:
                        if atomIndex not in angleList:
                            angleList.append(atomIndex)
Peter Eastman's avatar
Peter Eastman committed
3871
3872
                    angleDict['angle'] = angleList
                    angleDict['isConstrained'] = isConstrained
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
                    angleDict['inPlane'] = False
                    angles.append(angleDict)
            elif middleCovalency == 3 and middleAtom in skipAtoms:

                angleDict = {}
                angleList = list(angle[:3])
                for atomIndex in skipAtoms[middleAtom]:
                    if atomIndex not in angleList:
                        angleList.append(atomIndex)
                angleDict['angle'] = angleList
                angleDict['isConstrained'] = isConstrained
                angleDict['inPlane'] = True
                angles.append(angleDict)
3886

3887
3888
3889
3890
3891
3892
            else:
                angleDict = {}
                angleDict['angle'] = angle
                angleDict['isConstrained'] = isConstrained
                angleDict['inPlane'] = False
                angles.append(angleDict)
3893

3894
3895
        if len(existing) == 0 and force.getNumBonds() > 0:
            sys.addForce(force)
3896

3897
        # get AmoebaAngleGenerator and add AmoebaAngle and AmoebaInPlaneAngle forces
3898
3899

        for force in self.forceField._forces:
Justin MacCallum's avatar
Justin MacCallum committed
3900
            if (force.__class__.__name__ == 'AmoebaAngleGenerator'):
3901
3902
                force.createForcePostOpBendAngle(sys, data, self._nonbondedMethod, self._nonbondedCutoff, angles, args)
                force.createForcePostOpBendInPlaneAngle(sys, data, self._nonbondedMethod, self._nonbondedCutoff, angles, args)
3903
3904

        for force in self.forceField._forces:
Justin MacCallum's avatar
Justin MacCallum committed
3905
            if (force.__class__.__name__ == 'AmoebaStretchBendGenerator'):
3906
                force.createForcePostAmoebaBondForce(sys, data, self._nonbondedMethod, self._nonbondedCutoff, angles, args)
3907
3908
3909
3910
3911

parsers["AmoebaOutOfPlaneBendForce"] = AmoebaOutOfPlaneBendGenerator.parseElement

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

3912
## @private
3913
class AmoebaTorsionGenerator(object):
3914
3915
3916
3917
3918
3919
3920

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

    def __init__(self, torsionUnit):

Peter Eastman's avatar
Peter Eastman committed
3921
        self.torsionUnit = torsionUnit
3922

Peter Eastman's avatar
Peter Eastman committed
3923
3924
3925
3926
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.types4 = []
3927

Peter Eastman's avatar
Peter Eastman committed
3928
3929
3930
        self.t1 = []
        self.t2 = []
        self.t3 = []
Justin MacCallum's avatar
Justin MacCallum committed
3931

3932
3933
3934
3935
3936
3937
3938
3939
    #=============================================================================================

    @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
3940

Peter Eastman's avatar
Peter Eastman committed
3941
        generator = AmoebaTorsionGenerator(float(element.attrib['torsionUnit']))
3942
3943
3944
3945
3946
3947
        forceField._forces.append(generator)

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

        for torsion in element.findall('Torsion'):
3948
            types = forceField._findAtomTypes(torsion.attrib, 4)
peastman's avatar
peastman committed
3949
            if None not in types:
3950
3951
3952
3953
3954
3955
3956

                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
3957
3958
                    tInfo = []
                    suffix = str(ii)
3959
3960
3961
3962
3963
3964
                    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
3965
3966
3967
3968
3969
3970
                    if (ii == 1):
                        generator.t1.append(tInfo)
                    elif (ii == 2):
                        generator.t2.append(tInfo)
                    elif (ii == 3):
                        generator.t3.append(tInfo)
3971
3972
3973

            else:
                outputString = "AmoebaTorsionGenerator: error getting types: %s %s %s %s" % (
3974
3975
3976
3977
                                    torsion.attrib['class1'],
                                    torsion.attrib['class2'],
                                    torsion.attrib['class3'],
                                    torsion.attrib['class4'])
Justin MacCallum's avatar
Justin MacCallum committed
3978
3979
                raise ValueError(outputString)

3980
3981
3982
3983
    #=============================================================================================

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

3984
        existing = [f for f in sys.getForces() if type(f) == mm.PeriodicTorsionForce]
3985
        if len(existing) == 0:
3986
            force = mm.PeriodicTorsionForce()
3987
3988
3989
            sys.addForce(force)
        else:
            force = existing[0]
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
3990

3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
        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
4007
                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):
4008
4009
4010
4011
4012
4013
                    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])
4014
4015
4016
4017
4018
4019
                    break

parsers["AmoebaTorsionForce"] = AmoebaTorsionGenerator.parseElement

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

4020
## @private
4021
class AmoebaPiTorsionGenerator(object):
4022
4023
4024
4025
4026
4027

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

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

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

4029
    def __init__(self, piTorsionUnit):
Justin MacCallum's avatar
Justin MacCallum committed
4030
        self.piTorsionUnit = piTorsionUnit
Peter Eastman's avatar
Peter Eastman committed
4031
4032
4033
        self.types1 = []
        self.types2 = []
        self.k = []
Justin MacCallum's avatar
Justin MacCallum committed
4034

4035
4036
4037
4038
4039
4040
4041
4042
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

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

Peter Eastman's avatar
Peter Eastman committed
4043
        generator = AmoebaPiTorsionGenerator(float(element.attrib['piTorsionUnit']))
4044
4045
4046
        forceField._forces.append(generator)

        for piTorsion in element.findall('PiTorsion'):
4047
            types = forceField._findAtomTypes(piTorsion.attrib, 2)
peastman's avatar
peastman committed
4048
            if None not in types:
4049
4050
4051
4052
4053
4054
                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
4055
                                    piTorsion.attrib['class2'])
Justin MacCallum's avatar
Justin MacCallum committed
4056
4057
                raise ValueError(outputString)

4058
4059
    #=============================================================================================

4060
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
4061

4062
4063
4064
4065
4066
4067
4068
4069
4070
        energy = """2*k*sin(phi)^2;
                    phi = pointdihedral(x3+c1x, y3+c1y, z3+c1z, x3, y3, z3, x4, y4, z4, x4+c2x, y4+c2y, z4+c2z);
                    c1x = (d14y*d24z-d14z*d24y); c1y = (d14z*d24x-d14x*d24z); c1z = (d14x*d24y-d14y*d24x);
                    c2x = (d53y*d63z-d53z*d63y); c2y = (d53z*d63x-d53x*d63z); c2z = (d53x*d63y-d53y*d63x);
                    d14x = x1-x4; d14y = y1-y4; d14z = z1-z4;
                    d24x = x2-x4; d24y = y2-y4; d24z = z2-z4;
                    d53x = x5-x3; d53y = y5-y3; d53z = z5-z3;
                    d63x = x6-x3; d63y = y6-y3; d63z = z6-z3"""
        existing = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getEnergyFunction() == energy]
4071
4072

        if len(existing) == 0:
4073
4074
            force = mm.CustomCompoundBondForce(6, energy)
            force.addPerBondParameter('k')
4075
            force.setName('AmoebaPiTorsion')
4076
4077
4078
        else:
            force = existing[0]

Peter Eastman's avatar
Peter Eastman committed
4079
        for bond1 in data.bonds:
4080
4081

            # search for bonds with both atoms in bond having covalency == 3
Justin MacCallum's avatar
Justin MacCallum committed
4082

Peter Eastman's avatar
Peter Eastman committed
4083
4084
            atom1 = bond1.atom1
            atom2 = bond1.atom2
Justin MacCallum's avatar
Justin MacCallum committed
4085

4086
            if (len(data.atomBonds[atom1]) == 3 and len(data.atomBonds[atom2]) == 3):
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097

                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
4098
4099
                       # piTorsionAtom1, piTorsionAtom2 are the atoms bonded to atom1, excluding atom2
                       # piTorsionAtom5, piTorsionAtom6 are the atoms bonded to atom2, excluding atom1
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111

                       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
4112
                           if (bondedAtom1 != atom1):
4113
4114
4115
                               b1 = bondedAtom1
                           else:
                               b1 = bondedAtom2
Peter Eastman's avatar
Peter Eastman committed
4116
4117
                           if (b1 != atom2):
                               if (piTorsionAtom1 == -1):
Justin MacCallum's avatar
Justin MacCallum committed
4118
                                   piTorsionAtom1 = b1
4119
4120
4121
4122
4123
4124
                               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
4125
                           if (bondedAtom1 != atom2):
4126
4127
4128
4129
                               b1 = bondedAtom1
                           else:
                               b1 = bondedAtom2

Peter Eastman's avatar
Peter Eastman committed
4130
4131
                           if (b1 != atom1):
                               if (piTorsionAtom5 == -1):
Justin MacCallum's avatar
Justin MacCallum committed
4132
                                   piTorsionAtom5 = b1
4133
4134
                               else:
                                   piTorsionAtom6 = b1
Justin MacCallum's avatar
Justin MacCallum committed
4135

4136
                       force.addBond([piTorsionAtom1, piTorsionAtom2, piTorsionAtom3, piTorsionAtom4, piTorsionAtom5, piTorsionAtom6], [self.k[i]])
4137
4138
        if len(existing) == 0 and force.getNumBonds() > 0:
            sys.addForce(force)
4139
4140
4141
4142
4143

parsers["AmoebaPiTorsionForce"] = AmoebaPiTorsionGenerator.parseElement

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

4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
## @private
class AmoebaStretchTorsionGenerator(object):
    """An AmoebaStretchTorsionGenerator constructs a AmoebaStretchTorsionForce."""

    def __init__(self):
        self.torsions = []

    @staticmethod
    def parseElement(element, forceField):
        generator = AmoebaStretchTorsionGenerator()
        forceField._forces.append(generator)
        params = ('v11', 'v12', 'v13', 'v21', 'v22', 'v23', 'v31', 'v32', 'v33')
        for torsion in element.findall('Torsion'):
            types = forceField._findAtomTypes(torsion.attrib, 4)
            if None not in types:
                v = [float(torsion.attrib[param]) for param in params]
                generator.torsions.append((types, v))

    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        pass

    def postprocessSystem(self, sys, data, args):
        # We need to wait until after all bonds and torsions have been added before adding the stretch-torsions,
        # since it needs parameters from them.

        energy = """v11*(distance(p1,p2)-length1)*phi1 +
                    v12*(distance(p1,p2)-length1)*phi2 +
                    v13*(distance(p1,p2)-length1)*phi3 +
                    v21*(distance(p2,p3)-length2)*phi1 +
                    v22*(distance(p2,p3)-length2)*phi2 +
                    v23*(distance(p2,p3)-length2)*phi3 +
                    v31*(distance(p3,p4)-length3)*phi1 +
                    v32*(distance(p3,p4)-length3)*phi2 +
                    v33*(distance(p3,p4)-length3)*phi3;
                    phi1=1+cos(phi+phase1); phi2=1+cos(2*phi+phase2); phi3=1+cos(3*phi+phase3);
                    phi=dihedral(p1,p2,p3,p4)"""
        existing = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getEnergyFunction() == energy]
        if len(existing) == 0:
            force = mm.CustomCompoundBondForce(4, energy)
            for param in ('v11', 'v12', 'v13', 'v21', 'v22', 'v23', 'v31', 'v32', 'v33'):
                force.addPerBondParameter(param)
            for i in range(3):
                force.addPerBondParameter(f'length{i+1}')
            for i in range(3):
                force.addPerBondParameter(f'phase{i+1}')
            force.setName('AmoebaStretchTorsion')
        else:
            force = existing[0]

        # Record parameters for bonds and torsions so we can look them up quickly.

        bondForce = [f for f in sys.getForces() if type(f) == mm.CustomBondForce and f.getName() == 'AmoebaBond'][0]
        torsionForce = [f for f in sys.getForces() if type(f) == mm.PeriodicTorsionForce][0]
        bondLength = {}
        torsionPhase = defaultdict(lambda: [0.0, math.pi, 0.0])
        for i in range(bondForce.getNumBonds()):
            p1, p2, params = bondForce.getBondParameters(i)
            bondLength[(p1, p2)] = params[0]
            bondLength[(p2, p1)] = params[0]
        for i in range(torsionForce.getNumTorsions()):
            p1, p2, p3, p4, periodicity, phase, k = torsionForce.getTorsionParameters(i)
            if periodicity < 4:
                phase = phase.value_in_unit(unit.radian)
                torsionPhase[(p1, p2, p3, p4)][periodicity-1] = phase
                torsionPhase[(p4, p3, p2, p1)][periodicity-1] = phase

        # Add stretch-torsions.

        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 types, v in self.torsions:
                if (type1 in types[3] and type2 in types[2] and type3 in types[1] and type4 in types[0]):
                    type1, type2, type3, type4 = type4, type3, type2, type1
                    torsion = tuple(reversed(torsion))
                if (type1 in types[0] and type2 in types[1] and type3 in types[2] and type4 in types[3]):
                    params = list(v)
                    params.append(bondLength[(torsion[0], torsion[1])])
                    params.append(bondLength[(torsion[1], torsion[2])])
                    params.append(bondLength[(torsion[2], torsion[3])])
                    params += torsionPhase[torsion]
                    force.addBond(torsion, params)
                    break
        if len(existing) == 0 and force.getNumBonds() > 0:
            sys.addForce(force)

parsers["AmoebaStretchTorsionForce"] = AmoebaStretchTorsionGenerator.parseElement

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

## @private
class AmoebaAngleTorsionGenerator(object):
    """An AmoebaAngleTorsionGenerator constructs a AmoebaAngleTorsionForce."""

    def __init__(self):
        self.torsions = []

    @staticmethod
    def parseElement(element, forceField):
        generator = AmoebaAngleTorsionGenerator()
        forceField._forces.append(generator)
        params = ('v11', 'v12', 'v13', 'v21', 'v22', 'v23')
        for torsion in element.findall('Torsion'):
            types = forceField._findAtomTypes(torsion.attrib, 4)
            if None not in types:
                v = [float(torsion.attrib[param]) for param in params]
                generator.torsions.append((types, v))

    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        pass

    def postprocessSystem(self, sys, data, args):
        # We need to wait until after all angles and torsions have been added before adding the angle-torsions,
        # since it needs parameters from them.

        energy = """v11*(angle(p1,p2,p3)-angle1)*phi1 +
                    v12*(angle(p1,p2,p3)-angle1)*phi2 +
                    v13*(angle(p1,p2,p3)-angle1)*phi3 +
                    v21*(angle(p2,p3,p4)-angle2)*phi1 +
                    v22*(angle(p2,p3,p4)-angle2)*phi2 +
                    v23*(angle(p2,p3,p4)-angle2)*phi3;
                    phi1=1+cos(phi+phase1); phi2=1+cos(2*phi+phase2); phi3=1+cos(3*phi+phase3);
                    phi=dihedral(p1,p2,p3,p4)"""
        existing = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getEnergyFunction() == energy]
        if len(existing) == 0:
            force = mm.CustomCompoundBondForce(4, energy)
            for param in ('v11', 'v12', 'v13', 'v21', 'v22', 'v23'):
                force.addPerBondParameter(param)
            for i in range(2):
                force.addPerBondParameter(f'angle{i+1}')
            for i in range(3):
                force.addPerBondParameter(f'phase{i+1}')
            force.setName('AmoebaAngleTorsion')
        else:
            force = existing[0]

        # Record parameters for angles and torsions so we can look them up quickly.

        angleForce = [f for f in sys.getForces() if type(f) == mm.CustomAngleForce and f.getName() == 'AmoebaAngle'][0]
        inPlaneAngleForce = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getName() == 'AmoebaInPlaneAngle'][0]
        torsionForce = [f for f in sys.getForces() if type(f) == mm.PeriodicTorsionForce][0]
        equilAngle = {}
        torsionPhase = defaultdict(lambda: [0.0, math.pi, 0.0])
        angleScale = math.pi/180
        for i in range(angleForce.getNumAngles()):
            p1, p2, p3, params = angleForce.getAngleParameters(i)
            equilAngle[(p1, p2, p3)] = params[0]*angleScale
            equilAngle[(p3, p2, p1)] = params[0]*angleScale
        for i in range(inPlaneAngleForce.getNumBonds()):
            particles, params = inPlaneAngleForce.getBondParameters(i)
            equilAngle[tuple(particles[:3])] = params[0]*angleScale
            equilAngle[tuple(reversed(particles[:3]))] = params[0]*angleScale
        for i in range(torsionForce.getNumTorsions()):
            p1, p2, p3, p4, periodicity, phase, k = torsionForce.getTorsionParameters(i)
            if periodicity < 4:
                phase = phase.value_in_unit(unit.radian)
                torsionPhase[(p1, p2, p3, p4)][periodicity-1] = phase
                torsionPhase[(p4, p3, p2, p1)][periodicity-1] = phase

        # Add stretch-torsions.

        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 types, v in self.torsions:
                if (type1 in types[3] and type2 in types[2] and type3 in types[1] and type4 in types[0]):
                    type1, type2, type3, type4 = type4, type3, type2, type1
                    torsion = tuple(reversed(torsion))
                if (type1 in types[0] and type2 in types[1] and type3 in types[2] and type4 in types[3]):
                    params = list(v)
                    params.append(equilAngle[(torsion[0], torsion[1], torsion[2])])
                    params.append(equilAngle[(torsion[1], torsion[2], torsion[3])])
                    params += torsionPhase[torsion]
                    force.addBond(torsion, params)
                    break
        if len(existing) == 0 and force.getNumBonds() > 0:
            sys.addForce(force)

parsers["AmoebaAngleTorsionForce"] = AmoebaAngleTorsionGenerator.parseElement

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

4330
## @private
4331
class AmoebaTorsionTorsionGenerator(object):
4332
4333
4334
4335
4336

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

Peter Eastman's avatar
Peter Eastman committed
4337
    def __init__(self):
4338

Peter Eastman's avatar
Peter Eastman committed
4339
4340
4341
4342
4343
        self.types1 = []
        self.types2 = []
        self.types3 = []
        self.types4 = []
        self.types5 = []
4344

Peter Eastman's avatar
Peter Eastman committed
4345
        self.gridIndex = []
4346

Peter Eastman's avatar
Peter Eastman committed
4347
        self.grids = []
Justin MacCallum's avatar
Justin MacCallum committed
4348

4349
4350
4351
4352
4353
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):

Peter Eastman's avatar
Peter Eastman committed
4354
        generator = AmoebaTorsionTorsionGenerator()
4355
4356
4357
4358
4359
4360
4361
        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'):
4362
            types = forceField._findAtomTypes(torsionTorsion.attrib, 5)
peastman's avatar
peastman committed
4363
            if None not in types:
4364
4365
4366
4367
4368
4369
4370

                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
4371
4372
                gridIndex = int(torsionTorsion.attrib['grid'])
                if (gridIndex > maxGridIndex):
4373
4374
4375
4376
4377
4378
4379
4380
4381
                    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
4382
                                    torsionTorsion.attrib['class5'] )
Justin MacCallum's avatar
Justin MacCallum committed
4383
4384
                raise ValueError(outputString)

4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
        # 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
4395
4396
4397
4398
4399
4400
        #     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
4401
4402

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

Peter Eastman's avatar
Peter Eastman committed
4406
4407
4408
            gridIndex = int(torsionTorsionGrid.attrib[ "grid"])
            nx = int(torsionTorsionGrid.attrib[ "nx"])
            ny = int(torsionTorsionGrid.attrib[ "ny"])
4409

Peter Eastman's avatar
Peter Eastman committed
4410
4411
            grid = []
            gridCol = []
4412
4413
4414
4415
4416

            gridColIndex = 0

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

Peter Eastman's avatar
Peter Eastman committed
4417
4418
4419
4420
                gridRow = []
                gridRow.append(float(gridEntry.attrib['angle1']))
                gridRow.append(float(gridEntry.attrib['angle2']))
                gridRow.append(float(gridEntry.attrib['f']))
4421
                if 'fx' in gridEntry.attrib:
4422
4423
4424
                    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
4425
                gridCol.append(gridRow)
4426
4427

                gridColIndex  += 1
Peter Eastman's avatar
Peter Eastman committed
4428
4429
4430
                if (gridColIndex == nx):
                    grid.append(gridCol)
                    gridCol = []
4431
4432
                    gridColIndex = 0

Justin MacCallum's avatar
Justin MacCallum committed
4433

Peter Eastman's avatar
Peter Eastman committed
4434
4435
            if (gridIndex == len(generator.grids)):
                generator.grids.append(grid)
4436
            else:
Peter Eastman's avatar
Peter Eastman committed
4437
4438
                while(len(generator.grids) < gridIndex):
                    generator.grids.append([])
4439
4440
4441
4442
                generator.grids[gridIndex] = grid

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

Peter Eastman's avatar
Peter Eastman committed
4443
    def getChiralAtomIndex(self, data, sys, atomB, atomC, atomD):
4444
4445
4446
4447
4448
4449
4450
4451

        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
4452
        if (len(data.atomBonds[atomC]) == 4):
4453
4454
4455
4456
4457
            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
4458
4459
                hit = -1
                if (  bondedAtom1 == atomC and bondedAtom2 != atomB and bondedAtom2 != atomD):
4460
                    hit = bondedAtom2
Peter Eastman's avatar
Peter Eastman committed
4461
                elif (bondedAtom2 == atomC and bondedAtom1 != atomB and bondedAtom1 != atomD):
4462
4463
                    hit = bondedAtom1

Peter Eastman's avatar
Peter Eastman committed
4464
4465
                if (hit > -1):
                    if (atomE == -1):
4466
4467
4468
                        atomE = hit
                    else:
                        atomF = hit
Justin MacCallum's avatar
Justin MacCallum committed
4469

4470
4471
            # raise error if atoms E or F not found

Peter Eastman's avatar
Peter Eastman committed
4472
            if (atomE == -1 or atomF == -1):
4473
                outputString = "getChiralAtomIndex: error getting bonded partners of atomC=%s %d %s" % (atomC.name, atomC.residue.index, atomC.residue.name,)
Justin MacCallum's avatar
Justin MacCallum committed
4474
                raise ValueError(outputString)
4475
4476
4477
4478
4479

            # 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
4480
            if (typeE > typeF):
Justin MacCallum's avatar
Justin MacCallum committed
4481
                chiralAtomIndex = atomE
Peter Eastman's avatar
Peter Eastman committed
4482
            if (typeF > typeE):
Justin MacCallum's avatar
Justin MacCallum committed
4483
                chiralAtomIndex = atomF
4484

Peter Eastman's avatar
Peter Eastman committed
4485
4486
4487
            massE = sys.getParticleMass(atomE)/unit.dalton
            massF = sys.getParticleMass(atomE)/unit.dalton
            if (massE > massF):
Justin MacCallum's avatar
Justin MacCallum committed
4488
                chiralAtomIndex = massE
Peter Eastman's avatar
Peter Eastman committed
4489
            if (massF > massE):
Justin MacCallum's avatar
Justin MacCallum committed
4490
                chiralAtomIndex = massF
4491
4492
4493
4494

        return chiralAtomIndex

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

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

4498
        existing = [f for f in sys.getForces() if type(f) == mm.AmoebaTorsionTorsionForce]
4499
4500
4501
4502
4503
4504
4505
4506

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

        for angle in data.angles:

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

4509
4510
4511
4512
4513
4514
4515
            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
4516
                if (bondedAtom1 != ib):
4517
4518
4519
4520
                    ia = bondedAtom1
                else:
                    ia = bondedAtom2

Peter Eastman's avatar
Peter Eastman committed
4521
                if (ia != ic and ia != id):
Peter Eastman's avatar
Peter Eastman committed
4522
4523
4524
                    for bondIndex2 in data.atomBonds[id]:
                        bondedAtom1 = data.bonds[bondIndex2].atom1
                        bondedAtom2 = data.bonds[bondIndex2].atom2
Peter Eastman's avatar
Peter Eastman committed
4525
                        if (bondedAtom1 != id):
4526
4527
4528
4529
                            ie = bondedAtom1
                        else:
                            ie = bondedAtom2

Peter Eastman's avatar
Peter Eastman committed
4530
                        if (ie != ic and ie != ib and ie != ia):
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550

                            # 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
4551
4552
4553
                                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])
4554
4555
4556

                                # match in reverse order

4557
                                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
4558
4559
                                    chiralAtomIndex = self.getChiralAtomIndex(data, sys, ib, ic, id)
                                    force.addTorsionTorsion(ie, id, ic, ib, ia, chiralAtomIndex, self.gridIndex[i])
4560
4561
4562
4563

        # set grids

        for (index, grid) in enumerate(self.grids):
Peter Eastman's avatar
Peter Eastman committed
4564
            force.setTorsionTorsionGrid(index, grid)
4565
4566
        if len(existing) == 0 and force.getNumTorsionTorsions() > 0:
            sys.addForce(force)
Justin MacCallum's avatar
Justin MacCallum committed
4567

4568
4569
4570
4571
parsers["AmoebaTorsionTorsionForce"] = AmoebaTorsionTorsionGenerator.parseElement

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

4572
## @private
4573
class AmoebaStretchBendGenerator(object):
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
4574
4575

    #=============================================================================================
4576
4577
4578
    """An AmoebaStretchBendGenerator constructs a AmoebaStretchBendForce."""
    #=============================================================================================

4579
    def __init__(self, forcefield):
4580

4581
        self.forcefield = forcefield
Peter Eastman's avatar
Peter Eastman committed
4582
4583
4584
        self.types1 = []
        self.types2 = []
        self.types3 = []
4585

Peter Eastman's avatar
Peter Eastman committed
4586
4587
        self.k1 = []
        self.k2 = []
Justin MacCallum's avatar
Justin MacCallum committed
4588

4589
4590
4591
4592
    #=============================================================================================

    @staticmethod
    def parseElement(element, forceField):
4593
        generator = AmoebaStretchBendGenerator(forceField)
4594
4595
4596
4597
4598
4599
4600
        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'):
4601
            types = forceField._findAtomTypes(stretchBend.attrib, 3)
peastman's avatar
peastman committed
4602
            if None not in types:
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614

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

4618
4619
    #=============================================================================================

Justin MacCallum's avatar
Justin MacCallum committed
4620
    # The setup of this force is dependent on AmoebaBondForce and AmoebaAngleForce
4621
4622
    # 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
4623
4624
    # AmoebaBondForce and AmoebaAngleForce have been called prior to AmoebaStretchBendGenerator().
    # Instead, createForcePostAmoebaBondForce() is called
4625
    # after the generators for AmoebaBondForce and AmoebaAngleForce have been called
4626
4627
4628

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

Peter Eastman's avatar
Peter Eastman committed
4629
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
4630
4631
        if not any(isinstance(f, AmoebaOutOfPlaneBendGenerator) for f in self.forcefield.getGenerators()):
            raise ValueError('A ForceField containing an <AmoebaStretchBendForce> must also contain an <AmoebaOutOfPlaneBendForce>')
4632
4633
4634
4635
4636
4637
4638

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

    # Note: request for constrained bonds is ignored.

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

4639
    def createForcePostAmoebaBondForce(self, sys, data, nonbondedMethod, nonbondedCutoff, angleList, args):
4640

4641
4642
        energy = "(k1*(distance(p1,p2)-r12) + k2*(distance(p2,p3)-r23))*(%.15g*(angle(p1,p2,p3)-theta0))" % (180/math.pi)
        existing = [f for f in sys.getForces() if type(f) == mm.CustomCompoundBondForce and f.getEnergyFunction() == energy]
4643
        if len(existing) == 0:
4644
4645
4646
4647
4648
4649
            force = mm.CustomCompoundBondForce(3, energy)
            force.addPerBondParameter("r12")
            force.addPerBondParameter("r23")
            force.addPerBondParameter("theta0")
            force.addPerBondParameter("k1")
            force.addPerBondParameter("k2")
4650
            force.setName('AmoebaStretchBend')
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
            sys.addForce(force)
        else:
            force = existing[0]

        for angleDict in angleList:

            angle = angleDict['angle']

            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
4663
            radian = 57.2957795130
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
            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
4674
                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
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
                    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
4690

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

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
4693
                    if ('idealAngle' not in angleDict):
4694

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
4695
4696
4697
4698
4699
                       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
4700
                       raise ValueError(outputString)
4701

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
4702
4703
4704
4705
4706
4707
4708
                    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
4709
                       raise ValueError(outputString)
4710

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
4711
                    else:
4712
4713
4714
4715
4716
                        if type1 in types1 and type3 in types3:
                            k1, k2 = self.k1[i], self.k2[i]
                        else:
                            k1, k2 = self.k2[i], self.k1[i]
                        force.addBond((angle[0], angle[1], angle[2]), (bondAB, bondCB, angleDict['idealAngle']/radian, k1, k2))
4717

Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
4718
                    break
4719
4720
4721
4722
4723

parsers["AmoebaStretchBendForce"] = AmoebaStretchBendGenerator.parseElement

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

4724
## @private
4725
class AmoebaVdwGenerator(object):
4726
4727

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

4729
4730
    #=============================================================================================

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

Justin MacCallum's avatar
Justin MacCallum committed
4733
        self.type = type
4734

Peter Eastman's avatar
Peter Eastman committed
4735
4736
4737
        self.radiusrule = radiusrule
        self.radiustype = radiustype
        self.radiussize = radiussize
4738

Peter Eastman's avatar
Peter Eastman committed
4739
        self.epsilonrule = epsilonrule
4740

Peter Eastman's avatar
Peter Eastman committed
4741
4742
4743
        self.vdw13Scale = vdw13Scale
        self.vdw14Scale = vdw14Scale
        self.vdw15Scale = vdw15Scale
4744
4745
4746
4747
4748
4749
4750

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

    @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
4751
4752
4753
        #   <Vdw class="1" sigma="0.371" epsilon="0.46024" reduction="1.0" />
        #   <Vdw class="2" sigma="0.382" epsilon="0.422584" reduction="1.0" />

4754
4755
4756
        existing = [f for f in forceField._forces if isinstance(f, AmoebaVdwGenerator)]
        if len(existing) == 0:
            generator = AmoebaVdwGenerator(element.attrib['type'], element.attrib['radiusrule'], element.attrib['radiustype'], element.attrib['radiussize'], element.attrib['epsilonrule'],
Justin MacCallum's avatar
Justin MacCallum committed
4757
                                        float(element.attrib['vdw-13-scale']), float(element.attrib['vdw-14-scale']), float(element.attrib['vdw-15-scale']))
4758
            forceField.registerGenerator(generator)
4759
4760
            generator.params = {}
            generator.pairs = []
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
        else:
            # Multiple <AmoebaVdwForce> tags were found, probably in different files.  Simply add more types to the existing one.
            generator = existing[0]
            if abs(generator.vdw13Scale - float(element.attrib['vdw-13-scale'])) > NonbondedGenerator.SCALETOL or \
                    abs(generator.vdw14Scale - float(element.attrib['vdw-14-scale'])) > NonbondedGenerator.SCALETOL or \
                    abs(generator.vdw15Scale - float(element.attrib['vdw-15-scale'])) > NonbondedGenerator.SCALETOL:
                raise ValueError('Found multiple AmoebaVdwForce tags with different scale factors')
            if generator.radiusrule != element.attrib['radiusrule'] or generator.epsilonrule != element.attrib['epsilonrule'] or \
                    generator.radiustype != element.attrib['radiustype'] or generator.radiussize != element.attrib['radiussize']:
                raise ValueError('Found multiple AmoebaVdwForce tags with different combining rules')
4771
4772
4773
4774
4775
        for vdw in element.findall('Vdw'):
            generator.params[vdw.attrib['class']] = tuple(float(vdw.attrib[name]) for name in ('sigma', 'epsilon', 'reduction'))
        for pair in element.findall('Pair'):
            generator.pairs.append((pair.attrib['class1'], pair.attrib['class2'], float(pair.attrib['sigma']), float(pair.attrib['epsilon'])))
        generator.classNameForType = dict((t.name, t.atomClass) for t in forceField._atomTypes.values())
4776
4777
4778
4779

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

    @staticmethod
4780
    def getBondedParticleSets(sys, data):
4781

4782
4783
4784
4785
4786
4787
        bondedParticleSets = [set() for i in range(len(data.atoms))]
        bondIndices = _findBondsForExclusions(data, sys)
        for atom1, atom2 in bondIndices:
            bondedParticleSets[atom1].add(atom2)
            bondedParticleSets[atom2].add(atom1)
        return bondedParticleSets
Justin MacCallum's avatar
Justin MacCallum committed
4788

4789
4790
    #=============================================================================================

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

4793
        potentialMap = {'BUFFERED-14-7':0, 'LENNARD-JONES':1}
Peter Eastman's avatar
Peter Eastman committed
4794
        sigmaMap = {'ARITHMETIC':1, 'GEOMETRIC':1, 'CUBIC-MEAN':1}
Chengwen Liu's avatar
Chengwen Liu committed
4795
        epsilonMap = {'ARITHMETIC':1, 'GEOMETRIC':1, 'HARMONIC':1, 'W-H':1, 'HHG':1}
4796

4797
4798
        force = mm.AmoebaVdwForce()
        sys.addForce(force)
4799

4800
4801
4802
4803
4804
4805
4806
4807
        # Potential function

        if (self.type.upper() in potentialMap):
            force.setPotentialFunction(potentialMap[self.type.upper()])
        else:
            stringList = ' '.join(str(x) for x in potentialMap.keys())
            raise ValueError("AmoebaVdwGenerator: potential type %s not recognized; valid values are %s; using default." % (self.type, stringList))

4808
        # sigma and epsilon combining rules
4809

4810
4811
4812
4813
        if ('sigmaCombiningRule' in args):
            sigmaRule = args['sigmaCombiningRule'].upper()
            if (sigmaRule.upper() in sigmaMap):
                force.setSigmaCombiningRule(sigmaRule.upper())
4814
            else:
4815
4816
4817
4818
                stringList = ' ' . join(str(x) for x in sigmaMap.keys())
                raise ValueError( "AmoebaVdwGenerator: sigma combining rule %s not recognized; valid values are %s; using default." % (sigmaRule, stringList) )
        else:
            force.setSigmaCombiningRule(self.radiusrule)
4819

4820
4821
4822
4823
        if ('epsilonCombiningRule' in args):
            epsilonRule = args['epsilonCombiningRule'].upper()
            if (epsilonRule.upper() in epsilonMap):
                force.setEpsilonCombiningRule(epsilonRule.upper())
4824
            else:
4825
4826
4827
4828
                stringList = ' ' . join(str(x) for x in epsilonMap.keys())
                raise ValueError( "AmoebaVdwGenerator: epsilon combining rule %s not recognized; valid values are %s; using default." % (epsilonRule, stringList) )
        else:
            force.setEpsilonCombiningRule(self.epsilonrule)
Justin MacCallum's avatar
Justin MacCallum committed
4829

4830
        # cutoff
4831

4832
4833
4834
4835
        if ('vdwCutoff' in args):
            force.setCutoff(args['vdwCutoff'])
        else:
            force.setCutoff(nonbondedCutoff)
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
4836

4837
        # dispersion correction
4838

4839
4840
        if ('useDispersionCorrection' in args):
            force.setUseDispersionCorrection(bool(args['useDispersionCorrection']))
4841

4842
4843
        if (nonbondedMethod == PME):
            force.setNonbondedMethod(mm.AmoebaVdwForce.CutoffPeriodic)
4844

4845
        # Define types
4846

4847
4848
4849
4850
4851
        sigmaScale = 1
        if self.radiustype == 'SIGMA':
            sigmaScale = 1.122462048309372
        if self.radiussize == 'DIAMETER':
            sigmaScale = 0.5
4852
4853
4854
4855
4856
4857
4858
        classToTypeMap = {}
        for className in self.params:
            sigma, epsilon, _ = self.params[className]
            classToTypeMap[className] = force.addParticleType(sigma*sigmaScale, epsilon)

        # add particles to force

4859
        for (i, atom) in enumerate(data.atoms):
4860
4861
            className = self.classNameForType[data.atomType[atom]]
            _, _, reduction = self.params[className]
4862
4863
4864
4865
4866
4867
4868
4869
4870
            # 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
4871

4872
4873
4874
            force.addParticle(ivIndex, classToTypeMap[className], reduction)

        # Add pairs
4875

4876
4877
        for c1, c2, sigma, epsilon in self.pairs:
            force.addTypePair(classToTypeMap[c1], classToTypeMap[c2], sigma, epsilon)
4878
4879
4880
4881
4882
4883
4884

        # 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

4885
        bondedParticleSets = AmoebaVdwGenerator.getBondedParticleSets(sys, data)
4886
4887

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

4889
4890
4891
4892
4893
4894
            # 1-2 partners

            exclusionSet = bondedParticleSets[i].copy()

            # 1-3 partners

Peter Eastman's avatar
Peter Eastman committed
4895
            if (self.vdw13Scale == 0.0):
4896
                for bondedParticle in bondedParticleSets[i]:
Peter Eastman's avatar
Peter Eastman committed
4897
                    exclusionSet = exclusionSet.union(bondedParticleSets[bondedParticle])
4898
4899
4900
4901
4902

            # self

            exclusionSet.add(i)

4903
            force.setParticleExclusions(i, tuple(exclusionSet))
4904
4905
4906
4907
4908

parsers["AmoebaVdwForce"] = AmoebaVdwGenerator.parseElement

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

4909
## @private
4910
class AmoebaMultipoleGenerator(object):
4911
4912
4913
4914

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

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

4916
4917
    #=============================================================================================

4918
    def __init__(self, forceField):
Peter Eastman's avatar
Peter Eastman committed
4919
4920
        self.forceField = forceField
        self.typeMap = {}
4921
4922
4923
4924
4925
4926

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

    @staticmethod
Peter Eastman's avatar
Peter Eastman committed
4927
    def setAxisType(kIndices):
4928
4929
4930

                # set axis type

Peter Eastman's avatar
Peter Eastman committed
4931
4932
4933
                kIndicesLen = len(kIndices)
                if (kIndicesLen > 3):
                    ky = kIndices[3]
4934
                else:
Peter Eastman's avatar
Peter Eastman committed
4935
                    ky = 0
Justin MacCallum's avatar
Justin MacCallum committed
4936

Peter Eastman's avatar
Peter Eastman committed
4937
4938
                if (kIndicesLen > 2):
                    kx = kIndices[2]
4939
                else:
Peter Eastman's avatar
Peter Eastman committed
4940
                    kx = 0
Justin MacCallum's avatar
Justin MacCallum committed
4941

Peter Eastman's avatar
Peter Eastman committed
4942
4943
                if (kIndicesLen > 1):
                    kz = kIndices[1]
4944
                else:
Peter Eastman's avatar
Peter Eastman committed
4945
                    kz = 0
4946

Peter Eastman's avatar
Peter Eastman committed
4947
4948
                while(len(kIndices) < 4):
                    kIndices.append(0)
4949
4950

                axisType = mm.AmoebaMultipoleForce.ZThenX
Peter Eastman's avatar
Peter Eastman committed
4951
                if (kz == 0):
4952
                    axisType = mm.AmoebaMultipoleForce.NoAxisType
Peter Eastman's avatar
Peter Eastman committed
4953
                if (kz != 0 and kx == 0):
4954
                    axisType = mm.AmoebaMultipoleForce.ZOnly
Peter Eastman's avatar
Peter Eastman committed
4955
                if (kz < 0 or kx < 0):
4956
                    axisType = mm.AmoebaMultipoleForce.Bisector
Peter Eastman's avatar
Peter Eastman committed
4957
                if (kx < 0 and ky < 0):
4958
                    axisType = mm.AmoebaMultipoleForce.ZBisect
Peter Eastman's avatar
Peter Eastman committed
4959
                if (kz < 0 and kx < 0 and ky  < 0):
4960
4961
                    axisType = mm.AmoebaMultipoleForce.ThreeFold

Justin MacCallum's avatar
Justin MacCallum committed
4962
4963
4964
                kIndices[1] = abs(kz)
                kIndices[2] = abs(kx)
                kIndices[3] = abs(ky)
4965
4966
4967
4968
4969
4970
4971
4972

                return axisType

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

    @staticmethod
    def parseElement(element, forceField):

Justin MacCallum's avatar
Justin MacCallum committed
4973
        #   <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"  >
4974
4975
4976
        # <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"  />

4977
4978
4979
4980
4981
4982
4983
        existing = [f for f in forceField._forces if isinstance(f, AmoebaMultipoleGenerator)]
        if len(existing) == 0:
            generator = AmoebaMultipoleGenerator(forceField)
            forceField.registerGenerator(generator)
        else:
            # Multiple <AmoebaMultipoleForce> tags were found, probably in different files.  Simply add more types to the existing one.
            generator = existing[0]
4984
4985
4986
4987

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

        for atom in element.findall('Multipole'):
4988
            types = forceField._findAtomTypes(atom.attrib, 1)
peastman's avatar
peastman committed
4989
            if None not in types:
4990
4991
4992
4993
4994
4995
4996

                # k-indices not provided default to 0

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

                kStrings = [ 'kz', 'kx', 'ky' ]
                for kString in kStrings:
4997
                    kIndices.append(int(atom.attrib.get(kString,0)))
4998

Justin MacCallum's avatar
Justin MacCallum committed
4999
                # set axis type based on k-Indices
5000

Peter Eastman's avatar
Peter Eastman committed
5001
                axisType = AmoebaMultipoleGenerator.setAxisType(kIndices)
5002
5003
5004

                # set multipole

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

Peter Eastman's avatar
Peter Eastman committed
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
                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']))
5020
5021

                for t in types[0]:
Peter Eastman's avatar
Peter Eastman committed
5022
                    if (t not in generator.typeMap):
5023
5024
                        generator.typeMap[t] = []

Peter Eastman's avatar
Peter Eastman committed
5025
5026
5027
                    valueMap = dict()
                    valueMap['classIndex'] = atom.attrib['type']
                    valueMap['kIndices'] = kIndices
Justin MacCallum's avatar
Justin MacCallum committed
5028
                    valueMap['charge'] = charge
Peter Eastman's avatar
Peter Eastman committed
5029
5030
5031
5032
                    valueMap['dipole'] = dipole
                    valueMap['quadrupole'] = quadrupole
                    valueMap['axisType'] = axisType
                    generator.typeMap[t].append(valueMap)
Justin MacCallum's avatar
Justin MacCallum committed
5033

5034
            else:
Peter Eastman's avatar
Peter Eastman committed
5035
                outputString = "AmoebaMultipoleGenerator: error getting type for multipole: %s" % (atom.attrib['class'])
Justin MacCallum's avatar
Justin MacCallum committed
5036
5037
                raise ValueError(outputString)

5038
        # polarization parameters
Justin MacCallum's avatar
Justin MacCallum committed
5039

5040
        for atom in element.findall('Polarize'):
5041
            types = forceField._findAtomTypes(atom.attrib, 1)
peastman's avatar
peastman committed
5042
            if None not in types:
5043

Peter Eastman's avatar
Peter Eastman committed
5044
5045
5046
5047
                classIndex = atom.attrib['type']
                polarizability = float(atom.attrib['polarizability'])
                thole = float(atom.attrib['thole'])
                if (thole == 0):
5048
5049
                    pdamp = 0
                else:
Peter Eastman's avatar
Peter Eastman committed
5050
                    pdamp = pow(polarizability, 1.0/6.0)
5051

Peter Eastman's avatar
Peter Eastman committed
5052
5053
                pgrpMap = dict()
                for index in range(1, 7):
5054
                    pgrp = 'pgrp' + str(index)
Peter Eastman's avatar
Peter Eastman committed
5055
                    if (pgrp in atom.attrib):
5056
5057
5058
                        pgrpMap[int(atom.attrib[pgrp])] = -1

                for t in types[0]:
Peter Eastman's avatar
Peter Eastman committed
5059
5060
                    if (t not in generator.typeMap):
                        outputString = "AmoebaMultipoleGenerator: polarize type not present: %s" % (atom.attrib['type'])
Justin MacCallum's avatar
Justin MacCallum committed
5061
                        raise ValueError(outputString)
5062
5063
                    else:
                        typeMapList = generator.typeMap[t]
Peter Eastman's avatar
Peter Eastman committed
5064
5065
5066
5067
5068
5069
5070
                        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
5071
                                typeMap['pgrpMap'] = pgrpMap
Peter Eastman's avatar
Peter Eastman committed
5072
5073
5074
5075
5076
                                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
5077
5078
                            raise ValueError(outputString)

5079
            else:
Peter Eastman's avatar
Peter Eastman committed
5080
                outputString = "AmoebaMultipoleGenerator: error getting type for polarize: %s" % (atom.attrib['class'])
Justin MacCallum's avatar
Justin MacCallum committed
5081
5082
                raise ValueError(outputString)

5083
5084
    #=============================================================================================

Peter Eastman's avatar
Peter Eastman committed
5085
    def setPolarGroups(self, data, bonded12ParticleSets, force):
5086
5087
5088
5089
5090

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

            # assign multipole parameters via only 1-2 connected atoms

Peter Eastman's avatar
Peter Eastman committed
5091
5092
5093
5094
            multipoleDict = atom.multipoleDict
            pgrpMap = multipoleDict['pgrpMap']
            bondedAtomIndices = bonded12ParticleSets[atomIndex]
            atom.stage = -1
5095
5096
5097
5098
            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
5099
5100
                bondedAtom = data.atoms[bondedAtomIndex]
                if (bondedAtomType in pgrpMap):
5101
5102
                    atom.polarizationGroups[bondedAtomIndex] = 1
                    bondedAtom.polarizationGroups[atomIndex] = 1
Justin MacCallum's avatar
Justin MacCallum committed
5103

5104
5105
5106
5107
        # pgrp11

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

Peter Eastman's avatar
Peter Eastman committed
5108
            if (len( data.atoms[atomIndex].polarizationGroupSet) > 0):
5109
5110
                continue

Peter Eastman's avatar
Peter Eastman committed
5111
5112
            group = set()
            visited = set()
5113
5114
            notVisited = set()
            for pgrpAtomIndex in atom.polarizationGroups:
Peter Eastman's avatar
Peter Eastman committed
5115
5116
5117
5118
                group.add(pgrpAtomIndex)
                notVisited.add(pgrpAtomIndex)
            visited.add(atomIndex)
            while(len(notVisited) > 0):
5119
                nextAtom = notVisited.pop()
Peter Eastman's avatar
Peter Eastman committed
5120
5121
                if (nextAtom not in visited):
                   visited.add(nextAtom)
5122
                   for ii in data.atoms[nextAtom].polarizationGroups:
Peter Eastman's avatar
Peter Eastman committed
5123
5124
5125
                       group.add(ii)
                       if (ii not in visited):
                           notVisited.add(ii)
5126
5127
5128

            pGroup = group
            for pgrpAtomIndex in group:
Peter Eastman's avatar
Peter Eastman committed
5129
                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pGroup)
5130
5131

        for (atomIndex, atom) in enumerate(data.atoms):
Peter Eastman's avatar
Peter Eastman committed
5132
5133
            atom.polarizationGroupSet[0] = sorted(atom.polarizationGroupSet[0])
            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent11, atom.polarizationGroupSet[0])
5134
5135
5136
5137
5138

        # pgrp12

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

Peter Eastman's avatar
Peter Eastman committed
5139
            if (len( data.atoms[atomIndex].polarizationGroupSet) > 1):
5140
5141
                continue

Peter Eastman's avatar
Peter Eastman committed
5142
            pgrp11 = set(atom.polarizationGroupSet[0])
5143
5144
5145
            pgrp12 = set()
            for pgrpAtomIndex in pgrp11:
                for bonded12 in bonded12ParticleSets[pgrpAtomIndex]:
Peter Eastman's avatar
Peter Eastman committed
5146
                    pgrp12 = pgrp12.union(data.atoms[bonded12].polarizationGroupSet[0])
5147
5148
            pgrp12 = pgrp12 - pgrp11
            for pgrpAtomIndex in pgrp11:
Peter Eastman's avatar
Peter Eastman committed
5149
                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pgrp12)
Justin MacCallum's avatar
Justin MacCallum committed
5150

5151
        for (atomIndex, atom) in enumerate(data.atoms):
Peter Eastman's avatar
Peter Eastman committed
5152
5153
            atom.polarizationGroupSet[1] = sorted(atom.polarizationGroupSet[1])
            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent12, atom.polarizationGroupSet[1])
5154
5155
5156
5157
5158

        # pgrp13

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

Peter Eastman's avatar
Peter Eastman committed
5159
            if (len(data.atoms[atomIndex].polarizationGroupSet) > 2):
5160
5161
                continue

Peter Eastman's avatar
Peter Eastman committed
5162
5163
            pgrp11 = set(atom.polarizationGroupSet[0])
            pgrp12 = set(atom.polarizationGroupSet[1])
5164
5165
5166
            pgrp13 = set()
            for pgrpAtomIndex in pgrp12:
                for bonded12 in bonded12ParticleSets[pgrpAtomIndex]:
Peter Eastman's avatar
Peter Eastman committed
5167
                    pgrp13 = pgrp13.union(data.atoms[bonded12].polarizationGroupSet[0])
5168
            pgrp13 = pgrp13 - pgrp12
Peter Eastman's avatar
Peter Eastman committed
5169
            pgrp13 = pgrp13 - set(pgrp11)
5170
            for pgrpAtomIndex in pgrp11:
Peter Eastman's avatar
Peter Eastman committed
5171
                data.atoms[pgrpAtomIndex].polarizationGroupSet.append(pgrp13)
Justin MacCallum's avatar
Justin MacCallum committed
5172

5173
        for (atomIndex, atom) in enumerate(data.atoms):
Peter Eastman's avatar
Peter Eastman committed
5174
5175
            atom.polarizationGroupSet[2] = sorted(atom.polarizationGroupSet[2])
            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent13, atom.polarizationGroupSet[2])
5176
5177
5178
5179
5180

        # pgrp14

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

Peter Eastman's avatar
Peter Eastman committed
5181
            if (len(data.atoms[atomIndex].polarizationGroupSet) > 3):
5182
5183
                continue

Peter Eastman's avatar
Peter Eastman committed
5184
5185
5186
            pgrp11 = set(atom.polarizationGroupSet[0])
            pgrp12 = set(atom.polarizationGroupSet[1])
            pgrp13 = set(atom.polarizationGroupSet[2])
5187
5188
5189
            pgrp14 = set()
            for pgrpAtomIndex in pgrp13:
                for bonded12 in bonded12ParticleSets[pgrpAtomIndex]:
Peter Eastman's avatar
Peter Eastman committed
5190
                    pgrp14 = pgrp14.union(data.atoms[bonded12].polarizationGroupSet[0])
5191
5192
5193

            pgrp14 = pgrp14 - pgrp13
            pgrp14 = pgrp14 - pgrp12
Peter Eastman's avatar
Peter Eastman committed
5194
            pgrp14 = pgrp14 - set(pgrp11)
5195
5196

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

5199
        for (atomIndex, atom) in enumerate(data.atoms):
Peter Eastman's avatar
Peter Eastman committed
5200
5201
            atom.polarizationGroupSet[3] = sorted(atom.polarizationGroupSet[3])
            force.setCovalentMap(atomIndex, mm.AmoebaMultipoleForce.PolarizationCovalent14, atom.polarizationGroupSet[3])
5202
5203
5204

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

Peter Eastman's avatar
Peter Eastman committed
5205
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
5206
5207
5208
5209

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

5210
5211
5212
5213
5214
5215
5216
        force = mm.AmoebaMultipoleForce()
        sys.addForce(force)
        if (nonbondedMethod not in methodMap):
            raise ValueError( "AmoebaMultipoleForce: input cutoff method not available." )
        else:
            force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setCutoffDistance(nonbondedCutoff)
5217

5218
5219
        if ('ewaldErrorTolerance' in args):
            force.setEwaldErrorTolerance(float(args['ewaldErrorTolerance']))
5220

5221
5222
5223
5224
5225
5226
5227
5228
        if ('polarization' in args):
            polarizationType = args['polarization']
            if (polarizationType.lower() == 'direct'):
                force.setPolarizationType(mm.AmoebaMultipoleForce.Direct)
            elif (polarizationType.lower() == 'extrapolated'):
                force.setPolarizationType(mm.AmoebaMultipoleForce.Extrapolated)
            else:
                force.setPolarizationType(mm.AmoebaMultipoleForce.Mutual)
5229

5230
5231
        if ('aEwald' in args):
            force.setAEwald(float(args['aEwald']))
5232

5233
5234
        if ('pmeGridDimensions' in args):
            force.setPmeGridDimensions(args['pmeGridDimensions'])
5235

5236
5237
        if ('mutualInducedMaxIterations' in args):
            force.setMutualInducedMaxIterations(int(args['mutualInducedMaxIterations']))
5238

5239
5240
        if ('mutualInducedTargetEpsilon' in args):
            force.setMutualInducedTargetEpsilon(float(args['mutualInducedTargetEpsilon']))
5241
5242

        # add particles to force
Justin MacCallum's avatar
Justin MacCallum committed
5243
        # throw error if particle type not available
5244
5245
5246
5247
5248

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

        # 1-2

5249
        bonded12ParticleSets = AmoebaVdwGenerator.getBondedParticleSets(sys, data)
5250
5251
5252
5253
5254

        # 1-3

        bonded13ParticleSets = []
        for i in range(len(data.atoms)):
Peter Eastman's avatar
Peter Eastman committed
5255
            bonded13Set = set()
5256
            bonded12ParticleSet = bonded12ParticleSets[i]
Justin MacCallum's avatar
Justin MacCallum committed
5257
            for j in bonded12ParticleSet:
Peter Eastman's avatar
Peter Eastman committed
5258
                bonded13Set = bonded13Set.union(bonded12ParticleSets[j])
5259
5260
5261
5262

            # remove 1-2 and self from set

            bonded13Set = bonded13Set - bonded12ParticleSet
Peter Eastman's avatar
Peter Eastman committed
5263
            selfSet = set()
5264
5265
            selfSet.add(i)
            bonded13Set = bonded13Set - selfSet
Peter Eastman's avatar
Peter Eastman committed
5266
5267
            bonded13Set = set(sorted(bonded13Set))
            bonded13ParticleSets.append(bonded13Set)
5268
5269
5270
5271
5272

        # 1-4

        bonded14ParticleSets = []
        for i in range(len(data.atoms)):
Peter Eastman's avatar
Peter Eastman committed
5273
5274
            bonded14Set = set()
            bonded13ParticleSet = bonded13ParticleSets[i]
Justin MacCallum's avatar
Justin MacCallum committed
5275
            for j in bonded13ParticleSet:
Peter Eastman's avatar
Peter Eastman committed
5276
                bonded14Set = bonded14Set.union(bonded12ParticleSets[j])
Justin MacCallum's avatar
Justin MacCallum committed
5277

5278
5279
5280
5281
            # remove 1-3, 1-2 and self from set

            bonded14Set = bonded14Set - bonded12ParticleSets[i]
            bonded14Set = bonded14Set - bonded13ParticleSet
Peter Eastman's avatar
Peter Eastman committed
5282
            selfSet = set()
5283
5284
            selfSet.add(i)
            bonded14Set = bonded14Set - selfSet
Peter Eastman's avatar
Peter Eastman committed
5285
5286
            bonded14Set = set(sorted(bonded14Set))
            bonded14ParticleSets.append(bonded14Set)
5287
5288
5289
5290
5291

        # 1-5

        bonded15ParticleSets = []
        for i in range(len(data.atoms)):
Peter Eastman's avatar
Peter Eastman committed
5292
5293
            bonded15Set = set()
            bonded14ParticleSet = bonded14ParticleSets[i]
Justin MacCallum's avatar
Justin MacCallum committed
5294
            for j in bonded14ParticleSet:
Peter Eastman's avatar
Peter Eastman committed
5295
                bonded15Set = bonded15Set.union(bonded12ParticleSets[j])
5296
5297
5298
5299
5300
5301

            # 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
5302
            selfSet = set()
5303
5304
            selfSet.add(i)
            bonded15Set = bonded15Set - selfSet
Peter Eastman's avatar
Peter Eastman committed
5305
5306
            bonded15Set = set(sorted(bonded15Set))
            bonded15ParticleSets.append(bonded15Set)
5307
5308
5309
5310
5311

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

Peter Eastman's avatar
Peter Eastman committed
5312
5313
                multipoleList = self.typeMap[t]
                hit = 0
5314
5315
5316
5317
5318
5319
                savedMultipoleDict = 0

                # assign multipole parameters via only 1-2 connected atoms

                for multipoleDict in multipoleList:

Peter Eastman's avatar
Peter Eastman committed
5320
                    if (hit != 0):
5321
5322
                        break

Peter Eastman's avatar
Peter Eastman committed
5323
                    kIndices = multipoleDict['kIndices']
Justin MacCallum's avatar
Justin MacCallum committed
5324
5325

                    kz = kIndices[1]
Peter Eastman's avatar
Peter Eastman committed
5326
5327
                    kx = kIndices[2]
                    ky = kIndices[3]
5328
5329
5330
5331

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

5333
                    bondedAtomIndices = bonded12ParticleSets[atomIndex]
Peter Eastman's avatar
Peter Eastman committed
5334
5335
5336
                    zaxis = -1
                    xaxis = -1
                    yaxis = -1
5337
5338
                    for bondedAtomZIndex in bondedAtomIndices:

Peter Eastman's avatar
Peter Eastman committed
5339
                       if (hit != 0):
5340
5341
5342
                           break

                       bondedAtomZType = int(data.atomType[data.atoms[bondedAtomZIndex]])
Peter Eastman's avatar
Peter Eastman committed
5343
5344
                       bondedAtomZ = data.atoms[bondedAtomZIndex]
                       if (bondedAtomZType == kz):
5345
                          for bondedAtomXIndex in bondedAtomIndices:
Peter Eastman's avatar
Peter Eastman committed
5346
                              if (bondedAtomXIndex == bondedAtomZIndex or hit != 0):
5347
5348
                                  continue
                              bondedAtomXType = int(data.atomType[data.atoms[bondedAtomXIndex]])
Peter Eastman's avatar
Peter Eastman committed
5349
5350
5351
5352
                              if (bondedAtomXType == kx):
                                  if (ky == 0):
                                      zaxis = bondedAtomZIndex
                                      xaxis = bondedAtomXIndex
5353
5354
5355
5356
5357
                                      if( bondedAtomXType == bondedAtomZType and xaxis < zaxis ):
                                          swapI = zaxis
                                          zaxis = xaxis
                                          xaxis = swapI
                                      else:
Peter Eastman's avatar
Peter Eastman committed
5358
5359
5360
5361
                                          for bondedAtomXIndex2 in bondedAtomIndices:
                                              bondedAtomX1Type = int(data.atomType[data.atoms[bondedAtomXIndex2]])
                                              if( bondedAtomX1Type == kx and bondedAtomXIndex2 != bondedAtomZIndex and bondedAtomXIndex2 < xaxis ):
                                                  xaxis = bondedAtomXIndex2
5362

5363
                                      savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
5364
                                      hit = 1
5365
5366
                                  else:
                                      for bondedAtomYIndex in bondedAtomIndices:
Peter Eastman's avatar
Peter Eastman committed
5367
                                          if (bondedAtomYIndex == bondedAtomZIndex or bondedAtomYIndex == bondedAtomXIndex or hit != 0):
5368
5369
                                              continue
                                          bondedAtomYType = int(data.atomType[data.atoms[bondedAtomYIndex]])
Peter Eastman's avatar
Peter Eastman committed
5370
5371
5372
5373
                                          if (bondedAtomYType == ky):
                                              zaxis = bondedAtomZIndex
                                              xaxis = bondedAtomXIndex
                                              yaxis = bondedAtomYIndex
5374
                                              savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
5375
                                              hit = 2
Justin MacCallum's avatar
Justin MacCallum committed
5376

5377
5378
5379
5380
                # assign multipole parameters via 1-2 and 1-3 connected atoms

                for multipoleDict in multipoleList:

Peter Eastman's avatar
Peter Eastman committed
5381
                    if (hit != 0):
5382
5383
                        break

Peter Eastman's avatar
Peter Eastman committed
5384
                    kIndices = multipoleDict['kIndices']
Justin MacCallum's avatar
Justin MacCallum committed
5385
5386

                    kz = kIndices[1]
Peter Eastman's avatar
Peter Eastman committed
5387
5388
                    kx = kIndices[2]
                    ky = kIndices[3]
Justin MacCallum's avatar
Justin MacCallum committed
5389

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

5394
5395
5396
                    bondedAtom12Indices = bonded12ParticleSets[atomIndex]
                    bondedAtom13Indices = bonded13ParticleSets[atomIndex]

Peter Eastman's avatar
Peter Eastman committed
5397
5398
5399
                    zaxis = -1
                    xaxis = -1
                    yaxis = -1
5400
5401
5402

                    for bondedAtomZIndex in bondedAtom12Indices:

Peter Eastman's avatar
Peter Eastman committed
5403
                       if (hit != 0):
5404
5405
5406
                           break

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

Peter Eastman's avatar
Peter Eastman committed
5409
                       if (bondedAtomZType == kz):
5410
5411
                          for bondedAtomXIndex in bondedAtom13Indices:

Peter Eastman's avatar
Peter Eastman committed
5412
                              if (bondedAtomXIndex == bondedAtomZIndex or hit != 0):
5413
5414
                                  continue
                              bondedAtomXType = int(data.atomType[data.atoms[bondedAtomXIndex]])
Peter Eastman's avatar
Peter Eastman committed
5415
5416
5417
5418
                              if (bondedAtomXType == kx and bondedAtomZIndex in bonded12ParticleSets[bondedAtomXIndex]):
                                  if (ky == 0):
                                      zaxis = bondedAtomZIndex
                                      xaxis = bondedAtomXIndex
5419
5420
5421

                                      # select xaxis w/ smallest index

Peter Eastman's avatar
Peter Eastman committed
5422
5423
5424
5425
                                      for bondedAtomXIndex2 in bondedAtom13Indices:
                                          bondedAtomX1Type = int(data.atomType[data.atoms[bondedAtomXIndex2]])
                                          if( bondedAtomX1Type == kx and bondedAtomXIndex2 != bondedAtomZIndex and bondedAtomZIndex in bonded12ParticleSets[bondedAtomXIndex2] and bondedAtomXIndex2 < xaxis ):
                                              xaxis = bondedAtomXIndex2
5426

5427
                                      savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
5428
                                      hit = 3
5429
5430
                                  else:
                                      for bondedAtomYIndex in bondedAtom13Indices:
Peter Eastman's avatar
Peter Eastman committed
5431
                                          if (bondedAtomYIndex == bondedAtomZIndex or bondedAtomYIndex == bondedAtomXIndex or hit != 0):
5432
5433
                                              continue
                                          bondedAtomYType = int(data.atomType[data.atoms[bondedAtomYIndex]])
Peter Eastman's avatar
Peter Eastman committed
5434
5435
5436
5437
                                          if (bondedAtomYType == ky and bondedAtomZIndex in bonded12ParticleSets[bondedAtomYIndex]):
                                              zaxis = bondedAtomZIndex
                                              xaxis = bondedAtomXIndex
                                              yaxis = bondedAtomYIndex
5438
                                              savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
5439
                                              hit = 4
Justin MacCallum's avatar
Justin MacCallum committed
5440

5441
5442
5443
5444
                # assign multipole parameters via only a z-defining atom

                for multipoleDict in multipoleList:

Peter Eastman's avatar
Peter Eastman committed
5445
                    if (hit != 0):
5446
5447
                        break

Peter Eastman's avatar
Peter Eastman committed
5448
                    kIndices = multipoleDict['kIndices']
Justin MacCallum's avatar
Justin MacCallum committed
5449
5450
5451
5452

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

Peter Eastman's avatar
Peter Eastman committed
5453
5454
5455
                    zaxis = -1
                    xaxis = -1
                    yaxis = -1
5456
5457
5458

                    for bondedAtomZIndex in bondedAtom12Indices:

Peter Eastman's avatar
Peter Eastman committed
5459
                        if (hit != 0):
5460
5461
5462
                            break

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

Peter Eastman's avatar
Peter Eastman committed
5465
                        if (kx == 0 and kz == bondedAtomZType):
5466
                            zaxis = bondedAtomZIndex
5467
                            savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
5468
                            hit = 5
5469
5470
5471
5472
5473

                # assign multipole parameters via no connected atoms

                for multipoleDict in multipoleList:

Peter Eastman's avatar
Peter Eastman committed
5474
                    if (hit != 0):
5475
5476
                        break

Peter Eastman's avatar
Peter Eastman committed
5477
                    kIndices = multipoleDict['kIndices']
Justin MacCallum's avatar
Justin MacCallum committed
5478
5479
5480

                    kz = kIndices[1]

Peter Eastman's avatar
Peter Eastman committed
5481
5482
5483
                    zaxis = -1
                    xaxis = -1
                    yaxis = -1
5484

Peter Eastman's avatar
Peter Eastman committed
5485
                    if (kz == 0):
5486
                        savedMultipoleDict = multipoleDict
Peter Eastman's avatar
Peter Eastman committed
5487
                        hit = 6
Justin MacCallum's avatar
Justin MacCallum committed
5488

5489
5490
                # add particle if there was a hit

Peter Eastman's avatar
Peter Eastman committed
5491
                if (hit != 0):
5492

Peter Eastman's avatar
Peter Eastman committed
5493
                    atom.multipoleDict = savedMultipoleDict
5494
                    atom.polarizationGroups = dict()
5495
                    newIndex = force.addMultipole(savedMultipoleDict['charge'], savedMultipoleDict['dipole'], savedMultipoleDict['quadrupole'], savedMultipoleDict['axisType'],
5496
                                                                 zaxis, xaxis, yaxis, savedMultipoleDict['thole'], savedMultipoleDict['pdamp'], savedMultipoleDict['polarizability'])
Peter Eastman's avatar
Peter Eastman committed
5497
                    if (atomIndex == newIndex):
5498
5499
5500
5501
                        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]))
5502
                    else:
5503
                        raise ValueError("Atom %s of %s %d is out of sync!." %(atom.name, atom.residue.name, atom.residue.index))
5504
                else:
Peter Eastman's avatar
Peter Eastman committed
5505
                    raise ValueError("Atom %s of %s %d was not assigned." %(atom.name, atom.residue.name, atom.residue.index))
5506
            else:
Peter Eastman's avatar
Peter Eastman committed
5507
                raise ValueError('No multipole type for atom %s %s %d' % (atom.name, atom.residue.name, atom.residue.index))
5508
5509
5510

        # set polar groups

Peter Eastman's avatar
Peter Eastman committed
5511
        self.setPolarGroups(data, bonded12ParticleSets, force)
5512
5513
5514
5515
5516

parsers["AmoebaMultipoleForce"] = AmoebaMultipoleGenerator.parseElement

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

5517
## @private
5518
class AmoebaWcaDispersionGenerator(object):
5519
5520

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

5522
5523
    #=========================================================================================

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

Justin MacCallum's avatar
Justin MacCallum committed
5526
5527
        self.epso = epso
        self.epsh = epsh
Peter Eastman's avatar
Peter Eastman committed
5528
5529
5530
5531
5532
        self.rmino = rmino
        self.rminh = rminh
        self.awater = awater
        self.slevy = slevy
        self.dispoff = dispoff
Justin MacCallum's avatar
Justin MacCallum committed
5533
        self.shctd = shctd
5534
5535
5536
5537
5538
5539
5540
5541
5542

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

    @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
5543

5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
        existing = [f for f in forceField._forces if isinstance(f, AmoebaWcaDispersionGenerator)]
        if len(existing) == 0:
            generator = AmoebaWcaDispersionGenerator(element.attrib['epso'],
                                                     element.attrib['epsh'],
                                                     element.attrib['rmino'],
                                                     element.attrib['rminh'],
                                                     element.attrib['awater'],
                                                     element.attrib['slevy'],
                                                     element.attrib['dispoff'],
                                                     element.attrib['shctd'])
            forceField.registerGenerator(generator)
            generator.params = ForceField._AtomTypeParameters(forceField, 'AmoebaWcaDispersionForce', 'WcaDispersion', ('radius', 'epsilon'))
        else:
            # Multiple <AmoebaWcaDispersionForce> tags were found, probably in different files.  Simply add more types to the existing one.
            generator = existing[0]
5559
        generator.params.parseDefinitions(element)
Justin MacCallum's avatar
Justin MacCallum committed
5560

5561
    #=========================================================================================
Justin MacCallum's avatar
Justin MacCallum committed
5562

Peter Eastman's avatar
Peter Eastman committed
5563
    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
5564
5565
5566

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

5567
        existing = [f for f in sys.getForces() if type(f) == mm.AmoebaWcaDispersionForce]
5568
5569
5570
5571
5572
5573
5574
        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
5575
        # throw error if particle type not available
5576

Peter Eastman's avatar
Peter Eastman committed
5577
5578
5579
5580
5581
5582
5583
5584
        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  ))
5585

5586
5587
5588
        for atom in data.atoms:
            values = self.params.getAtomParameters(atom, data)
            force.addParticle(values[0], values[1])
5589
5590
5591
5592
5593

parsers["AmoebaWcaDispersionForce"] = AmoebaWcaDispersionGenerator.parseElement

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

5594
## @private
5595
class AmoebaGeneralizedKirkwoodGenerator(object):
5596
5597

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

5599
5600
    #=========================================================================================

Peter Eastman's avatar
Peter Eastman committed
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
    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
5612
        bondiMap = self.radiusTypeMap['Bondi']
Peter Eastman's avatar
Peter Eastman committed
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
        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
5638
5639
5640

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

Peter Eastman's avatar
Peter Eastman committed
5641
    def getObcShct(self, data, atomIndex):
5642

Peter Eastman's avatar
Peter Eastman committed
5643
        atom = data.atoms[atomIndex]
5644
        atomicNumber = atom.element.atomic_number
Peter Eastman's avatar
Peter Eastman committed
5645
        shct = -1.0
5646
5647

        # shct
Justin MacCallum's avatar
Justin MacCallum committed
5648

Peter Eastman's avatar
Peter Eastman committed
5649
        if (atomicNumber == 1):                 # H(1)
Justin MacCallum's avatar
Justin MacCallum committed
5650
            shct = 0.85
Peter Eastman's avatar
Peter Eastman committed
5651
        elif (atomicNumber == 6):               # C(6)
Justin MacCallum's avatar
Justin MacCallum committed
5652
            shct = 0.72
Peter Eastman's avatar
Peter Eastman committed
5653
        elif (atomicNumber == 7):               # N(7)
Justin MacCallum's avatar
Justin MacCallum committed
5654
            shct = 0.79
Peter Eastman's avatar
Peter Eastman committed
5655
        elif (atomicNumber == 8):               # O(8)
Justin MacCallum's avatar
Justin MacCallum committed
5656
            shct = 0.85
Peter Eastman's avatar
Peter Eastman committed
5657
        elif (atomicNumber == 9):               # F(9)
Justin MacCallum's avatar
Justin MacCallum committed
5658
5659
5660
            shct = 0.88
        elif (atomicNumber == 15):              # P(15)
            shct = 0.86
Peter Eastman's avatar
Peter Eastman committed
5661
        elif (atomicNumber == 16):              # S(16)
5662
            shct = 0.96
Peter Eastman's avatar
Peter Eastman committed
5663
        elif (atomicNumber == 26):              # Fe(26)
5664
5665
            shct = 0.88

Justin MacCallum's avatar
Justin MacCallum committed
5666
        if (shct < 0.0):
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
5667
            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
5668
5669

        return shct
5670
5671
5672

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

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

Peter Eastman's avatar
Peter Eastman committed
5675
        atom = data.atoms[atomIndex]
5676
        atomicNumber = atom.element.atomic_number
Peter Eastman's avatar
Peter Eastman committed
5677
        radius = -1.0
5678

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

Peter Eastman's avatar
Peter Eastman committed
5681
            radius = 0.132
Justin MacCallum's avatar
Justin MacCallum committed
5682

Peter Eastman's avatar
Peter Eastman committed
5683
            if (len(bondedAtomIndices) < 1):
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
5684
                 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
5685

5686
            for bondedAtomIndex in bondedAtomIndices:
Peter Eastman's avatar
Peter Eastman committed
5687
                bondedAtomAtomicNumber = data.atoms[bondedAtomIndex].element.atomic_number
5688

Peter Eastman's avatar
Peter Eastman committed
5689
            if (bondedAtomAtomicNumber == 7):
5690
                radius = 0.11
Peter Eastman's avatar
Peter Eastman committed
5691
            if (bondedAtomAtomicNumber == 8):
5692
                radius = 0.105
Justin MacCallum's avatar
Justin MacCallum committed
5693

Peter Eastman's avatar
Peter Eastman committed
5694
        elif (atomicNumber == 3):               # Li(3)
5695
            radius = 0.15
Peter Eastman's avatar
Peter Eastman committed
5696
        elif (atomicNumber == 6):               # C(6)
Justin MacCallum's avatar
Justin MacCallum committed
5697

5698
            radius = 0.20
Peter Eastman's avatar
Peter Eastman committed
5699
            if (len(bondedAtomIndices) == 3):
5700
5701
                radius = 0.205

Peter Eastman's avatar
Peter Eastman committed
5702
            elif (len(bondedAtomIndices) == 4):
5703
5704
                for bondedAtomIndex in bondedAtomIndices:
                   bondedAtomAtomicNumber = data.atoms[bondedAtomIndex].element.atomic_number
Peter Eastman's avatar
Peter Eastman committed
5705
                   if (bondedAtomAtomicNumber == 7 or bondedAtomAtomicNumber == 8):
5706
5707
                       radius = 0.175

Peter Eastman's avatar
Peter Eastman committed
5708
        elif (atomicNumber == 7):               # N(7)
5709
            radius = 0.16
Peter Eastman's avatar
Peter Eastman committed
5710
        elif (atomicNumber == 8):               # O(8)
5711
            radius = 0.155
Peter Eastman's avatar
Peter Eastman committed
5712
            if (len(bondedAtomIndices) == 2):
5713
                radius = 0.145
Peter Eastman's avatar
Peter Eastman committed
5714
        elif (atomicNumber == 9):               # F(9)
5715
            radius = 0.154
Justin MacCallum's avatar
Justin MacCallum committed
5716
        elif (atomicNumber == 10):
5717
            radius = 0.146
Justin MacCallum's avatar
Justin MacCallum committed
5718
        elif (atomicNumber == 11):
5719
            radius = 0.209
Justin MacCallum's avatar
Justin MacCallum committed
5720
        elif (atomicNumber == 12):
5721
            radius = 0.179
Justin MacCallum's avatar
Justin MacCallum committed
5722
        elif (atomicNumber == 14):
5723
            radius = 0.189
Justin MacCallum's avatar
Justin MacCallum committed
5724
        elif (atomicNumber == 15):              # P(15)
5725
            radius = 0.196
Peter Eastman's avatar
Peter Eastman committed
5726
        elif (atomicNumber == 16):              # S(16)
5727
            radius = 0.186
Justin MacCallum's avatar
Justin MacCallum committed
5728
        elif (atomicNumber == 17):
5729
            radius = 0.182
Justin MacCallum's avatar
Justin MacCallum committed
5730
        elif (atomicNumber == 18):
5731
            radius = 0.179
Justin MacCallum's avatar
Justin MacCallum committed
5732
        elif (atomicNumber == 19):
5733
            radius = 0.223
Justin MacCallum's avatar
Justin MacCallum committed
5734
        elif (atomicNumber == 20):
5735
            radius = 0.191
Justin MacCallum's avatar
Justin MacCallum committed
5736
        elif (atomicNumber == 35):
5737
            radius = 2.00
Justin MacCallum's avatar
Justin MacCallum committed
5738
        elif (atomicNumber == 36):
5739
            radius = 0.190
Justin MacCallum's avatar
Justin MacCallum committed
5740
        elif (atomicNumber == 37):
5741
            radius = 0.226
Justin MacCallum's avatar
Justin MacCallum committed
5742
        elif (atomicNumber == 53):
5743
            radius = 0.237
Justin MacCallum's avatar
Justin MacCallum committed
5744
        elif (atomicNumber == 54):
5745
            radius = 0.207
Justin MacCallum's avatar
Justin MacCallum committed
5746
        elif (atomicNumber == 55):
5747
            radius = 0.263
Justin MacCallum's avatar
Justin MacCallum committed
5748
        elif (atomicNumber == 56):
5749
5750
            radius = 0.230

Justin MacCallum's avatar
Justin MacCallum committed
5751
        if (radius < 0.0):
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
5752
5753
            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
5754

5755
5756
5757
5758
        return radius

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

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

Justin MacCallum's avatar
Justin MacCallum committed
5761
        bondiMap = self.radiusTypeMap['Bondi']
Peter Eastman's avatar
Peter Eastman committed
5762
        atom = data.atoms[atomIndex]
5763
        atomicNumber = atom.element.atomic_number
Justin MacCallum's avatar
Justin MacCallum committed
5764
        if (atomicNumber in bondiMap):
5765
5766
            radius = bondiMap[atomicNumber]
        else:
peastman's avatar
peastman committed
5767
            outputString = "Warning no Bondi radius for atom %s of %s %d using default value" % (atom.name, atom.residue.name, atom.residue.index)
Mark Friedrichs's avatar
Cleanup  
Mark Friedrichs committed
5768
            raise ValueError( outputString )
Justin MacCallum's avatar
Justin MacCallum committed
5769

5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
        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
5780

5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
        existing = [f for f in forceField._forces if isinstance(f, AmoebaGeneralizedKirkwoodGenerator)]
        if len(existing) == 0:
            generator = AmoebaGeneralizedKirkwoodGenerator(forceField, element.attrib['solventDielectric'],
                                                           element.attrib['soluteDielectric'],
                                                           element.attrib['includeCavityTerm'],
                                                           element.attrib['probeRadius'],
                                                           element.attrib['surfaceAreaFactor'])
            forceField.registerGenerator(generator)
        else:
            # Multiple <AmoebaGeneralizedKirkwoodFprce> tags were found, probably in different files.  Simply add more types to the existing one.
            generator = existing[0]
5792
5793

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

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

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

5800
5801
5802
        # check if AmoebaMultipoleForce exists since charges needed
        # if it has not been created, raise an error

5803
        amoebaMultipoleForceList = [f for f in sys.getForces() if type(f) == mm.AmoebaMultipoleForce]
Peter Eastman's avatar
Peter Eastman committed
5804
        if (len(amoebaMultipoleForceList) > 0):
5805
5806
5807
5808
5809
            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
5810
                if (force.__class__.__name__ == 'AmoebaMultipoleGenerator'):
Peter Eastman's avatar
Peter Eastman committed
5811
                    force.createForce(sys, data, nonbondedMethod, nonbondedCutoff, args)
Justin MacCallum's avatar
Justin MacCallum committed
5812

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

5815
        existing = [f for f in sys.getForces() if type(f) == mm.AmoebaGeneralizedKirkwoodForce]
5816
5817
5818
5819
        if len(existing) == 0:

            force = mm.AmoebaGeneralizedKirkwoodForce()
            sys.addForce(force)
Justin MacCallum's avatar
Justin MacCallum committed
5820

Peter Eastman's avatar
Peter Eastman committed
5821
5822
            if ('solventDielectric' in args):
                force.setSolventDielectric(float(args['solventDielectric']))
5823
            else:
Peter Eastman's avatar
Peter Eastman committed
5824
                force.setSolventDielectric(   float(self.solventDielectric))
5825

Peter Eastman's avatar
Peter Eastman committed
5826
5827
            if ('soluteDielectric' in args):
                force.setSoluteDielectric(float(args['soluteDielectric']))
5828
            else:
Peter Eastman's avatar
Peter Eastman committed
5829
                force.setSoluteDielectric(    float(self.soluteDielectric))
5830

Peter Eastman's avatar
Peter Eastman committed
5831
5832
            if ('includeCavityTerm' in args):
                force.setIncludeCavityTerm(int(args['includeCavityTerm']))
5833
            else:
Peter Eastman's avatar
Peter Eastman committed
5834
               force.setIncludeCavityTerm(   int(self.includeCavityTerm))
5835
5836
5837
5838
5839

        else:
            force = existing[0]

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

Peter Eastman's avatar
Peter Eastman committed
5842
5843
        force.setProbeRadius(         float(self.probeRadius))
        force.setSurfaceAreaFactor(   float(self.surfaceAreaFactor))
5844
5845
5846

        # 1-2

5847
        bonded12ParticleSets = AmoebaVdwGenerator.getBondedParticleSets(sys, data)
5848
5849

        radiusType = 'Bondi'
Peter Eastman's avatar
Peter Eastman committed
5850
5851
5852
5853
        for atomIndex in range(0, amoebaMultipoleForce.getNumMultipoles()):
            multipoleParameters = amoebaMultipoleForce.getMultipoleParameters(atomIndex)
            if (radiusType == 'Amoeba'):
                radius = self.getAmoebaTypeRadius(data, bonded12ParticleSets[atomIndex], atomIndex)
5854
            else:
Peter Eastman's avatar
Peter Eastman committed
5855
                radius = self.getBondiTypeRadius(data, bonded12ParticleSets[atomIndex], atomIndex)
5856
5857
            #shct = self.getObcShct(data, atomIndex)
            shct = 0.69
Peter Eastman's avatar
Peter Eastman committed
5858
            force.addParticle(multipoleParameters[0], radius, shct)
5859
5860
5861
5862
5863

parsers["AmoebaGeneralizedKirkwoodForce"] = AmoebaGeneralizedKirkwoodGenerator.parseElement

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

5864
## @private
5865
class AmoebaUreyBradleyGenerator(object):
5866
5867
5868
5869

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

5871
    def __init__(self):
5872

peastman's avatar
peastman committed
5873
        self.anglesForAtom2Type = defaultdict(list)
Peter Eastman's avatar
Peter Eastman committed
5874
5875
5876
        self.types1 = []
        self.types2 = []
        self.types3 = []
5877

Peter Eastman's avatar
Peter Eastman committed
5878
5879
        self.length = []
        self.k = []
5880
5881
5882
5883
5884
5885

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

    @staticmethod
    def parseElement(element, forceField):

5886
        #  <AmoebaUreyBradleyForce>
Justin MacCallum's avatar
Justin MacCallum committed
5887
        #   <UreyBradley class1="74" class2="73" class3="74" k="16003.8" d="0.15537" />
5888

5889
        generator = AmoebaUreyBradleyGenerator()
5890
5891
        forceField._forces.append(generator)
        for bond in element.findall('UreyBradley'):
5892
            types = forceField._findAtomTypes(bond.attrib, 3)
peastman's avatar
peastman committed
5893
            if None not in types:
peastman's avatar
peastman committed
5894
                index = len(generator.types1)
5895
5896
5897
                generator.types1.append(types[0])
                generator.types2.append(types[1])
                generator.types3.append(types[2])
peastman's avatar
peastman committed
5898
5899
                for t in types[1]:
                    generator.anglesForAtom2Type[t].append(index)
5900
5901
5902
5903
5904
                generator.length.append(float(bond.attrib['d']))
                generator.k.append(float(bond.attrib['k']))

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

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

5907
        existing = [f for f in sys.getForces() if type(f) == mm.HarmonicBondForce]
5908
5909

        if len(existing) == 0:
5910
            force = mm.HarmonicBondForce()
5911
5912
5913
5914
5915
            sys.addForce(force)
        else:
            force = existing[0]

        for (angle, isConstrained) in zip(data.angles, data.isAngleConstrained):
5916
            if (isConstrained and not args.get('flexibleConstraints', False)):
5917
5918
5919
5920
                continue
            type1 = data.atomType[data.atoms[angle[0]]]
            type2 = data.atomType[data.atoms[angle[1]]]
            type3 = data.atomType[data.atoms[angle[2]]]
peastman's avatar
peastman committed
5921
            for i in self.anglesForAtom2Type[type2]:
5922
5923
5924
                types1 = self.types1[i]
                types2 = self.types2[i]
                types3 = self.types3[i]
Peter Eastman's avatar
Peter Eastman committed
5925
                if ((type1 in types1 and type2 in types2 and type3 in types3) or (type3 in types1 and type2 in types2 and type1 in types3)):
5926
                    force.addBond(angle[0], angle[2], self.length[i], 2*self.k[i])
5927
5928
5929
5930
5931
                    break

parsers["AmoebaUreyBradleyForce"] = AmoebaUreyBradleyGenerator.parseElement

#=============================================================================================
peastman's avatar
peastman committed
5932
5933


5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
## @private
class HippoNonbondedGenerator(object):
    """A HippoNonbondedGenerator constructs a HippoNonbondedForce."""

    def __init__(self, forcefield, extrapCoeff):
        self.ff = forcefield
        self.extrapCoeff = extrapCoeff
        self.exceptions = {}

    @staticmethod
    def parseElement(element, ff):
        extrapCoeff = [float(c) for c in element.attrib['extrapolationCoefficients'].split(',')]
        generator = HippoNonbondedGenerator(ff, extrapCoeff)
        ff.registerGenerator(generator)
        scaleNames = ('mmScale', 'dmScale', 'ddScale', 'dispScale', 'repScale', 'ctScale')
        paramNames = ('charge', 'coreCharge', 'alpha', 'epsilon', 'damping', 'c6', 'pauliK', 'pauliQ', 'pauliAlpha', 'polarizability', 'axisType', 'd0', 'd1', 'd2', 'q11', 'q12', 'q13', 'q21', 'q22', 'q23', 'q31', 'q32', 'q33')
        for ex in element.findall('Exception'):
            separation = int(ex.attrib['separation'])
            ingroup = ex.attrib['ingroup'].lower() == 'true'
            key = (separation, ingroup)
            if key in generator.exceptions:
                raise ValueError('HippoNonbondedForce: multiple exceptions with separation=%d ingroup=%s' % (separation, ingroup))
            generator.exceptions[key] = [float(ex.attrib[s]) for s in scaleNames]
        generator.params = ForceField._AtomTypeParameters(ff, 'HippoNonbondedForce', 'Atom', paramNames)
        generator.params.parseDefinitions(element)

    def createForce(self, sys, data, nonbondedMethod, nonbondedCutoff, args):
        methodMap = {NoCutoff:mm.HippoNonbondedForce.NoCutoff,
                     PME:mm.HippoNonbondedForce.PME}
        if nonbondedMethod not in methodMap:
            raise ValueError('Illegal nonbonded method for HippoNonbondedForce')

        # Build data structures we'll need for building local coordinate frames.

        bondIndices = _findBondsForExclusions(data, sys)
        pairs = _findExclusions(bondIndices, 2, len(data.atoms))
        bonded12 = [set() for i in range(len(data.atoms))]
        bonded13 = [set() for i in range(len(data.atoms))]
        for atom1, atom2, sep in pairs:
            if sep == 1:
                bonded12[atom1].add(data.atoms[atom2])
                bonded12[atom2].add(data.atoms[atom1])
            else:
                bonded13[atom1].add(data.atoms[atom2])
                bonded13[atom2].add(data.atoms[atom1])

        # Create the force.

        force = mm.HippoNonbondedForce()
        for atom in data.atoms:
            values = self.params.getAtomParameters(atom, data)
            params = [float(v) for v in values[:10]]
            axisType = int(values[10])
            dipole = [float(v) for v in values[11:14]]
            quadrupole = [float(v) for v in values[14:23]]
            extra = self.params.getExtraParameters(atom, data)
            zAtom = self._findAxisAtom('zAtomType', extra, bonded12[atom.index], None, data, [])
            xAtom = self._findAxisAtom('xAtomType', extra, bonded12[atom.index], bonded13[atom.index], data, [zAtom])
            yAtom = self._findAxisAtom('yAtomType', extra, bonded12[atom.index], bonded13[atom.index], data, [zAtom, xAtom])
Peter Eastman's avatar
Peter Eastman committed
5993
            force.addParticle(params[0], dipole, quadrupole, *params[1:], axisType=axisType, multipoleAtomZ=zAtom, multipoleAtomX=xAtom, multipoleAtomY=yAtom)
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
        force.setNonbondedMethod(methodMap[nonbondedMethod])
        force.setExtrapolationCoefficients(self.extrapCoeff)
        force.setCutoffDistance(nonbondedCutoff)
        if args['switchDistance'] is not None:
            force.setSwitchingDistance(args['switchDistance'])
        if 'ewaldErrorTolerance' in args:
            force.setEwaldErrorTolerance(args['ewaldErrorTolerance'])
        sys.addForce(force)

    def _findAxisAtom(self, paramName, params, bonded12, bonded13, data, exclude):
        if paramName not in params:
            return -1
        atomType = params[paramName]
        for atom in bonded12:
            if data.atomType[atom] == atomType and atom.index not in exclude:
                return atom.index
        if bonded13 is not None:
            for atom in bonded13:
                if data.atomType[atom] == atomType and atom.index not in exclude:
                    return atom.index
        raise ValueError('No bonded atom of type %s' % atomType)

    def postprocessSystem(self, sys, data, args):
        # Identify polarization groups.

        bondIndices = _findBondsForExclusions(data, sys)
        groupBondTypes = [self.params.getExtraParameters(atom, data)['groupTypes'].split(',') for atom in data.atoms]
        groupBonds = [[] for i in range(len(data.atoms))]
        for i,j in bondIndices:
            if data.atomType[data.atoms[i]] in groupBondTypes[j]:
                groupBonds[i].append(j)
                groupBonds[j].append(i)
        polarizationGroup = _findGroups(groupBonds)

        # Create the exclusions.

        maxSeparation = max(e[0] for e in self.exceptions)
        hippo = [f for f in sys.getForces() if isinstance(f, mm.HippoNonbondedForce)][0]
        pairs = _findExclusions(bondIndices, maxSeparation, hippo.getNumParticles())
        for atom1, atom2, sep in pairs:
            params = self.exceptions[(sep, polarizationGroup[atom1] == polarizationGroup[atom2])]
            hippo.addException(atom1, atom2, *params)

parsers["HippoNonbondedForce"] = HippoNonbondedGenerator.parseElement


peastman's avatar
peastman committed
6040
## @private
6041
class DrudeGenerator(object):
peastman's avatar
peastman committed
6042
    """A DrudeGenerator constructs a DrudeForce."""
Justin MacCallum's avatar
Justin MacCallum committed
6043

6044
6045
    def __init__(self, forcefield):
        self.ff = forcefield
peastman's avatar
peastman committed
6046
6047
6048
6049
6050
6051
        self.typeMap = {}

    @staticmethod
    def parseElement(element, ff):
        existing = [f for f in ff._forces if isinstance(f, DrudeGenerator)]
        if len(existing) == 0:
6052
6053
            generator = DrudeGenerator(ff)
            ff.registerGenerator(generator)
peastman's avatar
peastman committed
6054
6055
6056
6057
        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'):
6058
            types = ff._findAtomTypes(particle.attrib, 5)
peastman's avatar
peastman committed
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
            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
6069

peastman's avatar
peastman committed
6070
6071
6072
6073
    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
6074

peastman's avatar
peastman committed
6075
        # Add Drude particles.
Justin MacCallum's avatar
Justin MacCallum committed
6076

peastman's avatar
peastman committed
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
        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
6093
6094
                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
6095
        sys.addForce(force)
Justin MacCallum's avatar
Justin MacCallum committed
6096

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

peastman's avatar
peastman committed
6100
6101
6102
6103
6104
6105
6106
        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)
6107
            if charge._value == 0 and epsilon._value == 0:
peastman's avatar
peastman committed
6108
6109
6110
6111
6112
                # 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]
6113
6114
                    type1 = data.atomType[data.atoms[particle1]]
                    type2 = data.atomType[data.atoms[particle2]]
peastman's avatar
peastman committed
6115
6116
6117
6118
                    thole1 = self.typeMap[type1][8]
                    thole2 = self.typeMap[type2][8]
                    drude.addScreenedPair(drude1, drude2, thole1+thole2)

6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
        # Set the masses of Drude particles.

        drudeMass = args['drudeMass']
        if not unit.is_quantity(drudeMass):
            drudeMass *= unit.dalton
        for i in range(drude.getNumParticles()):
            params = drude.getParticleParameters(i)
            particle = params[0]
            parent = params[1]
            transferMass = drudeMass-sys.getParticleMass(particle)
            sys.setParticleMass(particle, drudeMass)
            sys.setParticleMass(parent, sys.getParticleMass(parent)-transferMass)

Justin MacCallum's avatar
Justin MacCallum committed
6132
parsers["DrudeForce"] = DrudeGenerator.parseElement
John Chodera (MSKCC)'s avatar
John Chodera (MSKCC) committed
6133
6134

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