Source code for qdpy._archive_plot

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Matplotlib views for single and multiple QD archives.

"""Render descriptor-space maps from live or saved archives."""

from dataclasses import dataclass, replace
from math import ceil, sqrt
from operator import index

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d.art3d import Line3DCollection, Poly3DCollection
import numpy as np

from .containers.grids import _bin_index
from ._archive_data import _archive_data, _named_data
from ._archive_geometry import _bounded_cells, _sphere_cells

__all__ = ["plot_archive", "plot_archives"]

_EMPTY = "#e7e7e7"


@dataclass
class _Panel:
    archive: object
    view: str
    dimensions: tuple
    limits: tuple
    section: tuple
    centre: tuple
    points: np.ndarray
    values: np.ndarray
    label: str
    hint: tuple
    cmap: str
    vmin: float | None
    vmax: float | None

    @property
    def is_3d(self):
        return len(self.dimensions) == 3


def _span(low, high):
    if low == high:
        padding = max(abs(low) * 0.05, 0.5)
        return low - padding, high + padding
    return low, high


def _finite_extent(values):
    finite = np.asarray(values)[np.isfinite(values)]
    return (float(finite.min()), float(finite.max())) if finite.size else ()


def _metric_values(archive, metric, objective):
    if metric not in ("fitness", "occupancy", "activity"):
        raise ValueError("Use 'fitness', 'occupancy', or 'activity'.")
    if metric == "activity" and archive.activity is None:
        raise ValueError("Cell activity is unavailable for this archive.")
    if metric == "fitness":
        objective_count = len(archive.fitness_domain) or max((len(e.fitness) for e in archive.entries), default=1)
        if not 0 <= objective < objective_count:
            raise ValueError("The objective index is outside the archive's fitness vector.")
        point_values = np.array([e.fitness[objective] if objective < len(e.fitness) else np.nan
                                 for e in archive.entries])
    else:
        point_values = np.ones(len(archive.entries))
    if not archive.shape:
        return point_values, None

    values = np.full(archive.shape, np.nan)
    if metric == "activity":
        for cell, count in archive.activity:
            values[cell] = count
    elif metric == "occupancy":
        for entry in archive.entries:
            cell = entry.cell
            values[cell] = 1 if np.isnan(values[cell]) else values[cell] + 1
    else:
        best = {}
        for entry, raw in zip(archive.entries, point_values):
            if not np.isfinite(raw):
                continue
            weight = entry.fitness_weights[objective] if objective < len(entry.fitness_weights) else -1
            quality = raw * weight
            if entry.cell not in best or quality > best[entry.cell]:
                values[entry.cell] = raw
                best[entry.cell] = quality
    if metric != "fitness":
        point_values = np.array([values[e.cell] for e in archive.entries])
    return point_values, values


def _rectangle_slice(values, bounds, dimensions, section, edges=()):
    fixed = iter(section)
    keys = []
    for axis, (low, high) in enumerate(bounds):
        if axis in dimensions:
            keys.append(slice(None))
        else:
            n = values.shape[axis]
            value = next(fixed)
            keys.append(int(np.searchsorted(edges[axis][1:-1], value, side='right')) if edges
                        else _bin_index(value, low, high, n, (high - low) / n))
    sliced = values[tuple(keys)]
    return sliced.T if len(dimensions) == 2 and dimensions[0] > dimensions[1] else sliced


def _spherical_tessellation(data, dimensions, centre):
    if not data.centroids or data.dimension != 3:
        return (), ()
    sites = tuple(tuple(row[i] for i in dimensions) for row in data.centroids)
    bounds = tuple(data.descriptor_domain[i] for i in dimensions)
    return _sphere_cells(sites, bounds, centre)


