-
Notifications
You must be signed in to change notification settings - Fork 3
/
spectrum.py
337 lines (284 loc) · 12.2 KB
/
spectrum.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
import numpy as np
from numpy import array
def batch(iterable, n=1):
l = len(iterable)
for ndx in range(0, l, n):
yield iterable[ndx:min(ndx + n, l)]
defaultKeys = [ 'Frequency', 'ROA alpha*G', 'ROA Beta(G)^2', 'ROA Beta(A)^2',
'ROA R-L Delta(90)_z', 'ROA R-L Delta(90)_x', 'ROA R-L Delta(0)', 'ROA R-L Delta(180)' ]
#['Raman Intensity (linear)']
#['Raman Intensity (circular)'
#['ROA alpha*G'] = alpha[0:last] * G[0:last]
#['ROA Beta(G)^2'] = beta_G2[0:last]
#['ROA Beta(A)^2'] = betaA2[0:last]
class SPECTRUM(object):
def __init__(self, title=None, data={}):
self._title = title
self.data = data
def __str__(self):
s = '\n ROA Diff. Parameter R-L (Ang^4/amu * 1000)'
s += ' Filename: %15s, # of b.f.: %3d \n' % (self.title,self.data['Number of basis functions'])
s += 132*'-' + '\n'
s += ' '
for key in defaultKeys:
if key[:4] == 'ROA ':
s += '%16s' % key[4:] # truncate off 'ROA '
else:
s += '%16s' % key
s += '\n'
s += 132*'-' + '\n'
for i in range(len(self.data['Frequency'])):
s += '%4d' % (i+1)
for key in defaultKeys:
s += '%16.4f' % self.data[key][i]
s += '\n'
return s
def print_all(self):
# assume everything is either scalar or is an array of dimension 1 by # of frequencies
keys = list(self.data.keys())
fieldwidth = 25
s = '** Scalar Quantities:\n'
# Print scalars first
for k in list(keys):
if (not hasattr(self.data[k],'__len__')) or isinstance(self.data[k],str):
s += '{:30}{:^30}\n'.format(k,self.data[k])
keys.remove(k)
s += '** Vector Quantities:\n'
for keyRow in batch(keys,4):
s += 103*'-' + '\n' + ' '
for k in keyRow:
s += '{:>{fw}s}'.format(k,fw=fieldwidth)
s += '\n'
s += 103*'-' + '\n'
for i in range(len(self.data['Frequency'])):
s += '{:3d}'.format(i+1)
for k in keyRow:
s += '{:{fw}.4f}'.format(self.data[k][i],fw=fieldwidth)
s += '\n'
s += 103*'-' + '\n'
print(s)
return
def title(self, setval):
self._title = setval
@property
def title(self):
return self._title
def invert(self, invertKeys=None):
if not invertKeys:
invertKeys = ['ROA alpha*G', 'ROA Beta(G)^2', 'ROA Beta(A)^2',
'ROA R-L Delta(90)_z', 'ROA R-L Delta(90)_x', 'ROA R-L Delta(0)', 'ROA R-L Delta(180)']
for k in invertKeys:
self.data[k] *= -1.0
return
@classmethod
def fromDictionaryOutputFile(cls, filename):
with open(filename,'r') as f:
data_in = eval( f.read() )
if filename[-4:] == '.dat':
filename = filename[:-4]
filename = filename.replace("spectra","sp")
return cls(title=filename, data=data_in)
@classmethod
def fromPsi4OutputFile(cls, filename):
freq = []
alphaG = []
betaG2 = []
betaA2 = []
delta_z_90 = []
delta_x_90 = []
delta_0 = []
delta_180 = []
IRIntensity = []
RamanLinear = []
RamanCircular = []
wfn = ''
basis = ''
nbf = 0
data_in = {}
with open(filename,'r') as f:
startInvariants = 0
startDifference = 0
startParameters = 0
startOldFrequencies = 0
oldStyle = False
toInvariantsLine = 0
toDifferenceLine = 0
toParametersLine = 0
toStartOldFrequenciesLine = 0
for line in f:
words = line.split()
cnt = 0
if len(words) == 3:
if words[0] == 'Wavefunction' and words[1] == '=':
wfn = words[2]
elif words[0] == 'Basis' and words[1] == 'Set:':
basis = words[2]
if len(words) > 4:
if words[0] == 'Number' and words[1] == 'of' and words[2] == 'basis':
nbf = int(words[4])
if startInvariants:
toInvariantsLine += 1
if startDifference:
toDifferenceLine += 1
if startParameters:
toParametersLine += 1
if startOldFrequencies:
toStartOldFrequenciesLine += 1
if startParameters == False:
if len(words) > 2:
# OLD style output from 2019
if words[0] == "Harmonic" and words[1] == "Freq." and words[2] == "IR":
print("Reading old 2019 style output")
startOldFrequencies = True
oldStyle = True
elif words[0] == 'Raman' and words[1] == 'Scattering' and words[2] == 'Parameters':
startParameters = True
if startOldFrequencies and toStartOldFrequenciesLine > 2:
if len(words) < 2: # all done
startOldFrequencies = False
elif words[1][-1] == 'i': # hit an imaginary frequency
startOldFrequencies = False
elif float(words[1]) < 8.0: # hit a rotation
startOldFrequencies = False
else:
#freq.append(float(words[1]))
IRIntensity.append(float(words[2]))
lineOffset = (4 if oldStyle else 5)
if startParameters and toParametersLine > lineOffset:
if len(words) < 2: # all done
startParameters = False
elif words[1][-1] == 'i': # hit an imaginary frequency
startParameters = False
elif float(words[1]) < 8.0: # hit a rotation
startParameters = False
else:
if not oldStyle:
IRIntensity.append(float(words[2]))
RamanLinear.append(float(words[6]))
RamanCircular.append(float(words[8]))
else:
RamanLinear.append(float(words[4]))
RamanCircular.append(float(words[6]))
if startInvariants == False:
if len(words) > 2:
if words[0] == 'ROA' and words[1] == 'Scattering' and words[2] == 'Invariants':
startInvariants = True
lineOffset = (4 if oldStyle else 3)
if startInvariants and toInvariantsLine > lineOffset:
if len(words) < 2: # all done
startInvariants = False
elif words[1][-1] == 'i': # hit an imaginary frequency
startInvariants = False
elif float(words[1]) < 8.0: # hit a rotation
startInvariants = False
else:
freq.append( float(words[1]))
alphaG.append(float(words[2]))
betaG2.append(float(words[3]))
betaA2.append(float(words[4]))
if startDifference == False:
if len(words) > 2:
if words[0] == 'ROA' and words[1] == 'Difference' and words[2] == 'Parameter':
startDifference = True
if startDifference and toDifferenceLine > 4:
if len(words) < 2: # all done
startDifference = False
elif words[1][-1] == 'i': # hit an imaginary frequency
startDifference = False
elif float(words[1]) < 8.0:
startDifference = False
else:
delta_z_90.append( float(words[2]))
delta_x_90.append( float(words[3]))
delta_0.append( float(words[4]))
delta_180.append( float(words[5]))
data_in['Frequency'] = np.array( freq )
data_in['ROA alpha*G'] = np.array( alphaG )
data_in['ROA Beta(G)^2'] = np.array( betaG2 )
data_in['ROA Beta(A)^2'] = np.array( betaA2 )
data_in['ROA R-L Delta(90)_z']= np.array( delta_z_90 )
data_in['ROA R-L Delta(90)_x']= np.array( delta_x_90 )
data_in['ROA R-L Delta(0)'] = np.array( delta_0 )
data_in['ROA R-L Delta(180)'] = np.array( delta_180 )
data_in['IR Intensity'] = np.array( IRIntensity )
data_in['Raman Intensity (linear)'] = np.array( RamanLinear )
data_in['Raman Intensity (circular)'] = np.array( RamanCircular )
data_in['Calculation Type'] = wfn + '/' + basis
data_in['Number of basis functions'] = nbf
if filename[-4:] in ['.out', '.dat']:
filename = filename[:-4]
else:
filename = filename
return cls(title=filename, data=data_in)
@classmethod
def fromOutputFile(cls, filename):
if filename[-6:0] == 'sp.out':
return fromDictionaryOutputFile(filename)
else:
return fromPsi4OutputFile(filename)
def writeDictionaryOutputFile(self, outfile):
with open(outfile,'w') as f:
f.write(str(self.data))
def comparePeaksByAveDev(s, o, keys=None): #self,other
if len(s.data['Frequency']) != len(o.data['Frequency']):
raise Exception('Spectra cannot be compared')
if keys is None:
keys = defaultKeys
diff = np.zeros( len(keys) )
for i, k in enumerate(keys):
diff[i] = np.mean(s.data[k] - o.data[k])
return diff
def comparePeaksByRMSDev(s, o, keys=None): #self,other
if len(s.data['Frequency']) != len(o.data['Frequency']):
raise('spectra cannot be compared')
if keys is None:
keys = defaultKeys
diff = np.zeros( len(keys) )
for i, k in enumerate(keys):
diff[i] = np.sqrt(np.mean( (s.data[k] - o.data[k])**2 ) )
return diff
# omit values if reference is < 3.5% of maximum value
def comparePeaksByRelDev(s, o, keys=None, omitBelow=0.035): #self,other
if len(s.data['Frequency']) != len(o.data['Frequency']):
raise('spectra cannot be compared')
if keys is None:
keys = defaultKeys
diff = np.zeros( len(keys) )
for i, k in enumerate(keys):
diff[i] = aveRelDev(s.data[k], o.data[k], omitBelow)
return diff
def comparePeaksByAveRelAbsDev(s, o, keys=None, omitBelow=0.035): #self,other
if len(s.data['Frequency']) != len(o.data['Frequency']):
raise('spectra cannot be compared')
if keys is None:
keys = defaultKeys
diff = np.zeros( len(keys) )
for i, k in enumerate(keys):
diff[i] = aveRelAbsDev(s.data[k], o.data[k], omitBelow)
return diff
def aveRelDev(Values, refValues, omitBelow):
maxValCounted = omitBelow*max(refValues)
num = 0
rval = 0.0
for i in range(len(Values)):
if abs(refValues[i]) > maxValCounted:
num += 1
rval += (Values[i] - refValues[i]) / refValues[i]
else: print('aveRelDev: ignoring mode %d' % i)
rval /= num
return rval
def aveRelAbsDev(Values, refValues, omitBelow):
maxValCounted = omitBelow*max(refValues)
num = 0
rval = 0.0
ignore_mode = []
for i in range(len(Values)):
if abs(refValues[i]) > maxValCounted:
num += 1
rval += abs( (Values[i] - refValues[i]) / refValues[i])
else:
ignore_mode.append(i)
if len(ignore_mode) != 0:
print('In aveRelAbsDev, ignoring modes with small ref. values:', [m+1 for m in ignore_mode])
rval /= num
return rval