processTinkerForceField.py 54.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#=============================================================================================
# MODULE DOCSTRING
#=============================================================================================

"""
processTinkerForceField.py

   Convert TINKER force field files into xml files for use by pyopenmm

   (1) read residue template file
   (2) read TINKER parameter file
   (3) assign biotypes to each atom in residue template file
   (4) output force-field parameter file

"""
#=============================================================================================
# GLOBAL IMPORTS
#=============================================================================================

import os
import xml.etree.ElementTree as etree
import sys
import shlex
import math
import datetime
import os.path

#=============================================================================================
# Ion list
#=============================================================================================

# biotype    2003    NA      "Sodium Ion"                      250
# biotype    2004    K       "Potassium Ion"                   251
# biotype    2005    MG      "Magnesium Ion"                   255
# biotype    2006    CA      "Calcium Ion"                     256
# biotype    2007    CL      "Chloride Ion"                    258

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# Ions for amoeabio18.prm
ions2018    = { 'Li+' :  ['LI', 351],
                'Na+' :  ['NA', 352],
                'K+'  :  ['K',  353],
                'Rb+' :  ['RB', 354],  
                'Cs+' :  ['CS', 355], 
                'Be2' :  ['BE', 356],
                'Mg2' :  ['MG', 357],
                'Ca2' :  ['CA', 358],
                'Sr2' :  ['SR', 359],
                'Ba2' :  ['BA', 360],
                'Zn2' :  ['ZN', 361],
                'F-'  :  ['F',  362],
                'Cl-' :  ['Cl', 363],
                'Br-' :  ['Br', 364],
                'I-'  :  ['I',  365]
                }

# Ions for amoebapro13.prm
ions2013   = { 'Li+' :  ['LI', 249],
               'Na+' :  ['NA', 250],
               'K+'  :  ['K',  251],
               'Rb+' :  ['RB', 252],
               'Cs+' :  ['CS', 253],
               'Be2' :  ['BE', 254],
               'Mg2' :  ['MG', 255],
               'Ca2' :  ['CA', 256],
               'Sr2' :  ['SR', 257],
               'Ba2' :  ['BA', 258],
               'Zn2' :  ['ZN', 259],
               'F-'  :  ['F',  260],
               'Cl-' :  ['Cl', 261],
               'Br-' :  ['Br', 262],
               'I-'  :  ['I',  263]
               }

# Ions for amoebabio09.prm
ions2009 = { 'Li+' :  ['LI', 404],
             'Na+' :  ['NA', 405],
             'K+'  :  ['K',  406],
             'Rb+' :  ['RB', 407],
             'Cs+' :  ['CS', 408],
             'Be2' :  ['BE', 409],
             'Mg2' :  ['MG', 410],
             'Ca2' :  ['CA', 411],
             'Zn2' :  ['ZN', 412],
             'F-'  :  ['F',  413],
             'Cl-' :  ['Cl', 414],
             'Br-' :  ['Br', 415],
             'I-'  :  ['I',  416]
             }
89
90
91
92

atomTypes                    = {}
bioTypes                     = {}

93
94
95
96
97
98
99
100
101
102
103
104
105
#=============================================================================================
# Helper function for XML formatting
#=============================================================================================

def xml_float(x, min_decimals=1):
    """Format a float for XML, cleaning tiny floating-point errors and keeping at least one decimal."""
    f = float(x)
    s = format(f, ".15g")
    # Only add decimal if it is not already scientific and has no decimal
    if "e" not in s and "." not in s:
        s += "." + "0" * min_decimals
    return s

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#=============================================================================================
# Default 'constructor' for atoms 
#=============================================================================================

def getDefaultAtom( ):
 
    atom                     = dict();
    atom['tinkerLookupName'] = 'XXX'
    atom['type']             = -1
    atom['bonds']            = dict()

    return atom

#=============================================================================================
# Add bond to atomDict[]; atoms are added to atomDict[] if missing
#=============================================================================================

def addBond( atomDict, atom1, atom2 ):
    if( atom1 not in atomDict ):
        atomDict[atom1] = getDefaultAtom()
        
    if( atom2 not in atomDict ):
        atomDict[atom2] = getDefaultAtom()

    atomDict[atom2]['bonds'][atom1] = 1
    atomDict[atom1]['bonds'][atom2] = 1

#=============================================================================================
# Get atom dictionary from xml atom list
#=============================================================================================

def getXmlAtoms( atoms ):
 
    atomInfo = dict();
    for atom in atoms:
        name                               = atom.attrib['name']
        atomInfo[name]                     = getDefaultAtom()
        atomInfo[name]['tinkerLookupName'] = atom.attrib['tinkerLookupName']

    return atomInfo

#=============================================================================================
# Get bond dictionary from xml bond list
#=============================================================================================

def getXmlBonds( bonds ):
 
    bondInfo = dict();
    for bond in bonds:
        atom1                     = bond.attrib['from']
        atom2                     = bond.attrib['to']
        if( atom1 not in bondInfo ):
            bondInfo[atom1]       = dict()
        if( atom2 not in bondInfo ):
            bondInfo[atom2]       = dict()
    
        bondInfo[atom1][atom2] = 1
        bondInfo[atom2][atom1] = 1

    return bondInfo

#=============================================================================================
# Build entry for protein residue
#=============================================================================================

def buildProteinResidue( residueDict, atoms, bondInfo, abbr, loc, tinkerLookupName, include, residueName, type ):
    
    # residueDict[abbr]                         abbr=ALA, CALA, NALA, ...
    # residueDict[abbr]['atoms']                list if atom dict()
    # residueDict[abbr]['type']                 molecule type ('protein', 'nucleic acid', ...)
    # residueDict[abbr]['tinkerLookupName']     Tinker lookup name
    # residueDict[abbr]['residueName']          residueName
    # residueDict[abbr]['include']              include in output

    residueDict[abbr]                         = dict()
    residueDict[abbr]['atoms']                = atoms
    residueDict[abbr]['type']                 = type
    residueDict[abbr]['loc']                  = loc
    residueDict[abbr]['tinkerLookupName']     = tinkerLookupName
    residueDict[abbr]['residueName']          = residueName
    residueDict[abbr]['include']              = include

    # for each bond, add entry to 
    #   residueDict[abbr]['atoms'][atom]['bonds']
    #   residueDict[abbr]['atoms'][bondedAtom]['bonds']

    for atom in bondInfo:
        if( atom in residueDict[abbr]['atoms'] ):

            if( 'bonds' not in  residueDict[abbr]['atoms'][atom] ):
                residueDict[abbr]['atoms'][atom]['bonds'] = dict() 

            for bondedAtom in bondInfo[atom]:
                if( bondedAtom in  residueDict[abbr]['atoms'] ):
                    if( 'bonds' not in  residueDict[abbr]['atoms'][bondedAtom] ):
                        residueDict[abbr]['atoms'][bondedAtom]['bonds'] = dict() 
                    residueDict[abbr]['atoms'][bondedAtom]['bonds'][atom] = 1
                    residueDict[abbr]['atoms'][atom]['bonds'][bondedAtom] = 1
                else:
205
                    print("Error: bonded atom=%s not in residue=%s" % ( atom, abbr ))
206
        else:
207
            print("Error: bonded atom=%s nt in residue=%s" % ( atom, abbr ))
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256

    return

