QDpy
Loading...
Searching...
No Matches
_archive_plot.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Render descriptor-space maps from live or saved archives."""
6
7from dataclasses import dataclass, replace
8from math import ceil, sqrt
9from operator import index
10
11import matplotlib as mpl
12import matplotlib.pyplot as plt
13from matplotlib.collections import PolyCollection
14from mpl_toolkits.mplot3d.art3d import Line3DCollection, Poly3DCollection
15import numpy as np
16
17from .containers.grids import _bin_index
18from ._archive_data import _archive_data, _named_data
19from ._archive_geometry import _bounded_cells, _sphere_cells
20
21__all__ = ["plot_archive", "plot_archives"]
22
23_EMPTY = "#e7e7e7"
24
25
26@dataclass
27class _Panel:
28 archive: object
29 view: str
30 dimensions: tuple
31 limits: tuple
32 section: tuple
33 centre: tuple
34 points: np.ndarray
35 values: np.ndarray
36 label: str
37 hint: tuple
38 cmap: str
39 vmin: float | None
40 vmax: float | None
41
42 @property
43 def is_3d(self):
44 return len(self.dimensions) == 3
45
46
47def _span(low, high):
48 if low == high:
49 padding = max(abs(low) * 0.05, 0.5)
50 return low - padding, high + padding
51 return low, high
52
53
54def _finite_extent(values):
55 finite = np.asarray(values)[np.isfinite(values)]
56 return (float(finite.min()), float(finite.max())) if finite.size else ()
57
58
59def _metric_values(archive, metric, objective):
60 if metric not in ("fitness", "occupancy", "activity"):
61 raise ValueError("Use 'fitness', 'occupancy', or 'activity'.")
62 if metric == "activity" and archive.activity is None:
63 raise ValueError("Cell activity is unavailable for this archive.")
64 if metric == "fitness":
65 objective_count = len(archive.fitness_domain) or max((len(e.fitness) for e in archive.entries), default=1)
66 if not 0 <= objective < objective_count:
67 raise ValueError("The objective index is outside the archive's fitness vector.")
68 point_values = np.array([e.fitness[objective] if objective < len(e.fitness) else np.nan
69 for e in archive.entries])
70 else:
71 point_values = np.ones(len(archive.entries))
72 if not archive.shape:
73 return point_values, None
74
75 values = np.full(archive.shape, np.nan)
76 if metric == "activity":
77 for cell, count in archive.activity:
78 values[cell] = count
79 elif metric == "occupancy":
80 for entry in archive.entries:
81 cell = entry.cell
82 values[cell] = 1 if np.isnan(values[cell]) else values[cell] + 1
83 else:
84 best = {}
85 for entry, raw in zip(archive.entries, point_values):
86 if not np.isfinite(raw):
87 continue
88 weight = entry.fitness_weights[objective] if objective < len(entry.fitness_weights) else -1
89 quality = raw * weight
90 if entry.cell not in best or quality > best[entry.cell]:
91 values[entry.cell] = raw
92 best[entry.cell] = quality
93 if metric != "fitness":
94 point_values = np.array([values[e.cell] for e in archive.entries])
95 return point_values, values
96
97
98def _rectangle_slice(values, bounds, dimensions, section, edges=()):
99 fixed = iter(section)
100 keys = []
101 for axis, (low, high) in enumerate(bounds):
102 if axis in dimensions:
103 keys.append(slice(None))
104 else:
105 n = values.shape[axis]
106 value = next(fixed)
107 keys.append(int(np.searchsorted(edges[axis][1:-1], value, side='right')) if edges
108 else _bin_index(value, low, high, n, (high - low) / n))
109 sliced = values[tuple(keys)]
110 return sliced.T if len(dimensions) == 2 and dimensions[0] > dimensions[1] else sliced
111
112
113def _spherical_tessellation(data, dimensions, centre):
114 if not data.centroids or data.dimension != 3:
115 return (), ()
116 sites = tuple(tuple(row[i] for i in dimensions) for row in data.centroids)
117 bounds = tuple(data.descriptor_domain[i] for i in dimensions)
118 return _sphere_cells(sites, bounds, centre)
119
120
121def _prepare_panel(archive, *, view="auto", dimensions=None, slice_at=None, metric="fitness",
122 objective=0, sphere_center=(0, 0, 0), cmap="viridis", vmin=None, vmax=None):
123 data = _archive_data(archive)
124 if view not in ("auto", "grid", "cvt", "scatter", "sphere"):
125 raise ValueError("Use view='auto', 'grid', 'cvt', 'scatter', or 'sphere'.")
126 if dimensions is not None:
127 dimensions = tuple(map(index, dimensions))
128 count = data.dimension or (max(dimensions) + 1 if dimensions else (3 if view == "sphere" else 2))
129 if dimensions is None:
130 dimensions = tuple(range(min(count, 3 if view == "sphere" else 2)))
131 if (len(dimensions) not in (1, 2, 3) or len(set(dimensions)) != len(dimensions)
132 or any(not 0 <= i < count for i in dimensions)):
133 raise ValueError("Choose one to three distinct descriptor axes.")
134 objective = index(objective)
135 hidden = [i for i in range(count) if i not in dimensions]
136 section = ()
137 if slice_at is not None:
138 if set(slice_at) != set(hidden) or not data.shape:
139 raise ValueError("Supply one slice coordinate for each omitted grid axis.")
140 section = tuple(float(slice_at[i]) for i in hidden)
141 if not all(np.isfinite(x) and data.descriptor_domain[i][0] <= x <= data.descriptor_domain[i][1]
142 for i, x in zip(hidden, section)):
143 raise ValueError("Slice coordinates must lie inside the descriptor domain.")
144
145 histogram = data.shape and not data.centroids and len(dimensions) <= 2 and (not hidden or section)
146 voronoi = data.centroids and len(dimensions) == 2 and (not hidden or section)
147 if view == "auto":
148 view = "cvt" if voronoi else ("grid" if histogram else "scatter")
149 if ((view == "cvt" and not voronoi) or (view == "grid" and not histogram)):
150 raise ValueError("Select matching grid geometry and fix omitted axes with slice_at.")
151 if slice_at is not None and view not in ("grid", "cvt"):
152 raise ValueError("A slice requires a grid or CVT view.")
153
154 field, cells = _metric_values(data, metric, objective)
155 points = np.array([e.descriptors for e in data.entries]).reshape(-1, count)
156 hints = data.fitness_domain if metric == "fitness" else ()
157 hint = hints[objective] if 0 <= objective < len(hints) and np.isfinite(hints[objective]).all() else ()
158 label = f"Fitness {objective + 1}" if metric == "fitness" else metric.capitalize()
159 limits = []
160 for i in dimensions:
161 bounds = data.descriptor_domain[i] if data.descriptor_domain else ()
162 if bounds and np.isfinite(bounds).all():
163 limits.append(_span(*bounds))
164 else:
165 limits.append(_span(*(_finite_extent(points[:, i]) or (0, 1))))
166 centre = tuple(map(float, sphere_center))
167 points = points[:, dimensions]
168 if view == "grid":
169 values = _rectangle_slice(cells, data.descriptor_domain, dimensions, section, data.bin_edges)
170 elif view == "cvt":
171 polygons = _bounded_cells(data.centroids, tuple(limits), dimensions, section)
172 values = np.array([cells[i] for i, _ in polygons])
173 elif view == "sphere":
174 if len(dimensions) != 3 or len(centre) != 3 or not np.isfinite(centre).all():
175 raise ValueError("Use three descriptor axes and a finite three-coordinate sphere centre.")
176 faces, _ = _spherical_tessellation(data, dimensions, centre)
177 limits = [(-1.03, 1.03)] * 3
178 if faces:
179 view = "spherical_cvt"
180 values = cells
181 else:
182 directions = points - centre
183 lengths = np.linalg.norm(directions, axis=1)
184 visible = np.isfinite(lengths) & (lengths > 0)
185 points = directions[visible] / lengths[visible, None]
186 values = field[visible]
187 else:
188 valid = np.isfinite(points).all(axis=1)
189 points, values = points[valid], field[valid]
190
191 return _Panel(data, view, dimensions, tuple(limits), section, centre,
192 points, values, label, hint, cmap, vmin, vmax)
193
194
195def _colour_limits(panels):
196 hints = [panel.hint for panel in panels if panel.hint]
197 ranges = [hint for panel in panels if (hint := _finite_extent(panel.values))]
198 bounds = hints + ranges
199 low = min((limit[0] for limit in bounds), default=0.0)
200 high = max((limit[1] for limit in bounds), default=1.0)
201 low, high = _span(low, high)
202 lower = {panel.vmin for panel in panels if panel.vmin is not None}
203 upper = {panel.vmax for panel in panels if panel.vmax is not None}
204 if len(lower) > 1 or len(upper) > 1:
205 raise ValueError("Panels sharing a colourbar must agree on colour limits.")
206 low, high = next(iter(lower), low), next(iter(upper), high)
207 if not np.isfinite([low, high]).all() or low >= high:
208 raise ValueError("Colour limits must be finite and increasing.")
209 return low, high
210
211
212def _draw_panel(ax, panel, colour_limits, limits=None):
213 cmap = mpl.colormaps.get_cmap(panel.cmap).with_extremes(bad=_EMPTY)
214 scale = mpl.colors.Normalize(*colour_limits)
215 mappable = mpl.cm.ScalarMappable(norm=scale, cmap=cmap)
216 ax.set_facecolor(_EMPTY)
217 values = np.ma.masked_invalid(panel.values)
218 if panel.view == "grid":
219 edges = [np.linspace(*extent, n + 1) for extent, n in zip(panel.limits, values.shape)]
220 if panel.archive.bin_edges:
221 edges = [panel.archive.bin_edges[i] for i in panel.dimensions]
222 if len(edges) == 1:
223 edges.append(np.array([0, 1]))
224 values = values[:, None]
225 ax.pcolormesh(*edges, values.T, norm=scale, cmap=cmap, shading="flat")
226 elif panel.view == "cvt":
227 polygons = _bounded_cells(panel.archive.centroids, panel.limits, panel.dimensions, panel.section)
228 collection = PolyCollection([polygon for _, polygon in polygons], array=values, cmap=cmap,
229 norm=scale, edgecolors="#555555", linewidths=0.35)
230 ax.add_collection(collection)
231 elif panel.view == "spherical_cvt":
232 faces, edges = _spherical_tessellation(panel.archive, panel.dimensions, panel.centre)
233 face_colors = mappable.to_rgba([values.data[i] for i, _ in faces])
234 ax.add_collection3d(Poly3DCollection([triangle for _, triangle in faces], facecolors=face_colors,
235 edgecolors="none", antialiaseds=False))
236 ax.add_collection3d(Line3DCollection(edges, colors="#555555", linewidths=0.35))
237 else:
238 if panel.view == "sphere":
239 angles = np.linspace(0, 2 * np.pi, 32)
240 polar = np.linspace(0, np.pi, 17)
241 ax.plot_wireframe(np.outer(np.cos(angles), np.sin(polar)), np.outer(np.sin(angles), np.sin(polar)),
242 np.outer(np.ones_like(angles), np.cos(polar)), color="#cccccc", linewidth=0.35,
243 rstride=4, cstride=4)
244 coords = list(panel.points.T)
245 if len(coords) == 1:
246 coords.append(np.full(len(panel.points), 0.5))
247 ax.scatter(*coords, c=values, cmap=cmap, norm=scale, s=15, plotnonfinite=True,
248 **({"depthshade": False} if panel.is_3d else {}))
249
250 _style_axes(ax, panel, limits)
251 return mappable
252
253
254def _style_axes(ax, panel, limits=None):
255 limits = limits or panel.limits
256 ax.set_xlim(*limits[0])
257 ax.set_ylim(*(limits[1] if len(limits) > 1 else (0, 1)))
258 sphere = panel.view in ("sphere", "spherical_cvt")
259 prefix = "Direction " if sphere else "Descriptor "
260 ax.set_xlabel(f"{prefix}{panel.dimensions[0] + 1}")
261 if len(limits) == 1:
262 ax.set_yticks([])
263 else:
264 ax.set_ylabel(f"{prefix}{panel.dimensions[1] + 1}")
265 if panel.is_3d:
266 ax.set_zlim(*limits[2])
267 ax.set_zlabel(f"{prefix}{panel.dimensions[2] + 1}")
268 ax.set_box_aspect((1, 1, 1))
269 ax.view_init(elev=24, azim=-60)
270 elif panel.view in ("grid", "cvt") and len(limits) == 2:
271 ax.set_aspect("equal")
272 if sphere:
273 ax.set_facecolor("white")
274 ax.set_axis_off()
275 ax.set_proj_type("ortho")
276 ax.set_title("Spherical Voronoi" if panel.view == "spherical_cvt" else "Elite directions")
277 elif panel.section:
278 hidden = [i for i in range(panel.archive.dimension) if i not in panel.dimensions]
279 ax.set_title(", ".join(f"D{i + 1} = {value:g}" for i, value in zip(hidden, panel.section)))
280
281
282def _prepare_panels(archives, panel_options, options):
283 data = _named_data(archives)
284 overrides = panel_options or {}
285 if set(overrides) - set(data):
286 raise ValueError("Panel options must use an archive label.")
287 return {name: _prepare_panel(archive, **(options | overrides.get(name, {}))) for name, archive in data.items()}
288
289
290def _plot_panels(panels, *, columns=None, shared_scale=False, colorbar=True, figsize=None,
291 templates=None, scales=None, limits=None, bottom=None):
292 templates = panels if templates is None else templates
293 columns = min(len(templates), ceil(sqrt(len(templates)))) if columns is None else index(columns)
294 if columns < 1:
295 raise ValueError("columns must be positive.")
296 rows = ceil(len(templates) / columns)
297 if shared_scale and len({(panel.label, panel.cmap) for panel in templates.values()}) != 1:
298 raise ValueError("A shared colourbar needs the same metric and colormap on every panel.")
299 if scales is None:
300 shared = _colour_limits(list(panels.values())) if shared_scale else None
301 scales = {name: shared or _colour_limits([panel]) for name, panel in panels.items()}
302 fig = plt.figure(figsize=figsize or (4.3 * columns, 3.7 * rows), layout="none")
303 fig.subplots_adjust(wspace=0.42, hspace=0.38, bottom=bottom)
304 axes = {}
305 last_mappable = None
306 for position, (name, template) in enumerate(templates.items(), 1):
307 panel = panels.get(name)
308 ax = fig.add_subplot(rows, columns, position, projection="3d" if template.is_3d else None)
309 axes[name] = ax
310 if panel is None:
311 _style_axes(ax, template, None if limits is None else limits[name])
312 text = ax.text2D if template.is_3d else ax.text
313 text(0.5, 0.5, "Unavailable", transform=ax.transAxes, ha="center")
314 mappable = mpl.cm.ScalarMappable(norm=mpl.colors.Normalize(*scales[name]), cmap=template.cmap)
315 else:
316 mappable = _draw_panel(ax, panel, scales[name], None if limits is None else limits[name])
317 subtitle = ax.get_title()
318 ax.set_title(f"{name}\n{subtitle}" if subtitle else name)
319 if colorbar and not shared_scale:
320 fig.colorbar(mappable, ax=ax, label=template.label)
321 last_mappable = mappable
322 if colorbar and shared_scale:
323 fig.colorbar(last_mappable, ax=list(axes.values()), label=next(iter(templates.values())).label)
324 return fig, axes
325
326
327
328def plot_archive(archive, *, ax=None, view="auto", dimensions=None, slice_at=None, metric="fitness",
329 objective=0, sphere_center=(0, 0, 0), cmap="viridis", vmin=None, vmax=None,
330 colorbar=True):
331 """Plot an archive using the selected descriptor axes and raw metric.
332
333 :param archive: Live container, decorator, or numeric archive JSON path.
334 :param ax: Optional Matplotlib axes. Use 3D axes for a spherical view.
335 :param view: Automatic, grid, CVT, scatter, or sphere.
336 :param dimensions: Descriptor indices in plot order, starting at zero.
337 :param slice_at: Mapping from omitted descriptor indices to fixed values.
338 :param metric: Fitness, occupancy count, or cell activity.
339 :param objective: Index of the raw fitness objective.
340 :param sphere_center: Three coordinates for the centre of a sphere view.
341 :param cmap: Matplotlib colormap.
342 :param vmin: Lower colour limit.
343 :param vmax: Upper colour limit.
344 :param colorbar: Show the metric scale beside the axes.
345 :returns: The Matplotlib axes used for the plot.
346 """
347 panel = _prepare_panel(archive, view=view, dimensions=dimensions, slice_at=slice_at,
348 metric=metric, objective=objective, sphere_center=sphere_center,
349 cmap=cmap, vmin=vmin, vmax=vmax)
350 limits = _colour_limits([panel])
351 if ax is None:
352 ax = plt.figure().add_subplot(projection="3d" if panel.is_3d else None)
353 if panel.is_3d != (ax.name == "3d"):
354 raise ValueError("Supply Matplotlib axes that match the view's projection.")
355 mappable = _draw_panel(ax, panel, limits)
356 if colorbar:
357 ax.figure.colorbar(mappable, ax=ax, label=panel.label)
358 return ax
359
360
361
362def plot_trace_archive(archive, *, ax=None, trace_color="black", trace_alpha=.35, **options):
363 """Plot a two-dimensional TraceArchive and its distinct measurement paths.
364
365 :param archive: TraceArchive using two descriptor coordinates.
366 :param ax: Optional Matplotlib axes.
367 :param trace_color: Matplotlib color for the retained paths.
368 :param trace_alpha: Opacity of each path.
369 :param options: Remaining plot_archive settings, such as cmap or colorbar.
370 :returns: Matplotlib axes containing the archive and paths.
371 """
372 from qdpy.containers.trace import TraceArchive
373
374 if not isinstance(archive, TraceArchive):
375 raise TypeError("Supply a TraceArchive.")
376 if len(archive.features_domain) != 2 or options.get("view") == "sphere":
377 raise ValueError("The trajectory overlay uses two descriptor axes.")
378 dimensions = options.get("dimensions")
379 x_axis, y_axis = (0, 1) if dimensions is None else tuple(dimensions)
380 ax = plot_archive(archive.to_grid(), ax=ax, **options)
381 for elite in archive:
382 points = np.asarray(elite.trace)
383 ax.plot(points[:, x_axis], points[:, y_axis], color=trace_color, alpha=trace_alpha,
384 marker="." if len(points) == 1 else None,
385 scalex=False, scaley=False)
386 return ax
387
388
389
390def plot_archives(archives, *, shared_scale=False, panel_options=None, columns=None,
391 colorbar=True, figsize=None, **options):
392 """Return a figure and a mapping of archive labels to Matplotlib axes.
393
394 :param archives: Ordered mapping of labels to archives, or a sequence.
395 :param shared_scale: Use one colour scale for the same metric in every panel.
396 :param panel_options: Per-label overrides for the plot_archive view options.
397 :param columns: Number of panels per row.
398 :param colorbar: Show a colourbar or, with shared_scale, a common one.
399 :param figsize: Matplotlib figure size in inches.
400 :param options: Default view options shared by the panels.
401 """
402 panels = _prepare_panels(archives, panel_options, options)
403 return _plot_panels(panels, columns=columns, shared_scale=shared_scale, colorbar=colorbar, figsize=figsize)
404
405
406
407def plot_archive_difference(comparison, *, labels=("Reference", "Contender"), figsize=None):
408 """Draw the result of ``compare_archive_cells`` on a 1D or 2D grid or a 2D CVT."""
409 geometry = comparison.geometry
410 if geometry.dimension not in (1, 2) or (geometry.centroids and geometry.dimension != 2):
411 raise ValueError("Use a one- or two-dimensional Grid or a two-dimensional CVTGrid.")
412 panel = _prepare_panel(geometry, metric="occupancy")
413 order = ([i for i, _ in _bounded_cells(geometry.centroids, panel.limits, panel.dimensions, panel.section)]
414 if panel.view == "cvt" else slice(None))
415 count = len(comparison.paired_seeds)
416 delta = comparison.median_difference
417 extent = _finite_extent(delta)
418 span = max(abs(value) for value in extent) if extent else 0.
419 ref, other = labels
420 if ref == other:
421 raise ValueError("Use distinct method labels.")
422 panels = {}
423 for title, values in ((f"Only {ref}", comparison.reference_only),
424 (f"Only {other}", comparison.contender_only),
425 ("Median paired improvement", delta), ("Reached by both", comparison.both)):
426 if values is delta:
427 panels[title] = replace(panel, values=values[order], label="Fitness difference", cmap="RdBu",
428 vmin=-(span or 1.), vmax=span or 1.)
429 else:
430 panels[title] = replace(panel, values=values[order], label="Paired seeds", cmap="viridis",
431 vmin=0., vmax=count)
432 fig, axes = _plot_panels(panels, columns=2, figsize=figsize)
433 fig.suptitle(f"{other} vs {ref} ยท {count} paired seeds")
434 return fig, axes