Debian Codegraph @

goodvibes/pes.py

raw
1 # -*- coding: utf-8 -*-
2 """PES driver: legacy `get_pes` class re-implemented on top of the v4.2 model.
3
4 The class signature is unchanged; everything that printed/plotted off
5 `get_pes` instances in v4.0/v4.1 still does. Internally we delegate
6 parsing and rollup to `pes_loader` + `pes_model`, then project the
7 resulting `PESResult` into the legacy parallel-list attribute layout
8 that `output.print_pes_results` and `pes.graph_reaction_profile`
9 already consume.
10
11 This shim ships through the v4.x line. v5.1 removes `get_pes` entirely
12 in favor of the structured API (item 12 / Sub-plan B in ROADMAP.md).
13 """
14 import logging
15 import os.path
16
17 from .pes_loader import load_pes
18
19 log = logging.getLogger('goodvibes')
20
21 # PHYSICAL CONSTANTS UNITS
22 GAS_CONSTANT = 8.3144621 # J / K / mol
23 J_TO_AU = 4.184 * 627.509541 * 1000.0 # UNIT CONVERSION
24 KCAL_TO_AU = 627.509541 # UNIT CONVERSION
25
26
27 class get_pes:
28 """Back-compat surface around `pes_loader.load_pes`.
29
30 Reads a PES definition file (legacy line-based or modern YAML),
31 computes Boltzmann-weighted thermo at each pathway point with
32 optional gconf correction, and exposes the same parallel-list
33 attribute layout as the pre-v4.2 implementation: `path`, `species`,
34 `*_abs`, `*_zero`, plus `g_qhgvals` / `g_species_qhgzero` /
35 `g_rel_val` for the reaction-profile plot.
36 """
37
38 def __init__(self, file, thermo_data, temperature, gconf, QH):
39 # 1. Parse + resolve via the new pipeline.
40 result = load_pes(file, thermo_data, temperatures=[temperature])
41
42 # Surface options.
43 self.units = result.options.units
44 self.dec = result.options.decimals
45 # Legacy `boltz` flag (string like 'ee' or False) lives in format_extras.
46 # Re-parsed from the original file because PESOptions discards it.
47 self.boltz = _read_boltz(file)
48
49 # 2. Initialise legacy parallel-list attributes (one slot per pathway).
50 self.path = []
51 self.species = []
52 self.spc_zero = []; self.e_zero = []; self.zpe_zero = []
53 self.h_zero = []; self.qh_zero = []
54 self.ts_zero = []; self.qhts_zero = []
55 self.g_zero = []; self.qhg_zero = []
56 self.spc_abs = []; self.e_abs = []; self.zpe_abs = []
57 self.h_abs = []; self.qh_abs = []
58 self.s_abs = []; self.qs_abs = []
59 self.g_abs = []; self.qhg_abs = []
60 self.g_qhgvals = []
61 self.g_species_qhgzero = []
62 self.g_rel_val = []
63
64 # 3. Project each pathway into the legacy layout.
65 for pathway in result.pathways:
66 self.path.append(pathway.name)
67 zero_th = pathway.zero.thermo(temperature, gconf=gconf, QH=QH)
68
69 # Zero values (single-element lists per legacy convention).
70 self.spc_zero.append([zero_th.sp_energy if zero_th.sp_energy is not None else 0.0])
71 self.e_zero.append([zero_th.scf_energy])
72 self.zpe_zero.append([zero_th.zpe])
73 self.h_zero.append([zero_th.enthalpy])
74 self.qh_zero.append([zero_th.qh_enthalpy])
75 self.ts_zero.append([zero_th.entropy]) # raw S; T applied at print
76 self.qhts_zero.append([zero_th.qh_entropy])
77 self.g_zero.append([zero_th.gibbs])
78 self.qhg_zero.append([zero_th.qh_gibbs])
79
80 # Per-step abs lists.
81 self.species.append([])
82 self.spc_abs.append([]); self.e_abs.append([]); self.zpe_abs.append([])
83 self.h_abs.append([]); self.qh_abs.append([])
84 self.s_abs.append([]); self.qs_abs.append([])
85 self.g_abs.append([]); self.qhg_abs.append([])
86 self.g_qhgvals.append([])
87 self.g_species_qhgzero.append([])
88 self.g_rel_val.append([])
89
90 for point in pathway.points:
91 pt_th = point.thermo(temperature, gconf=gconf, QH=QH)
92 self.species[-1].append(point.label)
93 self.spc_abs[-1].append(
94 pt_th.sp_energy if pt_th.sp_energy is not None else 0.0
95 )
96 self.e_abs[-1].append(pt_th.scf_energy)
97 self.zpe_abs[-1].append(pt_th.zpe)
98 self.h_abs[-1].append(pt_th.enthalpy)
99 self.qh_abs[-1].append(pt_th.qh_enthalpy)
100 self.s_abs[-1].append(pt_th.entropy)
101 self.qs_abs[-1].append(pt_th.qh_entropy)
102 self.g_abs[-1].append(pt_th.gibbs)
103 self.qhg_abs[-1].append(pt_th.qh_gibbs)
104
105 # Per-conformer arrays for the reaction-profile plot.
106 # g_qhgvals[step] is a list of per-species lists of conformer qh-G;
107 # g_species_qhgzero[step] is the per-species Boltzmann reference;
108 # g_rel_val[step] is the stoichiometric sum across species.
109 step_qhgvals = []
110 step_species_zero = []
111 rel_val = 0.0
112 for coeff, cset in point.species:
113 step_qhgvals.append(
114 [b.qh_gibbs_free_energy for b in cset.bbes]
115 )
116 if cset.is_single:
117 species_zero = cset.bbes[0].qh_gibbs_free_energy
118 else:
119 species_zero = cset.boltzmann_weighted(temperature).qh_gibbs
120 step_species_zero.append(species_zero)
121 rel_val += coeff * species_zero
122 self.g_qhgvals[-1].append(step_qhgvals)
123 self.g_species_qhgzero[-1].append(step_species_zero)
124 self.g_rel_val[-1].append(rel_val)
125
126
127 def _read_boltz(path):
128 """Recover the legacy `boltz:` FORMAT key (string or False).
129
130 Lives outside `PESOptions` because it gates output behavior, not thermo
131 math. Returns False if not set or the file can't be opened.
132 """
133 try:
134 with open(path) as f:
135 for line in f:
136 stripped = line.strip()
137 if not stripped or stripped.startswith('#'):
138 continue
139 if 'boltz' not in stripped.lower():
140 continue
141 # `boltz: ee` or `boltz = ee`
142 for sep in (':', '='):
143 if sep in stripped:
144 key, _, value = stripped.partition(sep)
145 if key.strip().lower() == 'boltz':
146 return value.strip()
147 break
148 except OSError:
149 pass
150 return False
151
152
153 def jitter(datasets, color, ax, nx, marker, edgecol='black'):
154 """
155 Randomly offsets and plots vertically overlapping points to reduce marker overlap on a matplotlib Axes.
156
157 Parameters:
158 datasets (iterable): Iterable of numeric y-values (each element plotted as a point).
159 color (str or tuple): Marker color.
160 ax (matplotlib.axes.Axes): Axes on which to draw the markers.
161 nx (float): Center x-coordinate around which points are jittered.
162 marker (str): Marker style string.
163 edgecol (str, optional): Marker edge color. Defaults to 'black'.
164 """
165 import numpy as np
166 for i, p in enumerate(datasets):
167 y = [p]
168 x = np.random.normal(nx, 0.015, size=len(y))
169 ax.plot(x, y, alpha=0.5, markersize=7, color=color, marker=marker, markeredgecolor=edgecol,
170 markeredgewidth=1, linestyle='None')
171
172 def graph_reaction_profile(graph_data, options, plt):
173 """
174 Render a reaction energy profile plot using quasi-harmonic Gibbs free energies.
175
176 Parameters:
177 graph_data (get_pes): Populated PES object providing pathway labels and thermodynamic arrays used for plotting (e.g., `path`, `qhg_abs`, `qhg_zero`, `e_abs`, `species`, `g_qhgvals`, `g_species_qhgzero`, `g_rel_val`, and `units`).
178 options (object): Options container with a `graph` attribute pointing to a formatting file that controls plot appearance (ylim, colors, title, dpi, etc.). If `dpi` is set in that file, an image file named "Rxn_profile_<options.graph stem>.png" will be written.
179 plt (module): The matplotlib.pyplot module (used to create and display the figure).
180
181 """
182 import matplotlib.path as mpath
183 import matplotlib.patches as mpatches
184
185 log.info("\n Graphing Reaction Profile\n")
186 data = {}
187 # Get PES data
188 for i, path in enumerate(graph_data.path):
189 g_data = []
190 zero_val = graph_data.qhg_zero[i][0]
191 for j, e_abs in enumerate(graph_data.e_abs[i]):
192 species = graph_data.qhg_abs[i][j]
193 relative = species - zero_val
194 if graph_data.units == 'kJ/mol':
195 formatted_g = J_TO_AU / 1000.0 * relative
196 else:
197 formatted_g = KCAL_TO_AU * relative # Defaults to kcal/mol
198 g_data.append(formatted_g)
199 data[path] = g_data
200
201 # Grab any additional formatting for graph
202 with open(options.graph) as f:
203 yaml = f.readlines()
204 #defaults
205 ylim, color, show_conf, show_gconf, show_title = None, None, True, False, True
206 label_point, label_xaxis, dpi, dec, legend = False, True, None, 2, False,
207 colors, gridlines, title = None, False, 'Potential Energy Surface'
208 for i, line in enumerate(yaml):
209 if line.strip().find('FORMAT') > -1:
210 for j, line in enumerate(yaml[i + 1:]):
211 if line.strip().find('ylim') > -1:
212 try:
213 ylim = line.strip().replace(':', '=').split("=")[1].replace(' ', '').strip().split(',')
214 except IndexError:
215 pass
216 if line.strip().find('color') > -1:
217 try:
218 colors = line.strip().replace(':', '=').split("=")[1].replace(' ', '').strip().split(',')
219 except IndexError:
220 pass
221 if line.strip().find('title') > -1:
222 try:
223 title_input = line.strip().replace(':', '=').split("=")[1].strip().split(',')[0]
224 if title_input == 'false' or title_input == 'False':
225 show_title = False
226 else:
227 title = title_input
228 except IndexError:
229 pass
230 if line.strip().find('dec') > -1:
231 try:
232 dec = int(line.strip().replace(':', '=').split("=")[1].strip().split(',')[0])
233 except IndexError:
234 pass
235 if line.strip().find('pointlabel') > -1:
236 try:
237 label_input = line.strip().replace(':', '=').split("=")[1].strip().split(',')[0].lower()
238 if label_input == 'false':
239 label_point = False
240 except IndexError:
241 pass
242 if line.strip().find('show_conformers') > -1:
243 try:
244 conformers = line.strip().replace(':', '=').split("=")[1].strip().split(',')[0].lower()
245 if conformers == 'false':
246 show_conf = False
247 except IndexError:
248 pass
249 if line.strip().find('show_gconf') > -1:
250 try:
251 gconf_input = line.strip().replace(':', '=').split("=")[1].strip().split(',')[0].lower()
252 if gconf_input == 'true':
253 show_gconf = True
254 except IndexError:
255 pass
256 if line.strip().find('xlabel') > -1:
257 try:
258 label_input = line.strip().replace(':', '=').split("=")[1].strip().split(',')[0].lower()
259 if label_input == 'false':
260 label_xaxis = False
261 except IndexError:
262 pass
263 if line.strip().find('dpi') > -1:
264 try:
265 dpi = int(line.strip().replace(':', '=').split("=")[1].strip().split(',')[0])
266 except IndexError:
267 pass
268 if line.strip().find('legend') > -1:
269 try:
270 legend_input = line.strip().replace(':', '=').split("=")[1].strip().split(',')[0].lower()
271 if legend_input == 'false':
272 legend = False
273 except IndexError:
274 pass
275 if line.strip().find('gridlines') > -1:
276 try:
277 gridline_input = line.strip().replace(':', '=').split("=")[1].strip().split(',')[0].lower()
278 if gridline_input == 'true':
279 gridlines = True
280 except IndexError:
281 pass
282 # Do some graphing
283 Path = mpath.Path
284 fig, ax = plt.subplots()
285 for i, path in enumerate(graph_data.path):
286 for j in range(len(data[path]) - 1):
287 if colors is not None:
288 if len(colors) > 1:
289 color = colors[i]
290 else:
291 color = colors[0]
292 else:
293 color = 'k'
294 colors = ['k']
295 if j == 0:
296 path_patch = mpatches.PathPatch(
297 Path([(j, data[path][j]), (j + 0.5, data[path][j]), (j + 0.5, data[path][j + 1]),
298 (j + 1, data[path][j + 1])],
299 [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]),
300 label=path, fc="none", transform=ax.transData, color=color)
301 else:
302 path_patch = mpatches.PathPatch(
303 Path([(j, data[path][j]), (j + 0.5, data[path][j]), (j + 0.5, data[path][j + 1]),
304 (j + 1, data[path][j + 1])],
305 [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]),
306 fc="none", transform=ax.transData, color=color)
307 ax.add_patch(path_patch)
308 plt.hlines(data[path][j], j - 0.15, j + 0.15,colors=['k'])
309 plt.hlines(data[path][-1], len(data[path]) - 1.15, len(data[path]) - 0.85,colors=['k'])
310
311 if show_conf:
312 markers = ['o', 's', 'x', 'P', 'D']
313 for i in range(len(graph_data.g_qhgvals)): # i = reaction pathways
314 for j in range(len(graph_data.g_qhgvals[i])): # j = reaction steps
315 for k in range(len(graph_data.g_qhgvals[i][j])): # k = species
316 zero_val = graph_data.g_species_qhgzero[i][j][k]
317 points = graph_data.g_qhgvals[i][j][k]
318 points[:] = [((x - zero_val) + (graph_data.qhg_abs[i][j] - graph_data.qhg_zero[i][0]) + (
319 graph_data.g_rel_val[i][j] - graph_data.qhg_abs[i][j])) * KCAL_TO_AU for x in points]
320 if len(colors) > 1:
321 jitter(points, colors[i], ax, j, markers[k])
322 else:
323 jitter(points, color, ax, j, markers[k])
324 if show_gconf:
325 plt.hlines((graph_data.g_rel_val[i][j] - graph_data.qhg_zero[i][0]) * KCAL_TO_AU, j - 0.15,
326 j + 0.15, linestyles='dashed')
327
328 # Annotate points with energy level
329 if label_point:
330 for i, path in enumerate(graph_data.path):
331 for i, point in enumerate(data[path]):
332 if dec == 1:
333 ax.annotate("{:.1f}".format(point), (i, point - fig.get_figheight() * fig.dpi * 0.025),
334 horizontalalignment='center')
335 else:
336 ax.annotate("{:.2f}".format(point), (i, point - fig.get_figheight() * fig.dpi * 0.025),
337 horizontalalignment='center')
338 if ylim is not None:
339 ax.set_ylim(float(ylim[0]), float(ylim[1]))
340 if show_title:
341 if title is not None:
342 ax.set_title(title)
343 else:
344 ax.set_title("Reaction Profile")
345 ax.set_ylabel(r"$G_{rel}$ (kcal / mol)")
346 plt.minorticks_on()
347 ax.tick_params(axis='x', which='minor', bottom=False)
348 ax.tick_params(which='minor', labelright=True, right=True)
349 ax.tick_params(labelright=True, right=True)
350 if gridlines:
351 ax.yaxis.grid(linestyle='--', linewidth=0.5)
352 ax.xaxis.grid(linewidth=0)
353 ax_label = []
354 xaxis_text = []
355 newax_text_list = []
356 for i, path in enumerate(graph_data.path):
357 newax_text = []
358 ax_label.append(path)
359 for j, e_abs in enumerate(graph_data.e_abs[i]):
360 if i == 0:
361 xaxis_text.append(graph_data.species[i][j])
362 else:
363 newax_text.append(graph_data.species[i][j])
364 newax_text_list.append(newax_text)
365 # Label rxn steps
366 if label_xaxis:
367 if colors is not None:
368 plt.xticks(range(len(xaxis_text)), xaxis_text, color=colors[0])
369 else:
370 plt.xticks(range(len(xaxis_text)), xaxis_text, color='k')
371 locs, labels = plt.xticks()
372 newax = []
373 for i in range(len(ax_label)):
374 if i > 0:
375 y = ax.twiny()
376 newax.append(y)
377 for i in range(len(newax)):
378 newax[i].set_xticks(locs)
379 newax[i].set_xlim(ax.get_xlim())
380 if len(colors) > 1:
381 newax[i].tick_params(axis='x', colors=colors[i + 1])
382 else:
383 newax[i].tick_params(axis='x', colors='k')
384 newax[i].set_xticklabels(newax_text_list[i + 1])
385 newax[i].xaxis.set_ticks_position('bottom')
386 newax[i].xaxis.set_label_position('bottom')
387 newax[i].xaxis.set_ticks_position('none')
388 newax[i].spines['bottom'].set_position(('outward', 15 * (i + 1)))
389 newax[i].spines['bottom'].set_visible(False)
390 else:
391 plt.xticks(range(len(xaxis_text)))
392 ax.xaxis.set_ticklabels([])
393 if legend:
394 plt.legend()
395 if dpi is not None:
396 # `options.graph` may be a full path (e.g. when --graph is the
397 # PES file in another directory); strip to the basename's stem
398 # so the saved image lands in the cwd instead of an absolute
399 # path that mostly doesn't exist (Rxn_profile_/Users/.../foo.png).
400 stem = os.path.splitext(os.path.basename(options.graph))[0]
401 plt.savefig('Rxn_profile_' + stem + '.png', dpi=dpi)
402 plt.show()