#=============================================================================================
# Copy a bond (dict() copy)
#=============================================================================================

def copyBonds( bonds ):
    bondCopy = dict()
    for key in bonds.keys():
        bondCopy[key] = bonds[key]
    return bondCopy

#=============================================================================================
# Copy a atom (dict() copy, including the 'bonds' list)
#=============================================================================================

def copyAtom( atom ):
    atomCopy = dict()
    for key in atom.keys():
        if( key != 'bonds' ):
            atomCopy[key]      = atom[key]
        else:
            atomCopy['bonds']  = copyBonds( atom[key] )
    return atomCopy

#=============================================================================================
# Copy a residue, including atom list
#=============================================================================================

def copyProteinResidue( residue ):
    
    residueCopy                        = dict()
    residueCopy['atoms']               = dict()
    residueCopy['type']                = residue['type']
    residueCopy['loc']                 = residue['loc']
    residueCopy['tinkerLookupName']    = residue['tinkerLookupName']
    residueCopy['residueName']         = residue['residueName']
    residueCopy['include']             = residue['include']

    for atom in residue['atoms']:
        residueCopy['atoms'][atom] = copyAtom( residue['atoms'][atom] )

    return residueCopy

#=============================================================================================
# Build residue hash based on xml file
#=============================================================================================

257
def buildResidueDict( residueXmlFileName ):
258
259

    residueTree = etree.parse(residueXmlFileName)
260
    print("Read %s" % (residueXmlFileName))
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    root        = residueTree.getroot()
    residueDict = dict()

    # residueDict[residueName] = dict()
    #      ['loc']
    #      ['type']
    #      ['atoms'] = dict()
    #          [atomName]    = dict()
    #              ['bonds'] = dict{}
    for residue in root.findall('Residue'):

        #  <Residue abbreviation="MET" loc="middle" type="protein" tinkerLookupName="Methionine" fullName="Methionine">
        abbr        = residue.attrib['abbreviation']
        loc         = residue.attrib['loc']
        type        = residue.attrib['type']
        tinkerName  = residue.attrib['tinkerLookupName']
        residueName = residue.attrib['fullName']
278
279
280
281
282
283
284
285
286
287
288
289
        isProtein   = False
        isWater     = False
        isDNA       = False
        isRNA       = False
        if type == 'protein':
            isProtein = True
        elif type == 'AmoebaWater':
            isWater = True
        elif type == 'dna':
            isDNA = True
        elif type == 'rna':
            isRNA = True
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
        else:
            continue

        atoms       = getXmlAtoms( residue.findall('Atom') ) 
        bondInfo    = getXmlBonds( residue.findall('Bond') ) 

        # if residue is an amino acid, then create CALA and NALA residues, in addition to non-termianal residue, and include approriate atoms
        # HXT is excluded from all residues

        if( isWater ):

            buildProteinResidue( residueDict, atoms, bondInfo, abbr, 'x', tinkerName, 1, 'HOH', 'water' )

        elif( isProtein ):

            buildProteinResidue( residueDict, atoms, bondInfo, abbr, 'm', tinkerName, 1, residueName, 'protein' )

            cResidueName                                                      = 'C' + abbr
            residueDict[cResidueName]                                         = copyProteinResidue( residueDict[abbr] )
            residueDict[cResidueName]['loc']                                  = 'c'
            if( residueDict[abbr]['tinkerLookupName'].find('(') > -1 ):
                begin = residueDict[abbr]['tinkerLookupName'].find('(')
                end   = residueDict[abbr]['tinkerLookupName'].find(')') + 1
                sub   = residueDict[abbr]['tinkerLookupName'][begin:end]
                if( sub == '(HD)' or sub == '(HE)' ):
                    residueDict[cResidueName]['tinkerLookupName']                 = 'C-Terminal ' + 'HIS ' + sub
                else:
                    residueDict[cResidueName]['tinkerLookupName']                 = 'C-Terminal ' + abbr + ' ' + sub
318
                print("tinkerLookupName %s %s" % ( abbr, residueDict[cResidueName]['tinkerLookupName']))
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
            else:
                residueDict[cResidueName]['tinkerLookupName']                 = 'C-Terminal ' + abbr
            residueDict[cResidueName]['atoms']['OXT']                         = copyAtom( residueDict[abbr]['atoms']['O'] )
            residueDict[cResidueName]['atoms']['OXT']['tinkerLookupName']     = 'OXT'
            residueDict[cResidueName]['atoms']['O']['tinkerLookupName']       = 'OXT'
            residueDict[cResidueName]['parent']                               = residueDict[abbr]
 
            nResidueName                                                      = 'N' + abbr
            residueDict[nResidueName]                                         = copyProteinResidue( residueDict[abbr] )
            residueDict[nResidueName]['loc']                                  = 'n'
            residueDict[nResidueName]['tinkerLookupName']                     = 'N-Terminal ' + abbr
            residueDict[nResidueName]['parent']                               = residueDict[abbr]

            if( abbr == 'PRO' ):
               #<Atom name="H" tinkerLookupName="HN" bonds="1" />

               residueDict[nResidueName]['atoms']['H2']                     = getDefaultAtom()
               residueDict[nResidueName]['atoms']['H3']                     = getDefaultAtom()

               residueDict[nResidueName]['atoms']['H2']['tinkerLookupName'] = 'HN'
               residueDict[nResidueName]['atoms']['H3']['tinkerLookupName'] = 'HN'

               addBond( residueDict[nResidueName]['atoms'], 'H2', 'N' )
               addBond( residueDict[nResidueName]['atoms'], 'H3', 'N' )
 
            else:
               residueDict[nResidueName]['atoms']['H2']     = copyAtom( residueDict[abbr]['atoms']['H'] )
               residueDict[nResidueName]['atoms']['H3']     = copyAtom( residueDict[abbr]['atoms']['H'] )

348
349
350
351
        elif isDNA or isRNA:

            buildProteinResidue( residueDict, atoms, bondInfo, abbr, loc, tinkerName, 1, residueName, type )

352
    print("Start Lookup XML FFFFinal\n\n")
353
354
    printXml = 1
    if( printXml ):
355
        print("<Residues>")
356
357
358
359
360
361
362
        for resName in sorted( residueDict.keys() ):
            if( 'include' in residueDict[resName] and residueDict[resName]['include'] ):
                type         = residueDict[resName]['type']
                loc          = residueDict[resName]['loc']
                tinkerLookupName   = residueDict[resName]['tinkerLookupName']
                fullName     = residueDict[resName]['residueName']
                outputString = """  <Residue abbreviation="%s" loc="%s" type="%s" tinkerLookupName="%s" fullName="%s">""" % (resName, loc, type, tinkerLookupName, fullName )
363
                print("%s" % outputString)
364
365
366
367

                atomsInfo    = residueDict[resName]['atoms']
                for atomName in sorted( atomsInfo.keys() ):
                    tinkerLookupName = atomsInfo[atomName]['tinkerLookupName']
368
                    outputString = """  <Atom name="%s" tinkerLookupName="%s" />""" % (atomName, tinkerLookupName)
369
                    print("%s" % outputString)
