QDpy
Loading...
Searching...
No Matches
_archive_data.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Read archive measurements without storing genomes or estimator state."""
6
7from collections.abc import Mapping
8from dataclasses import dataclass
9import json
10from os import PathLike
11from pathlib import Path
12
13import numpy as np
14
15from .containers.base import ContainerDecorator
16from .containers.grids import CVTGrid, Grid
17from .results import _decode_float
18
19_RECTANGULAR_TYPES = ("Grid", "ParetoGrid", "SlidingBoundariesGrid", "TDominOGrid")
20_ARCHIVE_TYPES = (*_RECTANGULAR_TYPES, "CVTGrid", "points")
21
22@dataclass(frozen=True)
23class _Entry:
24 cell: tuple | None
25 descriptors: tuple
26 fitness: tuple
27 fitness_weights: tuple
28
29
30@dataclass(frozen=True)
32 """Snapshot of descriptor geometry, measurements and cell activity."""
33
34 descriptor_domain: tuple
35 fitness_domain: tuple
36 shape: tuple
37 centroids: tuple
38 entries: tuple
39 activity: tuple | None
40 bin_edges: tuple = ()
41
42 @property
43 def dimension(self):
44 return len(self.descriptor_domain) or (len(self.entries[0].descriptors) if self.entries else 0)
45
46
47def _rows(values):
48 return tuple(tuple(float(_decode_float(x) if isinstance(x, Mapping) else x)
49 for x in row) for row in values) if values is not None else ()
50
51
52def _is_archive(source):
53 return (isinstance(source, (_ArchiveData, str, PathLike))
54 or (isinstance(source, Mapping) and "schema_version" in source
55 and source.get("archive_type") in _ARCHIVE_TYPES)
56 or (callable(getattr(source, "get_ind_features", None))
57 and callable(getattr(source, "get_ind_fitness", None))))
58
59
60def _parse_archive(payload):
61 if payload.get("schema_version") != 1 or payload.get("archive_type") not in _ARCHIVE_TYPES:
62 raise ValueError("Expected a QDpy archive export or plotting snapshot.")
63 shape = tuple(payload["shape"])
64 bounds = _rows(payload["descriptor_domain"])
65 centres = _rows(payload.get("centroids"))
66 edges = _rows(payload.get("bin_edges"))
67 if (any(type(n) is not int or n < 1 for n in shape)
68 or any(len(interval) != 2 or interval[0] > interval[1] for interval in bounds)
69 or (payload["archive_type"] == "CVTGrid" and (not centres or shape != (len(centres),)))
70 or (payload["archive_type"] in _RECTANGULAR_TYPES and (not shape or len(shape) != len(bounds)))
71 or (payload["archive_type"] == "points" and (shape or centres))):
72 raise ValueError("Invalid archive geometry.")
73 if centres and (not all(len(row) == len(bounds) for row in centres)
74 or not np.isfinite(centres).all()):
75 raise ValueError("Invalid CVT centroid coordinates.")
76 if (payload["archive_type"] == "SlidingBoundariesGrid" and not edges) or (edges and (
77 centres or len(edges) != len(shape) or any(
78 len(row) != n + 1 or not np.isfinite(row).all() or row[0] != low or row[-1] != high
79 or any(a > b for a, b in zip(row, row[1:]))
80 for row, n, (low, high) in zip(edges, shape, bounds)))):
81 raise ValueError("Invalid rectangular bin edges.")
82 entries = tuple(_Entry(None if row["cell"] is None else tuple(row["cell"]),
83 tuple(map(float, row["descriptors"])), tuple(map(float, row["fitness"])),
84 tuple(map(float, row["fitness_weights"]))) for row in payload["entries"])
85 dimension = len(bounds) or (len(entries[0].descriptors) if entries else 0)
86 if any(len(entry.descriptors) != dimension for entry in entries):
87 raise ValueError("Archive descriptors have inconsistent dimensions.")
88 activity = payload.get("activity")
89 if activity is not None:
90 activity = tuple((tuple(cell), int(count)) for cell, count in activity)
91 for cell in [entry.cell for entry in entries] + [cell for cell, _ in activity or ()]:
92 if ((shape and cell is None) or (cell is not None and
93 (len(cell) != len(shape) or not all(type(i) is int and 0 <= i < n for i, n in zip(cell, shape))))):
94 raise ValueError("Archive entry is outside its declared cell shape.")
95 return _ArchiveData(bounds, _rows(payload["fitness_domain"]), shape, centres, entries, activity, edges)
96
97
98def _archive_data(archive):
99 if isinstance(archive, _ArchiveData):
100 return archive
101 if isinstance(archive, (str, PathLike)):
102 with Path(archive).open(encoding="utf-8") as file:
103 archive = json.load(file, object_hook=_decode_float)
104 if isinstance(archive, Mapping):
105 return _parse_archive(archive)
106 if not _is_archive(archive):
107 raise TypeError("Provide a QDpy container or numeric archive export.")
108
109 geometry = archive
110 while isinstance(geometry, ContainerDecorator):
111 geometry = geometry.container
112 if isinstance(geometry, Grid):
113 shape = tuple(map(int, geometry.shape))
114 cells = {id(elite): tuple(map(int, cell)) for cell, front in geometry.solutions.items() for elite in front}
115 centres = _rows(geometry.cluster_centers) if isinstance(geometry, CVTGrid) else ()
116 counts = geometry.activity_per_bin
117 activity = tuple((tuple(map(int, cell)), int(counts[tuple(cell)])) for cell in np.argwhere(counts))
118 else:
119 shape, cells, centres, activity = (), {}, (), None
120 entries = []
121 for elite in archive:
122 fitness = archive.get_ind_fitness(elite)
123 entries.append(_Entry(cells.get(id(elite)), tuple(map(float, archive.get_ind_features(elite))),
124 tuple(map(float, fitness.values)), tuple(map(float, fitness.weights))))
125 return _ArchiveData(_rows(archive.features_domain), _rows(archive.fitness_domain),
126 shape, centres, tuple(entries), activity, _rows(getattr(geometry, 'bin_edges', ())))
127
128
129def _named_data(archives):
130 if _is_archive(archives):
131 archives = {"Archive": archives}
132 elif not isinstance(archives, Mapping):
133 archives = {f"Archive {i}": archive for i, archive in enumerate(archives, 1)}
134 if not archives:
135 raise ValueError("Provide at least one archive.")
136 labels = [str(name) for name in archives]
137 if len(set(labels)) != len(labels):
138 raise ValueError("Archive labels must be distinct.")
139 return {label: _archive_data(archive) for label, archive in zip(labels, archives.values())}