Source code for qdpy._archive_history

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Record archive measurements and replay native QDpy results.

"""Portable histories for archive visualization."""

from collections.abc import Mapping
from dataclasses import dataclass
from hashlib import sha256
import json
from operator import index
from os import PathLike
from pathlib import Path
import re

from ._archive_data import _archive_data, _is_archive, _named_data
from .results import _decode_float, _json_bytes, _json_value, _write
from .tools import open_pickle_file

__all__ = ["ArchiveFrame", "ArchiveRecorder", "read_archive_history", "align_archive_histories"]

_FRAME = re.compile(r"frame-(\d+)\.json")
_ITERATION = re.compile(r"iteration-(\d+)\.(?:p|pkl|pickle)")


## @brief A set of archive measurements captured at a search boundary.
[docs] @dataclass(frozen=True) class ArchiveFrame: """A numbered archive snapshot with optional iteration and attempt counts.""" number: int archives: dict iteration: int | None = None evaluations: int | None = None
def _archive_payload(archive): kind = "CVTGrid" if archive.centroids else ("Grid" if archive.shape else "points") return { "schema_version": 1, "archive_type": kind, "descriptor_domain": archive.descriptor_domain, "fitness_domain": archive.fitness_domain, "shape": archive.shape, "centroids": archive.centroids, **({"bin_edges": archive.bin_edges} if archive.bin_edges else {}), "entries": [{"cell": entry.cell, "descriptors": entry.descriptors, "fitness": entry.fitness, "fitness_weights": entry.fitness_weights} for entry in archive.entries], "activity": archive.activity, } def _archive_payloads(archives): return _json_value({name: _archive_payload(archive) for name, archive in archives.items()}) def _write_archive_frame(directory, number, iteration, evaluations, payload): path = directory / f"frame-{number:06d}.json" if path.exists() or path.is_symlink(): raise FileExistsError(path) _write(path, _json_bytes({"qdpy_archive_frame": 1, "number": number, "iteration": iteration, "evaluations": evaluations, "archives": payload})) return path def _count(value): if value is None: return None count = index(value) if count < 0: raise ValueError("Iteration and evaluation counts must be nonnegative.") return count ## @brief Write plot-ready archive frames during an optimisation.
[docs] class ArchiveRecorder: """Capture archive measurements without running a renderer in the search. :param directory: New or empty output directory. :param every: Number of completed iterations between automatic captures. """ def __init__(self, directory, *, every=10): self.every = index(every) if self.every < 1: raise ValueError("every must be positive.") self.directory = Path(directory) self.directory.mkdir(parents=True, exist_ok=True) if any(self.directory.iterdir()): raise FileExistsError(f"Archive history directory must be empty: {self.directory}") self._number = 0 self._iteration = 0 self._last = None self._attached = False ## @brief Write one frame from a live archive or a collection of archives.
[docs] def capture(self, archives, *, iteration=None, evaluations=None): """Write an archive frame and return its JSON path.""" return self._capture(archives, iteration, evaluations, skip_duplicate=False)
def _capture(self, archives, iteration, evaluations, *, skip_duplicate): iteration, evaluations = _count(iteration), _count(evaluations) payload = _archive_payloads(_named_data(archives)) digest = sha256(_json_bytes(payload)).digest() state = evaluations, digest if skip_duplicate and state == self._last: return None path = _write_archive_frame(self.directory, self._number, iteration, evaluations, payload) self._number += 1 self._last = state return path ## @brief Attach initial, periodic and final captures to a native optimiser.
[docs] def attach(self, algorithm, archives=None): """Attach to an optimiser and return the recorder. Supply an archive mapping or a callable returning the archives at capture time. By default, record the optimiser's current container under one stable label. Attach after callbacks that update archives. """ if self._attached: raise ValueError("This recorder is already attached to an optimiser.") def source(algo): if archives is None: return algo.container return archives() if callable(archives) else archives def started(algo): self._iteration = 0 self.capture(source(algo), iteration=0, evaluations=algo.nb_evaluations) def periodic(algo, _elapsed): self._iteration += 1 if self._iteration % self.every == 0: self.capture(source(algo), iteration=self._iteration, evaluations=algo.nb_evaluations) def finished(algo, _elapsed): self._capture(source(algo), self._iteration, algo.nb_evaluations, skip_duplicate=True) algorithm.add_callback("started_optimisation", started) algorithm.add_callback("iteration", periodic) algorithm.add_callback("finished_optimisation", finished) self._attached = True return self
def _numbered_paths(directory, pattern): matches = [(int(match[1]), path.name, path) for path in directory.iterdir() if path.is_file() and (match := pattern.fullmatch(path.name))] return [path for _, _, path in sorted(matches)] def _history_inputs(source): if not isinstance(source, (str, PathLike)): return [source] if isinstance(source, ArchiveFrame) else list(source) path = Path(source) if not path.is_dir(): return [path] recorded = _numbered_paths(path, _FRAME) if recorded: return recorded checkpoints = _numbered_paths(path, _ITERATION) final = path / "final.p" if final.is_file(): checkpoints.append(final) return checkpoints def _pickle_frame(path, number): saved = open_pickle_file(path) evaluations = None if _is_archive(saved): archives = saved elif isinstance(saved, Mapping) and _is_archive(saved.get("container")): archives = saved["container"] evaluations = _count(saved.get("nb_evaluations")) elif isinstance(saved, Mapping) and isinstance(saved.get("archives"), (Mapping, list, tuple)): archives = saved["archives"] evaluations = _count(saved.get("nb_evaluations")) elif isinstance(saved, Mapping): archives = {} for name, value in saved.items(): candidate = getattr(value, "container", value) if _is_archive(candidate) and not isinstance(candidate, (str, PathLike)): archives[name] = candidate else: raise ValueError(f"No supported archive in {path}.") match = _ITERATION.fullmatch(path.name) return ArchiveFrame(number, _named_data(archives), int(match[1]) if match else None, evaluations) def _read_frame(path, number, trusted_pickle): if isinstance(path, ArchiveFrame): return path path = Path(path) if path.suffix.lower() in (".p", ".pkl", ".pickle"): if not trusted_pickle: raise ValueError("Set trusted_pickle=True only for a trusted QDpy checkpoint.") return _pickle_frame(path, number) with path.open(encoding="utf-8") as file: payload = json.load(file, object_hook=_decode_float) if not isinstance(payload, Mapping): raise ValueError(f"Expected an archive object in {path}.") if "qdpy_archive_frame" in payload: if payload["qdpy_archive_frame"] != 1: raise ValueError(f"Unsupported archive frame version in {path}.") return ArchiveFrame(_count(payload["number"]), _named_data(payload["archives"]), _count(payload.get("iteration")), _count(payload.get("evaluations"))) if "archive_type" in payload: return ArchiveFrame(number, {"Archive": _archive_data(payload)}) if "archive" in payload and "evaluation" in payload: reference = payload["archive"] name = reference.get("file") if not name or name != Path(name).name or (path.parent / name).resolve().parent != path.parent.resolve(): raise ValueError(f"Run manifest has no local numeric archive snapshot: {path}.") raw = (path.parent / name).read_bytes() if sha256(raw).hexdigest() != reference.get("sha256"): raise ValueError(f"Archive fingerprint does not match {path}.") archive = _archive_data(json.loads(raw, object_hook=_decode_float)) return ArchiveFrame(number, {"Archive": archive}, evaluations=_count(payload["evaluation"].get("attempted"))) raise ValueError(f"No supported archive in {path}.") ## @brief Read recorded frames or trusted historical checkpoints in time order.
[docs] def read_archive_history(source, *, trusted_pickle=False): """Yield archive frames from a file, directory, or explicit sequence. A directory uses recorded JSON frames when present. Native iteration pickles follow numeric order and a distinct final checkpoint follows them. Explicit sequences retain the caller's order. :param source: History path or sequence of paths or ArchiveFrame objects. :param trusted_pickle: Allow native Python checkpoints from trusted sources. """ inputs = _history_inputs(source) if not inputs: raise ValueError("No archive frames found.") previous = None for number, path in enumerate(inputs): frame = _read_frame(path, number, trusted_pickle) if (previous is not None and isinstance(path, (str, PathLike)) and Path(path).name == "final.p" and frame.evaluations == previous.evaluations and _archive_payloads(frame.archives) == _archive_payloads(previous.archives)): continue yield frame previous = frame
def _evaluation_frames(source, trusted_pickle): """Coalesce refits at the same budget and check that evaluation counts increase.""" prior = None for frame in read_archive_history(source, trusted_pickle=trusted_pickle): if frame.evaluations is None: raise ValueError("Budget alignment needs evaluation counts on every frame.") _count(frame.evaluations) if prior is not None: if frame.evaluations < prior.evaluations: raise ValueError("History evaluation counts must be nondecreasing.") if frame.evaluations > prior.evaluations: yield prior prior = frame yield prior ## @brief Align named runs using the latest observed archive at each shared budget.
[docs] def align_archive_histories(histories, *, trusted_pickle=False): """Yield aligned frames from a mapping of run label to history source. The timeline uses the union of recorded budgets within the overlap of all runs. Each panel shows the latest snapshot at or before the current budget. Named archives keep their labels with the run name prefixed. """ if not isinstance(histories, Mapping) or not histories: raise ValueError("Provide a mapping of run labels to their histories.") streams = {label: iter(_evaluation_frames(source, trusted_pickle)) for label, source in histories.items()} current = {label: next(stream) for label, stream in streams.items()} pending = {label: next(stream, None) for label, stream in streams.items()} budget = max(frame.evaluations for frame in current.values()) number = 0 while True: for label, stream in streams.items(): while pending[label] is not None and pending[label].evaluations <= budget: current[label] = pending[label] pending[label] = next(stream, None) if any(pending[label] is None and frame.evaluations < budget for label, frame in current.items()): if number == 0: raise ValueError("The histories have no overlapping evaluation budgets.") return archives = {} for label, frame in current.items(): panels = _named_data(frame.archives) for name, archive in panels.items(): panel = str(label) if name == "Archive" else f"{label} / {name}" if panel in archives: raise ValueError(f"Aligned panel label {panel!r} is ambiguous.") archives[panel] = archive yield ArchiveFrame(number, archives, evaluations=budget) if any(frame is None for frame in pending.values()): return number += 1 budget = min(frame.evaluations for frame in pending.values())