-
Notifications
You must be signed in to change notification settings - Fork 8
/
spectra.py
2741 lines (2451 loc) · 102 KB
/
spectra.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
"""classes for storing signal data and plotting various spectra (IR, UV/vis, etc.)"""
import re
import numpy as np
from AaronTools import addlogger
from AaronTools.const import (
UNIT,
PHYSICAL,
COMMONLY_ODD_ISOTOPES,
)
from AaronTools.utils.utils import (
float_num,
pascals_triangle,
shortest_path,
)
class Signal:
"""
parent class for each signal in a spectrum
"""
# attribute for the x position of this signal
x_attr = None
required_attrs = ()
nested = None
def __init__(self, x_var, **kwargs):
for attr in self.required_attrs:
setattr(self, attr, None)
for arg in kwargs:
setattr(self, arg, kwargs[arg])
setattr(self, self.x_attr, x_var)
def __repr__(self):
s = self.__class__.__name__
s += "("
s += str(getattr(self, self.x_attr))
s += ", "
for attr in self.__dict__:
if attr == self.x_attr:
continue
s += attr
s += "="
s += str(getattr(self, attr))
s += ", "
s.rstrip(", ")
s += ")"
return s
@addlogger
class Signals:
"""
parent class for storing data for different signals in the
spectrum and plotting a simulated spectrum
"""
# label for x axis - should be set by child classes
x_label = None
LOG = None
def __init__(self, data, style="gaussian", *args, **kwargs):
self.data = []
if isinstance(data[0], Signal):
self.data = data
return
lines = False
if isinstance(data, str):
lines = data.splitlines()
if lines and style == "gaussian":
self.parse_gaussian_lines(lines, *args, **kwargs)
elif lines and style == "orca":
self.parse_orca_lines(lines, *args, **kwargs)
elif lines and style == "psi4":
self.parse_psi4_lines(lines, *args, **kwargs)
elif lines and style == "qchem":
self.parse_qchem_lines(lines, *args, **kwargs)
else:
raise NotImplementedError("cannot parse data for %s" % style)
def parse_gaussian_lines(self, lines, *args, **kwargs):
"""parse data from Gaussian output files related to this spectrum"""
raise NotImplementedError(
"parse_gaussian_lines not implemented by %s" %
self.__class__.__name__
)
def parse_orca_lines(self, lines, *args, **kwargs):
"""parse data from ORCA output files related to this spectrum"""
raise NotImplementedError(
"parse_orca_lines not implemented by %s" %
self.__class__.__name__
)
def parse_psi4_lines(self, lines, *args, **kwargs):
"""parse data from Psi4 output files related to this spectrum"""
raise NotImplementedError(
"parse_psi4_lines not implemented by %s" %
self.__class__.__name__
)
def parse_qchem_lines(self, lines, *args, **kwargs):
"""parse data from Q-Chem output files related to this spectrum"""
raise NotImplementedError(
"parse_qchem_lines not implemented by %s" %
self.__class__.__name__
)
def filter_data(self, signal):
"""
used to filter out some data from the spectrum (e.g.
imaginary modes from an IR spec)
return False if signal should not be in the spectrum
"""
return True
def get_spectrum_functions(
self,
fwhm=15.0,
peak_type="pseudo-voigt",
voigt_mixing=0.5,
scalar_scale=0.0,
linear_scale=0.0,
quadratic_scale=0.0,
intensity_attr="intensity",
data_attr="data",
):
"""
returns a list of functions that can be evaluated to
produce a spectrum
:param float fwhm: full width at half max of each peak
:param str peak_type: gaussian, lorentzian, pseudo-voigt, or delta
:param float voigt_mixing: ratio of pseudo-voigt that is gaussian
:param float scalar_scale: shift x data
:param float linear_scale: scale x data
:param float quadratic_scale: scale x data
x' = (1 - linear_scale * x - quadratic_scale * x^2 - scalar_scale)
:param str intensity_attr: attribute of Signal used for the intensity
of that signal
:param str data_attr: attribute of self for the list of Signal()
"""
data = getattr(self, data_attr)
x_attr = data[0].x_attr
# scale x positions
if not data[0].nested:
x_positions = np.array(
[getattr(d, x_attr) for d in data if self.filter_data(d)]
)
intensities = [
getattr(d, intensity_attr) for d in data if self.filter_data(d)
]
else:
x_positions = []
intensities = []
x_positions.extend(
[getattr(d, x_attr) for d in data if self.filter_data(d)]
)
intensities.extend(
[getattr(d, intensity_attr) for d in data if self.filter_data(d)]
)
for nest in data[0].nested:
for d in data:
nest_attr = getattr(d, nest)
if isinstance(nest_attr, dict):
for value in nest_attr.values():
if hasattr(value, "__iter__"):
for item in value:
x_positions.append(getattr(item, x_attr))
intensities.append(getattr(item, intensity_attr))
else:
x_positions.append(getattr(value, x_attr))
intensities.append(getattr(value, intensity_attr))
elif hasattr(nest_attr, "__iter__"):
for item in nest_attr:
x_positions.append(getattr(item, x_attr))
intensities.append(getattr(item, intensity_attr))
else:
x_positions.append(getattr(nest_attr, x_attr))
intensities.append(getattr(nest_attr, intensity_attr))
x_positions = np.array(x_positions)
x_positions -= (
linear_scale * x_positions + quadratic_scale * x_positions ** 2
)
x_positions += scalar_scale
e_factor = -4 * np.log(2) / fwhm ** 2
sigma = fwhm / (2 * np.sqrt(2 * np.log(2)))
functions = []
for x_pos, intensity in zip(x_positions, intensities):
if intensity is not None:
if peak_type.lower() == "gaussian":
functions.append(
lambda x, x0=x_pos, inten=intensity: inten
* np.exp(e_factor * (x - x0) ** 2)
* fwhm / (2 * np.sqrt(2 * np.log(2)))
)
elif peak_type.lower() == "lorentzian":
functions.append(
lambda x, x0=x_pos, inten=intensity: inten
* (
0.5 * fwhm
/ (np.pi * ((x - x0) ** 2 + (0.5 * fwhm) ** 2))
)
)
elif peak_type.lower() == "pseudo-voigt":
functions.append(
lambda x, x0=x_pos, inten=intensity: inten
* (
(1 - voigt_mixing)
* (
(0.5 * fwhm) ** 2
/ (((x - x0) ** 2 + (0.5 * fwhm) ** 2))
)
+ voigt_mixing
* np.exp(-(x - x0) ** 2 / (2 * sigma ** 2))
)
)
elif peak_type.lower() == "delta":
functions.append(
lambda x, x0=x_pos, inten=intensity: inten
* int(x == x0)
)
return functions, x_positions, intensities
@staticmethod
def get_plot_data(
functions,
signal_centers,
point_spacing=None,
transmittance=False,
peak_type="pseudo-voigt",
normalize=True,
fwhm=15.0,
change_x_unit_func=None,
show_functions=None,
):
"""
:returns: arrays of x_values, y_values for a spectrum
:param float point_spacing: spacing between points, default is higher resolution around
each peak (i.e. not uniform)
this is pointless if peak_type == delta
:param float fwhm: full width at half max
:param bool transmittance: if true, take 10^(2 - y_values) before returning
to get transmittance as a %
:param str peak_type: pseudo-voigt, gaussian, lorentzian, or delta
:param float voigt_mixing: fraction of pseudo-voigt that is gaussian
:param float linear_scale: subtract linear_scale * frequency off each mode
:param float quadratic_scale: subtract quadratic_scale * frequency^2 off each mode
"""
other_y_list = []
if peak_type.lower() != "delta":
if point_spacing is not None:
x_values = []
x = -point_spacing
stop = max(signal_centers)
stop += 5 * fwhm
while x < stop:
x += point_spacing
x_values.append(x)
x_values = np.array(x_values)
else:
xmax = max(signal_centers) + 10 * (fwhm + 1)
xmin = min(signal_centers) - 10 * (fwhm + 1)
if xmax > 0:
xmax *= 1.1
else:
xmax *= 0.9
if xmin < 0:
xmin *= 1.1
else:
xmin = 0
x_values = np.linspace(
xmin,
xmax,
num=1000,
).tolist()
prev_pt = None
for x in signal_centers:
if prev_pt is not None and abs(x - prev_pt) < fwhm / 10:
continue
prev_pt = x
x_values.extend(
np.linspace(
x - (10 * fwhm),
x + (10 * fwhm),
num=250,
).tolist()
)
x_values.append(x)
if not point_spacing:
x_values = np.array(list(set(x_values)))
x_values.sort()
y_values = np.zeros(len(x_values))
for i, f in enumerate(functions):
y_values += f(x_values)
if show_functions:
if (
len(show_functions[0]) == 2 and
all(isinstance(n, int) for n in show_functions[0])
):
for (ndx1, ndx2) in show_functions:
other_y_list.append(
np.sum(
[f(x_values) for f in functions[ndx1: ndx2]],
axis=0,
)
)
else:
for comp in show_functions:
other_y_list.append(
np.sum([f(x_values) for f in comp], axis=0)
)
else:
x_values = []
y_values = []
for freq, func in zip(signal_centers, functions):
y_values.append(func(freq))
x_values.append(freq)
y_values = np.array(y_values)
if len(y_values) == 0:
Signals.LOG.warning("nothing to plot")
return None
if normalize or transmittance:
max_val = abs(max(y_values.max(), y_values.min(), key=abs))
y_values /= max_val
for y_vals in other_y_list:
y_vals /= max_val
if transmittance:
y_values = np.array([10 ** (2 - y) for y in y_values])
for i in range(0, len(other_y_list)):
other_y_list[i] = np.array(
[10 ** (2 - y) for y in other_y_list[i]]
)
if change_x_unit_func:
x_values, ndx = change_x_unit_func(x_values)
y_values = y_values[ndx]
for i in range(0, len(other_y_list)):
other_y_list[i] = other_y_list[i][ndx]
return x_values, y_values, other_y_list
@classmethod
def plot_spectrum(
cls,
figure,
x_values,
y_values,
other_y_values=None,
other_y_style=None,
centers=None,
widths=None,
exp_data=None,
reverse_x=None,
y_label=None,
plot_type="transmittance",
x_label=r"wavenumber (cm$^{-1}$)",
peak_type="pseudo-voigt",
rotate_x_ticks=False,
):
"""
plot the x_data and y_data on figure (matplotlib figure)
this is intended for IR spectra
:param np.ndarray centers: array-like of float, plot is split into sections centered
on the frequency specified by centers
default is to not split into sections
:param np.ndarray widths: array-like of float, defines the width of each section
:param list exp_data: other data to plot
should be a list of (x_data, y_data, color)
:param bool reverse_x: if True, 0 cm^-1 will be on the right
"""
if not centers:
# if no centers were specified, pretend they were so we
# can do everything the same way
axes = [figure.subplots(nrows=1, ncols=1)]
y_nonzero = np.nonzero(y_values)[0]
x_values = np.array(x_values)
widths = [max(x_values[y_nonzero])]
centers = [max(x_values[y_nonzero]) / 2]
else:
n_sections = len(centers)
figure.subplots_adjust(wspace=0.05)
# sort the sections so we don't jump around
widths = [
x
for _, x in sorted(
zip(centers, widths),
key=lambda p: p[0],
reverse=reverse_x,
)
]
centers = sorted(centers, reverse=reverse_x)
axes = figure.subplots(
nrows=1,
ncols=n_sections,
sharey=True,
gridspec_kw={"width_ratios": widths},
)
if not hasattr(axes, "__iter__"):
# only one section was specified (e.g. zooming in on a peak)
# make sure axes is iterable
axes = [axes]
for i, ax in enumerate(axes):
if i == 0:
ax.set_ylabel(y_label)
# need to split plot into sections
# put a / on the border at the top and bottom borders
# of the plot
if len(axes) > 1:
ax.spines["right"].set_visible(False)
ax.tick_params(labelright=False, right=False)
ax.plot(
[1, 1],
[0, 1],
marker=((-1, -1), (1, 1)),
markersize=5,
linestyle="none",
color="k",
mec="k",
mew=1,
clip_on=False,
transform=ax.transAxes,
)
elif i == len(axes) - 1 and len(axes) > 1:
# last section needs a set of / too, but on the left side
ax.spines["left"].set_visible(False)
ax.tick_params(labelleft=False, left=False)
ax.plot(
[0, 0],
[0, 1],
marker=((-1, -1), (1, 1)),
markersize=5,
linestyle="none",
color="k",
mec="k",
mew=1,
clip_on=False,
transform=ax.transAxes,
)
elif len(axes) > 1:
# middle sections need two sets of /
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.tick_params(
labelleft=False, labelright=False, left=False, right=False
)
ax.plot(
[0, 0],
[0, 1],
marker=((-1, -1), (1, 1)),
markersize=5,
linestyle="none",
label="Silence Between Two Subplots",
color="k",
mec="k",
mew=1,
clip_on=False,
transform=ax.transAxes,
)
ax.plot(
[1, 1],
[0, 1],
marker=((-1, -1), (1, 1)),
markersize=5,
label="Silence Between Two Subplots",
linestyle="none",
color="k",
mec="k",
mew=1,
clip_on=False,
transform=ax.transAxes,
)
if peak_type.lower() != "delta":
ax.plot(
x_values,
y_values,
color="k",
linewidth=1,
label="computed",
)
if other_y_values:
for y_vals, style in zip(other_y_values, other_y_style):
ax.plot(
x_values,
y_vals,
color=style[0],
linestyle=style[1],
linewidth=1,
label=style[2],
zorder=-1,
)
else:
if plot_type.lower() == "transmittance":
ax.vlines(
x_values,
y_values,
[100 for y in y_values],
linewidth=1,
colors=["k" for x in x_values],
label="computed",
)
ax.hlines(
100,
0,
max(4000, *x_values),
linewidth=1,
colors=["k" for y in y_values],
label="computed",
)
if other_y_values:
for y_vals, style in zip(other_y_values, other_y_style):
ax.vlines(
x_values,
y_vals,
[100 for y in y_vals],
colors=[style[0] for x in x_values],
linestyles=style[1],
linewidth=1,
label=style[2],
zorder=-1,
)
else:
ax.vlines(
x_values,
[0 for y in y_values],
y_values,
linewidth=1,
colors=["k" for x in x_values],
label="computed",
)
ax.hlines(
0,
0,
max(4000, *x_values),
linewidth=1,
colors=["k" for y in y_values],
label="computed",
)
if other_y_values:
for y_vals, style in zip(other_y_values, other_y_style):
ax.vlines(
x_values,
[0 for y in y_vals],
y_vals,
colors=[style[0] for x in x_values],
linestyles=style[1],
linewidth=1,
label=style[2],
zorder=-1,
)
if exp_data:
for x, y, color in exp_data:
ax.plot(
x,
y,
color=color,
zorder=1,
linewidth=1,
label="observed",
)
center = centers[i]
width = widths[i]
high = center + width / 2
low = center - width / 2
if reverse_x:
ax.set_xlim(high, low)
else:
ax.set_xlim(low, high)
# b/c we're doing things in sections, we can't add an x-axis label
# well we could, but which section would be put it one?
# it wouldn't be centered
# so instead the x-axis label is this
figure.text(
0.5, 0.0, x_label, ha="center", va="bottom"
)
if rotate_x_ticks:
figure.autofmt_xdate(rotation=-45, ha="center")
@classmethod
def get_mixed_signals(
cls,
signal_groups,
weights,
fractions=None,
data_attr="data",
**kwargs,
):
"""
get signals for a mixture of components or conformers
:param list(Signal)|list(list(Signal)) signal_groups: list of Signals() instances or list of lists of Signals()
a list of Signals() is a group of conformers
a list of lists of Signals() are the different components
:param iterable weights: weights for each conformer, organized according to signal_groups
:param iterable fractions: fraction of each component in the mixture
default: all components have equal fractions
:param str data_attr: attribute of Signals() for data
:param kwargs: passed to cls.__init__, along with a new list of data
"""
if not hasattr(signal_groups[0], "__iter__"):
signal_groups = [signal_groups]
if not hasattr(weights[0], "__iter__"):
weights = [weights]
if fractions is None:
fractions = np.ones(len(signal_groups))
new_data = []
for group, weighting, fraction in zip(signal_groups, weights, fractions):
for signals, weight in zip(group, weighting):
data = getattr(signals, data_attr)
for d in data:
x_val = getattr(d, d.x_attr)
vals = d.__dict__
data_cls = d.__class__
new_vals = dict()
for key, item in vals.items():
if isinstance(item, float):
new_vals[key] = fraction * weight * item
else:
new_vals[key] = item
if d.nested:
if not isinstance(d.nested, str):
for attr in d.nested:
nest = getattr(d, attr)
nest_vals = dict()
if isinstance(nest, dict):
for k, items in nest.items():
for i, item in enumerate(items):
nest_x_val = getattr(item, item.x_attr)
vals = item.__dict__
nest_cls = item.__class__
for k2, j in vals.items():
if isinstance(item, float):
nest_vals[k2] = fraction * weight * j
else:
nest_vals[k2] = j
new_vals[attr][k][i] = nest_cls(
nest_x_val, **nest_vals
)
elif hasattr(nest, "__iter__"):
for i, item in enumerate(nest):
nest_x_val = getattr(item, item.x_attr)
vals = item.__dict__
nest_cls = item.__class__
for k, j in vals.items():
if isinstance(item, float):
nest_vals[k] = fraction * weight * j
else:
nest_vals[k] = j
new_vals[attr][i] = nest_cls(
nest_x_val, **nest_vals
)
else:
nest_x_val = getattr(nest, nest.x_attr)
vals = nest.__dict__
nest_cls = nest.__class__
for k, j in vals.items():
if isinstance(nest, float):
nest_vals[k] = fraction * weight * j
else:
nest_vals[k] = j
new_vals[attr][k] = nest_cls(
nest_x_val, **nest_vals
)
new_data.append(data_cls(x_val, **new_vals))
return cls(new_data, **kwargs)
class HarmonicVibration(Signal):
x_attr = "frequency"
required_attrs = (
"intensity", "vector", "symmetry", "rotation", "raman_activity", "forcek", "red_mass",
)
class AnharmonicVibration(Signal):
x_attr = "frequency"
required_attrs = (
"intensity", "harmonic", "overtones", "combinations",
"rotation", "raman_activity",
)
nested = ("overtones", "combinations")
@property
def harmonic_frequency(self):
return self.harmonic.frequency
@property
def delta_anh(self):
return self.frequency - self.harmonic.frequency
class Frequency(Signals):
"""for spectra in the IR/NIR region based on vibrational modes"""
def __init__(self, *args, harmonic=True, hpmodes=None, **kwargs):
super().__init__(*args, harmonic=harmonic, hpmodes=hpmodes, **kwargs)
self.anharm_data = None
self.imaginary_frequencies = None
self.real_frequencies = None
self.lowest_frequency = None
self.by_frequency = {}
self.is_TS = None
self.sort_frequencies()
# some software doesn't print reduced mass or force constants
# we can calculate them if we have atom with mass, displacement
# vectors, and vibrational frequencies
try:
if self.data and (
not self.data[-1].forcek or
not self.data[-1].red_mass
) and "atoms" in kwargs:
atoms = kwargs["atoms"]
for mode in self.data:
norm = sum(np.sum(mode.vector ** 2, axis=1))
disp = mode.vector / norm
mode.vector = disp
mu = 0
for i in range(0, len(mode.vector)):
mu += np.dot(disp[i], disp[i]) * atoms[i].mass
mode.red_mass = mu
k = 4 * np.pi ** 2 * mode.frequency ** 2
k *= PHYSICAL.SPEED_OF_LIGHT ** 2 * mu
k *= UNIT.AMU_TO_KG * 1e-2
mode.forcek = k
except (IndexError, AttributeError):
# some software can compute frequencies with a user-supplied
# hessian, so it never prints the structure
# ORCA can do this. It will print the input structure, but
# we don't parse that
pass
def parse_gaussian_lines(
self, lines, *args, hpmodes=None, harmonic=True, **kwargs
):
if harmonic:
return self._parse_harmonic_gaussian(lines, hpmodes=hpmodes)
return self._parse_anharmonic_gaussian(lines)
def _parse_harmonic_gaussian(self, lines, hpmodes):
if hpmodes is None:
raise TypeError(
"hpmodes argument required when data is a string"
)
hpmodes_re = re.compile("^\s+\d+\s+\d+\s+\d+(\s+[+-]?\d+\.\d+)+$")
regmodes_re = re.compile("^\s+\d+\s+\d+(\s+[+-]?\d+\.\d+)+$")
num_head = 0
for line in lines:
if "Harmonic frequencies" in line:
num_head += 1
if hpmodes and num_head != 2:
raise RuntimeError("Log file damaged, cannot get frequencies")
num_head = 0
idx = -1
modes = []
for k, line in enumerate(lines):
if "Harmonic frequencies" in line:
num_head += 1
if hpmodes and num_head == 2:
# if hpmodes, want just the first set of freqs
break
continue
if not hpmodes and "Frequencies" in line and "---" in line:
hpmodes = True
if "Frequencies" in line and (
(hpmodes and "---" in line) or (" -- " in line and not hpmodes)
):
for i, symm in zip(
float_num.findall(line), lines[k - 1].split()
):
self.data += [HarmonicVibration(float(i), symmetry=symm)]
modes += [[]]
idx += 1
continue
if ("Force constants" in line and "---" in line and hpmodes) or (
"Frc consts" in line and "--" in line and not hpmodes
):
force_constants = float_num.findall(line)
for i in range(-len(force_constants), 0, 1):
self.data[i].forcek = float(force_constants[i])
continue
if ("Reduced masses" in line and "---" in line and hpmodes) or (
"Red. masses" in line and "--" in line and not hpmodes
):
red_masses = float_num.findall(line)
for i in range(-len(red_masses), 0, 1):
self.data[i].red_mass = float(red_masses[i])
continue
if ("Rot. strength" in line and "---" in line and hpmodes) or (
"Rot. str." in line and "--" in line and not hpmodes
):
roational_strength = float_num.findall(line)
for i in range(-len(roational_strength), 0, 1):
self.data[i].rotation = float(roational_strength[i])
continue
if ("Raman Activities" in line and "---" in line and hpmodes) or (
"Raman Activ" in line and "--" in line and not hpmodes
):
roational_strength = float_num.findall(line)
for i in range(-len(roational_strength), 0, 1):
self.data[i].raman_activity = float(roational_strength[i])
continue
if "IR Inten" in line and (
(hpmodes and "---" in line) or (not hpmodes and "--" in line)
):
intensities = float_num.findall(line)
for i in range(-len(intensities), 0, 1):
self.data[i].intensity = float(intensities[i])
continue
if hpmodes:
match = hpmodes_re.search(line)
if match is None:
continue
values = float_num.findall(line)
coord = int(values[0]) - 1
atom = int(values[1]) - 1
moves = values[3:]
for i, m in enumerate(moves):
tmp = len(moves) - i
mode = modes[-tmp]
try:
vector = mode[atom]
except IndexError:
vector = [0, 0, 0]
modes[-tmp] += [[]]
vector[coord] = m
modes[-tmp][atom] = vector
else:
match = regmodes_re.search(line)
if match is None:
continue
data = line.split()
# values = float_num.findall(line)
atom = int(data[0]) - 1
moves = np.array(data[2:], dtype=float)
n_moves = len(moves) // 3
for i in range(-n_moves, 0):
modes[i].append(
moves[3 * n_moves + 3 * i : 3 * n_moves + 3 * (i + 1)]
)
for mode, data in zip(modes, self.data):
data.vector = np.array(mode, dtype=np.float64)
def _parse_anharmonic_gaussian(self, lines):
reading_combinations = False
reading_overtones = False
reading_fundamentals = False
combinations = []
overtones = []
fundamentals = []
mode_re = re.compile(r"(\d+)\((\d+)\)")
for line in lines:
if "---" in line or "Mode" in line or not line.strip():
continue
if "Fundamental Bands" in line:
reading_fundamentals = True
continue
if "Overtones" in line:
reading_overtones = True
continue
if "Combination Bands" in line:
reading_combinations = True
continue
if reading_combinations:
info = line.split()
mode1 = mode_re.search(info[0])
mode2 = mode_re.search(info[1])
try:
ndx_1 = int(mode1.group(1))
exp_1 = int(mode1.group(2))
ndx_2 = int(mode2.group(1))
exp_2 = int(mode2.group(2))
except AttributeError:
raise RuntimeError("error while parsing anharmonic frequencies: %s" % line)
harm_freq = float(info[2])
anharm_freq = float(info[3])
anharm_inten = float(info[4])
harm_inten = 0
combinations.append(
(
ndx_1,
ndx_2,
exp_1,
exp_2,
anharm_freq,
anharm_inten,
harm_freq,
harm_inten,
)
)
elif reading_overtones:
info = line.split()
mode = mode_re.search(info[0])
try:
ndx = int(mode.group(1))
exp = int(mode.group(2))
except AttributeError:
raise RuntimeError("error while parsing overtones: %s" % line)
harm_freq = float(info[1])
anharm_freq = float(info[2])
anharm_inten = float(info[3])
harm_inten = 0
overtones.append(
(
ndx,
exp,
anharm_freq,
anharm_inten,
harm_freq,
harm_inten,
)
)
elif reading_fundamentals:
info = line.split()
harm_freq = float(info[1])
anharm_freq = float(info[2])
anharm_inten = float(info[4])
harm_inten = float(info[3])
fundamentals.append(
(anharm_freq, anharm_inten, harm_freq, harm_inten)
)
self.anharm_data = []
for i, mode in enumerate(
sorted(fundamentals, key=lambda pair: pair[2])
):
self.anharm_data.append(
AnharmonicVibration(mode[0], intensity=mode[1], harmonic=self.data[i])
)
self.anharm_data[-1].overtones = []
self.anharm_data[-1].combinations = dict()