-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathplotter.py
More file actions
1875 lines (1672 loc) · 85.1 KB
/
plotter.py
File metadata and controls
1875 lines (1672 loc) · 85.1 KB
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
"""
A module for plotting and saving output files such as RMG libraries.
"""
import matplotlib
# Force matplotlib to not use any Xwindows backend.
# This must be called before pylab, matplotlib.pyplot, or matplotlib.backends is imported.
# Do not warn if the backend has already been set, e.g., when running from an IPython notebook.
matplotlib.use('Agg', force=False)
import matplotlib.pyplot as plt
import numpy as np
import os
import shutil
from matplotlib.backends.backend_pdf import PdfPages
from mpl_toolkits.mplot3d import Axes3D
from typing import List, Optional, Tuple, Union
import py3Dmol as p3D
from rdkit import Chem
from arc.common import (NUMBER_BY_SYMBOL,
calculate_arrhenius_rate_coefficient,
extremum_list,
get_angle_in_180_range,
get_close_tuple,
get_logger,
is_notebook,
is_str_float,
read_yaml_file,
save_yaml_file,
sort_two_lists_by_the_first,
)
from arc.exceptions import InputError
from arc.level import Level
from arc.parser.parser import parse_trajectory
from arc.species.converter import (check_xyz_dict,
get_xyz_radius,
remove_dummies,
rdkit_conf_from_mol,
str_to_xyz,
xyz_from_data,
xyz_to_str,
xyz_to_x_y_z,
)
from arc.species.perceive import perceive_molecule_from_xyz
from arc.species.species import ARCSpecies, rmg_mol_to_dict_repr
PRETTY_UNITS = {'(s^-1)': r' (s$^-1$)',
'(cm^3/(mol*s))': r' (cm$^3$/(mol s))',
'(cm^6/(mol^2*s))': r' (cm$^6$/(mol$^2$ s))'}
logger = get_logger()
# *** Drawings species ***
def draw_structure(xyz=None, species=None, project_directory=None, method='show_sticks', show_atom_indices=False):
"""
A helper function for drawing a molecular structure using either show_sticks or draw_3d.
Args:
xyz (str, optional): The xyz coordinates to plot in string format.
species (ARCSpecies, optional): A species from which to extract the xyz coordinates to plot.
project_directory (str, optional): A directory for saving the image (only supported for draw_3d).
method (str, optional): The method to use, either 'show_sticks', 'draw_3d', or 'scatter'.
show_atom_indices (bool): whether to display atom indices on the 3D image.
"""
if method not in ['show_sticks', 'draw_3d', 'scatter']:
raise InputError(f"Recognized methods are 'show_sticks', 'draw_3d', or 'scatter', got: {method}")
success = False
notebook = is_notebook()
xyz = check_xyz_species_for_drawing(xyz, species)
if method == 'show_sticks' and notebook:
try:
success = show_sticks(xyz=xyz, species=species, project_directory=project_directory, show_atom_indices=show_atom_indices)
except (AttributeError, IndexError, InputError, TypeError):
pass
if method == 'draw_3d' or (method == 'show_sticks' and (not success or not notebook)):
draw_3d(xyz=xyz, species=species, project_directory=project_directory, save_only=not notebook)
elif method == 'scatter':
label = '' if species is None else species.label
plot_3d_mol_as_scatter(xyz, path=project_directory, plot_h=True, show_plot=True, name=label, index=0)
def show_sticks(xyz=None, species=None, project_directory=None, show_atom_indices=False):
"""
Draws the molecule in a "sticks" style according to the supplied xyz coordinates.
Returns whether successful of not. If successful, saves the image using draw_3d.
Either ``xyz`` or ``species`` must be specified.
Args:
xyz (str, dict, optional): The coordinates to display.
species (ARCSpecies, optional): xyz coordinates will be taken from the species.
project_directory (str): ARC's project directory to save a draw_3d image in.
show_atom_indices (bool): whether to display atom indices on the 3D image.
Returns: bool
Whether the show_sticks drawing was successful. ``True`` if it was.
"""
xyz = check_xyz_species_for_drawing(xyz, species)
if species is None:
mol = perceive_molecule_from_xyz(xyz,
charge=species.charge if species is not None else 0,
multiplicity=species.multiplicity if species is not None else None,
n_radicals=species.number_of_radicals if species is not None else 0,
)
else:
mol = species.mol.copy(deep=True)
try:
conf, rd_mol = rdkit_conf_from_mol(mol, xyz)
except (ValueError, AttributeError):
return False
if conf is None:
return False
mb = Chem.MolToMolBlock(rd_mol)
p = p3D.view(width=400, height=400)
p.addModel(mb, 'sdf')
p.setStyle({'stick': {}})
if show_atom_indices:
p.addPropertyLabels("index", "",
{'fontSize': 15,
'fontColor': 'white',
'alignment': 'center',
'showBackground': True,
'backgroundOpacity': 0.2,
'backgroundColor': 'black',
})
p.zoomTo()
p.show()
if project_directory is not None:
draw_3d(xyz=xyz, species=species, project_directory=project_directory, save_only=True)
return True
def draw_3d(xyz=None, species=None, project_directory=None, save_only=False):
"""
Draws the molecule in a "3D-balls" style.
Saves an image if a species and ``project_directory`` are provided.
Args:
xyz (str, dict, optional): The coordinates to display.
species (ARCSpecies, optional): xyz coordinates will be taken from the species.
project_directory (str): ARC's project directory to save the image in.
save_only (bool): Whether to only save an image without plotting it, ``True`` to only save.
"""
# this functionality has recently turned buggy, probably related to packages versions
# (it keeps zooming) in forever
# for now it is disabled
logger.debug('not drawing 3D!')
# ase_atoms = list()
# for symbol, coord in zip(xyz['symbols'], xyz['coords']):
# ase_atoms.append(Atom(symbol=symbol, position=coord))
# ase_mol = Atoms(ase_atoms)
# if not save_only:
# display(view(ase_mol, viewer='x3d'))
# if project_directory is not None and species is not None:
# folder_name = 'rxns' if species.is_ts else 'Species'
# geo_path = os.path.join(project_directory, 'output', folder_name, species.label, 'geometry')
# if not os.path.exists(geo_path):
# os.makedirs(geo_path)
# ase_write(filename=os.path.join(geo_path, 'geometry.png'), images=ase_mol, scale=100)
def plot_3d_mol_as_scatter(xyz, path=None, plot_h=True, show_plot=True, name='', index=0):
"""
Draws the molecule as scattered balls in space according to the supplied xyz coordinates.
Args:
xyz (dict, str): The xyz coordinates.
path (str, optional): A directory path to save the generated figure in.
plot_h (bool, optional): Whether to plot hydrogen atoms as well. ``True`` to plot them.
show_plot (bool, optional): Whether to show the plot. ``True`` to show.
name (str, optional): A name to be added to the saved file name.
index (int, optional): The index type (0 or 1) for printing atom numbers. Pass None to avoid printing numbers.
"""
xyz = check_xyz_species_for_drawing(xyz=xyz)
radius = get_xyz_radius(xyz)
coords, symbols, colors, sizes = list(), list(), list(), list()
for symbol, coord in zip(xyz['symbols'], xyz['coords']):
size = 10000 / radius
if symbol == 'H':
color = 'gray'
size = 2000 / radius
elif symbol == 'C':
color = 'k'
elif symbol == 'N':
color = 'b'
elif symbol == 'O':
color = 'r'
elif symbol == 'S':
color = 'orange'
else:
color = 'g'
if not (symbol == 'H' and not plot_h):
# we do want to plot this atom
coords.append(coord)
symbols.append(symbol)
colors.append(color)
sizes.append(size)
xyz_ = xyz_from_data(coords=coords, symbols=symbols)
x, y, z = xyz_to_x_y_z(xyz_)
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(xs=x, ys=y, zs=z, s=sizes, c=colors, depthshade=True)
for i, symbol in enumerate(symbols):
text = symbol if index is None else symbol + ' ' + str(i + index)
ax.text(x[i] + 0.01, y[i] + 0.01, z[i] + 0.01, text, size=10)
plt.axis('off')
if show_plot:
plt.show()
if path is not None:
if not os.path.isdir(path):
os.makedirs(path)
image_path = os.path.join(path, f'scattered_balls_structure_{name}.png')
plt.savefig(image_path, bbox_inches='tight')
plt.close(fig=fig)
def check_xyz_species_for_drawing(xyz=None, species=None):
"""
A helper function for checking the coordinates before drawing them.
Either ``xyz`` or ``species`` must be given. If both are given, ``xyz`` gets precedence.
If ``species`` is given, xys will be taken from it or cheaply generated for it.
Args:
xyz (dict, str, optional): The 3D coordinates in any form.
species (ARCSpecies, optional): A species to take the coordinates from.
Raises:
InputError: If neither ``xyz`` nor ``species`` are given.
TypeError: If ``species`` is of wrong type.
Returns: dict
The coordinates to plot.
"""
if xyz is None and species is None:
raise InputError('Either xyz or species must be given.')
if species is not None and not isinstance(species, ARCSpecies):
raise TypeError(f'Species must be an ARCSpecies instance. Got {type(species)}.')
if xyz is not None:
if isinstance(xyz, str):
xyz = str_to_xyz(xyz)
else:
xyz = species.get_xyz(generate=True)
return check_xyz_dict(remove_dummies(xyz))
def plot_ts_guesses_by_e_and_method(species: ARCSpecies,
path: str,
):
"""
Save a figure comparing all TS guesses by electronic energy and imaginary frequency.
Args:
species (ARCSpecies): The TS Species to consider.
path (str): The path for saving the figure.
"""
if not isinstance(species, ARCSpecies):
raise ValueError(f'The species argument must be of an ARC species type, '
f'got {species} which is a {type(species)}')
if not species.is_ts:
raise ValueError('The species must be a TS (got species.is_ts = False)')
dirname = os.path.dirname(path) if path.endswith('.png') else path
if not os.path.isdir(dirname):
os.makedirs(dirname)
if os.path.isdir(path):
path = os.path.join(path, 'ts_guesses.png')
if os.path.isfile(path):
os.remove(path)
results, map_tsg_to_results = list(), dict()
number_of_cluster_wo_energy = 0
for i, cluster in enumerate(species.ts_guesses):
if cluster.energy is not None:
results.append((cluster.method, cluster.energy, cluster.imaginary_freqs, cluster.index))
map_tsg_to_results[cluster.index] = i - number_of_cluster_wo_energy
else:
number_of_cluster_wo_energy += 1
ts_results = sorted(results, key=lambda x: x[1], reverse=False)
energy_sorting_map = list(range(len(ts_results)))
energy_sorting_map = sort_two_lists_by_the_first([r[1] for r in results], energy_sorting_map)[1]
x = np.arange(len(ts_results)) # the label locations
width = 0.45 # the width of the bars
y = [x[1] for x in ts_results] # electronic energies
if len(y):
fig, ax = plt.subplots(figsize=(10, 4), dpi=120)
rects = ax.bar(x - width / 2, y, width)
auto_label(rects, ts_results, ax)
if species.chosen_ts is not None and not species.ts_guesses_exhausted:
rects[energy_sorting_map.index(map_tsg_to_results[species.chosen_ts])].set_color('r')
ax.set_ylim(0, (max(y) or 1) * 1.2)
ax.set_ylabel(r'Relative electronic energy, kJ/mol')
ax.set_title(species.rxn_label)
ax.set_xticks([])
plt.savefig(path, dpi=120, facecolor='w', edgecolor='w', orientation='portrait',
format='png', transparent=False, bbox_inches=None, pad_inches=0.1, metadata=None)
def auto_label(rects, ts_results, ax):
"""Attach a text label above each bar in ``rects``, displaying its height."""
for i, rect in enumerate(rects):
height = rect.get_height()
method = ts_results[i][0]
imf = ''
if ts_results[i][2] is not None:
if not len(ts_results[i][2]):
imf = 'not a TS\n'
else:
imf = '\n'.join(f'{freq:.2f}' for freq in ts_results[i][2]) + '\n'
ax.annotate(f'{imf}{height:.2f}\n{method}',
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
# *** Logging output ***
def log_thermo(label, path):
"""
Logging thermodata from an Arkane output file.
Args:
label (str): The species label.
path (str): The path to the folder containing the relevant Arkane output file.
"""
logger.info('\n\n')
logger.debug(f'Thermodata for species {label}')
thermo_block = ''
log = False
with open(os.path.join(path, 'output.py'), 'r') as f:
line = f.readline()
while line != '':
if 'Thermodynamics for' in line:
thermo_block = ''
log = True
elif 'thermo(' in line:
log = False
if log:
thermo_block += line[2:]
line = f.readline()
logger.info(thermo_block)
logger.info('\n')
def log_kinetics(label, path):
"""
Logging kinetics from an Arkane output file.
Args:
label (str): The species label.
path (str): The path to the folder containing the relevant Arkane output file.
"""
logger.info('\n\n')
logger.debug(f'Kinetics for species {label}')
kinetics_block = ''
log = False
with open(os.path.join(path, 'output.py'), 'r') as f:
line = f.readline()
while line != '':
if 'kinetics(' in line:
kinetics_block = ''
log = True
elif 'thermo(' in line:
log = False
if log:
kinetics_block += line
line = f.readline()
logger.info(kinetics_block)
logger.info('\n')
def log_bde_report(path, bde_report, spc_dict):
"""
Prettify the report for bond dissociation energies. Log and save to file.
Args:
path (str): The file path.
bde_report (dict): The BDE report dictionary. Keys are species labels, values are species BDE dictionaries.
In the second level dict, keys are pivot tuples, values are energies in kJ/mol.
spc_dict (dict): The species dictionary.
"""
with open(path, 'w') as f:
content = ''
for label, bde_dict in bde_report.items():
spc = spc_dict[label]
content += f' BDE report for {label}:\n'
content += ' Pivots Atoms BDE (kJ/mol)\n'
content += ' -------- ----- ------------\n'
bde_list, pivots_list, na_bde_list, na_pivots_list = list(), list(), list(), list()
for pivots, bde in bde_dict.items():
if isinstance(bde, str):
na_bde_list.append(bde)
na_pivots_list.append(pivots)
elif isinstance(bde, float):
bde_list.append(bde)
pivots_list.append(pivots)
bde_list, pivots_list = sort_two_lists_by_the_first(list1=bde_list, list2=pivots_list)
for pivots, bde in zip(pivots_list, bde_list):
pivots_str = f'({pivots[0]}, {pivots[1]})'
content += ' {0:17} {1:2}- {2:2} {3:10.2f}\n'.format(pivots_str,
spc.mol.atoms[pivots[0] - 1].symbol,
spc.mol.atoms[pivots[1] - 1].symbol, bde)
for pivots, bde in zip(na_pivots_list, na_bde_list):
pivots_str = f'({pivots[0]}, {pivots[1]})'
# bde is an 'N/A' string, it cannot be formatted as a float
content += ' {0:17} {1:2}- {2:2} {3}\n'.format(pivots_str,
spc.mol.atoms[pivots[0] - 1].symbol,
spc.mol.atoms[pivots[1] - 1].symbol, bde)
content += '\n\n'
logger.info('\n\n')
logger.info(content)
f.write(content)
# *** Parity and kinetic plots ***
def draw_thermo_parity_plots(species_list: list,
path: Optional[str] = None):
"""
Draws parity plots of calculated thermo and RMG's estimates.
Saves a thermo.info file if a ``path`` is specified.
Args:
species_list (list): Species to compare.
path (str, optional): The path to the project's output folder.
"""
pp = None
if path is not None:
thermo_path = os.path.join(path, 'thermo_parity_plots.pdf')
if os.path.exists(thermo_path):
os.remove(thermo_path)
pp = PdfPages(thermo_path)
labels, comments, h298_arc, h298_rmg, s298_arc, s298_rmg = [], [], [], [], [], []
for spc in species_list:
labels.append(spc.label)
h298_arc.append(spc.thermo.H298)
h298_rmg.append(spc.rmg_thermo.H298)
s298_arc.append(spc.thermo.S298)
s298_rmg.append(spc.rmg_thermo.S298)
comments.append(spc.rmg_thermo.comment)
var_units_h = r"$\mathrm{J\,mol^{-1}}$"
var_units_s = r"$\mathrm{J\,mol^{-1}\,K^{-1}}$"
label_h = r"$\Delta H^\circ_{f}(298\,\mathrm{K})$"
label_s = r"$\Delta S^\circ_{f}(298\,\mathrm{K})$"
draw_parity_plot(var_arc=h298_arc, var_rmg=h298_rmg, var_label=label_h, var_units=var_units_h, labels=labels, pp=pp)
draw_parity_plot(var_arc=s298_arc, var_rmg=s298_rmg, var_label=label_s, var_units=var_units_s, labels=labels, pp=pp)
pp.close()
thermo_sources = '\nSources of thermodynamic properties determined by RMG for the parity plots:\n'
max_label_len = max([len(label) for label in labels])
for i, label in enumerate(labels):
thermo_sources += ' {0}: {1}{2}\n'.format(label, ' ' * (max_label_len - len(label)), comments[i])
logger.info(thermo_sources)
if path is not None:
with open(os.path.join(path, 'thermo.info'), 'w') as f:
f.write(thermo_sources)
def draw_parity_plot(var_arc, var_rmg, labels, var_label, var_units, pp=None):
"""
Draw a parity plot.
Args:
var_arc (list): The variable calculated by ARC.
var_rmg (list): The variable estimated by RMG.
labels (list): Species labels corresponding to the data in ``var_arc`` and ``var_rmg``.
var_label (str): The variable name.
var_units (str): The variable units.
pp (PdfPages, optional): Used for storing the image as a multipage PFD file.
"""
combined= [x for n in (var_arc, var_rmg) for x in n]
if any(x is None for x in combined):
return
min_var = min(combined)
max_var = max(combined)
fig, ax = plt.subplots(dpi=120)
ax.set_title(f'{var_label} parity plot')
for i, label in enumerate(labels):
ax.plot(var_arc[i], var_rmg[i], 'o', label=label)
ax.plot([min_var, max_var], [min_var, max_var], 'b-', linewidth=0.5)
ax.set_xlabel(f'{var_label} calculated by ARC {var_units}')
ax.set_ylabel(f'{var_label} determined by RMG {var_units}')
ax.set_xlim([min_var - abs(min_var * 0.1), max_var + abs(max_var * 0.1)])
ax.set_ylim([min_var - abs(min_var * 0.1), max_var + abs(max_var * 0.1)])
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.set_aspect('equal', adjustable='box')
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), shadow=False)
if pp is not None:
plt.savefig(pp, format='pdf', bbox_inches='tight')
if is_notebook():
plt.show()
plt.close(fig=fig)
def draw_kinetics_plots(rxn_list: list,
T_min: Optional[Tuple[float, str]] = None,
T_max: Optional[Tuple[float, str]] = None,
T_count: int = 50,
path: Optional[str] = None,
) -> None:
"""
Draws plots of calculated rate coefficients and RMG's estimates.
`rxn_list` has a .kinetics attribute calculated by ARC and an .rmg_kinetics list with RMG rates.
Args:
rxn_list (list): Reactions with a .kinetics attribute calculated by ARC
and an .rmg_kinetics list with RMG rates.
T_min (tuple): The minimum temperature to consider, e.g., (500, 'K').
T_max (tuple): The maximum temperature to consider, e.g., (3000, 'K').
T_count (int, optional): The number of temperature points between ``T_min`` and ``T_max``.
path (str, optional): The path to the project's output folder.
"""
T_min = T_min or (300, 'K')
if T_min is None:
T_min = (300, 'K')
elif isinstance(T_min, (int, float)):
T_min = (T_min, 'K')
if T_max is None:
T_max = (3000, 'K')
elif isinstance(T_max, (int, float)):
T_max = (T_min, 'K')
temperatures = np.linspace(T_min[0], T_max[0], T_count)
pp = None
if path is not None:
path = os.path.join(path, 'rate_plots.pdf')
if os.path.exists(path):
os.remove(path)
pp = PdfPages(path)
for rxn in rxn_list:
if rxn.kinetics is not None:
units, conversion_factor = get_rxn_units_and_conversion_factor(rxn)
arc_k = [calculate_arrhenius_rate_coefficient(A=rxn.kinetics['A'],
n=rxn.kinetics['n'],
Ea=rxn.kinetics['Ea'],
T=T,
) for T in temperatures]
rmg_rxns = list()
for kinetics in rxn.rmg_kinetics:
if kinetics.get('T_max', None) is None or kinetics.get('T_min', None) is None:
temps = temperatures
else:
temps = np.linspace(kinetics['T_min'].value_si, kinetics['T_max'].value_si, T_count)
rmg_rxns.append({'label': kinetics['comment'],
'T': temps,
'k': [calculate_arrhenius_rate_coefficient(A=kinetics['A'],# * conversion_factor,
n=kinetics['n'],
Ea=kinetics['Ea'],
T=T,
)
for T in temperatures]})
_draw_kinetics_plots(rxn.label, arc_k, temperatures, rmg_rxns, units, pp)
if path is not None:
pp.close()
def _draw_kinetics_plots(rxn_label, arc_k, temperature, rmg_rxns, units, pp, max_rmg_rxns=5):
"""
Draw the kinetics plots.
Args:
rxn_label (str): The reaction label.
arc_k (list): The ARC rate coefficients.
temperature (np.ndarray): The temperatures.
rmg_rxns (list): The RMG rate coefficients.
units (str): The units of the rate coefficients.
pp (PdfPages): Used for storing the image as a multipage PDF file.
max_rmg_rxns (int, optional): The maximum number of RMG rate coefficients to plot.
"""
kinetics_library_priority = ['primaryH2O2', 'Klippenstein_Glarborg2016', 'primaryNitrogenLibrary',
'primarySulfurLibrary', 'N-S_interactions', 'NOx2018',
'Nitrogen_Dean_and_Bozzelli', 'FFCM1(-)', 'JetSurF2.0']
fig = plt.figure(figsize=(8, 6), dpi=120)
ax = fig.add_subplot(111)
plt.title(rxn_label)
inverse_temperature = [1000 / t for t in temperature]
ax.semilogy(inverse_temperature, arc_k, 'k--', linewidth=2.5, label='ARC')
plotted_rmg_rxns = list()
remaining_rmg_rxns = list()
for i, rmg_rxn in enumerate(rmg_rxns):
if 'family' in rmg_rxn['label'].lower():
inverse_temp = [1000 / t for t in rmg_rxn['T']]
ax.semilogy(inverse_temp, rmg_rxn['k'], label=rmg_rxn['label'])
plotted_rmg_rxns.append(i)
else:
remaining_rmg_rxns.append(rmg_rxn)
for priority_lib in kinetics_library_priority:
for i, rmg_rxn in enumerate(remaining_rmg_rxns):
if i not in plotted_rmg_rxns and priority_lib.lower() in rmg_rxn['label'].lower() and len(plotted_rmg_rxns) <= max_rmg_rxns:
inverse_temp = [1000 / t for t in rmg_rxn['T']]
ax.semilogy(inverse_temp, rmg_rxn['k'], label=rmg_rxn['label'])
plotted_rmg_rxns.append(i)
for i, rmg_rxn in enumerate(rmg_rxns):
if i not in plotted_rmg_rxns and len(plotted_rmg_rxns) <= max_rmg_rxns:
inverse_temp = [1000 / t for t in rmg_rxn['T']]
ax.semilogy(inverse_temp, rmg_rxn['k'], label=rmg_rxn['label'])
plotted_rmg_rxns.append(i)
plt.xlabel(r'1000 / T (K$^-$$^1$)')
plt.ylabel(f'Rate coefficient{PRETTY_UNITS[units]}')
plt.legend()
plt.tight_layout()
if pp is not None:
plt.savefig(pp, format='pdf')
if is_notebook():
plt.show()
plt.close(fig=fig)
def get_text_positions(x_data, y_data, txt_width, txt_height):
"""
Get the positions of plot annotations to avoid overlapping.
Source: `stackoverflow <https://stackoverflow.com/questions/8850142/matplotlib-overlapping-annotations>`_.
"""
a = zip(y_data, x_data)
text_positions = y_data
for index, (y, x) in enumerate(a):
local_text_positions = [i for i in a if i[0] > (y - txt_height)
and (abs(i[1] - x) < txt_width * 2) and i != (y, x)]
if local_text_positions:
sorted_ltp = sorted(local_text_positions)
if abs(sorted_ltp[0][0] - y) < txt_height: # True means collision
differ = np.diff(sorted_ltp, axis=0)
a[index] = (sorted_ltp[-1][0] + txt_height, a[index][1])
text_positions[index] = sorted_ltp[-1][0] + txt_height
for k, (j, m) in enumerate(differ):
# j is the vertical distance between words
if j > txt_height * 1.5: # if True then room to fit a word in
a[index] = (sorted_ltp[k][0] + txt_height, a[index][1])
text_positions[index] = sorted_ltp[k][0] + txt_height
break
return text_positions
def text_plotter(x_data, y_data, labels, text_positions, axis, txt_width, txt_height):
"""
Annotate a plot and add an arrow.
Source: `stackoverflow <https://stackoverflow.com/questions/8850142/matplotlib-overlapping-annotations>`_.
"""
for x, y, lab, t in zip(x_data, y_data, labels, text_positions):
axis.text(x - .03, 1.02 * t, f'{lab}', rotation=0, color='black', fontsize=10)
if y != t:
axis.arrow(x, t + 20, 0, y - t, color='blue', alpha=0.2, width=txt_width * 0.0,
head_width=.02, head_length=txt_height * 0.5,
zorder=0, length_includes_head=True)
# *** Files (libraries, xyz, conformers) ***
def save_geo(species: Optional[ARCSpecies] = None,
xyz: Optional[dict] = None,
project_directory: Optional[str] = None,
path: Optional[str] = None,
filename: Optional[str] = None,
format_: str = 'all',
comment: Optional[str] = None,
):
"""
Save a geometry file.
If ``species`` is given, .final_xyz will be saved if it is not None, otherwise .initial_xyz will be used.
If ``xyz`` is given, it gets precedence over ``species``.
Either ``species`` or ``xyz`` must be specified. Either ``project_directory`` or ``path`` must be specified.
Args:
species (ARCSpecies): The species with the geometry attributes.
xyz (dict, optional): The xyz coordinates to save in a string format.
project_directory (str, optional): The project directory where the species folder is located.
path (str, optional): A specific directory path for saving the files.
filename (str, optional): A name for the file to save (without suffix).
format_ (str, optional): The format to save. Either 'xyz', 'gjf' or 'all' for both.
comment (str, optional): A comment to be stored in the XYZ file after the number of atoms line.
Raises:
InputError: If neither species nor xyz were given. Or if neither project_directory nor path were given.
"""
if project_directory is not None:
if species is None:
raise InputError('A species object must be specified when specifying the project directory')
folder_name = 'rxns' if species.is_ts else 'Species'
geo_path = os.path.join(project_directory, 'output', folder_name, species.label, 'geometry')
elif path is not None:
geo_path = path
else:
raise InputError('Either project_directory or path must be specified.')
if not os.path.exists(geo_path):
os.makedirs(geo_path)
if species is None and xyz is None:
raise InputError('Either a species or xyz must be given')
elif species is not None and species.final_xyz is None and species.initial_xyz is None:
raise InputError(f'Either initial_xyz or final_xyz of species {species.label} must be given')
filename = filename if filename is not None else species.label
xyz = xyz or species.final_xyz or species.initial_xyz
xyz_str = xyz_to_str(xyz)
number_of_atoms = species.number_of_atoms if species is not None \
else len(xyz['symbols'])
if format_ in ['xyz', 'all']:
# xyz format
xyz_file = f'{number_of_atoms}\n'
if species is not None:
xyz_file += f'{species.label} optimized at {species.opt_level}\n'
elif comment is not None:
xyz_file += f'{comment}\n'
else:
xyz_file += 'coordinates\n'
xyz_file += f'{xyz_str}\n'
with open(os.path.join(geo_path, f'{filename}.xyz'), 'w') as f:
f.write(xyz_file)
if format_ in ['gjf', 'gaussian', 'all']:
# GaussView file
if species is not None:
gv = f'# hf/3-21g\n\n{species.label} optimized at {species.opt_level}\n\n'
gv += f'{species.charge} {species.multiplicity}\n'
else:
gv = '# hf/3-21g\n\ncoordinates\n\n'
gv += '0 1\n'
gv += f'{xyz_str}\n'
with open(os.path.join(geo_path, f'{filename}.gjf'), 'w') as f:
f.write(gv)
def save_irc_traj_animation(irc_f_path, irc_r_path, out_path):
"""
Save an IRC trajectory animation file showing the entire reaction coordinate.
Args:
irc_f_path (str): The forward IRC computation.
irc_r_path (str): The reverse IRC computation.
out_path (str): The path to the output file.
"""
traj1 = parse_trajectory(irc_f_path)
traj2 = parse_trajectory(irc_r_path)
if traj1 is not None and traj2 is not None:
traj = traj1[:1:-1] + traj2[1:-1] + traj2[:1:-1] + traj1[1:-1]
with open(out_path, 'w') as f:
f.write('Entering Link 1\n')
for traj_index, xyz in enumerate(traj):
xs, ys, zs = xyz_to_x_y_z(xyz)
f.write(' Standard orientation:\n')
f.write(' ---------------------------------------------------------------------\n')
f.write(' Center Atomic Atomic Coordinates (Angstroms)\n')
f.write(' Number Number Type X Y Z\n')
f.write(' ---------------------------------------------------------------------\n')
for i, symbol in enumerate(xyz['symbols']):
el_num, x, y, z = NUMBER_BY_SYMBOL[symbol], xs[i], ys[i], zs[i]
f.write(f' {i + 1:>5} {el_num} 0 {x} {y} {z}\n')
f.write(' ---------------------------------------------------------------------\n')
f.write(' GradGradGradGradGradGradGradGradGradGradGradGradGradGradGradGradGradGrad\n')
f.write(f' Step number 1 out of a maximum of 29 on scan point '
f'{traj_index + 1} out of {len(traj)}\n')
f.write(' GradGradGradGradGradGradGradGradGradGradGradGradGradGradGradGradGradGrad\n')
f.write(' Normal termination of Gaussian 16\n')
def save_thermo_lib(species_list: list,
path: str,
name: str,
lib_long_desc: str,
) -> None:
"""
Save an RMG thermo library of all species.
Args:
species_list (list): Entries are ARCSpecies objects to be saved in the library.
path (str): The file path where the library should be created.
name (str): The library's name (or project's name).
lib_long_desc (str): A multiline string with level of theory description.
"""
thermo_txt = f"""#!/usr/bin/env python
# encoding: utf-8
name = "{name}"
shortDesc = ""
longDesc = \"\"\"\n{lib_long_desc}\n\"\"\"\n
"""
species_dict = dict()
if not len(species_list) or not any(spc.thermo for spc in species_list):
logger.warning('No species to save in the thermo library.')
return
for i, spc in enumerate(species_list):
if spc.thermo.data and spc.include_in_thermo_lib:
if spc.label not in species_dict:
adjlist = spc.adjlist or spc.mol_list[0].copy(deep=True).to_adjacency_list()
species_dict[spc.label] = adjlist
spc.long_thermo_description += (
f'\nExternal symmetry: {spc.external_symmetry}, '
f'optical isomers: {spc.optical_isomers}\n'
f'\nGeometry:\n{xyz_to_str(spc.final_xyz)}'
)
comment = spc.thermo.comment or ''
thermo_txt += f"""entry(
index = {i + 1},
label = "{spc.label}",
molecule = \"\"\"\n{species_dict[spc.label]}\n\"\"\",
thermo = {spc.thermo.data},
shortDesc = u\"\"\"{comment}\"\"\",
longDesc = u\"\"\"\n{spc.long_thermo_description}\n\"\"\",
)
"""
else:
logger.warning(f'Species {spc.label} did not contain any thermo data and was omitted from the thermo library.')
lib_path = os.path.join(path, 'thermo')
if os.path.isdir(lib_path):
shutil.rmtree(lib_path, ignore_errors=True)
os.makedirs(lib_path, exist_ok=True)
thermo_file = os.path.join(lib_path, f'{name}.py')
with open(thermo_file, 'w') as f:
f.write(thermo_txt)
species_dict_path = os.path.join(lib_path, 'species_dictionary.txt')
with open(species_dict_path, 'w') as f:
for label, adjlist in species_dict.items():
f.write(f'{label}\n{adjlist}\n')
def save_transport_lib(species_list, path, name, lib_long_desc=''):
"""
Save an RMG transport library of all species in `species_list` in the supplied `path`.
`name` is the library's name (or project's name).
`long_desc` is a multiline string with level of theory description.
"""
# not implemented yet, ARC still cannot calculate transport properties
pass
def save_kinetics_lib(rxn_list: list,
path: str,
name: str,
lib_long_desc: str,
T_min: float = 300,
T_max: float = 3000,
) -> None:
"""
Save a valid RMG kinetics library of all reactions in `rxn_list` in the supplied `path`.
Args:
rxn_list (list): Entries are ARCReaction objects to be saved in the library.
path (str): The file path where the library should be created.
name (str): The library's name (or project's name).
lib_long_desc (str): A multiline string with level of theory description.
T_min (float, optional): The minimum temperature for the kinetics fit.
T_max (float, optional): The maximum temperature for the kinetics fit.
"""
reactions_txt = f"""
#!/usr/bin/env python
# encoding: utf-8
name = "{name}"
shortDesc = ""
longDesc = \"\"\"\n{lib_long_desc}\n\"\"\"\n
"""
species_dict = dict()
if not len(rxn_list) or not any(rxn.kinetics for rxn in rxn_list):
logger.warning('No reactions to save in the kinetics library.')
for i, rxn in enumerate(rxn_list):
if rxn.kinetics is not None:
for spc in rxn.r_species + rxn.p_species:
if spc.label not in species_dict:
species_dict[spc.label] = spc.mol.to_adjacency_list()
else:
logger.warning(f'Reaction {rxn.label} did not contain any kinetic data and was omitted from the '
f'kinetics library.')
continue
rxn.ts_species.make_ts_report()
if 'rotors' not in rxn.ts_species.long_thermo_description:
rxn.ts_species.long_thermo_description += '\nNo rotors considered for this TS.'
long_desc = f'{rxn.ts_species.ts_report}\n\n' \
f'TS external symmetry: {rxn.ts_species.external_symmetry}, ' \
f'TS optical isomers: {rxn.ts_species.optical_isomers}\n\n' \
f'Optimized TS geometry:\n{xyz_to_str(rxn.ts_species.final_xyz)}\n\n' \
f'{rxn.ts_species.long_thermo_description}'
rxn_txt = f"""entry(
index = {i},
label = "{rxn.label}",
kinetics = Arrhenius(A=({rxn.kinetics['A'][0]:.2e}, '{rxn.kinetics['A'][1]}'), n={rxn.kinetics['n']:.2f}, Ea=({rxn.kinetics['Ea'][0]:.2f}, '{rxn.kinetics['Ea'][1]}'),
T0=(1, 'K'), Tmin=({T_min}, 'K'), Tmax=({T_max}, 'K')),
longDesc =
\"\"\"
{long_desc}
\"\"\",
)
"""
reactions_txt += rxn_txt
lib_path = os.path.join(path, 'kinetics')
if os.path.isdir(lib_path):
shutil.rmtree(lib_path, ignore_errors=True)
os.makedirs(lib_path, exist_ok=True)
reactions_file = os.path.join(lib_path, 'reactions.py')
with open(reactions_file, 'w') as f:
f.write(reactions_txt)
species_dict_path = os.path.join(lib_path, 'dictionary.txt')
with open(species_dict_path, 'w') as f:
for label, adjlist in species_dict.items():
f.write(f'{label}\n{adjlist}\n')
def save_conformers_file(project_directory: str,
label: str,
xyzs: List[dict],
level_of_theory: Union[Level, str],
multiplicity: Optional[int] = None,
charge: Optional[int] = None,
is_ts: bool = False,
energies: Optional[List[float]] = None,
ts_methods: Optional[List[str]] = None,
im_freqs: Optional[List[List[float]]] = None,
log_content: bool = False,
before_optimization: bool = True,
sp_flag = False,
):
"""
Save the conformers before or after optimization.
If energies are given, the conformers are considered to be optimized.
Args:
project_directory (str): The path to the project's directory.
label (str): The species label.
xyzs (list): Entries are dict-format xyz coordinates of conformers.
level_of_theory (Union[Level, str]): The level of theory used for the conformers' optimization.
multiplicity (int, optional): The species multiplicity, used for perceiving the molecule.
charge (int, optional): The species charge, used for perceiving the molecule.
is_ts (bool, optional): Whether the species represents a TS. True if it does.
energies (list, optional): Entries are energies corresponding to the conformer list in kJ/mol.
If not given (None) then the Species.conformer_energies are used instead.
ts_methods (list, optional): Entries are method names used to generate the TS guess.
im_freqs (list, optional): Entries lists of imaginary frequencies.
log_content (bool): Whether to log the content of the conformers file. ``True`` to log, default is ``False``.
before_optimization (bool): Whether the conformers are before DFT optimization. ``True`` for before, default is ``True``.
sp_flag (bool): Whether the conformers are single point calculations. ``True`` for single point, default is ``False``.
"""
spc_dir = 'rxns' if is_ts else 'Species'
geo_dir = os.path.join(project_directory, 'output', spc_dir, label, 'geometry', 'conformers')
if not os.path.exists(geo_dir):
os.makedirs(geo_dir)
if before_optimization:
conf_path = os.path.join(geo_dir, 'conformers_before_optimization.txt')
else:
conf_path = os.path.join(geo_dir, 'conformers_after_optimization.txt')
min_e = extremum_list(energies, return_min=True)
with open(conf_path, 'w') as f:
content = ''
if before_optimization:
content += f'Conformers for {label}, computed using a force field:\n\n'
else:
level_of_theory = level_of_theory.simple() if isinstance(level_of_theory, Level) else level_of_theory
if not sp_flag:
content += f'Conformers for {label}, optimized at the {level_of_theory} level:\n\n'
else:
content += f'Conformers for {label}, single point calculation at the {level_of_theory} level:\n\n'
for i, xyz in enumerate(xyzs):
content += f'conformer {i}:\n'
if xyz is not None:
content += xyz_to_str(xyz) + '\n'
if not is_ts:
mol = perceive_molecule_from_xyz(xyz, charge=charge, multiplicity=multiplicity, n_radicals=None)
smiles = mol.to_smiles() if mol is not None else 'Could not perceive molecule'
content += f'\nSMILES: {smiles}\n'
elif ts_methods is not None:
content += f'TS guess method: {ts_methods[i]}\n'
if im_freqs is not None and im_freqs[i] is not None:
content += f'Imaginary frequencies: {im_freqs[i]}\n'
if min_e is not None:
if energies[i] == min_e:
content += 'Relative Energy: 0 kJ/mol (lowest)'
elif energies[i] is not None:
content += f'Relative Energy: {energies[i] - min_e:9.3f} kJ/mol'
else:
# Failed to converge
if is_ts and ts_methods is not None:
content += 'TS guess method: ' + ts_methods[i] + '\n'
content += 'Failed to converge'
content += '\n\n\n'
if log_content:
logger.info(content)
f.write(content)
def augment_arkane_yml_file_with_mol_repr(species: ARCSpecies,
output_directory: str,
) -> None:
"""
Add a Molecule representation to an Arkane YAML file.