370
371
372
373
374
375
376
377
378
379
380
381
382

                includedBonds = dict()
                for atomName in sorted( atomsInfo.keys() ):
                    bondsInfo    = atomsInfo[atomName]['bonds']
                    for bondedAtom  in bondsInfo:
                        if( bondedAtom not in includedBonds or atomName not in includedBonds[bondedAtom] ):
                            outputString = """  <Bond from="%s" to="%s" />""" % (atomName, bondedAtom)
                            if( atomName not in includedBonds ):
                                includedBonds[atomName] = dict()
                            if( bondedAtom not in includedBonds ):
                                includedBonds[bondedAtom] = dict()
                            includedBonds[atomName][bondedAtom] = 1
                            includedBonds[bondedAtom][atomName] = 1
383
384
385
                            print("%s" % outputString)
                print("</Residue>")
        print("</Residues>")
386
387
388
389
390
391
392
393
394

    return residueDict

#=============================================================================================
# Set biotype for each atom in residueDict
#=============================================================================================

def setBioTypes( bioTypes, residueDict ):

395
    for resname, res in residueDict.items():
396
397
        for atom in res['atoms']:
            atomLookup = res['atoms'][atom]['tinkerLookupName']
398
            resLookup = []
399
400
401
402
403
404
405
406
407
408
409
410
            if res['type'] == 'dna':
                if res['loc'] in ('5', 'N'):
                    resLookup.append("5'-Hydroxyl DNA")
                if res['loc'] in ('3', 'N'):
                    resLookup.append("3'-Hydroxyl DNA")
                resLookup.append("Phosphodiester DNA")
            if res['type'] == 'rna':
                if res['loc'] in ('5', 'N'):
                    resLookup.append("5'-Hydroxyl RNA")
                if res['loc'] in ('3', 'N'):
                    resLookup.append("3'-Hydroxyl RNA")
                resLookup.append("Phosphodiester RNA")
411
            resLookup.append(res['tinkerLookupName'])
412
413
414
415
416
417
            for suffix in resLookup:
                lookupName = atomLookup+'_'+suffix
                if lookupName in bioTypes:
                    break
            if lookupName in bioTypes:
                res['atoms'][atom]['type'] = bioTypes[lookupName][3]
418
            else:
419
                print("For %s lookupName=%s not in biotype" % (atom,lookupName))
420
421
                if( 'parent' in res ):
                    lookupName =  res['atoms'][atom]['tinkerLookupName']  + '_' +  res['parent']['tinkerLookupName']
422
                    if( lookupName in bioTypes ):
423
                        res['atoms'][atom]['type'] = bioTypes[lookupName][3]
424
                    else:
425
                        print("Missing lookupName=%s from biotype" % (lookupName))
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
    return 0

#=============================================================================================
# Add multipole for forces[]; added entry is a list of axis info [kz, kx, ky] and another 
# list of multipoles [charge, dipole, quadrupole]
#=============================================================================================

def addMultipole( lineIndex, allLines, forces ):

    if( 'multipole' not in forces ):
        forces['multipole'] = []

    # axis indices and charge

    fields                  = allLines[lineIndex]
    multipoles              = [ fields[-1] ]
    axisInfo                = fields[1:-1]

    # dipole

    lineIndex              += 1
    fields                  = allLines[lineIndex]
    multipoles.append( fields[0] )
    multipoles.append( fields[1] )
    multipoles.append( fields[2] )

    # quadrupole

    lineIndex              += 1
    fields                  = allLines[lineIndex]
    multipoles.append( fields[0] )

    lineIndex              += 1
    fields                  = allLines[lineIndex]
    multipoles.append( fields[0] )
    multipoles.append( fields[1] )

    lineIndex              += 1
    fields                  = allLines[lineIndex]
    multipoles.append( fields[0] )
    multipoles.append( fields[1] )
    multipoles.append( fields[2] )

    lineIndex              += 1

    # save info

    multipoleInfo           = [ axisInfo, multipoles ]
    forces['multipole'].append( multipoleInfo )

    return (lineIndex)

#=============================================================================================
# Add tortor parameters/grid to forces[]; format of each entry is [ first tortor line, grid ]
#=============================================================================================

def addTorTor( lineIndex, allLines, forces ):

    if( 'tortors' not in forces ):
        forces['tortors'] = []

    fields         = allLines[lineIndex]
    tortorInfo     = fields[1:]

    # read grid lines
491
492
    # New format has multiple data points per line: angle1 angle2 f angle1 angle2 f ...
    # Need to calculate number of lines based on total grid points
493

494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
    nx = int(fields[6])
    ny = int(fields[7])
    totalGridPoints = nx * ny
    
    grid = []
    currentLineIndex = lineIndex + 1
    gridPointsProcessed = 0
    
    while gridPointsProcessed < totalGridPoints and currentLineIndex < len(allLines):
        lineFields = allLines[currentLineIndex]
        
        # Process triplets of (angle1, angle2, f) from current line
        i = 0
        while i + 3 <= len(lineFields) and gridPointsProcessed < totalGridPoints:
            angle1 = lineFields[i]
            angle2 = lineFields[i + 1] 
            f = lineFields[i + 2]
            grid.append([angle1, angle2, f])
            gridPointsProcessed += 1
            i += 3
            
        currentLineIndex += 1
516
517
518

    forces['tortors'].append( [ tortorInfo, grid ] )

519
    return (currentLineIndex - 1)
520
521
522
523
524
525
526
527
528
529
530


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

# recognizedForces[] contain raw list entries from TINKER parameter file

resAtomTypes                             = {}
forces                                   = {}
recognizedForces                         = {}
recognizedForces['bond']                 = 1
recognizedForces['angle']                = 1
531
recognizedForces['anglep']               = 1
532
533
534
535
536
recognizedForces['strbnd']               = 1
recognizedForces['ureybrad']             = 1
recognizedForces['opbend']               = 1
recognizedForces['torsion']              = 1
recognizedForces['pitors']               = 1
537
538
recognizedForces['strtors']              = 1
recognizedForces['angtors']              = 1
539
recognizedForces['vdw']                  = 1
540
recognizedForces['vdwpair']              = 1
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
recognizedForces['polarize']             = 1
recognizedForces['tortors']              = addTorTor
recognizedForces['multipole']            = addMultipole

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

# recognizedScalars[] contain raw scalar entries from TINKER parameter file

