/
RCSAnalysisFromT21.py
executable file
·587 lines (474 loc) · 15.5 KB
/
RCSAnalysisFromT21.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
#!/opt/local/bin/python
"""
Need to start Eclipse from command line (using executable inside app) to get
ADF env vars working right.
"""
import kf
import numpy as np
from random import randint
# Takes the path to a Tape21 file WITH BADER CP INFO
# Returns a list of triplets with XYZ coords of each CP
CurrentDir = ''
SubDir = '/Output' + str(randint(1,999999))
PathCoords = []
T21BaseName = ''
ScriptDir = ''
B2A = 0.52917721067
def GetCPCoords(T21FileName):
T21 = kf.kffile(T21FileName)
FullList = T21.read("Properties", "CP coordinates")
NumCPs = T21.read("Properties","CP number of")
T21.close()
CoordList = []
for i in range(NumCPs):
tmp = np.empty([3])
k = 0
for j in range(i,NumCPs * 3,NumCPs):
tmp[k] = FullList[j]
k += 1
CoordList.append(tmp)
return CoordList
# Takes the path to a Tape21 file WITH BADER CP INFO
# Returns a list of CP type numbers
#The "type" numbers go as {1,2,3,4} = {n,c,b,r}
def GetCPTypes(T21FileName):
TypeList = []
T21 = kf.kffile(T21FileName)
Types = T21.stringData("Properties","CP code number for (Rank,Signatu")
Types = Types.split('\n')
Types = Types[3:len(Types)-1]
for i in Types:
for j in i.split():
TypeList.append(int(float(j)))
T21.close()
return TypeList
def GenerateCoords(Pt1, Pt2, NumPts):
StepDir = Pt2.__sub__(Pt1)
StepSize = np.linalg.norm(StepDir)
StepDir /= StepSize
StepSize /= (NumPts - 1)
CoordList = [Pt1.__add__(np.multiply(StepDir,Step*StepSize)) for Step in range(NumPts)]
return CoordList
def DensfForCoords(T21FileName, GridCoords):
import StringIO
import os
import subprocess
global CurrentDir, T21BaseName, ScriptDir
T41FileName = CurrentDir + '/' + "Tape41_" + str(randint(1,999999)) + ".t41"
DensfScript = StringIO.StringIO()
DensfScript.write('''$ADFBIN/densf << eor
INPUTFILE ''' + T21FileName + '''
OUTPUTFILE ''' + T41FileName + '''
GRID Inline
''')
for i in GridCoords:
for j in i:
DensfScript.write(str(j) + ' ')
DensfScript.write('\n')
DensfScript.write('''End
Density SCF
DenGrad
DenHess
eor''')
DensfScript = DensfScript.getvalue()
#
# print DensfScript
subprocess.Popen(DensfScript, shell=True, stdout=subprocess.PIPE).stdout.read()
try:
os.remove(ScriptDir + '/logfile')
except: pass
subprocess.Popen('rm -rf ' + ScriptDir + '/IINFO*' + ScriptDir + '/SINFO*', shell=True, stdout=subprocess.PIPE).stdout.read()
return T41FileName
def GetDataFromT41(T41FileName):
T41Data = {}
T41VarStrs = ['Density']
for i in ['X','Y','Z']:
T41VarStrs.append('DensityGrad' + i)
for i in ['XX','XY','XZ','YY','YZ','ZZ']:
T41VarStrs.append('DensityHess' + i)
T41 = kf.kffile(T41FileName)
for i in T41VarStrs:
T41Data[i] = T41.read('SCF', i)
T41.close()
T41.delete()
return T41Data
# HessInd = [
# ['XX','XY','XZ'],
# ['XY','YY','YZ'],
# ['XZ','YZ','ZZ']]
HessInd = [
['XX','XY','XZ'],
['XY','YY','YZ'],
['XZ','YZ','ZZ']]
def GetHessForT41Index(T41Data,Ind):
H = np.empty([3,3])
for i in range(3):
for j in range(3):
H[i,j] = T41Data['DensityHess' + HessInd[i][j]][Ind]
return H
GradInd = ['X','Y','Z']
def GetGradForT41Index(T41Data,Ind):
G = np.empty([3])
for i in range(3):
G[i] = T41Data['DensityGrad' + GradInd[i]][Ind]
return
def GetEigenSystemForT41(T41Data):
from numpy import linalg as la
NumPts = len(T41Data['Density'])
T41Data['EigVals'] = [None]*NumPts
T41Data['EigVecs'] = [None]*NumPts
for i in range(NumPts):
T41Data['EigVals'][i], T41Data['EigVecs'][i] = la.eigh(GetHessForT41Index(T41Data, i))
# T41Data['EigVecs'][i] = np.transpose(T41Data['EigVecs'][i])
return
def tex_escape(text):
"""
:param text: a plain text message
:return: the message escaped to appear correctly in LaTeX
"""
import re
conv = {
'&': r'\&',
'%': r'\%',
'$': r'\$',
'#': r'\#',
'_': r'\_',
'{': r'\{',
'}': r'\}',
'~': r'\textasciitilde{}',
'^': r'\^{}',
'\\': r'\textbackslash{}',
'<': r'\textless',
'>': r'\textgreater',
}
regex = re.compile('|'.join(re.escape(unicode(key)) for key in sorted(conv.keys(), key = lambda item: - len(item))))
return regex.sub(lambda match: conv[match.group()], text)
# def forceAspect(ax,aspect=1):
# import matplotlib.pyplot as plt
# im = ax.get_images()
# extent = im[0].get_extent()
# ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)
def RCSMake1DPlot(T41Data, Tol, OutFileName, Res, ImgPath = ''):
import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np
import Image
import os
# import pylab as plt
# from matplotlib import rc
ValList = [[[0],[0]],[[0],[0]]]
NumPts = len(T41Data['Density'])
global CurrentDir, SubDir
import subprocess
subprocess.Popen('mkdir -p "' + CurrentDir + SubDir + '"', shell=True, stdout=subprocess.PIPE).stdout.read()
OutCSVName = CurrentDir + SubDir + "/" + OutFileName.replace(' ','_')
OutCSVName = OutCSVName.rpartition('_(')[0]
OutCSV = open(OutCSVName + '.csv','w')
Headings = ["PtNum","X","Y","Z","XBohr","YBohr","ZBohr","Rho","Lap"]
for i in ['1','2','3']:
Headings.append('DotPdt_' + i)
for i in ['1','2','3']:
Headings.append('EigVal_' + i)
for i in ['X','Y','Z']:
Headings.append('Grad_' + i)
for i in ['1','2','3']:
for j in ['1','2','3']:
Headings.append('EigVec_' + i + '_' + j)
for i in ['XX','XY','XZ','YY','YZ','ZZ']:
Headings.append('Hess_' + i)
for i in Headings:
OutCSV.write(i + ',')
OutCSV.write('\n')
RCS = [# [[dot products that should be below tolerence],[signs of eigenvalues],[value in plot]]
[[1,2,3],[1,1,1],[6,6]],
[[1,2],[-1,-1],[1,2]],
[[2,3],[1,1],[5,4]],
[[1,3],[1,1],[3,3]]
]
for i in range(NumPts):
G = [T41Data['DensityGrad' + j][i] for j in GradInd]
E = [T41Data['EigVals'][i][j] for j in range(3)]
# EV = np.transpose([T41Data['EigVecs'][i][j] for j in range(3)])
EV = np.transpose(T41Data['EigVecs'][i])
DP = [np.absolute(np.dot(G,j)) for j in EV]
PtNum = float(i + 1)
OutCSV.write(str(i+1) + ',')
for j in [T41Data['Coords'][i]]:
for k in j:
OutCSV.write(str(k) + ',')
for j in [T41Data['CoordsBohr'][i]]:
for k in j:
OutCSV.write(str(k) + ',')
OutCSV.write(str(T41Data['Density'][i]) + ',')
OutCSV.write(str(sum(E)) + ',')
for j in [DP,E,G]:
for k in j:
OutCSV.write(str(k) + ',')
for j in EV:
for k in j:
OutCSV.write(str(k) + ',')
for j in [T41Data['DensityHess' + k][i] for k in ['XX','XY','XZ','YY','YZ','ZZ']]:
OutCSV.write(str(j) + ',')
OutCSV.write('\n')
# HasVal = False
# SameSign = 0
for iRCS in RCS:
HasVal = True
for iDP in range(3):
if ((iDP + 1) in iRCS[0] and DP[iDP] > Tol) or ((iDP + 1) not in iRCS[0] and DP[iDP] <= Tol):
HasVal = False
break
if HasVal:
RCSInd = 0
for ei,es in zip(iRCS[0],iRCS[1]):
if np.sign(E[ei-1]) != es:
RCSInd = 1
break
SignInd = 0 if np.sign(E[iRCS[0][0]-1]) == np.sign(E[iRCS[0][1]-1]) else 1
ValList[SignInd][0].append(PtNum)
ValList[SignInd][1].append(iRCS[2][RCSInd])
# # CP (not used)
# if DP[0] <= Tol and DP[1] <= Tol and DP[2] <= Tol:
# Val = 6
# HasVal = True
#
# # Ridge and r-connector
# elif DP[0] <= Tol and DP[1] <= Tol and DP[2] > Tol:
# HasVal = True
# if E[0] < 0:
# if E[1] < 0: Val = 1
# else:
# SameSign = 1
# Val = 2
# else:
# Val = 2
# if E[1] < 0: SameSign = 1
#
# # Valley and v-connector
# elif DP[1] <= Tol and DP[2] <= Tol and DP[0] > Tol:
# HasVal = True
# if E[1] > 0:
# if E[2] > 0: Val = 5
# else:
# SameSign = 1
# Val = 4
# else:
# Val = 4
# if E[2] > 0: SameSign = 1
#
# # m-connector
# elif DP[0] <= Tol and DP[2] <= Tol and DP[1] > Tol:
# HasVal = True
# Val = 3
# if np.sign(E[2]) != np.sign(E[0]): SameSign = 1
#
# if HasVal:
# ValList[SameSign][0].append(PtNum)
# ValList[SameSign][1].append(Val)
OutCSV.close()
for j in ValList:
j[0].append(NumPts)
j[1].append(0)
NumPts = float(NumPts)
ValList = [[[j / NumPts * 100. for j in k[0]],[j for j in k[1]]] for k in ValList]
xVals = range(0,125,25)
yVals = range(1,7)
fig = plt.figure(figsize=(8,3))
if os.path.isfile(ImgPath):
gs = gridspec.GridSpec(1,2,width_ratios=[5.25,2.75])
ax = fig.add_subplot(gs[0]) # subplot required to change the aspect ratio
else:
ax = fig.add_subplot(111)
# ax.set_aspect(10)
# ax = fig.add_axes([0,0,6*Res,3*Res])
ax.plot(ValList[0][0], ValList[0][1], 'bs', ValList[1][0], ValList[1][1], 'r+')
plt.rc('text', usetex=True)
plt.rc('font', family='sans-serif')
plt.rc('font', size=12)
yLabels = ['Ridge',r'\textit{R}-connector',r'\textit{M}-connector',r'\textit{V}-connector','Valley','Critical point']
plt.xticks(xVals, xVals)
plt.yticks(yVals,yLabels,rotation=0)
plt.axis([-2,103,0.5,5.5])
plt.xlabel('\% of path langth')
fig.set_size_inches(8,3)
if os.path.isfile(ImgPath):
im = Image.open(ImgPath)
# height = im.size[1]
# im = np.array(im).astype(np.float) / 255
c = im.getbbox()
a = 5
cr = (c[0]+a,c[1]+a,c[2]-a,c[3]-a)
im = im.crop(cr).rotate(180)
w = 2.5 * Res
wp = w / float(im.size[0])
h = int(float(im.size[1]) * wp)
w = int(w)
im = im.resize([w,h],Image.BICUBIC)
fig.figimage(im, xo=5.5*Res, yo=0.5*Res + (w-h)/2, origin='lower')
fig.tight_layout()
fig.savefig(CurrentDir + SubDir + "/" + OutFileName.replace(' ','_') + '.png', dpi=Res)
# plt.axis([-2,103,0.5,6.5])
# fig.savefig(CurrentDir + SubDir + "/" + OutFileName.replace(' ','_') + '_wCP.png', dpi=Res)
#
# plt.title(tex_escape(OutFileName.replace('_',' ')))
# plt.axis([-2,103,0.5,5.5])
# fig.savefig(CurrentDir + SubDir + "/" + OutFileName.replace(' ','_') + '_wTitle.png', dpi=Res)
# plt.axis([-2,103,0.5,6.5])
# fig.savefig(CurrentDir + SubDir + "/" + OutFileName.replace(' ','_') + '_wTitle_wCP.png', dpi=Res)
# ax.set_aspect(10)
# f=plt.gcf()
# plt.show()
# fig.set_size_inches(7,4)
# fig.savefig(CurrentDir + SubDir + "/" + OutFileName.replace(' ','_') + '.eps', dpi=Res)
# plt.axis([-2,103,0.5,6.5])
# fig.set_size_inches(7.5,4.5)
# fig.savefig(CurrentDir + SubDir + "/" + OutFileName.replace(' ','_') + '_wCP.eps', dpi=Res)
#
# plt.title(tex_escape(OutFileName.replace('_',' ')))
# plt.axis([-2,103,0.5,5.5])
# fig.set_size_inches(7,4)
# fig.savefig(CurrentDir + SubDir + "/" + OutFileName.replace(' ','_') + '_wTitle.eps', dpi=Res)
# plt.axis([-2,103,0.5,6.5])
# fig.set_size_inches(7.5,4.5)
# fig.savefig(CurrentDir + SubDir + "/" + OutFileName.replace(' ','_') + '_wTitle_wCP.eps', dpi=Res)
# plt.show()
plt.close()
return
def GetCPsFromCoords(CPList,NewCoords,NewTypes,OldCoords,OldTypes):
CPNums = []
for CP in CPList:
MinDist = 1e100
MinInd = -1
for i in range(len(NewCoords)):
if NewTypes[i] == OldTypes[CP-1]:
TmpDist = np.linalg.norm(np.subtract(NewCoords[i],OldCoords[CP-1]))
if TmpDist < MinDist:
MinDist = TmpDist
MinInd = i
if MinInd >= 0:
CPNums.append(MinInd + 1)
return CPNums
CPTypeInd = ['N','C','B','R']
def main():
import ast
import os
import sys
import subprocess
global T21BaseName, ScriptDir, CurrentDir
Res = 1200 # dpi of resulting plots
NumPts = 101
Tols = [10**(-e) for e in range(3,9)]
# InputFilePath = "/Users/Haiiro/Safe/tmp/input.txt"
# InputFilePath = "/Users/Haiiro/ADFdata/1RidgePaper/first_round_data/input.txt"
# InputFilePath = "/Users/Haiiro/ADFdata/1RidgePaper/first_round_data/input_copy.txt"
InputFilePath = "/Users/Haiiro/ADFdata/bondalyzer_math_paper/DiSubstitutedBenzene/LDAautojobs/input.txt"
if len(sys.argv) > 1:
InputFilePath = sys.argv[1]
if len(sys.argv) > 2:
NumPts = int(sys.argv[2])
if len(sys.argv) > 3:
Tols = sys.argv[3]
if len(Tols.split(',')) > 1:
Tols = Tols.split(',')
Tols = [10**(-e) for e in range(int(Tols[0]),int(Tols[1])+1)]
else: Tols = [10**(-int(Tols))]
InputFile = open(InputFilePath, 'r')
InputFileContents = InputFile.readlines()
InputFile.close()
ScriptDir = os.path.dirname(os.path.realpath(__file__))
InputDir = os.path.dirname(os.path.realpath(InputFilePath))
FileNum = 0
for aLine in InputFileContents:
FileNum += 1
print '\nRunning file ' + str(FileNum) + ' of ' + str(len(InputFileContents))
aLine = aLine.split('\t')
if len(aLine) > 0:
InputT21FileName = aLine[0]
TargetCPs = ast.literal_eval(aLine[1])
ImgPaths = []
if len(aLine) > 3:
ImgPaths = aLine[3]
ImgPaths = eval(ImgPaths)
# ImgPaths = ast.literal_eval(ImgPaths)
if len(ImgPaths) < len(TargetCPs):
ImgPaths = [''] * len(TargetCPs)
print "File: %s with CPs: %s" % (InputT21FileName, str(TargetCPs))
T21BaseName = os.path.basename(InputT21FileName)
if T21BaseName != InputT21FileName:
CurrentDir = os.path.dirname(InputT21FileName)
else:
CurrentDir = InputDir
InputT21FileName = CurrentDir + '/' + T21BaseName
print "Adjusted file name: %s" % InputT21FileName
if '?' in InputT21FileName or '*' in InputT21FileName:
T21FileNames = subprocess.Popen("ls " + InputT21FileName, shell=True, stdout=subprocess.PIPE).stdout.read()
T21FileNames = T21FileNames.split('\n')
else:
T21FileNames = [InputT21FileName]
print "All T21s for file: %s" % str(T21FileNames)
OrigCPCoords = []
OrigCPTypes = []
for T21FileName in T21FileNames:
print "Running T21: %s" % T21FileName
if os.path.exists(T21FileName):
T21BaseName = os.path.basename(T21FileName)
if '.' in T21BaseName:
T21BaseName = T21BaseName.rpartition('.')[0]
# T21FileName = "'" + T21FileName + "'"
CPCoords = GetCPCoords(T21FileName)
CPTypes = GetCPTypes(T21FileName)
if len(OrigCPCoords) == 0: OrigCPCoords = CPCoords
if len(OrigCPTypes) == 0: OrigCPTypes = CPTypes
OutFileNames = []
if len(aLine) > 2:
OutFileNames = aLine[2]
OutFileNames = ast.literal_eval(OutFileNames)
if len(OutFileNames) != len(TargetCPs):
OutFileNames = []
break
Tmp = OutFileNames
OutFileNames = []
for i in Tmp:
TmpStr = T21BaseName + '_' + i + '_'
# First = True
# for i in c:
# if First: First = False
# else: TmpStr += '-'
# TmpStr += CPTypeInd[CPTypes[i-1]-1] + str(i)
OutFileNames.append(TmpStr)
if len(OutFileNames) == 0:
for c in TargetCPs:
TmpStr = T21BaseName + '_'
# First = True
# for i in c:
# if First: First = False
# else: TmpStr += '-'
# TmpStr += CPTypeInd[CPTypes[i-1]-1] + str(i)
OutFileNames.append(TmpStr)
global PathCoords
for Pts, PathName, ImgPath in zip(TargetCPs, OutFileNames, ImgPaths):
CPNums = GetCPsFromCoords(Pts, CPCoords, CPTypes, OrigCPCoords, OrigCPTypes)
if not os.path.exists(ImgPath):
ImgPath = CurrentDir + '/' + ImgPath
print "CP pair %s (%s)" % (str(CPNums), Pts)
OutFileName = PathName
First = True
for i in CPNums:
if First: First = False
else: OutFileName += '-'
OutFileName += CPTypeInd[CPTypes[i-1]-1] + str(i)
print "Outfile base: %s" % OutFileName
PathCoords = GenerateCoords(CPCoords[CPNums[0]-1] * B2A, CPCoords[CPNums[1]-1] * B2A, NumPts)
T41FileName = DensfForCoords(T21FileName, PathCoords)
T41Data = GetDataFromT41(T41FileName)
T41Data['Coords'] = PathCoords
T41Data['CoordsBohr'] = GenerateCoords(CPCoords[CPNums[0]-1], CPCoords[CPNums[1]-1], NumPts)
GetEigenSystemForT41(T41Data)
for Tol in Tols:
RCSMake1DPlot(T41Data, Tol, OutFileName + '_(' + '%.0e' % Tol + ')', Res, ImgPath)
# break
else:
print "File not found: %s" % T21FileName
print "Finished"
return
main()