5"""JSONL parentage and evaluation outcomes from an opt-in MAP-Elites run."""
7from collections
import defaultdict
8from dataclasses
import dataclass, replace
9from hashlib
import sha256
11from math
import isfinite
12from pathlib
import Path
13from weakref
import ref
15__all__ = [
"LineageNode",
"LineageRecorder",
"read_lineage",
"plot_lineage"]
19@dataclass(frozen=True)
21 """Hold proposal identity, parent IDs, operator, and archive outcome."""
24 parents: tuple[int, ...]
26 suggestion: int |
None
27 status: str =
"pending"
28 evaluation: int |
None =
None
29 cell: tuple[int, ...] |
None =
None
30 descriptors: tuple[float, ...] |
None =
None
31 fitness: tuple[float, ...] |
None =
None
32 fitness_weights: tuple[float, ...] |
None =
None
37 """Attach to one supported MAP-Elites optimiser and write a fresh JSONL log.
39 Use a context manager or call ``close()`` to flush the log and detach.
40 The recorder tracks live objects with weak references. Use
41 ``record_measurements=True`` to retain fitness and descriptors for
42 genealogical analysis. A newly attached recorder treats current
43 archive contents as founders. Genomes are never stored.
46 def __init__(self, path, *, record_measurements=False):
47 self.
path = Path(path)
59 """Attach to a supported polynomial, Gaussian, Iso+LineDD, or IsoLineCross emitter."""
62 def _attach(self, algorithm, *, checkpointed=False, state=None):
63 from .algorithms
import (CuriosityMutPolyBounded, IsoLineCrossMAPElites, IsoLineMAPElites, MutGaussian,
64 MutPolyBounded, RandomSearchMutGaussian, RandomSearchMutPolyBounded)
65 from .containers
import Grid
67 if type(algorithm)
not in (RandomSearchMutPolyBounded, MutPolyBounded, CuriosityMutPolyBounded,
68 RandomSearchMutGaussian, MutGaussian, IsoLineMAPElites, IsoLineCrossMAPElites):
69 raise TypeError(
"Use a supported native MAP-Elites emitter for lineage recording.")
70 if not isinstance(algorithm.container, Grid):
71 raise TypeError(
"Lineage recording needs a Grid or CVTGrid archive.")
72 if self.
_algorithm is not None or algorithm._lineage_recorder
is not None:
73 raise ValueError(
"The recorder or optimiser already has an active lineage recording.")
74 if not getattr(algorithm,
"deepcopy_on_selection",
True)
and type(algorithm)
is not CuriosityMutPolyBounded:
75 raise ValueError(
"Lineage recording requires copying selected parents before in-place variation.")
76 if getattr(algorithm,
"_select_fn",
None)
is not None:
77 raise ValueError(
"Lineage recording uses the native select-or-initialise path.")
78 self.
path.parent.mkdir(parents=
True, exist_ok=
True)
79 self.
_stream = self.
path.open(
"r+b" if state
is not None else "xb")
80 self.
_digest = sha256()
if checkpointed
else None
82 algorithm._lineage_recorder = self
85 self.
_write(qdpy_lineage=1)
86 for item
in algorithm.container:
97 raise ValueError(
"Attach the recorder before entering its context.")
100 def __exit__(self, *_):
105 """Close the trace. Pending proposals remain visible in the trace."""
117 """Return the lineage ID of this live object, or None if it is unknown."""
119 return found[1]
if found
is not None and found[0]()
is individual
else None
123 """Record a manually evaluated proposal as failed. Manage its budget externally."""
125 raise ValueError(
"Supply an outstanding proposal from this active recorder.")
126 self.
_result(individual,
"failed",
None)
128 def _write(self, **record):
129 row = (json.dumps(record, separators=(
",",
":")) +
"\n").encode()
135 """Identify the saved trace prefix and stable IDs of the checkpoint's live elites."""
138 raise RuntimeError(
"A lineage checkpoint requires completed proposals and known archive elites.")
143 """Verify the saved prefix, then discard records following the checkpoint boundary."""
144 size, digest, self.
_next_id, ids = state
145 if (size < 1
or self.
_next_id < 0
or len(set(ids)) != len(ids)
146 or any(
not 0 <= item < self.
_next_id for item
in ids)):
147 raise ValueError(
"Invalid lineage IDs or byte offset in the checkpoint.")
149 while remaining
and (data := self.
_stream.read(min(2**20, remaining))):
151 remaining -= len(data)
152 if remaining
or self.
_digest.hexdigest() != digest:
153 raise ValueError(
"Lineage prefix SHA-256 does not match the checkpoint.")
154 for individual, node_id
in zip(self.
_algorithm.container, ids, strict=
True):
158 def _remember(self, individual, node_id):
161 def collect(reference):
163 if found
is not None and found[0]
is reference:
166 self.
_identities[key] = ref(individual, collect), node_id
168 def _measurements(self, individual, *, rejected=False):
170 fitness = archive.get_ind_fitness(individual)
172 descriptors = _finite_vector(archive.get_ind_features(individual))
173 except (KeyError, IndexError, TypeError, ValueError, OverflowError):
177 return {
"fitness": _finite_vector(fitness.values),
"fitness_weights": _finite_vector(fitness.weights),
178 "descriptors": descriptors}
180 def _founder(self, individual, *, stored=False):
181 node_id = self.
id_for(individual)
188 fields[
"cell"] = tuple(map(int, self.
_algorithm.container._stored_cell(individual)))
189 self.
_write(event=
"proposal", id=node_id, parents=(), operator=
"founder", suggestion=
None, **fields)
192 def _parentage(self, operator, parents):
195 def _proposed(self, individual, suggestion):
196 if self.
id_for(individual)
is not None:
197 raise ValueError(
"Lineage recording requires a fresh object for each proposal.")
203 self.
_write(event=
"proposal", id=node_id, parents=parents,
204 operator=self.
_operator, suggestion=suggestion)
207 def _transfer(self, original, evaluated):
208 node_id = self.
id_for(original)
210 if self.
id_for(evaluated)
is not None:
211 raise ValueError(
"An evaluator replacement must be a fresh object for lineage recording.")
215 def _result(self, individual, status, evaluation):
216 node_id = self.
id_for(individual)
220 cell = self.
_algorithm.container._stored_cell(individual)
if status ==
"accepted" else None
223 fields = self.
_measurements(individual, rejected=status ==
"rejected")
224 self.
_write(event=
"result", id=node_id, status=status, evaluation=evaluation,
225 cell=
None if cell
is None else tuple(map(int, cell)), **fields)
228def _finite_vector(values):
229 numeric = tuple(map(float, values))
230 return numeric
if numeric
and all(map(isfinite, numeric))
else None
233def _observations(row):
234 return {name: tuple(value)
for name
in (
"cell",
"descriptors",
"fitness",
"fitness_weights")
235 if (value := row.get(name))
is not None}
239def read_lineage(path):
240 """Load a JSONL trace as a dictionary keyed by stable proposal ID."""
242 with Path(path).open(encoding=
"utf-8")
as source:
243 if json.loads(source.readline()) != {
"qdpy_lineage": 1}:
244 raise ValueError(
"Unsupported QDpy lineage format.")
246 row = json.loads(line)
248 if row[
"event"] ==
"proposal":
249 parents = tuple(row[
"parents"])
250 if node_id != len(nodes)
or any(parent
not in nodes
for parent
in parents):
251 raise ValueError(
"Invalid proposal order or unknown lineage parent.")
252 status =
"founder" if row[
"operator"] ==
"founder" else "pending"
253 nodes[node_id] =
LineageNode(node_id, parents, row[
"operator"], row[
"suggestion"], status,
254 **_observations(row))
255 elif row[
"event"] ==
"result":
256 status = row[
"status"]
257 if (node_id
not in nodes
or nodes[node_id].status !=
"pending"
258 or status
not in (
"accepted",
"rejected",
"failed")):
259 raise ValueError(
"Invalid or duplicate lineage outcome.")
260 nodes[node_id] = replace(nodes[node_id], status=status, evaluation=row[
"evaluation"],
261 **_observations(row))
263 raise ValueError(
"Unknown lineage event.")
268def plot_lineage(source, *, elite=None, highlight_edges=(), ax=
None):
269 """Plot all recorded nodes, or the ancestors of one proposal ID.
271 :param source: JSONL path or dictionary returned by ``read_lineage``.
272 :param elite: Optional selected proposal ID whose ancestors to display.
273 :param highlight_edges: Parent-child ID pairs to draw in accent color.
274 :param ax: Optional Matplotlib axes.
275 :return: The Matplotlib axes used for the plot.
277 import matplotlib.pyplot
as plt
278 from matplotlib.collections
import LineCollection
279 from matplotlib.ticker
import FuncFormatter, MaxNLocator
281 from .genealogy
import _ancestor_ids, _lineage_nodes
283 nodes = _lineage_nodes(source)
284 selected = nodes
if elite
is None else _ancestor_ids(nodes, (elite,))
286 raise ValueError(
"No recorded lineage nodes to plot.")
288 layers, depth, positions = defaultdict(list), {}, {}
289 ordered = sorted(selected)
291 depth[node] = 1 + max((depth[parent]
for parent
in nodes[node].parents), default=-1)
292 layers[depth[node]].append(node)
293 for level, members
in sorted(layers.items()):
295 members.sort(key=
lambda node: sum(positions[parent][0]
for parent
in nodes[node].parents)
296 / len(nodes[node].parents))
297 for column, node
in enumerate(members):
298 positions[node] = column - (len(members) - 1) / 2, -level
301 ax = plt.figure(figsize=(8, 5), layout=
"constrained").add_subplot()
302 edges = [(parent, node)
for node
in ordered
for parent
in dict.fromkeys(nodes[node].parents)]
303 links = [(positions[parent], positions[child])
for parent, child
in edges]
304 highlighted = set(highlight_edges)
306 colors = [
"#d45426" if edge
in highlighted
else "#64748b" for edge
in edges]
307 widths = [2.4
if edge
in highlighted
else 1.
for edge
in edges]
308 ax.add_collection(LineCollection(links, colors=colors, linewidths=widths, alpha=.85))
310 ax.add_collection(LineCollection(links, colors=
"#64748b", linewidths=1, alpha=.72))
311 colors = {
"founder":
"#8055a5",
"accepted":
"#007f79",
"rejected":
"#8294a6",
312 "failed":
"#bb523d",
"pending":
"#d2a332"}
313 for status, color
in colors.items():
314 points = [positions[node]
for node
in ordered
if nodes[node].status == status]
316 ax.scatter(*zip(*points), color=color, edgecolor=
"white", linewidth=.6, label=status.capitalize(), zorder=3)
317 if elite
is not None:
318 ax.scatter(*positions[elite], s=130, facecolors=
"none", edgecolors=
"#172638", zorder=4, label=
"Selected")
319 if len(selected) <= 25:
320 for node, position
in positions.items():
321 ax.annotate(str(node), position, xytext=(4, 5), textcoords=
"offset points", fontsize=8)
322 graph = any(len(set(nodes[node].parents)) > 1
for node
in selected)
323 title =
"Multi-parent lineage" if graph
else "Mutation lineage"
324 ax.set_title(title
if elite
is None else f
"{title} ยท ancestors of {elite}")
325 ax.set_ylabel(
"Variation depth")
329 ax.yaxis.set_major_locator(MaxNLocator(nbins=6, integer=
True))
330 ax.yaxis.set_major_formatter(FuncFormatter(
lambda value, _: f
"{int(-value)}" if value <= 0
else ""))
333 ax.legend(loc=
"best", frameon=
False)
One archived founder or evaluated proposal and its recorded parents.
Record actual parents on the coordinator without changing the candidate.
attach(self, algorithm)
Start a fresh trace and register any current archive entries.
_founder(self, individual, *, stored=False)
_measurements(self, individual, *, rejected=False)
_result(self, individual, status, evaluation)
_parentage(self, operator, parents)
_remember(self, individual, node_id)
id_for(self, individual)
Resolve the identity of a live candidate for ancestry plotting.
_attach(self, algorithm, *, checkpointed=False, state=None)
mark_failed(self, individual)
Close a failed manual ask without admitting a fake measurement.
close(self)
Flush the JSONL stream and detach the observer.