scalars                                  = {}
recognizedScalars                        = {}
recognizedScalars['forcefield']          = '-2.55'
recognizedScalars['bond-cubic']          = '-2.55'
recognizedScalars['bond-quartic']        = '3.793125'
recognizedScalars['angle-cubic']         = '-0.014'
recognizedScalars['angle-quartic']       = '0.000056'
recognizedScalars['angle-pentic']        = '-0.0000007'
recognizedScalars['angle-sextic']        = '0.000000022'
recognizedScalars['opbendtype']          = 'ALLINGER'
recognizedScalars['opbend-cubic']        = '-0.014'
recognizedScalars['opbend-quartic']      = '0.000056'
recognizedScalars['opbend-pentic']       = '-0.0000007'
recognizedScalars['opbend-sextic']       = '0.000000022'
recognizedScalars['torsionunit']         = '0.5'
recognizedScalars['vdwtype']             = 'BUFFERED-14-7'
recognizedScalars['radiusrule']          = 'CUBIC-MEAN'
recognizedScalars['radiustype']          = 'R-MIN'
recognizedScalars['radiussize']          = 'DIAMETER'
recognizedScalars['epsilonrule']         = 'HHG'
recognizedScalars['dielectric']          = '1.0'
recognizedScalars['polarization']        = 'MUTUAL'
recognizedScalars['vdw-13-scale']        = '0.0'
recognizedScalars['vdw-14-scale']        = '1.0'
recognizedScalars['vdw-15-scale']        = '1.0'
recognizedScalars['mpole-12-scale']      = '0.0'
recognizedScalars['mpole-13-scale']      = '0.0'
recognizedScalars['mpole-14-scale']      = '0.4'
recognizedScalars['mpole-15-scale']      = '0.8'
recognizedScalars['polar-12-scale']      = '0.0'
recognizedScalars['polar-13-scale']      = '0.0'
recognizedScalars['polar-14-scale']      = '1.0'
recognizedScalars['polar-15-scale']      = '1.0'
recognizedScalars['polar-14-intra']      = '0.5'
recognizedScalars['direct-11-scale']     = '0.0'
recognizedScalars['direct-12-scale']     = '1.0'
recognizedScalars['direct-13-scale']     = '1.0'
recognizedScalars['direct-14-scale']     = '1.0'
recognizedScalars['mutual-11-scale']     = '1.0'
recognizedScalars['mutual-12-scale']     = '1.0'
recognizedScalars['mutual-13-scale']     = '1.0'
recognizedScalars['mutual-14-scale']     = '1.0'

#=============================================================================================
# get all 'interesting' lines in file

595
596
597
598
599
600
601
602
603
604
605
606
607
608
fileName = sys.argv[1]
if fileName == 'amoebabio18.prm':
    ions = ions2018
    residueXmlFileName = 'residuesFinalAmoeba2018.xml'
elif fileName == 'amoebapro13.prm':
    ions = ions2013
    residueXmlFileName = 'residuesFinalAmoeba2013.xml'
elif fileName == 'amoebabio09.prm':
    ions = ions2009
    residueXmlFileName = 'residuesFinalAmoeba2009.xml'
else:
    print("Error: unrecognized force field file name %s" % (fileName))
    sys.exit()

609
allLines                                 = []
610
for line in open(fileName):
611
612
613
614
615
616
617
618
619
620
621
622
    try:
        fields = shlex.split(line)
    except:
        continue
    if len(fields) == 0:
        continue
    if fields[0][0] == '#':
        continue
    allLines.append( fields )

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

623
624
625
626
residueDict        = buildResidueDict( residueXmlFileName )
    
#=============================================================================================

627
628
629
630
631
632
633
634
635
636
637
# load lines in lists/scalar values

lineIndex = 0
while lineIndex < len( allLines ):

    fields = allLines[lineIndex]

    if fields[0] == 'atom':
        if( fields[3] in ions ):
            ionInfo = ions[fields[3]]
            element = ionInfo[0]
638
            ionInfo[1] = int(fields[1])
639
640
641
642
643
644
645
646
        else:
            element = fields[3][0]
        atomTypes[int(fields[1])] = (fields[2], element, fields[6])
        lineIndex += 1

    elif fields[0] == 'biotype':

        lookUp            = fields[2] + '_' + fields[3]
647
648
649
        if lookUp in bioTypes:
            # Workaround for Tinker using the same name but different types for H2', H2'', and for H5', H5''
            lookUp = fields[2]+'*_'+fields[3]
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
        bioTypes[lookUp]  = fields[1:]
        lineIndex        += 1

    elif fields[0] in recognizedForces:
        if( recognizedForces[fields[0]] == 1 ):
            if( fields[0] not in forces ):
                forces[fields[0]] = []
            forces[fields[0]].append( fields[1:] )
            lineIndex += 1
        else:
            lineIndex = recognizedForces[fields[0]]( lineIndex, allLines, forces )

    elif fields[0] in recognizedScalars:
        scalars[fields[0]] = fields[1]
        lineIndex += 1
    else:
666
        print("Field %s not recognized: line=<%s>" % ( fields[0], allLines[lineIndex] ))
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
        lineIndex += 1

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

# set biotypes for all atoms

setBioTypes( bioTypes, residueDict )

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

# open force field xml file for output

tinkerXmlFileName           = scalars['forcefield']
tinkerXmlFileName          += '.xml'
tinkerXmlFile               = open( tinkerXmlFileName, 'w' )
682
print("Opened %s." % (tinkerXmlFileName))
683
684
685
686

gkXmlFileName              = scalars['forcefield']
gkXmlFileName             += '_gk.xml'
gkXmlFile                  = open( gkXmlFileName, 'w' )
687
print("Opened %s." % (gkXmlFileName))
688
689
690

today = datetime.date.today().isoformat()
sourceFile = os.path.basename(sys.argv[1])
691
692
693
694
695
696
header = """ <Info>
  <Source>%s</Source>
  <DateGenerated>%s</DateGenerated>
  <Reference></Reference>
 </Info>
""" % (sourceFile, today)
697
698

gkXmlFile.write( "<ForceField>\n" )
699
gkXmlFile.write(header)
700
tinkerXmlFile.write( "<ForceField>\n" )
701
tinkerXmlFile.write(header)
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
tinkerXmlFile.write( " <AtomTypes>\n")

if( scalars['forcefield'].find( 'AMOEBA' ) > -1 ):
    isAmoeba = 1
else:
    isAmoeba = 0

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

# atom type/class

#         atmType  class   name  name                    atomicNo.     mass valence     
# atom          1    1    N     "Glycine N"                    7    14.003    3
# atom          2    2    CA    "Glycine CA"                   6    12.000    4
# atom          3    3    C     "Glycine C"                    6    12.000    3
# atom          4    4    HN    "Glycine HN"                   1     1.008    1
# atom          5    5    O     "Glycine O"                    8    15.995    1

# atom        380   73    O     "AMOEBA Water O"               8    15.999    2
# atom        381   74    H     "AMOEBA Water H"               1     1.008    1
# atom        383   76    Na+   "Sodium Ion Na+"              11    22.990    0
# atom        384   77    K+    "Potassium Ion K+"            19    39.098    0
# atom        385   78    Rb+   "Rubidium Ion Rb+"            37    85.468    0
# atom        386   79    Cs+   "Cesium Ion Cs+"              55   132.905    0
# atom        387   80    Be+   "Beryllium Ion Be+2"           4     9.012    0
# atom        388   81    Mg+   "Magnesium Ion Mg+2"          12    24.305    0
# atom        389   82    Ca+   "Calcium Ion Ca+2"            20    40.078    0
# atom        390   83    Cl-   "Chloride Ion Cl-"            17    35.453    0
  

#            biotype                                          atmType
# biotype       1    N       "Glycine"                           1     
# biotype       2    CA      "Glycine"                           2     
# biotype       3    C       "Glycine"                           3     
# biotype       4    HN      "Glycine"                           4     
# biotype       5    O       "Glycine"                           5     

# biotype    2001    O       "Water"                           380
# biotype    2002    H       "Water"                           381
# biotype    2003    NA      "Sodium Ion"                      383   
# biotype    2004    K       "Potassium Ion"                   384   
# biotype    2005    MG      "Magnesium Ion"                   388   
# biotype    2006    CA      "Calcium Ion"                     389   
# biotype    2007    CL      "Chloride Ion"                    390   
  