def _prepare_panel(archive, *, view="auto", dimensions=None, slice_at=None, metric="fitness",
                   objective=0, sphere_center=(0, 0, 0), cmap="viridis", vmin=None, vmax=None):
    data = _archive_data(archive)
    if view not in ("auto", "grid", "cvt", "scatter", "sphere"):
        raise ValueError("Use view='auto', 'grid', 'cvt', 'scatter', or 'sphere'.")
    if dimensions is not None:
        dimensions = tuple(map(index, dimensions))
    count = data.dimension or (max(dimensions) + 1 if dimensions else (3 if view == "sphere" else 2))
    if dimensions is None:
        dimensions = tuple(range(min(count, 3 if view == "sphere" else 2)))
    if (len(dimensions) not in (1, 2, 3) or len(set(dimensions)) != len(dimensions)
            or any(not 0 <= i < count for i in dimensions)):
        raise ValueError("Choose one to three distinct descriptor axes.")
    objective = index(objective)
    hidden = [i for i in range(count) if i not in dimensions]
    section = ()
    if slice_at is not None:
        if set(slice_at) != set(hidden) or not data.shape:
            raise ValueError("Supply one slice coordinate for each omitted grid axis.")
        section = tuple(float(slice_at[i]) for i in hidden)
        if not all(np.isfinite(x) and data.descriptor_domain[i][0] <= x <= data.descriptor_domain[i][1]
                   for i, x in zip(hidden, section)):
            raise ValueError("Slice coordinates must lie inside the descriptor domain.")

    histogram = data.shape and not data.centroids and len(dimensions) <= 2 and (not hidden or section)
    voronoi = data.centroids and len(dimensions) == 2 and (not hidden or section)
    if view == "auto":
        view = "cvt" if voronoi else ("grid" if histogram else "scatter")
    if ((view == "cvt" and not voronoi) or (view == "grid" and not histogram)):
        raise ValueError("Select matching grid geometry and fix omitted axes with slice_at.")
    if slice_at is not None and view not in ("grid", "cvt"):
        raise ValueError("A slice requires a grid or CVT view.")

    field, cells = _metric_values(data, metric, objective)
    points = np.array([e.descriptors for e in data.entries]).reshape(-1, count)
    hints = data.fitness_domain if metric == "fitness" else ()
    hint = hints[objective] if 0 <= objective < len(hints) and np.isfinite(hints[objective]).all() else ()
    label = f"Fitness {objective + 1}" if metric == "fitness" else metric.capitalize()
    limits = []
    for i in dimensions:
        bounds = data.descriptor_domain[i] if data.descriptor_domain else ()
        if bounds and np.isfinite(bounds).all():
            limits.append(_span(*bounds))
        else:
            limits.append(_span(*(_finite_extent(points[:, i]) or (0, 1))))
    centre = tuple(map(float, sphere_center))
    points = points[:, dimensions]
    if view == "grid":
        values = _rectangle_slice(cells, data.descriptor_domain, dimensions, section, data.bin_edges)
    elif view == "cvt":
        polygons = _bounded_cells(data.centroids, tuple(limits), dimensions, section)
        values = np.array([cells[i] for i, _ in polygons])
    elif view == "sphere":
        if len(dimensions) != 3 or len(centre) != 3 or not np.isfinite(centre).all():
            raise ValueError("Use three descriptor axes and a finite three-coordinate sphere centre.")
        faces, _ = _spherical_tessellation(data, dimensions, centre)
        limits = [(-1.03, 1.03)] * 3
        if faces:
            view = "spherical_cvt"
            values = cells
        else:
            directions = points - centre
            lengths = np.linalg.norm(directions, axis=1)
            visible = np.isfinite(lengths) & (lengths > 0)
            points = directions[visible] / lengths[visible, None]
            values = field[visible]
    else:
        valid = np.isfinite(points).all(axis=1)
        points, values = points[valid], field[valid]

    return _Panel(data, view, dimensions, tuple(limits), section, centre,
                  points, values, label, hint, cmap, vmin, vmax)


