Debian Codegraph @

goodvibes/plot.py

raw
1 """Visualization for GoodVibes (v5.0 ROADMAP item 14).
2
3 Pure plotting layer that renders the v4.2+ structured types
4 (`PESResult`, `SelectivityResult`, `ThermoResult`) to matplotlib axes.
5 matplotlib is an optional dependency; install with
6 `pip install goodvibes[plot]` (or `pip install matplotlib` directly).
7
8 All functions accept an optional `ax=None`; when None, they create a
9 fresh `plt.subplots()` figure and return the axes. The `plt` import
10 is deferred so just `import goodvibes.plot` doesn't fail when
11 matplotlib is missing — only the call-site fails, with a clear message.
12
13 Public API:
14 plot_pes(pes_result, ax=None, **kw) — reaction profile
15 plot_selectivity_strip(selectivity,
16 thermo_lookup, ax=None) — per-species scatter
17 plot_boltzmann_histogram(results, ax=None) — population bars
18 plot_temperature_scan(results_per_T, ax=None) — thermo vs T
19
20 The first two are implemented; the latter two are stubs that raise
21 `NotImplementedError` to lock in the API while leaving room for v5.1.
22 """
23 from __future__ import annotations
24
25 from typing import Any, Callable, Dict, Mapping, Optional, Sequence, Union
26
27 from .constants import KCAL_TO_AU
28
29
30 def _import_matplotlib():
31 """Import matplotlib.pyplot with a clear error if it isn't installed."""
32 try:
33 import matplotlib.pyplot as plt
34 return plt
35 except ImportError as exc: # pragma: no cover
36 raise ImportError(
37 "goodvibes.plot requires matplotlib; install with "
38 "`pip install goodvibes[plot]` or `pip install matplotlib`."
39 ) from exc
40
41
42 # ---------------------------------------------------------------------------
43 # Selectivity strip plot
44 # ---------------------------------------------------------------------------
45
46 def plot_selectivity_strip(
47 selectivity: Any,
48 thermo_lookup: Union[Mapping[str, float], Callable[[str], float]],
49 *,
50 ax=None,
51 units: str = "kcal/mol",
52 title: Optional[str] = None,
53 jitter: float = 0.04,
54 seed: int = 0,
55 ):
56 """Per-species strip plot of conformer ΔG values.
57
58 Each species is one column; conformer ΔG values (relative to the
59 lowest across all species) are scattered as dots.
60
61 Parameters:
62 selectivity: a `SelectivityResult` (from
63 `goodvibes.selectivity.compute_selectivity`) — provides the
64 label order, populations, and `files_per_label`.
65 thermo_lookup: either a `{file_path: qh_gibbs_free_energy}`
66 mapping (Hartree) or a callable that takes a path and
67 returns the same. Used to read the per-conformer ΔG.
68 ax: optional matplotlib Axes. New figure created if None.
69 units: 'kcal/mol' (default) or 'kJ/mol'.
70 title: figure title; auto-generated from the result's
71 temperature and key when None.
72 jitter: horizontal spread of conformer dots within each
73 species column (fraction of column width).
74 seed: RNG seed for the jitter (deterministic plots).
75
76 Returns:
77 The matplotlib Axes the strip plot was drawn on.
78 """
79 import random
80
81 plt = _import_matplotlib()
82
83 # Convert hartree → user units.
84 if units == "kJ/mol":
85 from .constants import J_TO_AU
86 scale = J_TO_AU / 1000.0
87 elif units == "kcal/mol":
88 scale = KCAL_TO_AU
89 else:
90 raise ValueError(f"units must be 'kcal/mol' or 'kJ/mol', got {units!r}")
91
92 # Resolve thermo_lookup to a callable.
93 if isinstance(thermo_lookup, Mapping):
94 _lookup = thermo_lookup.__getitem__
95 else:
96 _lookup = thermo_lookup
97
98 # Collect ΔG values per species (relative to global minimum).
99 per_species: Dict[str, list] = {}
100 all_g = []
101 for label in selectivity.labels:
102 files = selectivity.files_per_label.get(label, [])
103 gs = [_lookup(f) for f in files]
104 per_species[label] = gs
105 all_g.extend(gs)
106 if not all_g:
107 raise ValueError("plot_selectivity_strip: no conformers to plot")
108 g_min = min(all_g)
109 rel_per_species = {
110 label: [(g - g_min) * scale for g in gs]
111 for label, gs in per_species.items()
112 }
113
114 n_labels = len(selectivity.labels)
115 if ax is None:
116 # Compact aspect: ~0.8" per species column with a small base
117 # margin for the y-axis tick labels. Override by passing
118 # `ax=` from your own `plt.subplots(figsize=...)` if you want
119 # a different shape.
120 _, ax = plt.subplots(figsize=(max(3.0, 0.8 * n_labels + 1.4), 4))
121
122 rng = random.Random(seed)
123
124 for x, label in enumerate(selectivity.labels):
125 rels = rel_per_species[label]
126 if not rels:
127 continue
128 xs = [x + (rng.random() - 0.5) * 2 * jitter for _ in rels]
129 ax.scatter(xs, rels, alpha=0.6, edgecolor="black", linewidth=0.5)
130
131 ax.set_xticks(range(n_labels))
132 ax.set_xticklabels(selectivity.labels)
133 # Tighten the x-axis to the column footprint so dots don't float
134 # in oversized whitespace; matplotlib's default autoscale pads
135 # noticeably for small-N scatter.
136 ax.set_xlim(-0.5, n_labels - 0.5)
137 ax.set_ylabel(rf"$G_\mathrm{{rel}}$ ({units})")
138 if title is None:
139 title = (f"Selectivity strip ({selectivity.key}, "
140 f"T = {selectivity.temperature:.2f} K)")
141 ax.set_title(title)
142 return ax
143
144
145 # ---------------------------------------------------------------------------
146 # PES profile (clean rewrite consuming PESResult)
147 # ---------------------------------------------------------------------------
148
149 def plot_pes(
150 pes_result: Any,
151 *,
152 ax=None,
153 pathway_index: Optional[Union[int, Sequence[int]]] = None,
154 connector_style: str = "bezier",
155 colors: Optional[Sequence[str]] = None,
156 show_conformers: bool = False,
157 thermo_lookup: Optional[Union[Mapping[str, float], Callable[[str], float]]] = None,
158 title: Optional[str] = None,
159 label_points: bool = False,
160 ):
161 """Plot one or more pathways from a `PESResult` as a reaction profile.
162
163 Multi-pathway YAMLs (e.g. comparing R vs S transition states across
164 a shared set of points) are overlaid on the same axes by default,
165 each pathway in its own color from matplotlib's color cycle.
166
167 Parameters:
168 pes_result: a `PESResult` from `goodvibes.pes_loader.load_pes`.
169 ax: optional matplotlib Axes; new figure if None.
170 pathway_index: which pathway(s) to draw.
171 None (default) → all pathways overlaid.
172 int → just that pathway.
173 list of ints → that subset.
174 connector_style: 'bezier' (default; smooth curved jumps between
175 steps, like the legacy --graph plot) or 'linear' (straight
176 line between step ends).
177 colors: per-pathway colors (sequence of matplotlib color specs:
178 names, hex, rgb tuples). Falls back to the default color
179 cycle when None.
180 show_conformers: scatter individual conformer ΔG around each
181 step (single-pathway only when used; for multi-pathway
182 select one via `pathway_index=N`).
183 thermo_lookup: required when `show_conformers=True`; maps each
184 conformer file path → qh_gibbs_free_energy (Hartree).
185 title: figure title; defaults to the pathway names + temperature.
186 label_points: annotate each point's ΔqhG value above its
187 horizontal bar.
188
189 Returns:
190 The matplotlib Axes the profile(s) were drawn on.
191 """
192 plt = _import_matplotlib()
193 import matplotlib.path as mpath
194 import matplotlib.patches as mpatches
195
196 if connector_style not in ("bezier", "linear"):
197 raise ValueError(
198 f"connector_style must be 'bezier' or 'linear', got {connector_style!r}"
199 )
200
201 # Resolve which pathways to draw.
202 if pathway_index is None:
203 indices = list(range(len(pes_result.pathways)))
204 elif isinstance(pathway_index, int):
205 indices = [pathway_index]
206 else:
207 indices = list(pathway_index)
208 if not indices:
209 raise ValueError("plot_pes: no pathways to draw")
210 pathways = [pes_result.pathways[i] for i in indices]
211
212 # All chosen pathways must share the same number of points so the
213 # x-axis matches; mixed lengths would need a separate axes per
214 # pathway (legacy --graph supports this; deferred to v5.1).
215 n_points_per_path = {len(p.points) for p in pathways}
216 if len(n_points_per_path) > 1:
217 raise ValueError(
218 "plot_pes: all selected pathways must have the same number "
219 "of points; got "
220 + ", ".join(f"{p.name}={len(p.points)}" for p in pathways)
221 )
222 n_points = pathways[0].points.__len__()
223
224 pes_options = pes_result.options
225 T = pes_result.temperatures[0] if pes_result.temperatures else 298.15
226 units_factor = pes_options.to_user_units(1.0)
227 rollup_kw = dict(
228 gconf=pes_options.gconf, QH=pes_options.QH,
229 lowest_only=pes_options.lowest_only,
230 )
231
232 if ax is None:
233 _, ax = plt.subplots(figsize=(max(5, 0.9 * n_points + 1), 4))
234
235 # Resolve the per-pathway color cycle. Default for a single pathway
236 # is black (matches the legacy --graph plot's clean look); multiple
237 # pathways fall back to matplotlib's color cycle so they're
238 # distinguishable when overlaid.
239 if colors is None:
240 if len(pathways) == 1:
241 colors_resolved = ["k"]
242 else:
243 cycle = plt.rcParams["axes.prop_cycle"].by_key().get("color", ["C0"])
244 colors_resolved = [cycle[i % len(cycle)] for i in range(len(pathways))]
245 else:
246 if len(colors) < len(pathways):
247 raise ValueError(
248 f"plot_pes: need at least {len(pathways)} colors, got {len(colors)}"
249 )
250 colors_resolved = list(colors)
251
252 xs = list(range(n_points))
253 # Bar half-width 0.15 + bar/connector linewidth 1.5 mirror the legacy
254 # --graph reaction-profile plot (graph_reaction_profile in pes.py).
255 bar_half = 0.15
256 bar_lw = 1.5
257 connector_lw = 1.0
258 Path = mpath.Path
259
260 # Draw each pathway as: hlines at each level + curved/linear
261 # connectors between consecutive levels.
262 for path, color in zip(pathways, colors_resolved):
263 rels = path.relative(T, **rollup_kw)
264 qhg = [r.qh_gibbs * units_factor for r in rels]
265
266 # Step bars at each level.
267 for i in range(n_points):
268 ax.hlines(qhg[i], xs[i] - bar_half, xs[i] + bar_half,
269 colors=color, linewidth=bar_lw,
270 label=path.name if i == 0 else None,
271 zorder=3)
272 if label_points:
273 ax.annotate(f"{qhg[i]:.1f}", (xs[i], qhg[i]),
274 xytext=(0, 6), textcoords="offset points",
275 ha="center", fontsize="x-small", color=color)
276
277 # Connectors between consecutive levels. Endpoints are the
278 # *point centers*, not the bar edges — so the curve passes
279 # under each horizontal bar and the bar (drawn on top via
280 # zorder=3) appears as a small flat plateau on a continuous
281 # underlying line. This mirrors graph_reaction_profile in
282 # pes.py and is the "S-curve that smoothly transitions through
283 # the levels" look the legacy --graph plot has.
284 for i in range(n_points - 1):
285 x0, x1 = xs[i], xs[i + 1]
286 y0, y1 = qhg[i], qhg[i + 1]
287 if connector_style == "bezier":
288 # Cubic Bezier with horizontal handles, control points
289 # at the midpoint x and y0 / y1.
290 xm = (x0 + x1) / 2
291 patch = mpatches.PathPatch(
292 Path([(x0, y0), (xm, y0), (xm, y1), (x1, y1)],
293 [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]),
294 fc="none", color=color, linewidth=connector_lw, zorder=2,
295 )
296 ax.add_patch(patch)
297 else:
298 ax.plot([x0, x1], [y0, y1], color=color,
299 linewidth=connector_lw, zorder=2)
300
301 # Optional per-conformer scatter (single-pathway only — the spread
302 # is per-pathway; for multi-pathway choose one via `pathway_index`).
303 if show_conformers:
304 if thermo_lookup is None:
305 raise ValueError(
306 "plot_pes(show_conformers=True) requires thermo_lookup "
307 "(a {file: qh_g_in_Hartree} mapping or callable)."
308 )
309 if len(pathways) > 1:
310 raise ValueError(
311 "plot_pes(show_conformers=True) requires a single "
312 "pathway; pass `pathway_index=N` to pick one."
313 )
314 path = pathways[0]
315 if isinstance(thermo_lookup, Mapping):
316 _lookup = thermo_lookup.__getitem__
317 else:
318 _lookup = thermo_lookup
319 zero_qhg = path.zero.thermo(T, **rollup_kw).qh_gibbs
320 import random
321 rng = random.Random(0)
322 for i, point in enumerate(path.points):
323 for _coeff, cset in point.species:
324 if cset.is_single:
325 continue
326 for bbe in cset.bbes:
327 rel = (bbe.qh_gibbs_free_energy - zero_qhg) * units_factor
328 x = xs[i] + (rng.random() - 0.5) * 0.3
329 ax.scatter([x], [rel], alpha=0.4, s=18,
330 color="black", zorder=4)
331
332 # x-axis: point labels from the first pathway (all share the same
333 # length; labels may differ across pathways, so we just take one).
334 ax.set_xticks(xs)
335 ax.set_xticklabels([p.label for p in pathways[0].points],
336 rotation=15, ha="right", fontsize="small")
337 ax.set_ylabel(rf"$G_{{rel}}$ ({pes_options.units})")
338 if title is None:
339 names = ", ".join(p.name for p in pathways)
340 title = f"{names} (T = {T:g} K)"
341 ax.set_title(title)
342 # Minor ticks + a mirrored y-axis on the right. Mirrors the legacy
343 # --graph styling (minorticks_on + tick_params(labelright=True,
344 # right=True)). Suppress minor ticks on the x-axis since x is
345 # categorical (one tick per point).
346 ax.minorticks_on()
347 ax.tick_params(axis='x', which='minor', bottom=False, top=False)
348 ax.tick_params(axis='y', which='both', labelright=True, right=True)
349 if len(pathways) > 1:
350 ax.legend(loc="best", fontsize="small")
351 return ax
352
353
354 # ---------------------------------------------------------------------------
355 # Stubs for v5.1+ work
356 # ---------------------------------------------------------------------------
357
358 def plot_boltzmann_histogram(
359 thermo_results: Sequence[Any],
360 *,
361 ax=None,
362 temperature: float = 298.15,
363 ):
364 """Bar chart of per-conformer Boltzmann populations.
365
366 Not yet implemented — slated for v5.1 alongside the Ensemble
367 container that gives this a natural data source.
368 """
369 raise NotImplementedError(
370 "plot_boltzmann_histogram is reserved for v5.1; "
371 "follow ROADMAP.md item 14."
372 )
373
374
375 def plot_temperature_scan(
376 results_per_T: Sequence[tuple],
377 *,
378 ax=None,
379 ):
380 """Plot thermochemistry quantities (qh-G, S, H) vs temperature.
381
382 Not yet implemented — slated for v5.1 alongside a structured
383 representation of `--ti` output.
384 """
385 raise NotImplementedError(
386 "plot_temperature_scan is reserved for v5.1; "
387 "follow ROADMAP.md item 14."
388 )