if( isAmoeba ):
    for type in sorted(atomTypes):
        outputString = """  <Type name="%s" class="%s" element="%s" mass="%s"/>""" % (type, atomTypes[type][0], atomTypes[type][1], atomTypes[type][2])
        tinkerXmlFile.write( "%s\n" % (outputString) )
else:
    for type in sorted(atomTypes):
        outputString = """  <Type name="%s" class="%s" mass="%s"/>""" % (type, atomTypes[type][0], atomTypes[type][1])
        tinkerXmlFile.write( "%s\n" % (outputString) )

tinkerXmlFile.write( " </AtomTypes>\n")

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

# residues

tinkerXmlFile.write( " <Residues>\n" )
763
764
for resname, res in sorted(residueDict.items()):
    if res['include']:
765
766
767
768
        if resname == 'HOH':
            tinkerXmlFile.write(f'  <Residue name="{resname}" rigidWater="false">\n')
        else:
            tinkerXmlFile.write(f'  <Residue name="{resname}">\n')
769
770
        atomIndex    = dict()
        atomCount    = 0
771
772
        for atom in sorted( res['atoms'].keys() ):
            type  = res['atoms'][atom]['type']
773
774
            typeI = int( type )
            if( typeI < 0 ):
775
                print("Error: type=%s for atom=%s of residue=%s" % (type, atom, resname))
776
777
778
779
780
781
            tag  = "   <Atom name=\"%s\" type=\"%s\" />" % (atom, type)
            atomIndex[atom]  = atomCount
            atomCount       += 1
            tinkerXmlFile.write( "%s\n" % (tag) )
    
        includedBonds = dict()
782
783
        for atomName in sorted( res['atoms'].keys() ):
            bondsInfo    = res['atoms'][atomName]['bonds']
784
785
786
787
788
789
790
791
792
793
794
795
            for bondedAtom  in bondsInfo:
                if( bondedAtom not in includedBonds or atomName not in includedBonds[bondedAtom] ):
                    outputString = """   <Bond from="%s" to="%s" />""" % (str(atomIndex[atomName]), str(atomIndex[bondedAtom]))
                    if( atomName not in includedBonds ):
                        includedBonds[atomName] = dict()
                    if( bondedAtom not in includedBonds ):
                        includedBonds[bondedAtom] = dict()
                    includedBonds[atomName][bondedAtom] = 1
                    includedBonds[bondedAtom][atomName] = 1
                    tinkerXmlFile.write( "%s\n" % (outputString) )

        outputStrings = []
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
        if res['type'] in ('rna', 'dna'):
            if res['loc'] in ('middle', '3'):
                outputStrings.append( """   <ExternalBond from="%s" />""" % (str(atomIndex['P']) ))
            if res['loc'] in ('middle', '5'):
                outputStrings.append( """   <ExternalBond from="%s" />""" % (str(atomIndex["O3'"]) ))
        else:
            if res['loc'] == 'm':
                outputStrings.append( """   <ExternalBond from="%s" />""" % (str(atomIndex['N']) ))
                outputStrings.append( """   <ExternalBond from="%s" />""" % (str(atomIndex['C']) ) )
            if res['loc'] == 'n':
                outputStrings.append( """   <ExternalBond from="%s" />""" % (str(atomIndex['C']) ) )
            if res['loc'] == 'c':
                outputStrings.append( """   <ExternalBond from="%s" />""" % (str(atomIndex['N']) ) )
            if resname.find('CYX') > -1:
                outputStrings.append( """   <ExternalBond from="%s" />""" % (str(atomIndex['SG']) ) )
811
812
813
        for outputString in outputStrings:
            tinkerXmlFile.write( "%s\n" % (outputString) )

814
        tinkerXmlFile.write( "  </Residue>\n" )
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834

# End caps

tinkerXmlFile.write('  <Residue name="ACE">\n')
tinkerXmlFile.write('   <Atom name="HH31" type="%s"/>\n' % bioTypes['H_Acetyl N-Terminus'][3])
tinkerXmlFile.write('   <Atom name="CH3" type="%s"/>\n' % bioTypes['CH3_Acetyl N-Terminus'][3])
tinkerXmlFile.write('   <Atom name="HH32" type="%s"/>\n' % bioTypes['H_Acetyl N-Terminus'][3])
tinkerXmlFile.write('   <Atom name="HH33" type="%s"/>\n' % bioTypes['H_Acetyl N-Terminus'][3])
tinkerXmlFile.write('   <Atom name="C" type="%s"/>\n' % bioTypes['C_Acetyl N-Terminus'][3])
tinkerXmlFile.write('   <Atom name="O" type="%s"/>\n' % bioTypes['O_Acetyl N-Terminus'][3])
tinkerXmlFile.write('   <Bond from="0" to="1"/>\n')
tinkerXmlFile.write('   <Bond from="1" to="2"/>\n')
tinkerXmlFile.write('   <Bond from="1" to="3"/>\n')
tinkerXmlFile.write('   <Bond from="1" to="4"/>\n')
tinkerXmlFile.write('   <Bond from="4" to="5"/>\n')
tinkerXmlFile.write('   <ExternalBond from="4"/>\n')
tinkerXmlFile.write('  </Residue>\n')
tinkerXmlFile.write('  <Residue name="NME">\n')
tinkerXmlFile.write('   <Atom name="N" type="%s"/>\n' % bioTypes['N_N-MeAmide C-Terminus'][3])
tinkerXmlFile.write('   <Atom name="H" type="%s"/>\n' % bioTypes['HN_N-MeAmide C-Terminus'][3])
835
tinkerXmlFile.write('   <Atom name="CH3" type="%s"/>\n' % bioTypes['C_N-MeAmide C-Terminus'][3])
836
837
838
839
840
841
842
843
844
845
846
847
848
849
tinkerXmlFile.write('   <Atom name="HH31" type="%s"/>\n' % bioTypes['H_N-MeAmide C-Terminus'][3])
tinkerXmlFile.write('   <Atom name="HH32" type="%s"/>\n' % bioTypes['H_N-MeAmide C-Terminus'][3])
tinkerXmlFile.write('   <Atom name="HH33" type="%s"/>\n' % bioTypes['H_N-MeAmide C-Terminus'][3])
tinkerXmlFile.write('   <Bond from="0" to="1"/>\n')
tinkerXmlFile.write('   <Bond from="0" to="2"/>\n')
tinkerXmlFile.write('   <Bond from="2" to="3"/>\n')
tinkerXmlFile.write('   <Bond from="2" to="4"/>\n')
tinkerXmlFile.write('   <Bond from="2" to="5"/>\n')
tinkerXmlFile.write('   <ExternalBond from="0"/>\n')
tinkerXmlFile.write('  </Residue>\n')


# ions
 
850
for ion,ionInfo in ions.items():
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
    outputString  = """  <Residue name="%s">\n""" % (ionInfo[0])
    outputString += """   <Atom name="%s" type="%s"/>\n""" % (ionInfo[0], str(ionInfo[1]))
    outputString += """  </Residue>\n""" 
    tinkerXmlFile.write( "%s" % (outputString) )
    
tinkerXmlFile.write( " </Residues>\n" )