def _colour_limits(panels):
    hints = [panel.hint for panel in panels if panel.hint]
    ranges = [hint for panel in panels if (hint := _finite_extent(panel.values))]
    bounds = hints + ranges
    low = min((limit[0] for limit in bounds), default=0.0)
    high = max((limit[1] for limit in bounds), default=1.0)
    low, high = _span(low, high)
    lower = {panel.vmin for panel in panels if panel.vmin is not None}
    upper = {panel.vmax for panel in panels if panel.vmax is not None}
    if len(lower) > 1 or len(upper) > 1:
        raise ValueError("Panels sharing a colourbar must agree on colour limits.")
    low, high = next(iter(lower), low), next(iter(upper), high)
    if not np.isfinite([low, high]).all() or low >= high:
        raise ValueError("Colour limits must be finite and increasing.")
    return low, high


def _draw_panel(ax, panel, colour_limits, limits=None):
    cmap = mpl.colormaps.get_cmap(panel.cmap).with_extremes(bad=_EMPTY)
    scale = mpl.colors.Normalize(*colour_limits)
    mappable = mpl.cm.ScalarMappable(norm=scale, cmap=cmap)
    ax.set_facecolor(_EMPTY)
    values = np.ma.masked_invalid(panel.values)
    if panel.view == "grid":
        edges = [np.linspace(*extent, n + 1) for extent, n in zip(panel.limits, values.shape)]
        if panel.archive.bin_edges:
            edges = [panel.archive.bin_edges[i] for i in panel.dimensions]
        if len(edges) == 1:
            edges.append(np.array([0, 1]))
            values = values[:, None]
        ax.pcolormesh(*edges, values.T, norm=scale, cmap=cmap, shading="flat")
    elif panel.view == "cvt":
        polygons = _bounded_cells(panel.archive.centroids, panel.limits, panel.dimensions, panel.section)
        collection = PolyCollection([polygon for _, polygon in polygons], array=values, cmap=cmap,
                                    norm=scale, edgecolors="#555555", linewidths=0.35)
        ax.add_collection(collection)
    elif panel.view == "spherical_cvt":
        faces, edges = _spherical_tessellation(panel.archive, panel.dimensions, panel.centre)
        face_colors = mappable.to_rgba([values.data[i] for i, _ in faces])
        ax.add_collection3d(Poly3DCollection([triangle for _, triangle in faces], facecolors=face_colors,
                                             edgecolors="none", antialiaseds=False))
        ax.add_collection3d(Line3DCollection(edges, colors="#555555", linewidths=0.35))
    else:
        if panel.view == "sphere":
            angles = np.linspace(0, 2 * np.pi, 32)
            polar = np.linspace(0, np.pi, 17)
            ax.plot_wireframe(np.outer(np.cos(angles), np.sin(polar)), np.outer(np.sin(angles), np.sin(polar)),
                              np.outer(np.ones_like(angles), np.cos(polar)), color="#cccccc", linewidth=0.35,
                              rstride=4, cstride=4)
        coords = list(panel.points.T)
        if len(coords) == 1:
            coords.append(np.full(len(panel.points), 0.5))
        ax.scatter(*coords, c=values, cmap=cmap, norm=scale, s=15, plotnonfinite=True,
                   **({"depthshade": False} if panel.is_3d else {}))

    _style_axes(ax, panel, limits)
    return mappable


def _style_axes(ax, panel, limits=None):
    limits = limits or panel.limits
    ax.set_xlim(*limits[0])
    ax.set_ylim(*(limits[1] if len(limits) > 1 else (0, 1)))
    sphere = panel.view in ("sphere", "spherical_cvt")
    prefix = "Direction " if sphere else "Descriptor "
    ax.set_xlabel(f"{prefix}{panel.dimensions[0] + 1}")
    if len(limits) == 1:
        ax.set_yticks([])
    else:
        ax.set_ylabel(f"{prefix}{panel.dimensions[1] + 1}")
    if panel.is_3d:
        ax.set_zlim(*limits[2])
        ax.set_zlabel(f"{prefix}{panel.dimensions[2] + 1}")
        ax.set_box_aspect((1, 1, 1))
        ax.view_init(elev=24, azim=-60)
    elif panel.view in ("grid", "cvt") and len(limits) == 2:
        ax.set_aspect("equal")
    if sphere:
        ax.set_facecolor("white")
        ax.set_axis_off()
        ax.set_proj_type("ortho")
        ax.set_title("Spherical Voronoi" if panel.view == "spherical_cvt" else "Elite directions")
    elif panel.section:
        hidden = [i for i in range(panel.archive.dimension) if i not in panel.dimensions]
        ax.set_title(", ".join(f"D{i + 1} = {value:g}" for i, value in zip(hidden, panel.section)))


