# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Versioned experiment metadata and portable numeric grid snapshots.
"""Write or inspect results without loading Python objects from a pickle."""
from collections import Counter
from collections.abc import Mapping
from functools import partial
from hashlib import sha256
from importlib import metadata
import json
import math
import os
from pathlib import Path
import platform
import subprocess
import numpy as np
from qdpy import __version__
from qdpy.base import _atomic_output_path
from qdpy.containers import CVTGrid, Grid, ParetoGrid, SlidingBoundariesGrid, TDominOGrid
from qdpy.phenotype import Features, Fitness, Individual, ScoresDict, _CellIndividual
__all__ = ["export_grid", "load_grid", "grid_to_dataframe", "read_run_manifest", "write_run_manifest"]
_FORMAT_VERSION = 1
_GRID_TYPES = {kind.__name__: kind for kind in (Grid, CVTGrid, ParetoGrid, SlidingBoundariesGrid, TDominOGrid)}
_GRID_SETTINGS = {
"ParetoGrid": ("truncation",),
"SlidingBoundariesGrid": ("remap_frequency", "buffer_capacity"),
"TDominOGrid": ("anchor_capacity", "neighbor_radius"),
}
_FLOAT_KEY = "$qdpy_float"
_DEPENDENCIES = ("deprecation", "matplotlib", "numpy", "pandas", "psutil", "PyYAML",
"scikit-learn", "scipy", "sortedcollections", "typing_extensions",
"cma", "deap", "gymnasium", "ray", "tables", "torch")
## @brief Convert configuration to JSON, preserving iteration order and tagging nonfinite floats.
def _json_value(value):
if isinstance(value, np.generic):
value = value.item()
if value is None or isinstance(value, (bool, int, str)):
return value
if isinstance(value, float):
return value if math.isfinite(value) else {_FLOAT_KEY: str(value)}
if isinstance(value, Path):
return os.fspath(value)
if isinstance(value, Mapping):
if any(not isinstance(key, str) for key in value) or _FLOAT_KEY in value:
raise TypeError("Configuration keys must be strings and may not use the reserved float tag.")
return {key: _json_value(item) for key, item in value.items()}
if isinstance(value, np.ndarray):
return _json_value(value.tolist())
if isinstance(value, (list, tuple)):
return [_json_value(item) for item in value]
raise TypeError(f"Unsupported configuration value of type {type(value).__name__}.")
## @brief Decode reserved tags used for nonfinite configuration values and bounds.
def _decode_float(value):
if set(value) == {_FLOAT_KEY} and value[_FLOAT_KEY] in ("inf", "-inf", "nan"):
return float(value[_FLOAT_KEY])
return value
## @brief Encode a portable JSON document as UTF-8.
def _json_bytes(value):
return (json.dumps(value, allow_nan=False, ensure_ascii=False, indent=2) + "\n").encode()
## @brief Publish a complete file atomically on the output filesystem.
def _write(path, payload):
with _atomic_output_path(path) as temporary:
temporary.write_bytes(payload)
## @brief Preserve integer and floating point measurements without converting integer genomes.
def _numeric_row(values):
row = []
for value in values:
if isinstance(value, np.generic):
value = value.item()
if not isinstance(value, (int, float)) or isinstance(value, bool) or (
isinstance(value, float) and not math.isfinite(value)):
raise TypeError("Grid exports require finite real genomes, fitness values and descriptors.")
row.append(value)
return row
## @brief Record built-in grid geometry, admission settings, and live entries.
def _grid_snapshot(grid):
kind = type(grid).__name__
if _GRID_TYPES.get(kind) is not type(grid):
raise TypeError("Portable export supports fixed, CVT, Pareto, Sliding Boundaries and T-DominO grids.")
cells = {id(ind): cell for cell, entries in grid.solutions.items() for ind in entries}
entries = []
for ind in grid:
fitness = grid.get_ind_fitness(ind)
entries.append({
"cell": [int(i) for i in cells[id(ind)]],
"genome": _numeric_row(ind),
"fitness": _numeric_row(fitness.values),
"fitness_weights": _numeric_row(fitness.weights),
"descriptors": _numeric_row(grid.get_ind_features(ind)),
})
snapshot = {
"schema_version": _FORMAT_VERSION,
"archive_type": kind,
"shape": [int(size) for size in grid.shape],
"max_items_per_bin": int(grid.max_items_per_bin),
"fitness_domain": _json_value(grid.fitness_domain),
"descriptor_domain": _json_value(grid.features_domain),
"fitness_weights": _json_value(grid.fitness_weights),
"fitness_score_names": list(grid.fitness_score_names),
"descriptor_score_names": list(grid.features_score_names),
"centroids": _json_value(grid.cluster_centers) if type(grid) is CVTGrid else None,
"entries": entries,
}
if isinstance(grid, SlidingBoundariesGrid):
snapshot["bin_edges"] = _json_value(grid.bin_edges)
if kind in _GRID_SETTINGS:
snapshot["archive_settings"] = {
key: _json_value(value) for key in _GRID_SETTINGS[kind]
if (value := getattr(grid, key, None)) is not None
}
return snapshot
## @brief Write a numeric archive snapshot without pickle or estimator objects.
[docs]
def export_grid(grid, path):
"""Export a built-in grid and return its SHA-256 fingerprint.
Rows follow archive storage order. They contain the numeric genome,
effective fitness and descriptors, and the stored cell. A CVT file
includes centroid coordinates and a Sliding Boundaries file records
its current bin edges. Specialized grids include admission settings.
The snapshot is for inspection, comparison, and plotting. Custom
objects, historical offers, and optimiser state use other formats.
"""
payload = _json_bytes(_grid_snapshot(grid))
_write(path, payload)
return sha256(payload).hexdigest()
def _row(values):
if not isinstance(values, list):
raise ValueError("Expected a numeric list.")
return tuple(_numeric_row(values))
def _domains(values):
if not isinstance(values, list) or not values:
raise ValueError("Expected nonempty domain bounds.")
for interval in values:
if (not isinstance(interval, list) or len(interval) != 2
or any(type(x) not in (float, int) or math.isnan(x) for x in interval)
or interval[0] > interval[1]):
raise ValueError("Invalid domain interval.")
return tuple(map(tuple, values))
def _score_names(values, dimension):
if (not isinstance(values, list) or len(values) not in (0, dimension)
or any(not isinstance(name, str) for name in values)):
raise ValueError("Invalid named score fields.")
return tuple(values)
def _restore_geometry(kind, settings, snapshot):
centroids = snapshot["centroids"]
if kind == "CVTGrid":
if not isinstance(centroids, list):
raise ValueError("Missing CVT centroids.")
return CVTGrid(centroids=[_row(centre) for centre in centroids], **settings)
if centroids is not None:
raise ValueError("Rectangular grids cannot have CVT centroids.")
# Older Sliding Boundaries and T-DominO snapshots used the same schema
# but did not record constructor options.
options = snapshot.get("archive_settings", {})
if not isinstance(options, dict) or not options.keys() <= set(_GRID_SETTINGS.get(kind, ())):
raise ValueError("Invalid grid admission settings.")
if any(type(value) is not (str if key == "truncation" else int) for key, value in options.items()):
raise ValueError("Invalid grid admission setting value.")
if kind == "ParetoGrid":
fitness_names = settings.pop("fitness_score_names")
features_names = settings.pop("features_score_names")
grid = ParetoGrid(**settings, **options)
grid.fitness_score_names, grid.features_score_names = fitness_names, features_names
return grid
grid = _GRID_TYPES[kind](**settings, **options)
if kind == "SlidingBoundariesGrid":
edges = tuple(map(_row, snapshot["bin_edges"]))
if len(edges) != len(grid.shape) or any(
len(axis) != bins + 1 or axis[0] != low or axis[-1] != high
or any(a > b for a, b in zip(axis, axis[1:]))
for axis, bins, (low, high) in zip(edges, grid.shape, grid.features_domain)
):
raise ValueError("Invalid Sliding Boundaries bin edges.")
grid._edges = edges
return grid
def _restore_grid(snapshot):
"""Rebuild a portable archive in storage order, validating every admission."""
if (not isinstance(snapshot, dict) or type(snapshot.get("schema_version")) is not int
or snapshot["schema_version"] != _FORMAT_VERSION):
raise ValueError("Unsupported numeric archive version.")
archive_type = snapshot.get("archive_type")
if not isinstance(archive_type, str) or archive_type not in _GRID_TYPES:
raise ValueError("Unsupported portable grid type.")
try:
shape = snapshot["shape"]
depth = snapshot["max_items_per_bin"]
if (not isinstance(shape, list) or not shape
or any(type(size) is not int or size < 1 for size in shape)
or type(depth) is not int or depth < 1):
raise ValueError("Invalid archive shape or depth.")
fitness_domain = _domains(snapshot["fitness_domain"])
descriptors = _domains(snapshot["descriptor_domain"])
fitness_names = _score_names(snapshot["fitness_score_names"], len(fitness_domain))
descriptor_names = _score_names(snapshot["descriptor_score_names"], len(descriptors))
weights = snapshot["fitness_weights"]
if weights is not None:
weights = _row(weights)
if len(weights) != len(fitness_domain):
raise ValueError("Archive weights do not match the objective count.")
settings = dict(shape=shape, max_items_per_bin=depth, fitness_domain=fitness_domain,
features_domain=descriptors, fitness_score_names=fitness_names,
features_score_names=descriptor_names, fitness_weights=weights)
grid = _restore_geometry(archive_type, settings, snapshot)
entries = snapshot["entries"]
if not isinstance(entries, list):
raise ValueError("Expected a list of archive entries.")
genomes = [_row(row["genome"]) for row in entries]
repeats = Counter(genomes)
for row, genome in zip(entries, genomes):
fitness = _row(row["fitness"])
features = _row(row["descriptors"])
row_weights = _row(row["fitness_weights"])
if (len(fitness) != len(fitness_domain) or len(row_weights) != len(fitness)
or len(features) != len(descriptors)
or (weights is not None and weights != row_weights)):
raise ValueError("Invalid objective, descriptor, or weight dimensions.")
scores = ScoresDict()
for name, value in (*zip(fitness_names, fitness), *zip(descriptor_names, features)):
if scores.setdefault(name, value) != value:
raise ValueError("Conflicting values for a named score.")
cell = row["cell"]
if (not isinstance(cell, list) or any(type(axis) is not int for axis in cell)
or tuple(cell) != grid.index_grid(features)):
raise ValueError("Stored cell does not match the descriptor geometry.")
slot = tuple(cell)
measured = dict(fitness=Fitness(fitness, weights=row_weights), features=Features(features), scores=scores)
elite = (_CellIndividual(genome, slot, **measured) if repeats[genome] > 1
else Individual(genome, **measured))
effective = grid.get_ind_fitness(elite)
if tuple(effective.weights) != row_weights or len(grid.solutions[slot]) >= depth:
raise ValueError("Inconsistent entry weights or cell depth.")
before = len(grid)
if archive_type == "SlidingBoundariesGrid":
# A snapshot describes a completed remap. Reoffering the
# retained entries would update its edges and offer history.
grid._check_if_can_be_added(elite)
grid._add_to_grid(elite, slot, False)
else:
grid.add(elite)
if len(grid) != before + 1:
raise ValueError("Duplicate or rejected archive entry.")
return grid
except (KeyError, IndexError, TypeError, ValueError, OverflowError) as error:
raise ValueError(f"Invalid numeric archive: {error}") from error
## @brief Load a portable grid without executing serialized Python.
[docs]
def load_grid(path, *, expected_sha256=None):
"""Load a numeric archive from :func:`export_grid` or a run manifest.
Pass the manifest's archive SHA-256 to verify the file before parsing.
The archive owns newly created individuals and preserves storage order,
geometry, effective named scores and fitness weights. Offer history,
T-DominO anchors, and custom candidate attributes are outside the
portable format. Use a checkpoint for exact continuation.
"""
payload = Path(path).read_bytes()
if expected_sha256 is not None and sha256(payload).hexdigest() != expected_sha256:
raise ValueError("Archive SHA-256 does not match.")
try:
snapshot = json.loads(payload, object_hook=_decode_float)
except (UnicodeError, ValueError, TypeError) as error:
raise ValueError("Invalid numeric archive JSON.") from error
return _restore_grid(snapshot)
## @brief Expose archive rows and geometry to pandas.
[docs]
def grid_to_dataframe(grid):
"""Return an independent DataFrame of numeric elite records in storage order.
The columns are ``cell``, ``genome``, ``fitness``, ``fitness_weights``
and ``descriptors``. Each stores a tuple per elite. The DataFrame's
``attrs`` hold the snapshot header, including the descriptor bounds,
named score order and any CVT centroids.
"""
import pandas as pd
snapshot = _grid_snapshot(grid)
entries = snapshot.pop("entries")
columns = ("cell", "genome", "fitness", "fitness_weights", "descriptors")
frame = pd.DataFrame.from_records(
(tuple(tuple(row[name]) for name in columns) for row in entries), columns=columns,
)
frame.attrs.update(snapshot)
return frame
## @brief Record the installed versions relevant to QDpy and its integrations.
def _installed_versions():
versions = {}
for name in _DEPENDENCIES:
try:
versions[name] = metadata.version(name)
except metadata.PackageNotFoundError:
pass
return versions
## @brief Resolve the source revision for a checkout, VCS install or stamped build.
def _source_revision():
override = os.environ.get("QDPY_SOURCE_REVISION")
if override:
return {"commit": override, "source": "environment", "tracked_changes": None}
try:
from qdpy._build_info import SOURCE_REVISION
except ImportError:
pass
else:
return {"commit": SOURCE_REVISION, "source": "build", "tracked_changes": False}
root = Path(__file__).resolve().parents[1]
if (root / ".git").exists():
def git(*arguments):
return subprocess.run(
["git", "-C", os.fspath(root), *arguments], capture_output=True, text=True,
check=True, timeout=2,
).stdout.strip()
try:
return {"commit": git("rev-parse", "HEAD"), "source": "checkout",
"tracked_changes": bool(git("status", "--porcelain", "--untracked-files=no"))}
except (OSError, subprocess.SubprocessError):
pass
try:
direct_url = metadata.distribution("qdpy").read_text("direct_url.json")
commit = json.loads(direct_url or "{}").get("vcs_info", {}).get("commit_id")
except (AttributeError, OSError, ValueError, metadata.PackageNotFoundError):
commit = None
return {"commit": commit, "source": "vcs_install" if commit else None, "tracked_changes": None}
## @brief Identify an evaluator and retain positional and keyword bindings of partials.
def _evaluator_info(evaluate):
def name(function):
kind = type(function)
return f"{getattr(function, '__module__', kind.__module__)}.{getattr(function, '__qualname__', kind.__qualname__)}"
def argument(value):
return {"callable": name(value)} if callable(value) else _json_value(value)
bindings = {}
function = evaluate
if isinstance(evaluate, partial):
function = evaluate.func
try:
bindings = {"args": [argument(value) for value in evaluate.args],
"kwargs": {key: argument(value) for key, value in evaluate.keywords.items()}}
except (TypeError, RecursionError):
bindings = None
return {"name": name(function), "bindings": bindings}
## @brief Read a versioned manifest and restore tagged values.
[docs]
def read_run_manifest(path):
"""Read JSON result metadata, checking the schema version."""
with Path(path).open(encoding="utf-8") as file:
manifest = json.load(file, object_hook=_decode_float)
if not isinstance(manifest, dict) or manifest.get("schema_version") != _FORMAT_VERSION:
raise ValueError("Unsupported QDpy run manifest version.")
return manifest
## @brief Write run metadata and, when supported, a content-addressed grid result.
[docs]
def write_run_manifest(path, algorithm, *, configuration, evaluate, execution,
initial_evaluations=0, final_pickle=None, bundle=None):
"""Publish a manifest for the search's current evaluation count.
Supply the resolved configuration and execution settings. When
reusing an optimiser, pass its initial evaluation count to report
only attempts from this run. A built-in numeric grid gets a sibling
JSON export. Unsupported archive and configuration values are
recorded with a reason. Sweep reports mark a run as incomplete until
its attempted count reaches the configured budget. An optional
``bundle`` includes portable artifact links and their checksums.
"""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
configuration_error = None
seed = None
try:
if isinstance(configuration, Mapping):
seed = _json_value(configuration.get("seed"))
resolved = _json_value(configuration)
except (TypeError, RecursionError) as error:
resolved, configuration_error = None, str(error)
grid = algorithm.container
try:
archive_bytes = _json_bytes(_grid_snapshot(grid))
except TypeError as error:
archive = {"type": type(grid).__name__, "size": len(grid), "export_error": str(error)}
else:
digest = sha256(archive_bytes).hexdigest()
name = f"archive-{digest}.json"
_write(path.parent / name, archive_bytes)
archive = {"type": type(grid).__name__, "size": len(grid), "file": name, "sha256": digest}
manifest = {
"schema_version": _FORMAT_VERSION,
"qdpy_version": __version__,
"revision": _source_revision(),
"python": {"version": platform.python_version(), "implementation": platform.python_implementation()},
"platform": {"system": platform.system(), "machine": platform.machine()},
"dependencies": _installed_versions(),
"seed": seed,
"configuration": resolved,
"configuration_error": configuration_error,
"algorithm": type(algorithm).__name__,
"evaluation": {
"budget": _json_value(algorithm.budget),
"attempted": int(algorithm.nb_evaluations) - initial_evaluations,
"initial_count": initial_evaluations, "evaluator": _evaluator_info(evaluate),
"execution": _json_value(execution),
},
"archive": archive,
"final_pickle": Path(final_pickle).name if final_pickle else None,
}
if bundle is not None:
manifest["bundle"] = _json_value(bundle)
_write(path, _json_bytes(manifest))