radian              = 57.2957795130
if( isAmoeba ):

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

    # AmoebaBondForce

    cubic           = 10.*float(scalars['bond-cubic']) 
    quartic         = 100.*float(scalars['bond-quartic']) 
    outputString    = """ <AmoebaBondForce bond-cubic="%s" bond-quartic="%s">""" %( str(cubic), str(quartic) )
    tinkerXmlFile.write( "%s\n" % (outputString ) )
    bonds        = forces['bond']
    for bond in bonds:
       length       = float(bond[3])*0.1
       k            = float(bond[2])*100.0*4.184
873
       outputString = """  <Bond class1="%s" class2="%s" length="%s" k="%s"/>""" % (bond[0], bond[1], xml_float(length), xml_float(k) )
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
       tinkerXmlFile.write( "%s\n" % (outputString ) )
    tinkerXmlFile.write( " </AmoebaBondForce>\n" )

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

    # AmoebaAngleForce

    cubic           = float(scalars['angle-cubic']) 
    quartic         = float(scalars['angle-quartic']) 
    pentic          = float(scalars['angle-pentic']) 
    sextic          = float(scalars['angle-sextic']) 
    outputString    = """ <AmoebaAngleForce angle-cubic="%s" angle-quartic="%s" angle-pentic="%s" angle-sextic="%s">""" %( str(cubic), str(quartic), str(pentic), str(sextic) )
    tinkerXmlFile.write( "%s\n" % (outputString ) )
    radian          = 57.2957795130
    radian2         = 4.184/(radian*radian)
889
890
891
    for set in ['angle', 'anglep']:
        for angle in forces[set]:
           k            = float(angle[3])*radian2
892
           outputString = '  <Angle class1="%s" class2="%s" class3="%s" k="%s" angle1="%s"' % (angle[0], angle[1], angle[2], xml_float(k), xml_float(angle[4]) )
893
894
895
896
897
898
899
900
           if( len(angle) > 5 ):
               outputString += ' angle2="%s"' % (angle[5])
    
           if( len(angle) > 6 ):
               outputString += ' angle3="%s"' % (angle[6])
           outputString += ' inPlane="%s"/>' % (set == 'anglep')
    
           tinkerXmlFile.write( "%s\n" % (outputString ) )
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
    tinkerXmlFile.write( " </AmoebaAngleForce>\n" )

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

    # AmoebaOutOfPlaneBendForce

    cubic           = float(scalars['opbend-cubic']) 
    quartic         = float(scalars['opbend-quartic']) 
    pentic          = float(scalars['opbend-pentic']) 
    sextic          = float(scalars['opbend-sextic']) 
    type            = scalars['opbendtype'] 
    outputString    = """ <AmoebaOutOfPlaneBendForce type="%s" opbend-cubic="%s" opbend-quartic="%s" opbend-pentic="%s" opbend-sextic="%s">""" % ( 
                            type, str(cubic), str(quartic), str(pentic), str(sextic) )
    tinkerXmlFile.write( "%s\n" % (outputString ) )
    opbends         = forces['opbend']
    radian2         = 4.184/(radian*radian)
    for opbend in opbends:
918
919
920
921
        k            = float(opbend[4])*radian2
        for i in range(4):
            if opbend[i] == '0':
                opbend[i] = ''
922
        outputString = """  <Angle class1="%s" class2="%s" class3="%s" class4="%s" k="%s"/>""" % (opbend[0], opbend[1], opbend[2],  opbend[3], xml_float(k))
923
        tinkerXmlFile.write( "%s\n" % (outputString ) )
924
925
926
927
928
929
930
    tinkerXmlFile.write( " </AmoebaOutOfPlaneBendForce>\n" )

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

    # AmoebaTorsionForce

    torsionUnit      = float(scalars['torsionunit']) 
931
    outputString     = """ <PeriodicTorsionForce>"""
932
933
934
935
    tinkerXmlFile.write( "%s\n" % (outputString ) )
    torsions         = forces['torsion']
    conversion       = 4.184*torsionUnit
    for torsion in torsions:
936
       outputString  = """  <Proper class1="%s" class2="%s" class3="%s" class4="%s" """ % (torsion[0], torsion[1], torsion[2],  torsion[3])
937
938
939
       startIndex    = 4
       for ii in range(0,3):
          torsionSuffix            = str(ii+1)
940
941
942
          amplitudeAttributeName   = 'k'+torsionSuffix
          angleAttributeName       = 'phase'+torsionSuffix
          periodicityAttributeName = 'periodicity'+torsionSuffix
943
944
          amplitude                = float(torsion[startIndex])*conversion
          angle                    = float(torsion[startIndex+1])/radian
945
          periodicity              = int(torsion[startIndex+2])
946
          outputString            += """  %s="%s" %s="%s" %s="%d" """ % (amplitudeAttributeName, xml_float(amplitude), angleAttributeName, xml_float(angle), periodicityAttributeName, periodicity)
947
948
949
          startIndex              += 3
       outputString += "/>"
       tinkerXmlFile.write( "%s\n" % (outputString ) )
950
    tinkerXmlFile.write( " </PeriodicTorsionForce>\n" )
951
952
953
954
955
956
957
958
959
960
961
962

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

    # AmoebaPiTorsionForce

    piTorsionUnit      = 1.0
    outputString       = """ <AmoebaPiTorsionForce piTorsionUnit="%s">""" % ( piTorsionUnit )
    tinkerXmlFile.write( "%s\n" % (outputString ) )
    piTorsions         = forces['pitors']
    conversion         = 4.184*piTorsionUnit
    for piTorsion in piTorsions:
       k             = float(piTorsion[2])*conversion
963
       outputString  = """  <PiTorsion class1="%s" class2="%s" k="%s" />""" % (piTorsion[0], piTorsion[1], xml_float(k))
964
965
966
       tinkerXmlFile.write( "%s\n" % (outputString ) )
    tinkerXmlFile.write( " </AmoebaPiTorsionForce>\n" )

967
968
969
#=============================================================================================

    # Stretch torsion
970
971
972
973
974
975
    if 'strtors' in forces:
        tinkerXmlFile.write(' <AmoebaStretchTorsionForce>\n')
        for torsion in forces['strtors']:
            v = [float(x)*10*4.184 for x in torsion[4:]]
            tinkerXmlFile.write(f'  <Torsion class1="{torsion[0]}" class2="{torsion[1]}" class3="{torsion[2]}" class4="{torsion[3]}" v11="{xml_float(v[0])}" v12="{xml_float(v[1])}" v13="{xml_float(v[2])}" v21="{xml_float(v[3])}" v22="{xml_float(v[4])}" v23="{xml_float(v[5])}" v31="{xml_float(v[6])}" v32="{xml_float(v[7])}" v33="{xml_float(v[8])}"/>\n')
        tinkerXmlFile.write(' </AmoebaStretchTorsionForce>\n')
976
977
978
979

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

    # Angle torsion
980
981
982
983
984
985
    if 'angtors' in forces:
        tinkerXmlFile.write(' <AmoebaAngleTorsionForce>\n')
        for torsion in forces['angtors']:
            v = [float(x)*4.184 for x in torsion[4:]]
            tinkerXmlFile.write(f'  <Torsion class1="{torsion[0]}" class2="{torsion[1]}" class3="{torsion[2]}" class4="{torsion[3]}" v11="{xml_float(v[0])}" v12="{xml_float(v[1])}" v13="{xml_float(v[2])}" v21="{xml_float(v[3])}" v22="{xml_float(v[4])}" v23="{xml_float(v[5])}"/>\n')
        tinkerXmlFile.write(' </AmoebaAngleTorsionForce>\n')