def _prepare_panels(archives, panel_options, options):
    data = _named_data(archives)
    overrides = panel_options or {}
    if set(overrides) - set(data):
        raise ValueError("Panel options must use an archive label.")
    return {name: _prepare_panel(archive, **(options | overrides.get(name, {}))) for name, archive in data.items()}


def _plot_panels(panels, *, columns=None, shared_scale=False, colorbar=True, figsize=None,
                 templates=None, scales=None, limits=None, bottom=None):
    templates = panels if templates is None else templates
    columns = min(len(templates), ceil(sqrt(len(templates)))) if columns is None else index(columns)
    if columns < 1:
        raise ValueError("columns must be positive.")
    rows = ceil(len(templates) / columns)
    if shared_scale and len({(panel.label, panel.cmap) for panel in templates.values()}) != 1:
        raise ValueError("A shared colourbar needs the same metric and colormap on every panel.")
    if scales is None:
        shared = _colour_limits(list(panels.values())) if shared_scale else None
        scales = {name: shared or _colour_limits([panel]) for name, panel in panels.items()}
    fig = plt.figure(figsize=figsize or (4.3 * columns, 3.7 * rows), layout="none")
    fig.subplots_adjust(wspace=0.42, hspace=0.38, bottom=bottom)
    axes = {}
    last_mappable = None
    for position, (name, template) in enumerate(templates.items(), 1):
        panel = panels.get(name)
        ax = fig.add_subplot(rows, columns, position, projection="3d" if template.is_3d else None)
        axes[name] = ax
        if panel is None:
            _style_axes(ax, template, None if limits is None else limits[name])
            text = ax.text2D if template.is_3d else ax.text
            text(0.5, 0.5, "Unavailable", transform=ax.transAxes, ha="center")
            mappable = mpl.cm.ScalarMappable(norm=mpl.colors.Normalize(*scales[name]), cmap=template.cmap)
        else:
            mappable = _draw_panel(ax, panel, scales[name], None if limits is None else limits[name])
        subtitle = ax.get_title()
        ax.set_title(f"{name}\n{subtitle}" if subtitle else name)
        if colorbar and not shared_scale:
            fig.colorbar(mappable, ax=ax, label=template.label)
        last_mappable = mappable
    if colorbar and shared_scale:
        fig.colorbar(last_mappable, ax=list(axes.values()), label=next(iter(templates.values())).label)
    return fig, axes


