5"""Write or inspect results without loading Python objects from a pickle."""
7from collections
import Counter
8from collections.abc
import Mapping
9from functools
import partial
10from hashlib
import sha256
11from importlib
import metadata
15from pathlib
import Path
21from qdpy
import __version__
23from qdpy.containers import CVTGrid, Grid, ParetoGrid, SlidingBoundariesGrid, TDominOGrid
24from qdpy.phenotype import Features, Fitness, Individual, ScoresDict, _CellIndividual
26__all__ = [
"export_grid",
"load_grid",
"grid_to_dataframe",
"read_run_manifest",
"write_run_manifest"]
29_GRID_TYPES = {kind.__name__: kind
for kind
in (Grid, CVTGrid, ParetoGrid, SlidingBoundariesGrid, TDominOGrid)}
31 "ParetoGrid": (
"truncation",),
32 "SlidingBoundariesGrid": (
"remap_frequency",
"buffer_capacity"),
33 "TDominOGrid": (
"anchor_capacity",
"neighbor_radius"),
35_FLOAT_KEY =
"$qdpy_float"
36_DEPENDENCIES = (
"deprecation",
"matplotlib",
"numpy",
"pandas",
"psutil",
"PyYAML",
37 "scikit-learn",
"scipy",
"sortedcollections",
"typing_extensions",
38 "cma",
"deap",
"gymnasium",
"ray",
"tables",
"torch")
42def _json_value(value):
43 if isinstance(value, np.generic):
45 if value
is None or isinstance(value, (bool, int, str)):
47 if isinstance(value, float):
48 return value
if math.isfinite(value)
else {_FLOAT_KEY: str(value)}
49 if isinstance(value, Path):
50 return os.fspath(value)
51 if isinstance(value, Mapping):
52 if any(
not isinstance(key, str)
for key
in value)
or _FLOAT_KEY
in value:
53 raise TypeError(
"Configuration keys must be strings and may not use the reserved float tag.")
54 return {key: _json_value(item)
for key, item
in value.items()}
55 if isinstance(value, np.ndarray):
56 return _json_value(value.tolist())
57 if isinstance(value, (list, tuple)):
58 return [_json_value(item)
for item
in value]
59 raise TypeError(f
"Unsupported configuration value of type {type(value).__name__}.")
63def _decode_float(value):
64 if set(value) == {_FLOAT_KEY}
and value[_FLOAT_KEY]
in (
"inf",
"-inf",
"nan"):
65 return float(value[_FLOAT_KEY])
70def _json_bytes(value):
71 return (json.dumps(value, allow_nan=
False, ensure_ascii=
False, indent=2) +
"\n").encode()
75def _write(path, payload):
76 with _atomic_output_path(path)
as temporary:
77 temporary.write_bytes(payload)
81def _numeric_row(values):
84 if isinstance(value, np.generic):
86 if not isinstance(value, (int, float))
or isinstance(value, bool)
or (
87 isinstance(value, float)
and not math.isfinite(value)):
88 raise TypeError(
"Grid exports require finite real genomes, fitness values and descriptors.")
94def _grid_snapshot(grid):
95 kind = type(grid).__name__
96 if _GRID_TYPES.get(kind)
is not type(grid):
97 raise TypeError(
"Portable export supports fixed, CVT, Pareto, Sliding Boundaries and T-DominO grids.")
98 cells = {id(ind): cell
for cell, entries
in grid.solutions.items()
for ind
in entries}
101 fitness = grid.get_ind_fitness(ind)
103 "cell": [int(i)
for i
in cells[id(ind)]],
104 "genome": _numeric_row(ind),
105 "fitness": _numeric_row(fitness.values),
106 "fitness_weights": _numeric_row(fitness.weights),
107 "descriptors": _numeric_row(grid.get_ind_features(ind)),
110 "schema_version": _FORMAT_VERSION,
111 "archive_type": kind,
112 "shape": [int(size)
for size
in grid.shape],
113 "max_items_per_bin": int(grid.max_items_per_bin),
114 "fitness_domain": _json_value(grid.fitness_domain),
115 "descriptor_domain": _json_value(grid.features_domain),
116 "fitness_weights": _json_value(grid.fitness_weights),
117 "fitness_score_names": list(grid.fitness_score_names),
118 "descriptor_score_names": list(grid.features_score_names),
119 "centroids": _json_value(grid.cluster_centers)
if type(grid)
is CVTGrid
else None,
122 if isinstance(grid, SlidingBoundariesGrid):
123 snapshot[
"bin_edges"] = _json_value(grid.bin_edges)
124 if kind
in _GRID_SETTINGS:
125 snapshot[
"archive_settings"] = {
126 key: _json_value(value)
for key
in _GRID_SETTINGS[kind]
127 if (value := getattr(grid, key,
None))
is not None
133def export_grid(grid, path):
134 """Export a built-in grid and return its SHA-256 fingerprint.
136 Rows follow archive storage order. They contain the numeric genome,
137 effective fitness and descriptors, and the stored cell. A CVT file
138 includes centroid coordinates and a Sliding Boundaries file records
139 its current bin edges. Specialized grids include admission settings.
140 The snapshot is for inspection, comparison, and plotting. Custom
141 objects, historical offers, and optimiser state use other formats.
143 payload = _json_bytes(_grid_snapshot(grid))
144 _write(path, payload)
145 return sha256(payload).hexdigest()
149 if not isinstance(values, list):
150 raise ValueError(
"Expected a numeric list.")
151 return tuple(_numeric_row(values))
155 if not isinstance(values, list)
or not values:
156 raise ValueError(
"Expected nonempty domain bounds.")
157 for interval
in values:
158 if (
not isinstance(interval, list)
or len(interval) != 2
159 or any(type(x)
not in (float, int)
or math.isnan(x)
for x
in interval)
160 or interval[0] > interval[1]):
161 raise ValueError(
"Invalid domain interval.")
162 return tuple(map(tuple, values))
165def _score_names(values, dimension):
166 if (
not isinstance(values, list)
or len(values)
not in (0, dimension)
167 or any(
not isinstance(name, str)
for name
in values)):
168 raise ValueError(
"Invalid named score fields.")
172def _restore_geometry(kind, settings, snapshot):
173 centroids = snapshot[
"centroids"]
174 if kind ==
"CVTGrid":
175 if not isinstance(centroids, list):
176 raise ValueError(
"Missing CVT centroids.")
177 return CVTGrid(centroids=[_row(centre)
for centre
in centroids], **settings)
178 if centroids
is not None:
179 raise ValueError(
"Rectangular grids cannot have CVT centroids.")
183 options = snapshot.get(
"archive_settings", {})
184 if not isinstance(options, dict)
or not options.keys() <= set(_GRID_SETTINGS.get(kind, ())):
185 raise ValueError(
"Invalid grid admission settings.")
186 if any(type(value)
is not (str
if key ==
"truncation" else int)
for key, value
in options.items()):
187 raise ValueError(
"Invalid grid admission setting value.")
188 if kind ==
"ParetoGrid":
189 fitness_names = settings.pop(
"fitness_score_names")
190 features_names = settings.pop(
"features_score_names")
191 grid = ParetoGrid(**settings, **options)
192 grid.fitness_score_names, grid.features_score_names = fitness_names, features_names
195 grid = _GRID_TYPES[kind](**settings, **options)
196 if kind ==
"SlidingBoundariesGrid":
197 edges = tuple(map(_row, snapshot[
"bin_edges"]))
198 if len(edges) != len(grid.shape)
or any(
199 len(axis) != bins + 1
or axis[0] != low
or axis[-1] != high
200 or any(a > b
for a, b
in zip(axis, axis[1:]))
201 for axis, bins, (low, high)
in zip(edges, grid.shape, grid.features_domain)
203 raise ValueError(
"Invalid Sliding Boundaries bin edges.")
208def _restore_grid(snapshot):
209 """Rebuild a portable archive in storage order, validating every admission."""
210 if (
not isinstance(snapshot, dict)
or type(snapshot.get(
"schema_version"))
is not int
211 or snapshot[
"schema_version"] != _FORMAT_VERSION):
212 raise ValueError(
"Unsupported numeric archive version.")
213 archive_type = snapshot.get(
"archive_type")
214 if not isinstance(archive_type, str)
or archive_type
not in _GRID_TYPES:
215 raise ValueError(
"Unsupported portable grid type.")
217 shape = snapshot[
"shape"]
218 depth = snapshot[
"max_items_per_bin"]
219 if (
not isinstance(shape, list)
or not shape
220 or any(type(size)
is not int
or size < 1
for size
in shape)
221 or type(depth)
is not int
or depth < 1):
222 raise ValueError(
"Invalid archive shape or depth.")
223 fitness_domain = _domains(snapshot[
"fitness_domain"])
224 descriptors = _domains(snapshot[
"descriptor_domain"])
225 fitness_names = _score_names(snapshot[
"fitness_score_names"], len(fitness_domain))
226 descriptor_names = _score_names(snapshot[
"descriptor_score_names"], len(descriptors))
227 weights = snapshot[
"fitness_weights"]
228 if weights
is not None:
229 weights = _row(weights)
230 if len(weights) != len(fitness_domain):
231 raise ValueError(
"Archive weights do not match the objective count.")
232 settings = dict(shape=shape, max_items_per_bin=depth, fitness_domain=fitness_domain,
233 features_domain=descriptors, fitness_score_names=fitness_names,
234 features_score_names=descriptor_names, fitness_weights=weights)
235 grid = _restore_geometry(archive_type, settings, snapshot)
236 entries = snapshot[
"entries"]
237 if not isinstance(entries, list):
238 raise ValueError(
"Expected a list of archive entries.")
239 genomes = [_row(row[
"genome"])
for row
in entries]
240 repeats = Counter(genomes)
241 for row, genome
in zip(entries, genomes):
242 fitness = _row(row[
"fitness"])
243 features = _row(row[
"descriptors"])
244 row_weights = _row(row[
"fitness_weights"])
245 if (len(fitness) != len(fitness_domain)
or len(row_weights) != len(fitness)
246 or len(features) != len(descriptors)
247 or (weights
is not None and weights != row_weights)):
248 raise ValueError(
"Invalid objective, descriptor, or weight dimensions.")
249 scores = ScoresDict()
250 for name, value
in (*zip(fitness_names, fitness), *zip(descriptor_names, features)):
251 if scores.setdefault(name, value) != value:
252 raise ValueError(
"Conflicting values for a named score.")
254 if (
not isinstance(cell, list)
or any(type(axis)
is not int
for axis
in cell)
255 or tuple(cell) != grid.index_grid(features)):
256 raise ValueError(
"Stored cell does not match the descriptor geometry.")
258 measured = dict(fitness=Fitness(fitness, weights=row_weights), features=Features(features), scores=scores)
259 elite = (_CellIndividual(genome, slot, **measured)
if repeats[genome] > 1
260 else Individual(genome, **measured))
261 effective = grid.get_ind_fitness(elite)
262 if tuple(effective.weights) != row_weights
or len(grid.solutions[slot]) >= depth:
263 raise ValueError(
"Inconsistent entry weights or cell depth.")
265 if archive_type ==
"SlidingBoundariesGrid":
268 grid._check_if_can_be_added(elite)
269 grid._add_to_grid(elite, slot,
False)
272 if len(grid) != before + 1:
273 raise ValueError(
"Duplicate or rejected archive entry.")
275 except (KeyError, IndexError, TypeError, ValueError, OverflowError)
as error:
276 raise ValueError(f
"Invalid numeric archive: {error}")
from error
280def load_grid(path, *, expected_sha256=None):
281 """Load a numeric archive from :func:`export_grid` or a run manifest.
283 Pass the manifest's archive SHA-256 to verify the file before parsing.
284 The archive owns newly created individuals and preserves storage order,
285 geometry, effective named scores and fitness weights. Offer history,
286 T-DominO anchors, and custom candidate attributes are outside the
287 portable format. Use a checkpoint for exact continuation.
289 payload = Path(path).read_bytes()
290 if expected_sha256
is not None and sha256(payload).hexdigest() != expected_sha256:
291 raise ValueError(
"Archive SHA-256 does not match.")
293 snapshot = json.loads(payload, object_hook=_decode_float)
294 except (UnicodeError, ValueError, TypeError)
as error:
295 raise ValueError(
"Invalid numeric archive JSON.")
from error
296 return _restore_grid(snapshot)
300def grid_to_dataframe(grid):
301 """Return an independent DataFrame of numeric elite records in storage order.
303 The columns are ``cell``, ``genome``, ``fitness``, ``fitness_weights``
304 and ``descriptors``. Each stores a tuple per elite. The DataFrame's
305 ``attrs`` hold the snapshot header, including the descriptor bounds,
306 named score order and any CVT centroids.
310 snapshot = _grid_snapshot(grid)
311 entries = snapshot.pop(
"entries")
312 columns = (
"cell",
"genome",
"fitness",
"fitness_weights",
"descriptors")
313 frame = pd.DataFrame.from_records(
314 (tuple(tuple(row[name])
for name
in columns)
for row
in entries), columns=columns,
316 frame.attrs.update(snapshot)
321def _installed_versions():
323 for name
in _DEPENDENCIES:
325 versions[name] = metadata.version(name)
326 except metadata.PackageNotFoundError:
332def _source_revision():
333 override = os.environ.get(
"QDPY_SOURCE_REVISION")
335 return {
"commit": override,
"source":
"environment",
"tracked_changes":
None}
337 from qdpy._build_info
import SOURCE_REVISION
341 return {
"commit": SOURCE_REVISION,
"source":
"build",
"tracked_changes":
False}
343 root = Path(__file__).resolve().parents[1]
344 if (root /
".git").exists():
346 return subprocess.run(
347 [
"git",
"-C", os.fspath(root), *arguments], capture_output=
True, text=
True,
348 check=
True, timeout=2,
352 return {
"commit": git(
"rev-parse",
"HEAD"),
"source":
"checkout",
353 "tracked_changes": bool(git(
"status",
"--porcelain",
"--untracked-files=no"))}
354 except (OSError, subprocess.SubprocessError):
357 direct_url = metadata.distribution(
"qdpy").read_text(
"direct_url.json")
358 commit = json.loads(direct_url
or "{}").get(
"vcs_info", {}).get(
"commit_id")
359 except (AttributeError, OSError, ValueError, metadata.PackageNotFoundError):
361 return {
"commit": commit,
"source":
"vcs_install" if commit
else None,
"tracked_changes":
None}
365def _evaluator_info(evaluate):
367 kind = type(function)
368 return f
"{getattr(function, '__module__', kind.__module__)}.{getattr(function, '__qualname__', kind.__qualname__)}"
371 return {
"callable": name(value)}
if callable(value)
else _json_value(value)
375 if isinstance(evaluate, partial):
376 function = evaluate.func
378 bindings = {
"args": [argument(value)
for value
in evaluate.args],
379 "kwargs": {key: argument(value)
for key, value
in evaluate.keywords.items()}}
380 except (TypeError, RecursionError):
382 return {
"name": name(function),
"bindings": bindings}
386def read_run_manifest(path):
387 """Read JSON result metadata, checking the schema version."""
388 with Path(path).open(encoding=
"utf-8")
as file:
389 manifest = json.load(file, object_hook=_decode_float)
390 if not isinstance(manifest, dict)
or manifest.get(
"schema_version") != _FORMAT_VERSION:
391 raise ValueError(
"Unsupported QDpy run manifest version.")
396def write_run_manifest(path, algorithm, *, configuration, evaluate, execution,
397 initial_evaluations=0, final_pickle=None, bundle=None):
398 """Publish a manifest for the search's current evaluation count.
400 Supply the resolved configuration and execution settings. When
401 reusing an optimiser, pass its initial evaluation count to report
402 only attempts from this run. A built-in numeric grid gets a sibling
403 JSON export. Unsupported archive and configuration values are
404 recorded with a reason. Sweep reports mark a run as incomplete until
405 its attempted count reaches the configured budget. An optional
406 ``bundle`` includes portable artifact links and their checksums.
409 path.parent.mkdir(parents=
True, exist_ok=
True)
410 configuration_error =
None
413 if isinstance(configuration, Mapping):
414 seed = _json_value(configuration.get(
"seed"))
415 resolved = _json_value(configuration)
416 except (TypeError, RecursionError)
as error:
417 resolved, configuration_error =
None, str(error)
418 grid = algorithm.container
420 archive_bytes = _json_bytes(_grid_snapshot(grid))
421 except TypeError
as error:
422 archive = {
"type": type(grid).__name__,
"size": len(grid),
"export_error": str(error)}
424 digest = sha256(archive_bytes).hexdigest()
425 name = f
"archive-{digest}.json"
426 _write(path.parent / name, archive_bytes)
427 archive = {
"type": type(grid).__name__,
"size": len(grid),
"file": name,
"sha256": digest}
430 "schema_version": _FORMAT_VERSION,
431 "qdpy_version": __version__,
432 "revision": _source_revision(),
433 "python": {
"version": platform.python_version(),
"implementation": platform.python_implementation()},
434 "platform": {
"system": platform.system(),
"machine": platform.machine()},
435 "dependencies": _installed_versions(),
437 "configuration": resolved,
438 "configuration_error": configuration_error,
439 "algorithm": type(algorithm).__name__,
441 "budget": _json_value(algorithm.budget),
442 "attempted": int(algorithm.nb_evaluations) - initial_evaluations,
443 "initial_count": initial_evaluations,
"evaluator": _evaluator_info(evaluate),
444 "execution": _json_value(execution),
447 "final_pickle": Path(final_pickle).name
if final_pickle
else None,
449 if bundle
is not None:
450 manifest[
"bundle"] = _json_value(bundle)
451 _write(path, _json_bytes(manifest))