Source code for qdpy.lineage

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Record and display measured parentage for native MAP-Elites.

"""JSONL parentage and evaluation outcomes from an opt-in MAP-Elites run."""

from collections import defaultdict
from dataclasses import dataclass, replace
from hashlib import sha256
import json
from math import isfinite
from pathlib import Path
from weakref import ref

__all__ = ["LineageNode", "LineageRecorder", "read_lineage", "plot_lineage"]


## @brief One archived founder or evaluated proposal and its recorded parents.
[docs] @dataclass(frozen=True) class LineageNode: """Hold proposal identity, parent IDs, operator, and archive outcome.""" id: int parents: tuple[int, ...] operator: str suggestion: int | None status: str = "pending" evaluation: int | None = None cell: tuple[int, ...] | None = None descriptors: tuple[float, ...] | None = None fitness: tuple[float, ...] | None = None fitness_weights: tuple[float, ...] | None = None
## @brief Record actual parents on the coordinator without changing the candidate.
[docs] class LineageRecorder: """Attach to one supported MAP-Elites optimiser and write a fresh JSONL log. Use a context manager or call ``close()`` to flush the log and detach. The recorder tracks live objects with weak references. Use ``record_measurements=True`` to retain fitness and descriptors for genealogical analysis. A newly attached recorder treats current archive contents as founders. Genomes are never stored. """ def __init__(self, path, *, record_measurements=False): self.path = Path(path) self.record_measurements = bool(record_measurements) self._algorithm = None self._stream = None self._next_id = 0 self._identities = {} self._pending = set() self._digest = None self._parentage("initialise", ()) ## @brief Start a fresh trace and register any current archive entries.
[docs] def attach(self, algorithm): """Attach to a supported polynomial, Gaussian, Iso+LineDD, or IsoLineCross emitter.""" return self._attach(algorithm)
def _attach(self, algorithm, *, checkpointed=False, state=None): from .algorithms import (CuriosityMutPolyBounded, IsoLineCrossMAPElites, IsoLineMAPElites, MutGaussian, MutPolyBounded, RandomSearchMutGaussian, RandomSearchMutPolyBounded) from .containers import Grid if type(algorithm) not in (RandomSearchMutPolyBounded, MutPolyBounded, CuriosityMutPolyBounded, RandomSearchMutGaussian, MutGaussian, IsoLineMAPElites, IsoLineCrossMAPElites): raise TypeError("Use a supported native MAP-Elites emitter for lineage recording.") if not isinstance(algorithm.container, Grid): raise TypeError("Lineage recording needs a Grid or CVTGrid archive.") if self._algorithm is not None or algorithm._lineage_recorder is not None: raise ValueError("The recorder or optimiser already has an active lineage recording.") if not getattr(algorithm, "deepcopy_on_selection", True) and type(algorithm) is not CuriosityMutPolyBounded: raise ValueError("Lineage recording requires copying selected parents before in-place variation.") if getattr(algorithm, "_select_fn", None) is not None: raise ValueError("Lineage recording uses the native select-or-initialise path.") self.path.parent.mkdir(parents=True, exist_ok=True) self._stream = self.path.open("r+b" if state is not None else "xb") self._digest = sha256() if checkpointed else None self._algorithm = algorithm algorithm._lineage_recorder = self try: if state is None: self._write(qdpy_lineage=1) for item in algorithm.container: self._founder(item, stored=True) else: self._restore(state) except BaseException: self.close() raise return self def __enter__(self): if self._stream is None: raise ValueError("Attach the recorder before entering its context.") return self def __exit__(self, *_): self.close() ## @brief Flush the JSONL stream and detach the observer.
[docs] def close(self): """Close the trace. Pending proposals remain visible in the trace.""" if self._stream is not None: try: self._stream.close() finally: self._stream = None self._algorithm._lineage_recorder = None self._algorithm = None self._parents = ()
## @brief Resolve the identity of a live candidate for ancestry plotting.
[docs] def id_for(self, individual): """Return the lineage ID of this live object, or None if it is unknown.""" found = self._identities.get(id(individual)) return found[1] if found is not None and found[0]() is individual else None
## @brief Close a failed manual ask without admitting a fake measurement.
[docs] def mark_failed(self, individual): """Record a manually evaluated proposal as failed. Manage its budget externally.""" if self._stream is None or self.id_for(individual) not in self._pending: raise ValueError("Supply an outstanding proposal from this active recorder.") self._result(individual, "failed", None)
def _write(self, **record): row = (json.dumps(record, separators=(",", ":")) + "\n").encode() self._stream.write(row) if self._digest is not None: self._digest.update(row) def _boundary(self): """Identify the saved trace prefix and stable IDs of the checkpoint's live elites.""" ids = tuple(self.id_for(item) for item in self._algorithm.container) if self._pending or None in ids: raise RuntimeError("A lineage checkpoint requires completed proposals and known archive elites.") self._stream.flush() return self._stream.tell(), self._digest.hexdigest(), self._next_id, ids def _restore(self, state): """Verify the saved prefix, then discard records following the checkpoint boundary.""" size, digest, self._next_id, ids = state if (size < 1 or self._next_id < 0 or len(set(ids)) != len(ids) or any(not 0 <= item < self._next_id for item in ids)): raise ValueError("Invalid lineage IDs or byte offset in the checkpoint.") remaining = size while remaining and (data := self._stream.read(min(2**20, remaining))): self._digest.update(data) remaining -= len(data) if remaining or self._digest.hexdigest() != digest: raise ValueError("Lineage prefix SHA-256 does not match the checkpoint.") for individual, node_id in zip(self._algorithm.container, ids, strict=True): self._remember(individual, node_id) self._stream.truncate(size) def _remember(self, individual, node_id): key = id(individual) def collect(reference): found = self._identities.get(key) if found is not None and found[0] is reference: del self._identities[key] self._identities[key] = ref(individual, collect), node_id def _measurements(self, individual, *, rejected=False): archive = self._algorithm.container fitness = archive.get_ind_fitness(individual) try: descriptors = _finite_vector(archive.get_ind_features(individual)) except (KeyError, IndexError, TypeError, ValueError, OverflowError): if not rejected: raise descriptors = None return {"fitness": _finite_vector(fitness.values), "fitness_weights": _finite_vector(fitness.weights), "descriptors": descriptors} def _founder(self, individual, *, stored=False): node_id = self.id_for(individual) if node_id is None: node_id = self._next_id self._next_id += 1 self._remember(individual, node_id) fields = self._measurements(individual) if self.record_measurements else {} if stored and self.record_measurements: fields["cell"] = tuple(map(int, self._algorithm.container._stored_cell(individual))) self._write(event="proposal", id=node_id, parents=(), operator="founder", suggestion=None, **fields) return node_id def _parentage(self, operator, parents): self._operator, self._parents = operator, parents def _proposed(self, individual, suggestion): if self.id_for(individual) is not None: raise ValueError("Lineage recording requires a fresh object for each proposal.") parents = [self._founder(parent) for parent in self._parents] node_id = self._next_id self._next_id += 1 self._remember(individual, node_id) self._pending.add(node_id) self._write(event="proposal", id=node_id, parents=parents, operator=self._operator, suggestion=suggestion) self._parents = () def _transfer(self, original, evaluated): node_id = self.id_for(original) if node_id in self._pending: if self.id_for(evaluated) is not None: raise ValueError("An evaluator replacement must be a fresh object for lineage recording.") del self._identities[id(original)] self._remember(evaluated, node_id) def _result(self, individual, status, evaluation): node_id = self.id_for(individual) if node_id not in self._pending: return self._pending.remove(node_id) cell = self._algorithm.container._stored_cell(individual) if status == "accepted" else None fields = {} if self.record_measurements and status != "failed": fields = self._measurements(individual, rejected=status == "rejected") self._write(event="result", id=node_id, status=status, evaluation=evaluation, cell=None if cell is None else tuple(map(int, cell)), **fields)
def _finite_vector(values): numeric = tuple(map(float, values)) return numeric if numeric and all(map(isfinite, numeric)) else None def _observations(row): return {name: tuple(value) for name in ("cell", "descriptors", "fitness", "fitness_weights") if (value := row.get(name)) is not None} ## @brief Read an ordered lineage log and validate its parent references.
[docs] def read_lineage(path): """Load a JSONL trace as a dictionary keyed by stable proposal ID.""" nodes = {} with Path(path).open(encoding="utf-8") as source: if json.loads(source.readline()) != {"qdpy_lineage": 1}: raise ValueError("Unsupported QDpy lineage format.") for line in source: row = json.loads(line) node_id = row["id"] if row["event"] == "proposal": parents = tuple(row["parents"]) if node_id != len(nodes) or any(parent not in nodes for parent in parents): raise ValueError("Invalid proposal order or unknown lineage parent.") status = "founder" if row["operator"] == "founder" else "pending" nodes[node_id] = LineageNode(node_id, parents, row["operator"], row["suggestion"], status, **_observations(row)) elif row["event"] == "result": status = row["status"] if (node_id not in nodes or nodes[node_id].status != "pending" or status not in ("accepted", "rejected", "failed")): raise ValueError("Invalid or duplicate lineage outcome.") nodes[node_id] = replace(nodes[node_id], status=status, evaluation=row["evaluation"], **_observations(row)) else: raise ValueError("Unknown lineage event.") return nodes
## @brief Draw a mutation tree or multi-parent ancestry graph with Matplotlib.
[docs] def plot_lineage(source, *, elite=None, highlight_edges=(), ax=None): """Plot all recorded nodes, or the ancestors of one proposal ID. :param source: JSONL path or dictionary returned by ``read_lineage``. :param elite: Optional selected proposal ID whose ancestors to display. :param highlight_edges: Parent-child ID pairs to draw in accent color. :param ax: Optional Matplotlib axes. :return: The Matplotlib axes used for the plot. """ import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib.ticker import FuncFormatter, MaxNLocator from .genealogy import _ancestor_ids, _lineage_nodes nodes = _lineage_nodes(source) selected = nodes if elite is None else _ancestor_ids(nodes, (elite,)) if not selected: raise ValueError("No recorded lineage nodes to plot.") layers, depth, positions = defaultdict(list), {}, {} ordered = sorted(selected) for node in ordered: depth[node] = 1 + max((depth[parent] for parent in nodes[node].parents), default=-1) layers[depth[node]].append(node) for level, members in sorted(layers.items()): if level: members.sort(key=lambda node: sum(positions[parent][0] for parent in nodes[node].parents) / len(nodes[node].parents)) for column, node in enumerate(members): positions[node] = column - (len(members) - 1) / 2, -level if ax is None: ax = plt.figure(figsize=(8, 5), layout="constrained").add_subplot() edges = [(parent, node) for node in ordered for parent in dict.fromkeys(nodes[node].parents)] links = [(positions[parent], positions[child]) for parent, child in edges] highlighted = set(highlight_edges) if highlighted: colors = ["#d45426" if edge in highlighted else "#64748b" for edge in edges] widths = [2.4 if edge in highlighted else 1. for edge in edges] ax.add_collection(LineCollection(links, colors=colors, linewidths=widths, alpha=.85)) else: ax.add_collection(LineCollection(links, colors="#64748b", linewidths=1, alpha=.72)) colors = {"founder": "#8055a5", "accepted": "#007f79", "rejected": "#8294a6", "failed": "#bb523d", "pending": "#d2a332"} for status, color in colors.items(): points = [positions[node] for node in ordered if nodes[node].status == status] if points: ax.scatter(*zip(*points), color=color, edgecolor="white", linewidth=.6, label=status.capitalize(), zorder=3) if elite is not None: ax.scatter(*positions[elite], s=130, facecolors="none", edgecolors="#172638", zorder=4, label="Selected") if len(selected) <= 25: for node, position in positions.items(): ax.annotate(str(node), position, xytext=(4, 5), textcoords="offset points", fontsize=8) graph = any(len(set(nodes[node].parents)) > 1 for node in selected) title = "Multi-parent lineage" if graph else "Mutation lineage" ax.set_title(title if elite is None else f"{title} · ancestors of {elite}") ax.set_ylabel("Variation depth") if max(layers) == 0: ax.set_yticks([0]) else: ax.yaxis.set_major_locator(MaxNLocator(nbins=6, integer=True)) ax.yaxis.set_major_formatter(FuncFormatter(lambda value, _: f"{int(-value)}" if value <= 0 else "")) ax.set_xticks([]) ax.margins(.15) ax.legend(loc="best", frameon=False) return ax