## @brief Draw a live archive or numeric export and return its Matplotlib axes.
[docs] def plot_archive(archive, *, ax=None, view="auto", dimensions=None, slice_at=None, metric="fitness", objective=0, sphere_center=(0, 0, 0), cmap="viridis", vmin=None, vmax=None, colorbar=True): """Plot an archive using the selected descriptor axes and raw metric. :param archive: Live container, decorator, or numeric archive JSON path. :param ax: Optional Matplotlib axes. Use 3D axes for a spherical view. :param view: Automatic, grid, CVT, scatter, or sphere. :param dimensions: Descriptor indices in plot order, starting at zero. :param slice_at: Mapping from omitted descriptor indices to fixed values. :param metric: Fitness, occupancy count, or cell activity. :param objective: Index of the raw fitness objective. :param sphere_center: Three coordinates for the centre of a sphere view. :param cmap: Matplotlib colormap. :param vmin: Lower colour limit. :param vmax: Upper colour limit. :param colorbar: Show the metric scale beside the axes. :returns: The Matplotlib axes used for the plot. """ panel = _prepare_panel(archive, view=view, dimensions=dimensions, slice_at=slice_at, metric=metric, objective=objective, sphere_center=sphere_center, cmap=cmap, vmin=vmin, vmax=vmax) limits = _colour_limits([panel]) if ax is None: ax = plt.figure().add_subplot(projection="3d" if panel.is_3d else None) if panel.is_3d != (ax.name == "3d"): raise ValueError("Supply Matplotlib axes that match the view's projection.") mappable = _draw_panel(ax, panel, limits) if colorbar: ax.figure.colorbar(mappable, ax=ax, label=panel.label) return ax
## @brief Overlay one descriptor path per retained Trace-Elites measurement. def plot_trace_archive(archive, *, ax=None, trace_color="black", trace_alpha=.35, **options): """Plot a two-dimensional TraceArchive and its distinct measurement paths. :param archive: TraceArchive using two descriptor coordinates. :param ax: Optional Matplotlib axes. :param trace_color: Matplotlib color for the retained paths. :param trace_alpha: Opacity of each path. :param options: Remaining plot_archive settings, such as cmap or colorbar. :returns: Matplotlib axes containing the archive and paths. """ from qdpy.containers.trace import TraceArchive if not isinstance(archive, TraceArchive): raise TypeError("Supply a TraceArchive.") if len(archive.features_domain) != 2 or options.get("view") == "sphere": raise ValueError("The trajectory overlay uses two descriptor axes.") dimensions = options.get("dimensions") x_axis, y_axis = (0, 1) if dimensions is None else tuple(dimensions) ax = plot_archive(archive.to_grid(), ax=ax, **options) for elite in archive: points = np.asarray(elite.trace) ax.plot(points[:, x_axis], points[:, y_axis], color=trace_color, alpha=trace_alpha, marker="." if len(points) == 1 else None, scalex=False, scaley=False) return ax ## @brief Plot named archives side by side with individual or shared colours.
[docs] def plot_archives(archives, *, shared_scale=False, panel_options=None, columns=None, colorbar=True, figsize=None, **options): """Return a figure and a mapping of archive labels to Matplotlib axes. :param archives: Ordered mapping of labels to archives, or a sequence. :param shared_scale: Use one colour scale for the same metric in every panel. :param panel_options: Per-label overrides for the plot_archive view options. :param columns: Number of panels per row. :param colorbar: Show a colourbar or, with shared_scale, a common one. :param figsize: Matplotlib figure size in inches. :param options: Default view options shared by the panels. """ panels = _prepare_panels(archives, panel_options, options) return _plot_panels(panels, columns=columns, shared_scale=shared_scale, colorbar=colorbar, figsize=figsize)
## @brief Render occupancy, paired fitness differences, and their seed support.
[docs] def plot_archive_difference(comparison, *, labels=("Reference", "Contender"), figsize=None): """Draw the result of ``compare_archive_cells`` on a 1D or 2D grid or a 2D CVT.""" geometry = comparison.geometry if geometry.dimension not in (1, 2) or (geometry.centroids and geometry.dimension != 2): raise ValueError("Use a one- or two-dimensional Grid or a two-dimensional CVTGrid.") panel = _prepare_panel(geometry, metric="occupancy") order = ([i for i, _ in _bounded_cells(geometry.centroids, panel.limits, panel.dimensions, panel.section)] if panel.view == "cvt" else slice(None)) count = len(comparison.paired_seeds) delta = comparison.median_difference extent = _finite_extent(delta) span = max(abs(value) for value in extent) if extent else 0. ref, other = labels if ref == other: raise ValueError("Use distinct method labels.") panels = {} for title, values in ((f"Only {ref}", comparison.reference_only), (f"Only {other}", comparison.contender_only), ("Median paired improvement", delta), ("Reached by both", comparison.both)): if values is delta: panels[title] = replace(panel, values=values[order], label="Fitness difference", cmap="RdBu", vmin=-(span or 1.), vmax=span or 1.) else: panels[title] = replace(panel, values=values[order], label="Paired seeds", cmap="viridis", vmin=0., vmax=count) fig, axes = _plot_panels(panels, columns=2, figsize=figsize) fig.suptitle(f"{other} vs {ref} · {count} paired seeds") return fig, axes