986

987
988
989
990
991
992
993
994
995
996
997
998
#=============================================================================================

    # AmoebaStretchBendForce

    stretchBendUnit      = 1.0
    outputString         = """ <AmoebaStretchBendForce stretchBendUnit="%s">""" % ( stretchBendUnit )
    tinkerXmlFile.write( "%s\n" % (outputString ) )
    conversion           = 41.84/radian
    stretchBends         = forces['strbnd']
    for stretchBend in stretchBends:
       k1            = float(stretchBend[3])*conversion
       k2            = float(stretchBend[4])*conversion
999
       outputString  = """  <StretchBend class1="%s" class2="%s" class3="%s" k1="%s" k2="%s" />""" % (stretchBend[0], stretchBend[1], stretchBend[2], xml_float(k1), xml_float(k2))
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
       tinkerXmlFile.write( "%s\n" % (outputString ) )
    tinkerXmlFile.write( "</AmoebaStretchBendForce>\n" )

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

    # AmoebaTorsionTorsionForce

    torsionTorsionUnit      = 1.0
    outputString            = """ <AmoebaTorsionTorsionForce >"""
    tinkerXmlFile.write( "%s\n" % (outputString ) )
    torsionTorsions         = forces['tortors']
    for (index, torsionTorsion) in enumerate(torsionTorsions):
       torInfo       = torsionTorsion[0]
       grid          = torsionTorsion[1]
       outputString  = """  <TorsionTorsion class1="%s" class2="%s" class3="%s" class4="%s" class5="%s" grid="%s" nx="%s" ny="%s" />""" % (torInfo[0], torInfo[1], torInfo[2], torInfo[3], torInfo[4], str(index),
                              torInfo[5], torInfo[6] )
       tinkerXmlFile.write( "%s\n" % (outputString ) )

    for (index, torsionTorsion) in enumerate(torsionTorsions):
       torInfo       = torsionTorsion[0]
       grid          = torsionTorsion[1]
       outputString  = """  <TorsionTorsionGrid grid="%s" nx="%s" ny="%s" >""" % (str(index), torInfo[5], torInfo[6] )
       tinkerXmlFile.write( "%s\n" % (outputString ) )
       for (gridIndex, gridEntry) in enumerate(grid):
1024
           print("Gxx %d  %s" % ( gridIndex, str(gridEntry) ))
1025
1026
1027
1028
1029
           if( len( gridEntry ) > 5 ):
               f   = float( gridEntry[2] )*4.184
               fx  = float( gridEntry[3] )*4.184
               fy  = float( gridEntry[4] )*4.184
               fxy = float( gridEntry[5] )*4.184
1030
               outputString  = """  <Grid angle1="%s" angle2="%s" f="%s" fx="%s" fy="%s" fxy="%s" />""" % ( gridEntry[0], gridEntry[1], xml_float(f), xml_float(fx), xml_float(fy), xml_float(fxy) )
1031
1032
1033
               tinkerXmlFile.write( "  %s\n" % (outputString ) )
           elif( len( gridEntry ) > 2 ):
               f   = float( gridEntry[2] )*4.184
1034
               outputString  = """  <Grid angle1="%s" angle2="%s" f="%s" />""" % ( gridEntry[0], gridEntry[1], xml_float(f) )
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
               tinkerXmlFile.write( "  %s\n" % (outputString ) )
       outputString  = '</TorsionTorsionGrid >'
       tinkerXmlFile.write( "%s\n" % (outputString ) )

    tinkerXmlFile.write( "</AmoebaTorsionTorsionForce>\n" )

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

    # AmoebaVdwForce

    outputString         = """ <AmoebaVdwForce type="%s" radiusrule="%s" radiustype="%s" radiussize="%s" epsilonrule="%s" vdw-13-scale="%s" vdw-14-scale="%s" vdw-15-scale="%s" >""" % (
         scalars['vdwtype'], scalars['radiusrule'], scalars['radiustype'], scalars['radiussize'], scalars['epsilonrule'], scalars['vdw-13-scale'], scalars['vdw-14-scale'], scalars['vdw-15-scale'] )
    tinkerXmlFile.write( "%s\n" % (outputString ) )
1048
    for vdw in forces['vdw']:
1049
1050
1051
1052
1053
1054
       sigma             = float(vdw[1])*0.1
       epsilon           = float(vdw[2])*4.184
       if( len(vdw) > 3 ): 
           reduction = vdw[3]
       else:
           reduction = 1.0
1055
       outputString      = """  <Vdw class="%s" sigma="%s" epsilon="%s" reduction="%s" />""" % (vdw[0], xml_float(sigma), xml_float(epsilon), xml_float(reduction))
1056
       tinkerXmlFile.write( "%s\n" % (outputString ) )
1057
    for pair in forces['vdwpair']:
1058
1059
       sigma             = float(pair[2])*0.1
       epsilon           = float(pair[3])*4.184
1060
       outputString      = """  <Pair class1="%s" class2="%s" sigma="%s" epsilon="%s"/>""" % (pair[0], pair[1], xml_float(sigma), xml_float(epsilon))
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
       tinkerXmlFile.write( "%s\n" % (outputString ) )
    tinkerXmlFile.write( " </AmoebaVdwForce>\n" )

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

    # AmoebaMultipoleForce

    scalarList                  = dict()
    scalarList['mpole12Scale']  = recognizedScalars['mpole-12-scale']
    scalarList['mpole13Scale']  = recognizedScalars['mpole-13-scale']
    scalarList['mpole14Scale']  = recognizedScalars['mpole-14-scale']
    scalarList['mpole15Scale']  = recognizedScalars['mpole-15-scale']

    scalarList['polar12Scale']  = recognizedScalars['polar-12-scale']
    scalarList['polar13Scale']  = recognizedScalars['polar-13-scale']
    scalarList['polar14Scale']  = recognizedScalars['polar-14-scale']
    scalarList['polar15Scale']  = recognizedScalars['polar-15-scale']
    scalarList['polar14Intra']  = recognizedScalars['polar-14-intra']

    scalarList['direct11Scale'] = recognizedScalars['direct-11-scale']
    scalarList['direct12Scale'] = recognizedScalars['direct-12-scale']
    scalarList['direct13Scale'] = recognizedScalars['direct-13-scale']
    scalarList['direct14Scale'] = recognizedScalars['direct-14-scale']

    scalarList['mutual11Scale'] = recognizedScalars['mutual-11-scale']
    scalarList['mutual12Scale'] = recognizedScalars['mutual-12-scale']
    scalarList['mutual13Scale'] = recognizedScalars['mutual-13-scale']
    scalarList['mutual14Scale'] = recognizedScalars['mutual-14-scale']

    outputString         = """ <AmoebaMultipoleForce """
    for key in sorted( scalarList.keys() ): 
        outputString    += """ %s="%s" """ % ( key, scalarList[key] )
    outputString        += """ > """
    tinkerXmlFile.write( "%s\n" % (outputString ) )

    multipoleArray       = forces['multipole']
    bohr                 = 0.52917720859
    dipoleConversion     = 0.1*bohr
    quadrupoleConversion = 0.01*bohr*bohr/3.0
    for multipoleInfo in multipoleArray:
       axisInfo          = multipoleInfo[0]
       multipoles        =  multipoleInfo[1]
       outputString      = """  <Multipole type="%s" """ % (axisInfo[0] )
       axisInfoLen       = len(axisInfo)

       if( axisInfoLen > 1 ):
           outputString += """kz="%s" """ % ( axisInfo[1] )

       if( axisInfoLen > 2 ):
           outputString += """kx="%s" """ % ( axisInfo[2] )

       if( axisInfoLen > 3 ):
           outputString += """ky="%s" """ % ( axisInfo[3] )

