5"""Portable histories for archive visualization."""
7from collections.abc
import Mapping
8from dataclasses
import dataclass
9from hashlib
import sha256
11from operator
import index
12from os
import PathLike
13from pathlib
import Path
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
20__all__ = [
"ArchiveFrame",
"ArchiveRecorder",
"read_archive_history",
"align_archive_histories"]
22_FRAME = re.compile(
r"frame-(\d+)\.json")
23_ITERATION = re.compile(
r"iteration-(\d+)\.(?:p|pkl|pickle)")
27@dataclass(frozen=True)
29 """A numbered archive snapshot with optional iteration and attempt counts."""
33 iteration: int |
None =
None
34 evaluations: int |
None =
None
37def _archive_payload(archive):
38 kind =
"CVTGrid" if archive.centroids
else (
"Grid" if archive.shape
else "points")
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,
51def _archive_payloads(archives):
52 return _json_value({name: _archive_payload(archive)
for name, archive
in archives.items()})
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}))
69 raise ValueError(
"Iteration and evaluation counts must be nonnegative.")
75 """Capture archive measurements without running a renderer in the search.
77 :param directory: New or empty output directory.
78 :param every: Number of completed iterations between automatic captures.
81 def __init__(self, directory, *, every=10):
82 self.
every = index(every)
84 raise ValueError(
"every must be positive.")
86 self.
directory.mkdir(parents=
True, exist_ok=
True)
88 raise FileExistsError(f
"Archive history directory must be empty: {self.directory}")
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)
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:
106 path = _write_archive_frame(self.
directory, self.
_number, iteration, evaluations, payload)
112 def attach(self, algorithm, archives=None):
113 """Attach to an optimiser and return the recorder.
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.
120 raise ValueError(
"This recorder is already attached to an optimiser.")
124 return algo.container
125 return archives()
if callable(archives)
else archives
129 self.
capture(source(algo), iteration=0, evaluations=algo.nb_evaluations)
131 def periodic(algo, _elapsed):
134 self.
capture(source(algo), iteration=self.
_iteration, evaluations=algo.nb_evaluations)
136 def finished(algo, _elapsed):
137 self.
_capture(source(algo), self.
_iteration, algo.nb_evaluations, skip_duplicate=
True)
139 algorithm.add_callback(
"started_optimisation", started)
140 algorithm.add_callback(
"iteration", periodic)
141 algorithm.add_callback(
"finished_optimisation", finished)
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)]
152def _history_inputs(source):
153 if not isinstance(source, (str, PathLike)):
154 return [source]
if isinstance(source, ArchiveFrame)
else list(source)
156 if not path.is_dir():
158 recorded = _numbered_paths(path, _FRAME)
161 checkpoints = _numbered_paths(path, _ITERATION)
162 final = path /
"final.p"
164 checkpoints.append(final)
168def _pickle_frame(path, number):
169 saved = open_pickle_file(path)
171 if _is_archive(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):
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
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)
191def _read_frame(path, number, trusted_pickle):
192 if isinstance(path, ArchiveFrame):
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}.")
224def read_archive_history(source, *, trusted_pickle=False):
225 """Yield archive frames from a file, directory, or explicit sequence.
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.
231 :param source: History path or sequence of paths or ArchiveFrame objects.
232 :param trusted_pickle: Allow native Python checkpoints from trusted sources.
234 inputs = _history_inputs(source)
236 raise ValueError(
"No archive frames found.")
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)):
248def _evaluation_frames(source, trusted_pickle):
249 """Coalesce refits at the same budget and check that evaluation counts increase."""
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:
265def align_archive_histories(histories, *, trusted_pickle=False):
266 """Yield aligned frames from a mapping of run label to history source.
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.
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())
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()):
286 raise ValueError(
"The histories have no overlapping evaluation budgets.")
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()):
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)