-
Notifications
You must be signed in to change notification settings - Fork 11
/
poltype.py
executable file
·3610 lines (3299 loc) · 140 KB
/
poltype.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
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
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
##################################################################
#
# Title: Poltype
# Description: Atomic typer for the polarizable AMOEBA force field
#
# Copyright: Copyright (c) Johnny C. Wu,
# Gaurav Chattree, & Pengyu Ren 2010-2011
#
# Poltype is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# Poltype is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# if not, write to:
# Free Software Foundation, Inc.
# 59 Temple Place, Suite 330
# Boston, MA 02111-1307 USA
#
##################################################################
import os
import sys
import time
import string
from collections import deque
from types import *
import re
import getopt
import tempfile
import shutil
import pprint
import subprocess
import inspect
from socket import gethostname
from math import *
import numpy
from scipy import optimize
import matplotlib
matplotlib.use('Agg')
import pylab as plt
import openbabel
import valence
# Implementation Notes
# 1) Minimize Structure
# 2) Run SP Calculations
# 3) Run GDMA DONE (electrostatic-param.pl)
# 4) Run poledit (to extract atom types) DONE (electrostatic-param.pl)
# 4) Run avgmpoles.pl
# Default starting index of atom type
prmstartidx = 401
# These values can be edited. Affect speed of QM calculations.
numproc = 1
maxmem = "700MB"
maxdisk = "100GB"
# Initilize directories
gausdir = None
gdmadir = None
tinkerdir = None
scratchdir = "/scratch"
paramfname = sys.path[0] + "/amoeba_v2_new.prm"
paramhead = sys.path[0] + "/amoeba_v2_new_head.prm"
obdatadir = sys.path[0] + "/datadir"
amoeba_conv_spec_fname = "amoeba_t5_t4.txt"
# Initilize executables
babelexe = "babel"
gausexe = "g09"
formchkexe = "formchk"
cubegenexe = "cubegen"
gdmaexe = "gdma"
eleparmexe = sys.path[0] + "/electrostatic-param.pl"
groupsymexe = sys.path[0] + "/groupsym.exe"
avgmpolesexe = sys.path[0] + "/avgmpoles.pl"
peditexe = "poledit.x"
potentialexe = "potential.x"
valenceexe = "valence.x"
minimizeexe = "minimize.x"
analyzeexe = "analyze.x"
superposeexe = "superpose.x"
#peditexe = "poledit"
#potentialexe = "potential"
#valenceexe = "valence"
#minimizeexe = "minimize"
#analyzeexe = "analyze"
#superposeexe = "superpose"
# Initialize constants, basis sets
defopbendval = 0.20016677990819662
Hartree2kcal_mol = 627.5095
optbasisset = "6-31G*"
dmabasisset = "6-311G**"
popbasisset = "6-31G*"
espbasisset = "6-311++G(2d,2p)"
m06lbasisset = "6-311++G**"
# Initialize some global variables such as arrays and booleans
qmonly = False
espfit = True
parmtors = True
uniqidx = False
torkeyfname = None
nfoldlist = range(1,4)
foldoffsetlist = [ 0.0, 180.0, 0.0, 0.0, 0.0, 0.0 ]
torlist = []
rotbndlist = []
mm_tor_count = 1
output_format = 5
toromit_list = []
omittorsion2 = False
do_tor_qm_opt = False
# Poltype begins with the 'main' method which is found towards the bottom of the program
def call_subsystem(cmdstr, iscritical=False):
"""
Intent: Run 'cmdstr' on the command line
Input:
cmdstr: command string to be run on command line
Output:
Description: -
"""
now = time.strftime("%c",time.localtime())
logfh.write(now + " Calling: " + cmdstr + "\n")
logfh.flush()
os.fsync(logfh.fileno())
p = subprocess.Popen(cmdstr, shell=True,
stdout=logfh, stderr=logfh)
if p.wait() != 0:
now = time.strftime("%c",time.localtime())
logfh.write(now + " ERROR: " + cmdstr + "\n")
logfh.flush()
os.fsync(logfh.fileno())
if iscritical:
sys.exit(1)
return p.wait()
def which(program,pathlist=os.environ["PATH"]):
"""
Intent: Check if the 'program' is in the user's path
Input:
program: Program name
pathlist: members of the user's path
Output:
program: path to program
exe_file: path to program
None: program was not found
Referenced By: initialize
Description: -
"""
def is_exe(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in pathlist.split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def rotate_list(l1):
deq = deque(l1)
deq.rotate(-1)
return list(deq)
def parse_options(argv):
"""
Intent: Set up variables based on arguments supplied by user
Input:
argv: command line arguments supplied by user
Output:
Referenced By: main
Description:
"""
global molecprefix
global qmonly
global molstructfname
global chkname
global fname
global gausfname
global gausoptfname
global gdmafname
global comfname
global prmstartidx
global numproc
global maxmem
global maxdisk
# global gausdir
global espfit
global parmtors
global uniqidx
global torkeyfname
global optbasisset
global dmabasisset
global popbasisset
global espbasisset
global comoptfname
global chkoptfname
global fckoptfname
global logoptfname
global compopfname
global chkpopfname
global fckpopfname
global logpopfname
global comdmafname
global chkdmafname
global fckdmafname
global logdmafname
global comespfname
global chkespfname
global fckespfname
global logespfname
global output_format
global paramhead
global omittorsion2
global do_tor_qm_opt
try:
opts, xargs = getopt.getopt(argv[1:],'hqn:m:M:a:s:p:d:u:',["help","qmonly","optbasisset=","dmabasisset=","popbasisset=","espbasisset=","m06lbasisset=","optlog=","dmalog=","esplog=","dmafck=","espfck=","numproc=","maxmem=","maxdisk=","atmidx=","structure=","prefix=","gdmaout=","gbindir=","qm-scratch-dir=","omit-espfit","omit-torsion","test-tor-key=","uniqidx","tinker4format","omit-torsion2","do-tor-qm-opt"])
except getopt.GetoptError, err:
print str(err)
usage()
sys.exit(2)
for o, a in opts:
if o in ("-s", "--structure"):
molstructfname = a
elif o in ("-n", "--numproc"):
numproc = a
elif o in ("-m", "--maxmem"):
maxmem = a
elif o in ("-M", "--maxdisk"):
maxdisk = a
elif o in ("-a", "--atmidx"):
prmstartidx = int(a)
elif o in ("--optbasisset"):
optbasisset = a
elif o in ("--dmabasisset"):
dmabasisset = a
elif o in ("--popbasisset"):
popbasisset = a
elif o in ("--espbasisset"):
espbasisset = a
elif o in ("--m06lbasisset"):
m06lbasisset = a
elif o in ("--optlog"):
logoptfname = a
elif o in ("--dmalog"):
logdmafname = a
elif o in ("--esplog"):
logespfname = a
elif o in ("--dmafck"):
fckdmafname = a
elif o in ("--espfck"):
fckespfname = a
elif o in ("--dmachk"):
chkdmafname = a
elif o in ("--espchk"):
chkespfname = a
elif o in ("-f", "--formchk"):
fname = a
elif o in ("-d", "--gdmaout"):
gdmafname = a
elif o in ("-u", "--gbindir"):
gausdir = a
elif o in ("-q", "--qmonly"):
qmonly = True
elif o in ("--omit-espfit"):
espfit = False
elif o in ("--omit-torsion"):
parmtors = False
elif o in ("--omit-torsion2"):
omittorsion2 = True
elif o in ("--do-tor-qm-opt"):
do_tor_qm_opt = True
elif o in ("--test-tor-key"):
torkeyfname = a
elif o in ("--uniqidx"):
uniqidx = True
elif o in ("-h", "--help"):
usage()
sys.exit(2)
elif o in ("--version"):
printversion()
sys.exit(2)
elif o in ("--tinker4format"):
output_format = 4
paramhead = sys.path[0] + "/amoeba_v2_new_head_tinker_4.prm"
else:
assert False, "unhandled option"
assert globals().has_key("molstructfname"), "Molecule structure file (-s) needs to be defined."
class PrettyFloat(float):
def __repr__(self):
return '%.3f' % self
def pretty_floats(obj):
if isinstance(obj, float):
return PrettyFloat(obj)
if isinstance(obj, openbabel.OBAtom):
return obj.GetIdx()
elif isinstance(obj, dict):
return dict((k, pretty_floats(v)) for k, v in obj.items())
elif isinstance(obj, (list, tuple, numpy.ndarray)):
return map(pretty_floats, obj)
return obj
def dispvar(label, *vars):
"""
Intent: Output variable to stdout
"""
print label + ': ',
for var in vars:
print pretty_floats(var),
print ""
def print_error(errstrarr,kill=None):
now = time.strftime("%c",time.localtime())
sys.stderr.write('ERROR (%s): ' % now)
logfh.write('ERROR (%s): ' % now)
if isinstance(errstrarr, (list,tuple)):
for errstr in errstrarr:
sys.stderr.write(str(pretty_floats(errstr)) + '\n')
logfh.write(str(pretty_floats(errstr)) + '\n')
else:
sys.stderr.write(str(pretty_floats(errstrarr)) + '\n')
logfh.write(str(pretty_floats(errstrarr)) + '\n')
if kill is not None:
if isinstance(kill,int):
sys.exit(kill)
else:
sys.exit(255)
def write_arr_to_file(fname, array_list):
"""
Intent: Write out information in array to file
Input:
fname: file name
array_list: array with data to be printed
Output:
file is written to 'filename'
Referenced By: fit_rot_bond_tors, eval_rot_bond_parms
Description: -
"""
outfh = open(fname,'w')
rows = zip(*array_list)
for cols in rows:
for ele in cols:
outfh.write("%10.4f" % ele)
outfh.write("\n")
def initialize ():
"""
Intent: Initialize all paths to needed executables
Input:
Output:
Referenced By: main
Description: -
"""
global gausdir
global gausexe
global formchkexe
global cubegenexe
global tinkerdir
global peditexe
global potentialexe
global valenceexe
global minimizeexe
global analyzeexe
global superposeexe
global gdmaexe
if (gausdir is not None):
if which(os.path.join(gausdir,"g09")) is not None:
gausexe = os.path.join(gausdir,"g09")
formchkexe = os.path.join(gausdir,formchkexe)
cubegenexe = os.path.join(gausdir,cubegenexe)
elif which(os.path.join(gausdir,"g03")) is not None:
gausexe = os.path.join(gausdir,"g03")
formchkexe = os.path.join(gausdir,formchkexe)
cubegenexe = os.path.join(gausdir,cubegenexe)
else:
print "ERROR: Invalid Gaussian directory: ", gausdir
sys.exit(1)
else:
if which("g09") is not None:
gausexe = "g09"
elif which("g03") is not None:
gausexe = "g03"
else:
print "ERROR: Cannot find Gaussian executable in $PATH. Please install Gaussian or specify Gaussian directory with --gbindir flag."
sys.exit(1)
if ("TINKERDIR" in os.environ):
tinkerdir = os.environ["TINKERDIR"]
promof = open(tinkerdir+"/promo.f")
latestversion = False
for line in promof:
if "6.2" in line:
latestversion = True
break
promof.close()
if(not latestversion):
print "ERROR: Not latest version of tinker (6.2)"
sys.exit(1)
peditexe = os.path.join(tinkerdir,peditexe)
potentialexe = os.path.join(tinkerdir,potentialexe)
valenceexe = os.path.join(tinkerdir,valenceexe)
minimizeexe = os.path.join(tinkerdir,minimizeexe)
analyzeexe = os.path.join(tinkerdir,analyzeexe)
superposeexe = os.path.join(tinkerdir,superposeexe)
if (not which(analyzeexe)):
print "ERROR: Cannot find TINKER analyze executable"
sys.exit(2)
if ("GDMADIR" in os.environ):
gdmadir = os.environ["GDMADIR"]
gdmaexe = os.path.join(gdmadir,gdmaexe)
if (not which(gdmaexe)):
print "ERROR: Cannot find GDMA executable"
sys.exit(2)
if ("GAUSS_SCRDIR" in os.environ):
scratchdir = os.environ["GAUSS_SCRDIR"]
vfs = os.statvfs(scratchdir)
gbfree = (vfs.f_bavail * vfs.f_frsize) / (1024*1024*1024)
if(float(maxdisk[:-2]) > gbfree):
print "ERROR: maxdisk greater than free space in scratch directory"
sys.exit(2)
if (not which(scratchdir)):
print "ERROR: Cannot find Gaussian scratch directory"
sys.exit(2)
#os.putenv('BABEL_DATADIR',obdatadir)
def init_filenames ():
"""
Intent: Initialize file names
Input:
Output:
Referenced By: main
Description: -
"""
global logfname
global molecprefix
global molstructfname
global chkname
global fname
global gausfname
global gausoptfname
global gdmafname
global keyfname
global xyzfname
global peditinfile
global valinfile
global superposeinfile
global espgrdfname
global qmespfname
global qmesp2fname
global grpfname
global key2fname
global key3fname
global key4fname
global key5fname
global xyzoutfile
global valoutfname
global scrtmpdir
global tmpxyzfile
global tmpkeyfile
molecprefix = os.path.splitext(molstructfname)[0]
logfname = assign_filenames ( "logfname" , "-poltype.log")
chkname = assign_filenames ( "chkname" , ".chk")
fname = assign_filenames ( "fname" , ".fchk")
gausfname = assign_filenames ( "gausfname" , ".log")
gausoptfname = assign_filenames ( "gausoptfname" , "-opt.log")
gdmafname = assign_filenames ( "gdmafname" , ".gdmaout")
keyfname = assign_filenames ( "keyfname" , ".key")
xyzfname = assign_filenames ( "xyzfname" , ".xyz")
peditinfile = assign_filenames ( "peditinfile" , "-peditin.txt")
valinfile = assign_filenames ( "valinfile" , "-valin.txt")
superposeinfile = assign_filenames ( "superposeinfile" , "-superin.txt")
espgrdfname = assign_filenames ( "espgrdfname" , ".grid")
qmespfname = assign_filenames ( "qmespfname" , ".cube")
#qmesp2fname = assign_filenames ( "qmesp2fname" , ".cube_2")
qmesp2fname = assign_filenames ( "qmesp2fname" , ".pot")
grpfname = assign_filenames ( "grpfname" , "-groups.txt")
key2fname = assign_filenames ( "key2fname" , ".key_2")
key3fname = assign_filenames ( "key3fname" , ".key_3")
key4fname = assign_filenames ( "key4fname" , ".key_4")
key5fname = assign_filenames ( "key5fname" , ".key_5")
xyzoutfile = assign_filenames ( "xyzoutfile" , ".xyz_2")
valoutfname = assign_filenames ( "valoutfname" , "sp.valout")
scrtmpdir = scratchdir + '/Gau-' + molecprefix
tmpxyzfile = 'ttt.xyz'
tmpkeyfile = 'ttt.key'
def assign_filenames (filename,suffix):
global molecprefix
if globals().has_key(filename):
return eval(filename)
else:
return molecprefix + suffix
def printversion ():
print os.path.basename(sys.argv[0]) + \
''': Version 1.0.2'''
def copyright ():
print '''
Poltype -- Polarizable atom typer of small molecules for the
AMOEBA polarizable force field
Please cite:
Wu, J.C.; Chattree, G.; Ren, P.Y.; Automation of AMOEBA polarizable force field
parameterization for small molecules. Theor Chem Acc. (Accepted).
Version 1.1.4 June 2015
Copyright (c) Johnny Wu and Pengyu Ren 2011
All Rights Reserved
######################################################################################
'''
def usage ():
print '''poltype:
-h, --help -- displays this help message
-s, --structure -- Gaussian checkpoint file
-a, --atmidx -- Starting index of atom type
-m MEMORY , --maxmem --
-M, --maxdisk
-q, --qmonly
--optbasisset
--dmabasisset
--espbasisset
--m06lbasisset
--omit-espfit
--omit-torsion
--version -- displays version of script'''
def load_structfile(structfname):
"""
Intent: load 'structfname' as an OBMol structure
Input:
structfname: structure file name
Output:
tmpmol: OBMol object with information loaded from structfname
Referenced By: run_gaussian, tor_opt_sp, compute_qm_tor_energy, compute_mm_tor_energy
Description: -
"""
strctext = os.path.splitext(structfname)[1]
tmpconv = openbabel.OBConversion()
if strctext in '.fchk':
tmpconv.SetInFormat('fchk')
elif strctext in '.log':
tmpconv.SetInFormat('g03')
else:
inFormat = openbabel.OBConversion.FormatFromExt(structfname)
tmpconv.SetInFormat(inFormat)
tmpmol = openbabel.OBMol()
tmpconv.ReadFile(tmpmol, structfname)
return tmpmol
#def verify_topology (newmol, refmol):
#for atm in openbabel.OBMolAtomIter(refmol):
# newatm = newmol.
#return True
def rebuild_bonds(newmol, refmol):
for b in openbabel.OBMolBondIter(refmol):
beg = b.GetBeginAtomIdx()
end = b.GetEndAtomIdx()
if not newmol.GetBond(beg,end):
newmol.AddBond(beg,end, b.GetBO(), b.GetFlags())
return True
def get_class_number(idx):
"""
Intent: Given an atom idx, return the atom's class number
"""
maxidx = max(symmetryclass)
return prmstartidx + (maxidx - symmetryclass[idx - 1])
def get_class_key(a, b, c, d):
"""
Intent: Given a set of atom idx's, return the class key for the set (the class numbers of the atoms appended together)
"""
cla = get_class_number(a)
clb = get_class_number(b)
clc = get_class_number(c)
cld = get_class_number(d)
if ((clb > clc) or (clb == clc and cla > cld)):
return '%d %d %d %d' % (cld, clc, clb, cla)
return '%d %d %d %d' % (cla, clb, clc, cld)
def get_uniq_rotbnd(a, b, c, d):
"""
Intent: Return the atom idx's defining a rotatable bond in the order of the class key
found by 'get_class_key'
"""
cla = get_class_number(a)
clb = get_class_number(b)
clc = get_class_number(c)
cld = get_class_number(d)
tmpkey = '%d %d %d %d' % (cla,clb,clc,cld)
if (get_class_key(a,b,c,d) == tmpkey):
return (a, b, c, d)
return (d, c, b, a)
def obatom2idx(obatoms):
"""
Intent: Given a list of OBAtom objects, return a list of their corresponding idx's
Referenced By: get_torlist_opt_angle
"""
atmidxlist = []
for obatm in obatoms:
atmidxlist.append(obatm.GetIdx())
return atmidxlist
def save_structfile(molstruct, structfname):
"""
Intent: Output the data in the OBMol structure to a file (such as *.xyz)
Input:
molstruct: OBMol structure
structfname: output file name
Output:
file is output to structfname
Referenced By: tor_opt_sp, compute_mm_tor_energy
Description: -
"""
strctext = os.path.splitext(structfname)[1]
tmpconv = openbabel.OBConversion()
if strctext in '.xyz':
tmpfh = open(structfname, "w")
maxidx = max(symmetryclass)
iteratom = openbabel.OBMolAtomIter(molstruct)
etab = openbabel.OBElementTable()
tmpfh.write('%6d %s\n' % (molstruct.NumAtoms(), molstruct.GetTitle()))
for ia in iteratom:
tmpfh.write( '%6d %2s %13.6f %11.6f %11.6f %5d' % (ia.GetIdx(), etab.GetSymbol(ia.GetAtomicNum()), ia.x(), ia.y(), ia.z(), prmstartidx + (maxidx - symmetryclass[ia.GetIdx() - 1])))
iteratomatom = openbabel.OBAtomAtomIter(ia)
neighbors = []
for iaa in iteratomatom:
neighbors.append(iaa.GetIdx())
neighbors = sorted(neighbors)
for iaa in neighbors:
tmpfh.write('%5d' % iaa)
tmpfh.write('\n')
else:
inFormat = openbabel.OBConversion.FormatFromExt(structfname)
tmpconv.SetOutFormat(inFormat)
return tmpconv.WriteFile(molstruct, structfname)
def rads(degrees):
"""
Intent: Convert degrees to radians
"""
if type(degrees) == ListType:
return [ deg * pi / 180 for deg in degrees ]
else:
return degrees * pi / 180
def getCan(x):
"""
Intent: For a given atom, output it's canonical label if it exists
Input:
x: atom in question
Output:
canonical label if it exists, -1 if not
"""
if (str(type(mol.GetAtom(x))).find("OBAtom") >= 0):
return canonicallabel[x-1]
else:
return -1
def get_symm_class(x):
"""
Intent: For a given atom, output it's symmetry class if it exists
Input:
x: atom in question
Output:
symmetry class if it exists, -1 if not
"""
if (str(type(mol.GetAtom(x))).find("OBAtom") >= 0):
return symmetryclass[x-1]
else:
return -1
def prepend_keyfile(keyfilename):
"""
Intent: Adds a header to the key file given by 'keyfilename'
"""
tmpfname = keyfilename + "_tmp"
tmpfh = open(tmpfname, "w")
keyfh = open(keyfilename, "r")
tmpfh.write("parameters " + paramhead + "\n")
tmpfh.write("bondterm none\n")
tmpfh.write("angleterm none\n")
tmpfh.write("torsionterm none\n")
tmpfh.write("vdwterm none\n")
tmpfh.write("fix-monopole\n")
tmpfh.write("potential-offset 1.0\n\n")
for line in keyfh:
tmpfh.write(line)
shutil.move(tmpfname, keyfilename)
def scale_multipoles (symmclass, mpolelines,scalelist):
"""
Intent: Scale multipoles based on value in scalelist
"""
symmclass = int(symmclass)
if scalelist[symmclass][2]:
qp1 = float(mpolelines[2])
qp1 = map(float, mpolelines[2].split())
qp1 = [ scalelist[symmclass][2] * x for x in qp1 ]
mpolelines[2] = '%46.5f\n' % qp1[0]
qp2 = map(float, mpolelines[3].split())
qp2 = [ scalelist[symmclass][2] * x for x in qp2 ]
mpolelines[3] = '%46.5f %10.5f\n' % tuple(qp2)
qp3 = map(float, mpolelines[4].split())
qp3 = [ scalelist[symmclass][2] * x for x in qp3 ]
mpolelines[4] = '%46.5f %10.5f %10.5f\n' % tuple(qp3)
return mpolelines
def rm_esp_terms_keyfile(keyfilename):
"""
Intent: Remove unnecessary terms from the key file
"""
tmpfname = keyfilename + "_tmp"
cmdstr = "sed -e \'/\(.* none$\|^#\|^fix\|^potential-offset\)/d\' " + keyfilename + " > " + tmpfname
call_subsystem(cmdstr)
shutil.move(tmpfname, keyfilename)
# Removes redundant multipole definitions created after potential fitting
keyfh = open(keyfilename)
lines = keyfh.readlines()
newlines = []
tmpfh = open(tmpfname, "w")
mpolelines = 0
for ln1 in range(len(lines)):
if mpolelines > 0:
mpolelines -= 1
continue
if 'multipole' in lines[ln1]:
nllen = len(newlines)
for ln2 in range(len(newlines)):
if len(lines[ln1].split()) <= 1 or len(lines[ln2].split()) <= 1:
continue
if lines[ln1].split()[0] in newlines[ln2].split()[0] and \
lines[ln1].split()[0] in 'multipole' and \
lines[ln1].split()[1] in newlines[ln2].split()[1]:
newlines[ln2] = lines[ln1]
newlines[ln2+1] = lines[ln1+1]
newlines[ln2+2] = lines[ln1+2]
newlines[ln2+3] = lines[ln1+3]
newlines[ln2+4] = lines[ln1+4]
mpolelines = 4
break
if mpolelines == 0:
newlines.append(lines[ln1])
else:
newlines.append(lines[ln1])
for nline in newlines:
tmpfh.write(nline)
tmpfh.close()
keyfh.close()
shutil.move(tmpfname, keyfilename)
def post_proc_localframes(keyfilename, lfzerox):
"""
Intent: This method runs after the tinker tool Poledit has run and created an
initial *.key file. The local frames for each multipole are "post processed".
Zeroed out x-components of the local frame are set back to their original values
If certain multipole values were not zeroed out by poltype this method zeroes them out
Input:
keyfilename: string containing file name of *.key file
lfzerox: array containing a boolean about whether the x-component of the local frame
for a given atom should be zeroed or not. Filled in method 'gen_peditin'.
'lfzerox' is true for atoms that are only bound to one other atom (valence = 1)
that have more than one possible choice for the x-component of their local frame
Output: *.key file is edited
Referenced By: main
Description:
1. Move the original *.key file to *.keyb
2. Create new empty file *.key
3. Iterate through the lines of *.keyb.
a. If poledit wrote out the local frame with an x-component missing or as 0
Then rewrite it with the original x-component (lf2) found in gen_peditin
b. If poledit did not zero out the local frame x-component for an atom but
lfzerox is true, zero out the necessary multipole components manually
4. Write the edited multipole information to *.key
"""
# mv *.key to *.keyb
tmpfname = keyfilename + "b"
shutil.move(keyfilename, tmpfname)
keyfh = open(tmpfname)
lines = keyfh.readlines()
newlines = []
# open *.key which is currently empty
tmpfh = open(keyfilename, "w")
mpolelines = 0
# iterate over lines in the *.key file
for ln1 in range(len(lines)):
# skip over the lines containing multipole values
if mpolelines > 0:
mpolelines -= 1
continue
elif 'multipole' in lines[ln1]:
# Check what poledit wrote as localframe2
tmplst = lines[ln1].split()
if len(tmplst) == 5:
(keywd,atmidx,lf1,lf2,chg) = tmplst
elif len(tmplst) == 4:
(keywd,atmidx,lf1,chg) = tmplst
lf2 = '0'
# If poledit set lf2 to 0, then replace it with the lf2 found in gen_peditin
if int(lf2) == 0:
lf2 = localframe2[int(atmidx) - 1]
lines[ln1] = '%s %5s %4s %4d %21s\n' % (keywd,
atmidx, lf1, lf2, chg)
# manually zero out components of the multipole if they were not done by poledit
elif lfzerox[int(atmidx) - 1]:
tmpmp = map(float, lines[ln1+1].split())
tmpmp[0] = 0.
lines[ln1+1] = '%46.5f %10.5f %10.5f\n' % tuple(tmpmp)
tmpmp = map(float, lines[ln1+4].split())
tmpmp[0] = 0.
lines[ln1+4] = '%46.5f %10.5f %10.5f\n' % tuple(tmpmp)
newlines.extend(lines[ln1:ln1+5])
mpolelines = 4
# append any lines unrelated to multipoles as is
else:
newlines.append(lines[ln1])
# write out the new lines to *.key
for nline in newlines:
tmpfh.write(nline)
tmpfh.close()
keyfh.close()
def post_process_mpoles(keyfilename, scalelist):
"""
Intent: Iterate through multipoles in 'keyfilename' and scale them if necessary
Calls 'scale_multipoles'
Input:
keyfilename: file name for key file
scalelist: structure containing scaling information. Found in process_types
Output: new *.key file
Referenced By: main
Description:
1. Move old keyfile to tmpfname
2. open an empty key file
3. iterate through tmpfname scaling the multipoles if necessary
4. output new multipoles to the new key file
"""
tmpfname = keyfilename + "b"
shutil.move(keyfilename, tmpfname)
keyfh = open(tmpfname)
lines = keyfh.readlines()
newlines = []
tmpfh = open(keyfilename, "w")
mpolelines = 0
for ln1 in range(len(lines)):
if mpolelines > 0:
mpolelines -= 1
continue
elif 'multipole' in lines[ln1]:
(keywd,symcls,lf1,lf2,chg) = lines[ln1].split()
newlines.extend(scale_multipoles(symcls,lines[ln1:ln1+5],scalelist))
mpolelines = 4
else:
newlines.append(lines[ln1])
for nline in newlines:
tmpfh.write(nline)
tmpfh.close()
keyfh.close()
def append_basisset (comfname, spacedformulastr,basissetstr):
"""
Intent: Append terms to *.com file if necessary
Input:
comfname: com file name
spacedformulastr: stoichoimetric molecular formula in spaced form (e.g. C 4 H 6 O 1)
basissetstr: basis set string
Output:
comfname is possibly appended to
Referenced By: gen_optcomfile, gen_comfile, tor_opt_sp
Description:
"""
if ('I ' in spacedformulastr):
fh = open(comfname, "a")
fh.write(' ' + re.sub(r'(\d+|I)\s+',r'', spacedformulastr) + '0\n')
fh.write(' %s\n' % basissetstr)
fh.write(' ****\n')
# if re.search('6-31',basissetstr,re.I):
fh.write(' I 0 \n')
fh.write(' S 5 1.00\n')
fh.write(' 444750.000 0.0008900 \n')
fh.write(' 66127.0000 0.0069400 \n')
fh.write(' 14815.0000 0.0360900 \n')
fh.write(' 4144.90000 0.1356800 \n')
fh.write(' 1361.20000 0.3387800 \n')
fh.write(' S 2 1.00\n')
fh.write(' 508.440000 0.4365900 \n')
fh.write(' 209.590000 0.1837500 \n')
fh.write(' S 1 1.00\n')
fh.write(' 81.9590000 1.0000000 \n')
fh.write(' S 1 1.00\n')
fh.write(' 36.8050000 1.0000000 \n')
fh.write(' S 1 1.00\n')
fh.write(' 13.4950000 1.0000000 \n')
fh.write(' S 1 1.00\n')
fh.write(' 6.88590000 1.0000000 \n')
fh.write(' S 1 1.00\n')
fh.write(' 2.55200000 1.0000000 \n')
fh.write(' S 1 1.00\n')
fh.write(' 1.20880000 1.0000000 \n')
fh.write(' S 1 1.00\n')
fh.write(' 0.27340000 1.0000000 \n')
fh.write(' S 1 1.00\n')
fh.write(' 0.10090000 1.0000000 \n')
fh.write(' P 4 1.00\n')
fh.write(' 2953.60000 0.0122100 \n')
fh.write(' 712.610000 0.0858700 \n')
fh.write(' 236.710000 0.2949300 \n')
fh.write(' 92.6310000 0.4784900 \n')
fh.write(' P 1 1.00\n')
fh.write(' 39.7320000 1.0000000 \n')
fh.write(' P 1 1.00\n')
fh.write(' 17.2730000 1.0000000 \n')
fh.write(' P 1 1.00\n')
fh.write(' 7.95700000 1.0000000 \n')
fh.write(' P 1 1.00\n')
fh.write(' 3.15290000 1.0000000 \n')
fh.write(' P 1 1.00\n')
fh.write(' 1.33280000 1.0000000 \n')
fh.write(' P 1 1.00\n')
fh.write(' 0.49470000 1.0000000 \n')
fh.write(' P 1 1.00\n')
fh.write(' 0.21600000 1.0000000 \n')
fh.write(' P 1 1.00\n')
fh.write(' 0.08293000 1.0000000 \n')
fh.write(' D 3 1.00\n')
fh.write(' 261.950000 0.0314400 \n')
fh.write(' 76.7340000 0.1902800 \n')
fh.write(' 27.5510000 0.4724700 \n')
fh.write(' D 1 1.00\n')
fh.write(' 10.6060000 1.0000000 \n')
fh.write(' D 1 1.00\n')
fh.write(' 3.42170000 1.0000000 \n')
fh.write(' D 1 1.00\n')
fh.write(' 1.13700000 1.0000000 \n')
fh.write(' D 1 1.00\n')
fh.write(' 0.30200000 1.0000000 \n')
fh.write(' ****\n\n')
fh.close()
def is_qm_normal_termination(logfname):
"""
Intent: Checks the *.log file for normal termination
"""
if os.path.isfile(logfname):
for line in open(logfname):
if "Normal termination" in line:
logfh.write("Normal termination: %s\n" % logfname)
return True
return False
def gen_opt_str(optimizeoptlist):
optstr = "#opt"
if optimizeoptlist:
optstr += "=(" + ','.join(optimizeoptlist) + ")"
return optstr