-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdipole_plotter.py
166 lines (134 loc) · 4.36 KB
/
dipole_plotter.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
"""
Plots a series of multireference calculation dipole moments
"""
import argparse
from string import digits
import os
import logging
import pathlib
from molextract.rules.molcas import log, general, rasscf
from molextract.parser import Parser
import matplotlib.pyplot as plt
LOG_EXT = '.log'
DEFAULT_COLOR = 'pink'
SIMPLE_CPK_COLORS = {
'H': 'white',
'C': 'black',
'N': 'blue',
'O': 'red',
'F': 'green',
'CL': 'green',
'P': 'orange',
'S': 'yellow',
}
HYDROGEN_MARKER_SIZE = 100
HYDROGEN_RADIUS = 25
DEFAULT_ATOMIC_RADIUS = HYDROGEN_RADIUS * 4
SIMPLE_ATOMIC_RADII = {
'H': HYDROGEN_RADIUS,
'C': 70,
'N': 65,
'O': 60,
'F': 50,
'CL': 100,
'P': 100,
'S': 100,
}
logger = logging.getLogger('active_space_chooser')
handler = logging.StreamHandler()
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
class RASSCFModule(log.ModuleRule):
def __init__(self):
rules = [rasscf.RASSCFCartesianCoords(), general.MolProps()]
super().__init__('rasscf', rules)
class DipolePlotter:
def __init__(self, mr_files):
self.mr_files = mr_files
self.fig = plt.figure()
self.ax = self.fig.add_subplot(1, 1, 1, projection='3d')
def plot(self, show_legend=True):
plot_coords = True
for path in self.mr_files:
stem = pathlib.Path(path).stem
try:
coords, mol_props = self._parse_mr_file(path)
except ValueError:
continue
logger.debug(f'processed {stem}')
if plot_coords:
self._plot_coords(coords)
plot_coords = False
ground_dipole = mol_props[0]['dipole']
xs = (0, ground_dipole['x'])
ys = (0, ground_dipole['y'])
zs = (0, ground_dipole['z'])
self.ax.plot(xs, ys, zs, 'o-', label=stem)
self.ax.set_xlabel('X Dipole (Ang)')
self.ax.set_ylabel('Y Dipole (Ang)')
self.ax.set_zlabel('Z Dipole (Ang)')
if show_legend:
self.ax.legend()
def _parse_mr_file(self, path):
parser = Parser(RASSCFModule())
try:
with open(path, 'r') as f:
raw_data = f.read()
parsed_data = parser.feed(raw_data)
except ValueError:
logger.warning(f'unabled to parse {path}, removing from plot')
raise
if parsed_data is None or len(parsed_data) == 0:
logger.warning(f'no data parsed from {path}, removing from plot')
raise ValueError('no data parsed')
coords, mol_props = parsed_data
# TODO: verify coords are consistent across files
return coords, mol_props
def _plot_coords(self, coords):
xs, ys, zs = [], [], []
colors = []
sizes = []
for element, x, y, z in coords:
color, size = self._get_atom_visuals(element)
colors.append(color)
sizes.append(size)
xs.append(x)
ys.append(y)
zs.append(z)
self.ax.scatter(xs, ys, zs, s=sizes, c=colors, edgecolors='black')
def _get_atom_visuals(self, element):
element = element.rstrip(digits)
color = SIMPLE_CPK_COLORS.get(element, DEFAULT_COLOR)
radius = SIMPLE_ATOMIC_RADII.get(element, DEFAULT_ATOMIC_RADIUS)
size = (radius / HYDROGEN_RADIUS) * HYDROGEN_MARKER_SIZE
return color, size
def show(self):
plt.show()
def save(self, path):
raise NotImplementedError
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
'mr_files',
type=str,
nargs='+',
help='The path(s) to the multi-reference calculation log files')
parser.add_argument('--no-legend',
action='store_true',
help="don't display a legend in the plot")
return parser
def process_opts(parser, opts):
for file in opts.mr_files:
if not os.path.exists(file):
parser.error(f'{file} does not exit')
if not file.endswith(LOG_EXT):
parser.error(f'{file} must be .log file')
def main(args=None):
parser = get_parser()
opts = parser.parse_args(args)
process_opts(parser, opts)
plotter = DipolePlotter(opts.mr_files)
plotter.plot(show_legend=not opts.no_legend)
plotter.show()
if __name__ == '__main__':
main()