QDpy
Loading...
Searching...
No Matches
_archive_history.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Portable histories for archive visualization."""
6
7from collections.abc import Mapping
8from dataclasses import dataclass
9from hashlib import sha256
10import json
11from operator import index
12from os import PathLike
13from pathlib import Path
14import re
15
16from ._archive_data import _archive_data, _is_archive, _named_data
17from .results import _decode_float, _json_bytes, _json_value, _write
18from .tools import open_pickle_file
19
20__all__ = ["ArchiveFrame", "ArchiveRecorder", "read_archive_history", "align_archive_histories"]
21
22_FRAME = re.compile(r"frame-(\d+)\.json")
23_ITERATION = re.compile(r"iteration-(\d+)\.(?:p|pkl|pickle)")
24
25
26
27@dataclass(frozen=True)
29 """A numbered archive snapshot with optional iteration and attempt counts."""
30
31 number: int
32 archives: dict
33 iteration: int | None = None
34 evaluations: int | None = None
35
36
37def _archive_payload(archive):
38 kind = "CVTGrid" if archive.centroids else ("Grid" if archive.shape else "points")
39 return {
40 "schema_version": 1, "archive_type": kind,
41 "descriptor_domain": archive.descriptor_domain, "fitness_domain": archive.fitness_domain,
42 "shape": archive.shape, "centroids": archive.centroids,
43 **({"bin_edges": archive.bin_edges} if archive.bin_edges else {}),
44 "entries": [{"cell": entry.cell, "descriptors": entry.descriptors,
45 "fitness": entry.fitness, "fitness_weights": entry.fitness_weights}
46 for entry in archive.entries],
47 "activity": archive.activity,
48 }
49
50
51def _archive_payloads(archives):
52 return _json_value({name: _archive_payload(archive) for name, archive in archives.items()})
53
54
55def _write_archive_frame(directory, number, iteration, evaluations, payload):
56 path = directory / f"frame-{number:06d}.json"
57 if path.exists() or path.is_symlink():
58 raise FileExistsError(path)
59 _write(path, _json_bytes({"qdpy_archive_frame": 1, "number": number,
60 "iteration": iteration, "evaluations": evaluations, "archives": payload}))
61 return path
62
63
64def _count(value):
65 if value is None:
66 return None
67 count = index(value)
68 if count < 0:
69 raise ValueError("Iteration and evaluation counts must be nonnegative.")
70 return count
71
72
73
75 """Capture archive measurements without running a renderer in the search.
76
77 :param directory: New or empty output directory.
78 :param every: Number of completed iterations between automatic captures.
79 """
80
81 def __init__(self, directory, *, every=10):
82 self.every = index(every)
83 if self.every < 1:
84 raise ValueError("every must be positive.")
85 self.directory = Path(directory)
86 self.directory.mkdir(parents=True, exist_ok=True)
87 if any(self.directory.iterdir()):
88 raise FileExistsError(f"Archive history directory must be empty: {self.directory}")
89 self._number = 0
90 self._iteration = 0
91 self._last = None
92 self._attached = False
93
94
95 def capture(self, archives, *, iteration=None, evaluations=None):
96 """Write an archive frame and return its JSON path."""
97 return self._capture(archives, iteration, evaluations, skip_duplicate=False)
98
99 def _capture(self, archives, iteration, evaluations, *, skip_duplicate):
100 iteration, evaluations = _count(iteration), _count(evaluations)
101 payload = _archive_payloads(_named_data(archives))
102 digest = sha256(_json_bytes(payload)).digest()
103 state = evaluations, digest
104 if skip_duplicate and state == self._last:
105 return None
106 path = _write_archive_frame(self.directory, self._number, iteration, evaluations, payload)
107 self._number += 1
108 self._last = state
109 return path
110
111
112 def attach(self, algorithm, archives=None):
113 """Attach to an optimiser and return the recorder.
114
115 Supply an archive mapping or a callable returning the archives at
116 capture time. By default, record the optimiser's current container
117 under one stable label. Attach after callbacks that update archives.
118 """
119 if self._attached:
120 raise ValueError("This recorder is already attached to an optimiser.")
121
122 def source(algo):
123 if archives is None:
124 return algo.container
125 return archives() if callable(archives) else archives
126
127 def started(algo):
128 self._iteration = 0
129 self.capture(source(algo), iteration=0, evaluations=algo.nb_evaluations)
130
131 def periodic(algo, _elapsed):
132 self._iteration += 1
133 if self._iteration % self.every == 0:
134 self.capture(source(algo), iteration=self._iteration, evaluations=algo.nb_evaluations)
135
136 def finished(algo, _elapsed):
137 self._capture(source(algo), self._iteration, algo.nb_evaluations, skip_duplicate=True)
138
139 algorithm.add_callback("started_optimisation", started)
140 algorithm.add_callback("iteration", periodic)
141 algorithm.add_callback("finished_optimisation", finished)
142 self._attached = True
143 return self
144
145
146def _numbered_paths(directory, pattern):
147 matches = [(int(match[1]), path.name, path) for path in directory.iterdir()
148 if path.is_file() and (match := pattern.fullmatch(path.name))]
149 return [path for _, _, path in sorted(matches)]
150
151
152def _history_inputs(source):
153 if not isinstance(source, (str, PathLike)):
154 return [source] if isinstance(source, ArchiveFrame) else list(source)
155 path = Path(source)
156 if not path.is_dir():
157 return [path]
158 recorded = _numbered_paths(path, _FRAME)
159 if recorded:
160 return recorded
161 checkpoints = _numbered_paths(path, _ITERATION)
162 final = path / "final.p"
163 if final.is_file():
164 checkpoints.append(final)
165 return checkpoints
166
167
168def _pickle_frame(path, number):
169 saved = open_pickle_file(path)
170 evaluations = None
171 if _is_archive(saved):
172 archives = saved
173 elif isinstance(saved, Mapping) and _is_archive(saved.get("container")):
174 archives = saved["container"]
175 evaluations = _count(saved.get("nb_evaluations"))
176 elif isinstance(saved, Mapping) and isinstance(saved.get("archives"), (Mapping, list, tuple)):
177 archives = saved["archives"]
178 evaluations = _count(saved.get("nb_evaluations"))
179 elif isinstance(saved, Mapping):
180 archives = {}
181 for name, value in saved.items():
182 candidate = getattr(value, "container", value)
183 if _is_archive(candidate) and not isinstance(candidate, (str, PathLike)):
184 archives[name] = candidate
185 else:
186 raise ValueError(f"No supported archive in {path}.")
187 match = _ITERATION.fullmatch(path.name)
188 return ArchiveFrame(number, _named_data(archives), int(match[1]) if match else None, evaluations)
189
190
191def _read_frame(path, number, trusted_pickle):
192 if isinstance(path, ArchiveFrame):
193 return path
194 path = Path(path)
195 if path.suffix.lower() in (".p", ".pkl", ".pickle"):
196 if not trusted_pickle:
197 raise ValueError("Set trusted_pickle=True only for a trusted QDpy checkpoint.")
198 return _pickle_frame(path, number)
199 with path.open(encoding="utf-8") as file:
200 payload = json.load(file, object_hook=_decode_float)
201 if not isinstance(payload, Mapping):
202 raise ValueError(f"Expected an archive object in {path}.")
203 if "qdpy_archive_frame" in payload:
204 if payload["qdpy_archive_frame"] != 1:
205 raise ValueError(f"Unsupported archive frame version in {path}.")
206 return ArchiveFrame(_count(payload["number"]), _named_data(payload["archives"]),
207 _count(payload.get("iteration")), _count(payload.get("evaluations")))
208 if "archive_type" in payload:
209 return ArchiveFrame(number, {"Archive": _archive_data(payload)})
210 if "archive" in payload and "evaluation" in payload:
211 reference = payload["archive"]
212 name = reference.get("file")
213 if not name or name != Path(name).name or (path.parent / name).resolve().parent != path.parent.resolve():
214 raise ValueError(f"Run manifest has no local numeric archive snapshot: {path}.")
215 raw = (path.parent / name).read_bytes()
216 if sha256(raw).hexdigest() != reference.get("sha256"):
217 raise ValueError(f"Archive fingerprint does not match {path}.")
218 archive = _archive_data(json.loads(raw, object_hook=_decode_float))
219 return ArchiveFrame(number, {"Archive": archive}, evaluations=_count(payload["evaluation"].get("attempted")))
220 raise ValueError(f"No supported archive in {path}.")
221
222
223
224def read_archive_history(source, *, trusted_pickle=False):
225 """Yield archive frames from a file, directory, or explicit sequence.
226
227 A directory uses recorded JSON frames when present. Native iteration
228 pickles follow numeric order and a distinct final checkpoint follows
229 them. Explicit sequences retain the caller's order.
230
231 :param source: History path or sequence of paths or ArchiveFrame objects.
232 :param trusted_pickle: Allow native Python checkpoints from trusted sources.
233 """
234 inputs = _history_inputs(source)
235 if not inputs:
236 raise ValueError("No archive frames found.")
237 previous = None
238 for number, path in enumerate(inputs):
239 frame = _read_frame(path, number, trusted_pickle)
240 if (previous is not None and isinstance(path, (str, PathLike)) and Path(path).name == "final.p"
241 and frame.evaluations == previous.evaluations
242 and _archive_payloads(frame.archives) == _archive_payloads(previous.archives)):
243 continue
244 yield frame
245 previous = frame
246
247
248def _evaluation_frames(source, trusted_pickle):
249 """Coalesce refits at the same budget and check that evaluation counts increase."""
250 prior = None
251 for frame in read_archive_history(source, trusted_pickle=trusted_pickle):
252 if frame.evaluations is None:
253 raise ValueError("Budget alignment needs evaluation counts on every frame.")
254 _count(frame.evaluations)
255 if prior is not None:
256 if frame.evaluations < prior.evaluations:
257 raise ValueError("History evaluation counts must be nondecreasing.")
258 if frame.evaluations > prior.evaluations:
259 yield prior
260 prior = frame
261 yield prior
262
263
264
265def align_archive_histories(histories, *, trusted_pickle=False):
266 """Yield aligned frames from a mapping of run label to history source.
267
268 The timeline uses the union of recorded budgets within the overlap of
269 all runs. Each panel shows the latest snapshot at or before the current
270 budget. Named archives keep their labels with the run name prefixed.
271 """
272 if not isinstance(histories, Mapping) or not histories:
273 raise ValueError("Provide a mapping of run labels to their histories.")
274 streams = {label: iter(_evaluation_frames(source, trusted_pickle)) for label, source in histories.items()}
275 current = {label: next(stream) for label, stream in streams.items()}
276 pending = {label: next(stream, None) for label, stream in streams.items()}
277 budget = max(frame.evaluations for frame in current.values())
278 number = 0
279 while True:
280 for label, stream in streams.items():
281 while pending[label] is not None and pending[label].evaluations <= budget:
282 current[label] = pending[label]
283 pending[label] = next(stream, None)
284 if any(pending[label] is None and frame.evaluations < budget for label, frame in current.items()):
285 if number == 0:
286 raise ValueError("The histories have no overlapping evaluation budgets.")
287 return
288 archives = {}
289 for label, frame in current.items():
290 panels = _named_data(frame.archives)
291 for name, archive in panels.items():
292 panel = str(label) if name == "Archive" else f"{label} / {name}"
293 if panel in archives:
294 raise ValueError(f"Aligned panel label {panel!r} is ambiguous.")
295 archives[panel] = archive
296 yield ArchiveFrame(number, archives, evaluations=budget)
297 if any(frame is None for frame in pending.values()):
298 return
299 number += 1
300 budget = min(frame.evaluations for frame in pending.values())
A set of archive measurements captured at a search boundary.
Write plot-ready archive frames during an optimisation.
attach(self, algorithm, archives=None)
Attach initial, periodic and final captures to a native optimiser.
capture(self, archives, *, iteration=None, evaluations=None)
Write one frame from a live archive or a collection of archives.
_capture(self, archives, iteration, evaluations, *, skip_duplicate)