QDpy
Loading...
Searching...
No Matches
trace.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""A best-per-cell archive for evaluations with multiple descriptor points."""
7
8from copy import deepcopy
9from dataclasses import dataclass
10from math import isfinite
11from types import MappingProxyType
12
13import numpy as np
14
15from qdpy.phenotype import Features, Fitness, _CellIndividual
16
17from .base import _IndexedOrderedSet
18from .grids import CVTGrid, Grid
19
20__all__ = ["TraceArchive", "TraceElite"]
21
22
23
24@dataclass(eq=False, frozen=True, slots=True)
26 """A single measurement referenced by every cell it wins."""
27
28 genome: tuple[float, ...]
29 fitness: float
30 trace: tuple[tuple[float, ...], ...]
31
32
33
35 """Use native Grid or CVTGrid geometry with independent competition per cell.
36
37 In-bounds points compete using the same signed fitness. Duplicate points
38 or visits to the same cell compete once. Equal fitness keeps the existing
39 winner. Multiple cells can reference the same immutable record. The
40 archive releases the record when the last cell is taken by another elite.
41
42 :param geometry: Empty, parentless, best-only Grid or CVTGrid with one
43 explicit signed objective and direct fitness and descriptors.
44 """
45
46 def __init__(self, geometry):
47 if (type(geometry) not in (Grid, CVTGrid) or len(geometry) or geometry.parents
48 or geometry.max_items_per_bin != 1 or geometry.discard_random_on_bin_overload
49 or len(geometry.fitness_domain or ()) != 1 or len(geometry.fitness_weights or ()) != 1
50 or not isfinite(geometry.fitness_weights[0]) or not geometry.fitness_weights[0]
51 or geometry.features_score_names or geometry.fitness_score_names
52 or geometry.capacity < len(geometry.solutions)):
53 raise ValueError("Supply an empty best-only Grid or CVTGrid with one explicit signed objective.")
54 self._geometry = deepcopy(geometry)
55 self._cells = {}
58 self._references = {}
59
60 def __len__(self):
61 """Count distinct retained measurement records."""
62 return len(self._elites)
63
64 def __iter__(self):
65 """Iterate retained measurements once each in admission order."""
66 return iter(self._elites)
67
68 def __getitem__(self, index):
69 """Return a retained measurement by admission order."""
70 return self._elites[index]
71
72 @property
73 def cell_elites(self):
74 """Return a read-only view from cell indices to their measured elites."""
75 return MappingProxyType(self._cells)
76
77 @property
78 def filled_bins(self):
79 """Count cells with a retained winner."""
80 return len(self._cells)
81
82 @property
83 def coverage(self):
84 """Return the fraction of geometry cells that have a winner."""
85 return self.filled_bins / len(self._geometry.solutions)
86
87 @property
88 def features_domain(self):
89 """Return the native descriptor bounds."""
90 return self._geometry.features_domain
91
92 def _trace_points(self, trace):
93 points = np.asarray(trace, dtype=float)
94 if points.shape == (0,):
95 return ()
96 if (points.ndim != 2 or points.shape[1] != len(self.features_domain)
97 or not np.isfinite(points).all()):
98 raise ValueError("Supply finite points of the archive descriptor dimension.")
99 return tuple(tuple(map(float, point)) for point in points)
100
101 def _locate(self, points):
102 geometry = self._geometry
103 for point in points:
104 if geometry.in_bounds(point, geometry.features_domain):
105 yield geometry.index_grid(point), point
106
107
108 def cells_for(self, trace):
109 """Return the cell indices visited by the in-bounds points."""
110 return tuple(dict.fromkeys(cell for cell, _ in self._locate(self._trace_points(trace))))
111
112
113 def sample(self, rng, *, by_cell=True):
114 """Use a NumPy random generator to draw a parent uniformly from the selected pool."""
115 if not self._elites:
116 raise ValueError("The trace archive is empty.")
117 if by_cell:
118 return self._cells[self._occupied[rng.integers(self.filled_bins)]]
119 return self._elites[rng.integers(len(self))]
120
121
122 def add(self, genome, fitness, trace):
123 """Return the cell indices won by this measurement.
124
125 Genome coordinates, scalar fitness and descriptor points must be
126 finite. Empty traces, out-of-domain points and out-of-domain fitness
127 never win a cell.
128 """
129 values = np.asarray(genome, dtype=float)
130 score = np.asarray(fitness, dtype=float)
131 if (values.ndim != 1 or not len(values) or not np.isfinite(values).all()
132 or score.shape not in ((), (1,)) or not np.isfinite(score).all()):
133 raise ValueError("Supply a finite nonempty genome and a finite scalar fitness.")
134 fitness = float(score.item())
135 points = self._trace_points(trace)
136 geometry = self._geometry
137 if not geometry.in_bounds((fitness,), geometry.fitness_domain):
138 return ()
139 direction = 1 if geometry.fitness_weights[0] > 0 else -1
140 visited = dict.fromkeys(cell for cell, _ in self._locate(points))
141 winners = tuple(cell for cell in visited if cell not in self._cells
142 or fitness * direction > self._cells[cell].fitness * direction)
143 if winners:
144 elite = TraceElite(tuple(map(float, values)), fitness, points)
145 self._elites.add(elite)
146 self._references[elite] = len(winners)
147 for cell in winners:
148 previous = self._cells.get(cell)
149 if previous is None:
150 self._occupied.add(cell)
151 else:
152 self._references[previous] -= 1
153 if not self._references[previous]:
154 del self._references[previous]
155 self._elites.discard(previous)
156 self._cells[cell] = elite
157 return winners
158
159
160 def to_grid(self):
161 """Return a fresh native grid with one representative point per won cell."""
162 geometry = deepcopy(self._geometry)
163 inserted = set()
164 for elite in self:
165 for cell, point in self._locate(elite.trace):
166 if self._cells.get(cell) is elite and cell not in inserted:
167 geometry.add(_CellIndividual(elite.genome, cell,
168 fitness=Fitness((elite.fitness,), weights=geometry.fitness_weights),
169 features=Features(point)))
170 inserted.add(cell)
171 return geometry
172
173
174 def qd_score(self, normalized=True):
175 """Count every occupied cell, including cells won by the same elite."""
176 if not normalized:
177 return sum((elite.fitness for elite in self._cells.values()), 0.)
178 if not self._cells:
179 return 0.
180 low, high = self._geometry.fitness_domain[0]
181 if not (isfinite(low) and isfinite(high)):
182 return float("nan")
183 width = high - low if high > low else 1.
184 if self._geometry.fitness_weights[0] < 0:
185 return sum((high - elite.fitness) / width for elite in self._cells.values())
186 return sum((elite.fitness - low) / width for elite in self._cells.values())
Best-only multi-point archive with one record per retained measurement.
Definition trace.py:34
qd_score(self, normalized=True)
Sum the fitness of cell winners as in a best-only grid.
Definition trace.py:174
to_grid(self)
Materialize a per-cell reporting grid for plotting or export.
Definition trace.py:160
cells_for(self, trace)
Identify distinct cells in order of their first visit.
Definition trace.py:108
sample(self, rng, *, by_cell=True)
Sample one parent by cell or by retained measurement.
Definition trace.py:113
add(self, genome, fitness, trace)
Apply the same measurement independently to all visited cells.
Definition trace.py:122
The immutable genome, quality and descriptor trace from one evaluation.
Definition trace.py:25
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405