QDpy
Loading...
Searching...
No Matches
lineage.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""JSONL parentage and evaluation outcomes from an opt-in MAP-Elites run."""
6
7from collections import defaultdict
8from dataclasses import dataclass, replace
9from hashlib import sha256
10import json
11from math import isfinite
12from pathlib import Path
13from weakref import ref
14
15__all__ = ["LineageNode", "LineageRecorder", "read_lineage", "plot_lineage"]
16
17
18
19@dataclass(frozen=True)
21 """Hold proposal identity, parent IDs, operator, and archive outcome."""
22
23 id: int
24 parents: tuple[int, ...]
25 operator: str
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
33
34
35
37 """Attach to one supported MAP-Elites optimiser and write a fresh JSONL log.
38
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.
44 """
45
46 def __init__(self, path, *, record_measurements=False):
47 self.path = Path(path)
48 self.record_measurements = bool(record_measurements)
49 self._algorithm = None
50 self._stream = None
51 self._next_id = 0
52 self._identities = {}
53 self._pending = set()
54 self._digest = None
55 self._parentage("initialise", ())
56
57
58 def attach(self, algorithm):
59 """Attach to a supported polynomial, Gaussian, Iso+LineDD, or IsoLineCross emitter."""
60 return self._attach(algorithm)
61
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
66
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
81 self._algorithm = algorithm
82 algorithm._lineage_recorder = self
83 try:
84 if state is None:
85 self._write(qdpy_lineage=1)
86 for item in algorithm.container:
87 self._founder(item, stored=True)
88 else:
89 self._restore(state)
90 except BaseException:
91 self.close()
92 raise
93 return self
94
95 def __enter__(self):
96 if self._stream is None:
97 raise ValueError("Attach the recorder before entering its context.")
98 return self
99
100 def __exit__(self, *_):
101 self.close()
102
103
104 def close(self):
105 """Close the trace. Pending proposals remain visible in the trace."""
106 if self._stream is not None:
107 try:
108 self._stream.close()
109 finally:
110 self._stream = None
111 self._algorithm._lineage_recorder = None
112 self._algorithm = None
113 self._parents = ()
114
115
116 def id_for(self, individual):
117 """Return the lineage ID of this live object, or None if it is unknown."""
118 found = self._identities.get(id(individual))
119 return found[1] if found is not None and found[0]() is individual else None
120
121
122 def mark_failed(self, individual):
123 """Record a manually evaluated proposal as failed. Manage its budget externally."""
124 if self._stream is None or self.id_for(individual) not in self._pending:
125 raise ValueError("Supply an outstanding proposal from this active recorder.")
126 self._result(individual, "failed", None)
127
128 def _write(self, **record):
129 row = (json.dumps(record, separators=(",", ":")) + "\n").encode()
130 self._stream.write(row)
131 if self._digest is not None:
132 self._digest.update(row)
133
134 def _boundary(self):
135 """Identify the saved trace prefix and stable IDs of the checkpoint's live elites."""
136 ids = tuple(self.id_for(item) for item in self._algorithm.container)
137 if self._pending or None in ids:
138 raise RuntimeError("A lineage checkpoint requires completed proposals and known archive elites.")
139 self._stream.flush()
140 return self._stream.tell(), self._digest.hexdigest(), self._next_id, ids
141
142 def _restore(self, state):
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.")
148 remaining = size
149 while remaining and (data := self._stream.read(min(2**20, remaining))):
150 self._digest.update(data)
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):
155 self._remember(individual, node_id)
156 self._stream.truncate(size)
157
158 def _remember(self, individual, node_id):
159 key = id(individual)
160
161 def collect(reference):
162 found = self._identities.get(key)
163 if found is not None and found[0] is reference:
164 del self._identities[key]
165
166 self._identities[key] = ref(individual, collect), node_id
167
168 def _measurements(self, individual, *, rejected=False):
169 archive = self._algorithm.container
170 fitness = archive.get_ind_fitness(individual)
171 try:
172 descriptors = _finite_vector(archive.get_ind_features(individual))
173 except (KeyError, IndexError, TypeError, ValueError, OverflowError):
174 if not rejected:
175 raise
176 descriptors = None
177 return {"fitness": _finite_vector(fitness.values), "fitness_weights": _finite_vector(fitness.weights),
178 "descriptors": descriptors}
179
180 def _founder(self, individual, *, stored=False):
181 node_id = self.id_for(individual)
182 if node_id is None:
183 node_id = self._next_id
184 self._next_id += 1
185 self._remember(individual, node_id)
186 fields = self._measurements(individual) if self.record_measurements else {}
187 if stored and self.record_measurements:
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)
190 return node_id
191
192 def _parentage(self, operator, parents):
193 self._operator, self._parents = operator, parents
194
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.")
198 parents = [self._founder(parent) for parent in self._parents]
199 node_id = self._next_id
200 self._next_id += 1
201 self._remember(individual, node_id)
202 self._pending.add(node_id)
203 self._write(event="proposal", id=node_id, parents=parents,
204 operator=self._operator, suggestion=suggestion)
205 self._parents = ()
206
207 def _transfer(self, original, evaluated):
208 node_id = self.id_for(original)
209 if node_id in self._pending:
210 if self.id_for(evaluated) is not None:
211 raise ValueError("An evaluator replacement must be a fresh object for lineage recording.")
212 del self._identities[id(original)]
213 self._remember(evaluated, node_id)
214
215 def _result(self, individual, status, evaluation):
216 node_id = self.id_for(individual)
217 if node_id not in self._pending:
218 return
219 self._pending.remove(node_id)
220 cell = self._algorithm.container._stored_cell(individual) if status == "accepted" else None
221 fields = {}
222 if self.record_measurements and status != "failed":
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)
226
227
228def _finite_vector(values):
229 numeric = tuple(map(float, values))
230 return numeric if numeric and all(map(isfinite, numeric)) else None
231
232
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}
236
237
238
239def read_lineage(path):
240 """Load a JSONL trace as a dictionary keyed by stable proposal ID."""
241 nodes = {}
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.")
245 for line in source:
246 row = json.loads(line)
247 node_id = row["id"]
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))
262 else:
263 raise ValueError("Unknown lineage event.")
264 return nodes
265
266
267
268def plot_lineage(source, *, elite=None, highlight_edges=(), ax=None):
269 """Plot all recorded nodes, or the ancestors of one proposal ID.
270
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.
276 """
277 import matplotlib.pyplot as plt
278 from matplotlib.collections import LineCollection
279 from matplotlib.ticker import FuncFormatter, MaxNLocator
280
281 from .genealogy import _ancestor_ids, _lineage_nodes
282
283 nodes = _lineage_nodes(source)
284 selected = nodes if elite is None else _ancestor_ids(nodes, (elite,))
285 if not selected:
286 raise ValueError("No recorded lineage nodes to plot.")
287
288 layers, depth, positions = defaultdict(list), {}, {}
289 ordered = sorted(selected)
290 for node in ordered:
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()):
294 if level:
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
299
300 if ax is None:
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)
305 if highlighted:
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))
309 else:
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]
315 if points:
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")
326 if max(layers) == 0:
327 ax.set_yticks([0])
328 else:
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 ""))
331 ax.set_xticks([])
332 ax.margins(.15)
333 ax.legend(loc="best", frameon=False)
334 return ax
One archived founder or evaluated proposal and its recorded parents.
Definition lineage.py:20
Record actual parents on the coordinator without changing the candidate.
Definition lineage.py:36
attach(self, algorithm)
Start a fresh trace and register any current archive entries.
Definition lineage.py:58
_founder(self, individual, *, stored=False)
Definition lineage.py:180
_measurements(self, individual, *, rejected=False)
Definition lineage.py:168
_write(self, **record)
Definition lineage.py:128
_result(self, individual, status, evaluation)
Definition lineage.py:215
_parentage(self, operator, parents)
Definition lineage.py:192
_remember(self, individual, node_id)
Definition lineage.py:158
id_for(self, individual)
Resolve the identity of a live candidate for ancestry plotting.
Definition lineage.py:116
_attach(self, algorithm, *, checkpointed=False, state=None)
Definition lineage.py:62
mark_failed(self, individual)
Close a failed manual ask without admitting a fake measurement.
Definition lineage.py:122
close(self)
Flush the JSONL stream and detach the observer.
Definition lineage.py:104