1115
1116
1117
1118
       outputString += """c0="%s" d1="%s" d2="%s" d3="%s" q11="%s" q21="%s" q22="%s" q31="%s" q32="%s" q33="%s"  """ % ( xml_float(multipoles[0]),
                                    xml_float(dipoleConversion*float(multipoles[1])), xml_float(dipoleConversion*float(multipoles[2])), xml_float(dipoleConversion*float(multipoles[3])),
                                    xml_float(quadrupoleConversion*float(multipoles[4])), xml_float(quadrupoleConversion*float(multipoles[5])), xml_float(quadrupoleConversion*float(multipoles[6])),
                                    xml_float(quadrupoleConversion*float(multipoles[7])), xml_float(quadrupoleConversion*float(multipoles[8])), xml_float(quadrupoleConversion*float(multipoles[9])) )
1119
1120
1121
1122
1123
1124
1125
1126
1127
       outputString     += "/>"
       tinkerXmlFile.write( "%s\n" % (outputString ) )

    polarizeArray = forces['polarize']
    
    polarityConversion = 0.001
    m = {}
    for polarize in polarizeArray:
       m[polarize[0]] = []
1128
       outputString      = """  <Polarize type="%s" polarizability="%s" thole="%s" """ % (polarize[0], xml_float(polarityConversion*float(polarize[1])), xml_float(float(polarize[2])) )
1129
       for ii in range( 3, len(polarize) ):
1130
          outputString  += """pgrp%d="%s" """ % (ii-2, polarize[ii])
1131
1132
1133
1134
          m[polarize[0]].append(polarize[ii])
          
       outputString     += "/>"
       tinkerXmlFile.write( "%s\n" % (outputString ) )
1135
       print(m[polarize[0]])
1136
1137
1138
    for t in sorted(m):
        for k in m[t]:
            if t not in m[k]:
1139
                print(t, k)
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152

    tinkerXmlFile.write( " </AmoebaMultipoleForce>\n" )

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

    # AmoebaGeneralizedKirkwoodForce

    solventDielectric = 78.3
    soluteDielectric  = 1.0
    includeCavityTerm = 1
    probeRadius       = 0.14
    surfaceAreaFactor = -6.0*3.1415926535*0.0216*1000.0*0.4184
    outputString      = """ <AmoebaGeneralizedKirkwoodForce solventDielectric="%s" soluteDielectric="%s" includeCavityTerm="%s" probeRadius="%s" surfaceAreaFactor="%s">""" % (
1153
                           solventDielectric, soluteDielectric, includeCavityTerm, probeRadius, surfaceAreaFactor )
1154
1155
1156
1157
1158
    gkXmlFile.write( "%s\n" % (outputString ) )

    # radii are set in forcefield.py

    for type in sorted( atomTypes ):
1159
        print("atom type=%s  %s" % ( str(type), str(atomTypes[type]) ))
1160
1161

    for type in sorted( bioTypes ):
1162
        print("bio type=%s  %s" % ( str(type), str(bioTypes[type]) ))
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188

    multipoleArray       = forces['multipole']
    for multipoleInfo in multipoleArray:
       axisInfo          = multipoleInfo[0]
       multipoles        =  multipoleInfo[1]
       type              = int(axisInfo[0])
       shct              = 0.8
       if( type in atomTypes ):
           element =  atomTypes[type][1]
           if( element == 'H' ):
               shct = 0.85
           elif( element == 'C' ):
               shct = 0.72
           elif( element == 'N' ):
               shct = 0.79
           elif( element == 'O' ):
               shct = 0.85
           elif( element == 'F' ):
               shct = 0.88
           elif( element == 'P' ):
               shct = 0.86
           elif( element == 'S' ):
               shct = 0.96
           elif( element == 'Fe' ):
               shct = 0.88
           else:
1189
               print("Warning no overlap scale factor for type=%d element=%s" % (type, element))
1190
       else:
1191
           print("Warning no overlap scale factor for type=%d " % (type))
1192

1193
       outputString      = """  <GeneralizedKirkwood type="%s" charge="%s" shct="%s"  /> """ % ( axisInfo[0], xml_float(multipoles[0]),  xml_float(shct) )
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
       gkXmlFile.write( "%s\n" % (outputString ) )
    gkXmlFile.write( " </AmoebaGeneralizedKirkwoodForce>\n" )

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

    # AmoebaWcaDispersionForce

    epso         = 0.1100
    epsh         = 0.0135
    rmino        = 1.7025
    rminh        = 1.3275
    awater       = 0.033428
    slevy        = 1.0 
    dispoff      = 0.26
    shctd        = 0.81

    outputString         = """ <AmoebaWcaDispersionForce epso="%s" epsh="%s" rmino="%s" rminh="%s" awater="%s" slevy="%s"  dispoff="%s" shctd="%s" >""" % (
1211
                           epso*4.184, epsh*4.184, rmino*0.1, rminh*0.1, 1000.0*awater, slevy, 0.1*dispoff, shctd )
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
    gkXmlFile.write( "%s\n" % (outputString ) )
    vdws                 = forces['vdw']
    convert              = 0.1
    if( scalars['radiustype'] == 'SIGMA' ):
        convert         *= 1.122462048309372

    if( scalars['radiussize'] == 'DIAMETER' ):
        convert         *= 0.5

    for vdw in vdws:
       sigma             = float(vdw[1])
       sigma            *= convert
       epsilon           = float(vdw[2])*4.184
1225
       outputString      = """  <WcaDispersion class="%s" radius="%s" epsilon="%s" /> """ % ( vdw[0], xml_float(sigma), xml_float(epsilon) )
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
       gkXmlFile.write( "%s\n" % (outputString ) )
    gkXmlFile.write( " </AmoebaWcaDispersionForce>\n" )

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

    # AmoebaUreyBradleyForce

    cubic        = 0.0
    quartic      = 0.0

1236
    outputString         = """ <AmoebaUreyBradleyForce cubic="%s" quartic="%s"  >""" % ( cubic, quartic )
1237
1238
1239
1240
1241
    tinkerXmlFile.write( "%s\n" % (outputString ) )
    ubs                  = forces['ureybrad']
    for ub in ubs:
       k                 = float(ub[3])*4.184*100.0
       d                 = float(ub[4])*0.1
1242
       outputString      = """  <UreyBradley class1="%s" class2="%s" class3="%s" k="%s" d="%s" /> """ % ( ub[0],  ub[1],  ub[2], xml_float(k), xml_float(d) )
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
       tinkerXmlFile.write( "%s\n" % (outputString ) )
    tinkerXmlFile.write( " </AmoebaUreyBradleyForce>\n" )

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

tinkerXmlFile.write("</ForceField>\n")
gkXmlFile.write("</ForceField>\n")
tinkerXmlFile.close()
gkXmlFile.close()