25 """Project bounded features into [0, 1] using signed, L1-normalized rows."""
27 weights: tuple[tuple[float, ...], ...]
28 base_domain: tuple[tuple[float, float], ...]
30 def __post_init__(self):
31 domain, weights = np.asarray(self.
base_domain, dtype=float), np.asarray(self.
weights, dtype=float)
32 if (domain.ndim != 2
or domain.shape[1] != 2
or not len(domain)
or weights.ndim != 2
or not len(weights)
33 or weights.shape[1] != len(domain)
or not np.isfinite(domain).all()
34 or not np.isfinite(weights).all()):
35 raise ValueError(
"Supply a finite weight matrix and two bounds per base feature.")
36 widths = domain[:, 1] - domain[:, 0]
37 if not np.isfinite(widths).all()
or np.any(widths <= 0):
38 raise ValueError(
"Base feature intervals must have positive finite spans.")
39 scale = np.abs(weights).max(axis=1, keepdims=
True)
40 scaled = np.divide(weights, scale, out=np.zeros_like(weights), where=scale > 0)
41 total = np.abs(scaled).sum(axis=1, keepdims=
True)
42 normalized = np.divide(scaled, total, out=scaled, where=total > 0)
43 object.__setattr__(self,
"weights", tuple(tuple(map(float, row))
for row
in normalized))
44 object.__setattr__(self,
"base_domain", tuple(tuple(map(float, row))
for row
in domain))
47 """Map one vector or a matrix of rows into the learned descriptor space."""
48 values = np.asarray(features, dtype=float)
50 if (values.ndim
not in (1, 2)
or values.shape[-1] != len(lower)
or not np.isfinite(values).all()
51 or np.any((values < lower) | (values > upper))):
52 raise ValueError(
"Base features must be finite and within base_domain.")
53 normalized = (values - lower) / (upper - lower) - .5
54 return (normalized @ np.asarray(self.
weights).T + .5).clip(0., 1.)
80 """QD Meta-Evolution following Bossens and Tarapore.
82 Each generation samples a population of linear feature maps. It
83 rebuilds a best-only grid for each map from the same shared database
84 snapshot and runs a fixed number of MAP-Elites proposals. Newly
85 evaluated genomes join the database for the next generation. Meta
86 fitness ranks the maps for a limited-memory evolution strategy.
88 :param dimension: Length of the real-valued genome.
89 :param base_domain: Finite bounds for each measured base feature.
90 :param shape: Target grid shape, with one output of the projection per axis.
91 :param ind_domain: Common lower and upper genome bounds.
92 :param maximize: Whether greater inner fitness should be retained.
93 :param initial_samples: Number of real evaluations for initial shared records.
94 :param inner_evaluations: Number of fresh attempts per projection and generation.
95 :param population_size: Number of feature maps per outer generation.
96 :param database_capacity: Capacity of the shared FIFO measurement database.
97 :param sigma0: Initial step size for the outer limited-memory ES.
98 :param iso_sigma: Inner isotropic mutation scale.
99 :param line_sigma: Inner directional mutation scale.
100 :param seed: Seed for the database initialization, inner searches and outer ES.
103 def __init__(self, dimension, base_domain, shape, *, ind_domain=(0., 1.), maximize=
True,
104 initial_samples=32, inner_evaluations=16, population_size=6, database_capacity=4096,
105 sigma0=.45, iso_sigma=.05, line_sigma=.2, seed=0):
106 self.
dimension = _positive_int(dimension,
"dimension")
107 self.
shape = tuple(_positive_int(bins,
"bin count")
for bins
in shape)
109 raise ValueError(
"Provide at least one target descriptor axis.")
110 self.
base_domain = tuple(tuple(pair)
for pair
in base_domain)
116 raise ValueError(
"Use at least two feature maps and a positive finite sigma0.")
117 self.
ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
119 raise ValueError(
"The genome domain must have a finite width.")
122 self.
_initial = _positive_int(initial_samples,
"initial_samples")
124 self.
_database = deque(maxlen=_positive_int(database_capacity,
"database_capacity"))
125 seeds = np.random.SeedSequence(seed).spawn(2)
126 self.
_rng, outer_rng = (np.random.default_rng(seed)
for seed
in seeds)
128 center = outer_rng.uniform(-.5, .5, size=n)
130 (-1., 1.), outer_rng)
137 """Return the best learned archive and cumulative cost counters."""
138 projection, grid, quality = (
None,
None,
None)
if self.
_best is None else self.
_best
145 def _measure(self, evaluate, genome):
146 genome = tuple(map(float, genome))
148 result = evaluate(genome)
151 fitness, features = result
152 fitness, base = float(fitness), tuple(map(float, features))
153 if (
not isfinite(fitness)
or len(base) != len(self.
base_domain)
154 or not all(isfinite(value)
and lo <= value <= hi
155 for value, (lo, hi)
in zip(base, self.
base_domain))):
156 raise ValueError(
"Return finite scalar fitness and one value inside each base feature interval.")
159 def _offer(self, archive, item, descriptors):
160 cell = archive.index_grid(descriptors)
161 entries = archive.solutions[cell]
162 if not entries
or self.
_direction * item.fitness > self.
_direction * entries[0].fitness.values[0]:
165 candidate.scores[
"base_features"] = item.base
166 archive.add(candidate)
168 def _inner(self, projection, snapshot, evaluate):
169 archive =
Grid(shape=self.
shape, max_items_per_bin=1, features_domain=((0., 1.),) * len(self.
shape),
170 fitness_domain=((-np.inf, np.inf),), fitness_weights=(self.
_direction,))
172 existing = projection([item.base
for item
in snapshot])
173 for item, descriptor
in zip(snapshot, existing):
174 self.
_offer(archive, item, descriptor)
178 first, second = (archive[i]
for i
in self.
_rng.integers(len(archive), size=2))
179 genes = iso_line_dd(first, second, bounds=self.
ind_domain, rng=self.
_rng,
183 measured = self.
_measure(evaluate, genes)
184 if measured
is not None:
186 self.
_offer(archive, measured, projection(measured.base))
190 def run(self, evaluate, meta_fitness, *, generations=1):
191 """Run fresh inner searches. Both callbacks may return None for a failed measurement.
193 evaluate takes a genome and returns (scalar fitness, base_features).
194 meta_fitness takes a completed Grid and returns a scalar to maximize.
195 The latter should treat the supplied Grid as read-only. Its own
196 simulator interactions can be tracked in the callback.
198 generations = _positive_int(generations,
"generations")
199 if not callable(evaluate)
or not callable(meta_fitness):
200 raise TypeError(
"evaluate and meta_fitness must be callable.")
204 if measured
is not None:
207 for _
in range(generations):
211 scores = np.full(len(vectors), -np.inf)
212 for row, vector
in enumerate(vectors):
214 grid, new = self.
_inner(projection, snapshot, evaluate)
219 value = meta_fitness(grid)
222 quality = float(value)
223 if not isfinite(quality):
224 raise ValueError(
"Meta-fitness must be finite.")
225 scores[row] = quality
226 if self.
_best is None or quality > self.
_best[2]:
227 self.
_best = projection, grid, quality
229 valid = np.flatnonzero(np.isfinite(scores))
230 self.
_outer.adapt(vectors, valid[np.argsort(-scores[valid], kind=
"stable")])