QDpy
Loading...
Searching...
No Matches
qd_meta.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Bounded QD-Meta with a shared database of measured base features."""
6
7from collections import deque
8from dataclasses import dataclass
9from math import isfinite, log
10
11import numpy as np
12
13from qdpy.containers import Grid
14from qdpy.phenotype import Features, Fitness, Individual
15from qdpy.tools import iso_line_dd
16from .lm_ma_mae import _LMMAES
17from .modern import _positive_int, _variation_settings
18
19__all__ = ["FeatureProjection", "QDMetaResult", "QDMeta"]
20
21
22
23@dataclass(frozen=True)
25 """Project bounded features into [0, 1] using signed, L1-normalized rows."""
26
27 weights: tuple[tuple[float, ...], ...]
28 base_domain: tuple[tuple[float, float], ...]
29
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))
45
46 def __call__(self, features):
47 """Map one vector or a matrix of rows into the learned descriptor space."""
48 values = np.asarray(features, dtype=float)
49 lower, upper = np.asarray(self.base_domain).T
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.)
55
56
57
58@dataclass(frozen=True)
60 """Describe the best archive by meta-fitness. An unsuccessful search has no archive."""
61
62 projection: FeatureProjection | None
63 archive: Grid | None
64 meta_fitness: float | None
65 evaluations: int
66 meta_evaluations: int
67 generations: int
68 database_size: int
69
70
71@dataclass(frozen=True)
73 genome: tuple
74 fitness: float
75 base: tuple
76
77
78
79class QDMeta:
80 """QD Meta-Evolution following Bossens and Tarapore.
81
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.
87
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.
101 """
102
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)
108 if not self.shape:
109 raise ValueError("Provide at least one target descriptor axis.")
110 self.base_domain = tuple(tuple(pair) for pair in base_domain)
111 weights = np.ones((len(self.shape), len(self.base_domain)))
112 projection = FeatureProjection(weights, self.base_domain)
113 self.base_domain = projection.base_domain
114 self._population_size = _positive_int(population_size, "population_size")
115 if self._population_size < 2 or not 0 < sigma0 < np.inf:
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)
118 if not isfinite(self.ind_domain[1] - self.ind_domain[0]):
119 raise ValueError("The genome domain must have a finite width.")
120 self._direction = 1. if maximize else -1.
121 self._iso_sigma, self._line_sigma = iso_sigma, line_sigma
122 self._initial = _positive_int(initial_samples, "initial_samples")
123 self.inner_evaluations = _positive_int(inner_evaluations, "inner_evaluations")
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)
127 n = weights.size
128 center = outer_rng.uniform(-.5, .5, size=n)
129 self._outer = _LMMAES(center, sigma0, self._population_size, min(n, 4 + int(3 * log(n))),
130 (-1., 1.), outer_rng)
131 self._initialized = False
132 self._evaluations = self._meta_evaluations = self._generations = 0
133 self._best = None
134
135 @property
136 def result(self):
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
139 return QDMetaResult(projection, grid, quality, self._evaluations, self._meta_evaluations,
140 self._generations, len(self._database))
141
142 def _fresh(self):
143 return self._rng.uniform(*self.ind_domain, self.dimension)
144
145 def _measure(self, evaluate, genome):
146 genome = tuple(map(float, genome))
147 self._evaluations += 1
148 result = evaluate(genome)
149 if result is None:
150 return None
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.")
157 return _Measurement(genome, fitness, base)
158
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]:
163 candidate = Individual(item.genome, fitness=Fitness((item.fitness,), weights=(self._direction,)),
164 features=Features(descriptors))
165 candidate.scores["base_features"] = item.base
166 archive.add(candidate)
167
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,))
171 if snapshot:
172 existing = projection([item.base for item in snapshot])
173 for item, descriptor in zip(snapshot, existing):
174 self._offer(archive, item, descriptor)
175 new = []
176 for _ in range(self.inner_evaluations):
177 if archive:
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,
180 iso_sigma=self._iso_sigma, line_sigma=self._line_sigma)
181 else:
182 genes = self._fresh()
183 measured = self._measure(evaluate, genes)
184 if measured is not None:
185 new.append(measured)
186 self._offer(archive, measured, projection(measured.base))
187 return archive, new
188
189
190 def run(self, evaluate, meta_fitness, *, generations=1):
191 """Run fresh inner searches. Both callbacks may return None for a failed measurement.
192
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.
197 """
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.")
201 if not self._initialized:
202 for _ in range(self._initial):
203 measured = self._measure(evaluate, self._fresh())
204 if measured is not None:
205 self._database.append(measured)
206 self._initialized = True
207 for _ in range(generations):
208 vectors = self._outer.ask(self._population_size)
209 snapshot = tuple(self._database)
210 accepted = []
211 scores = np.full(len(vectors), -np.inf)
212 for row, vector in enumerate(vectors):
213 projection = FeatureProjection(vector.reshape(len(self.shape), -1), self.base_domain)
214 grid, new = self._inner(projection, snapshot, evaluate)
215 accepted.extend(new)
216 if not grid:
217 continue
218 self._meta_evaluations += 1
219 value = meta_fitness(grid)
220 if value is None:
221 continue
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
228 self._database.extend(accepted)
229 valid = np.flatnonzero(np.isfinite(scores))
230 self._outer.adapt(vectors, valid[np.argsort(-scores[valid], kind="stable")])
231 self._generations += 1
232 return self.result
Store an evolved linear map from normalized base features to grid descriptors.
Definition qd_meta.py:24
Return a measured repertoire, its feature map, and cumulative budget accounting.
Definition qd_meta.py:59
Optimize a feature map with an outer ES and a population of inner MAP-Elites runs.
Definition qd_meta.py:79
_measure(self, evaluate, genome)
Definition qd_meta.py:145
run(self, evaluate, meta_fitness, *, generations=1)
Spend complete outer generations and return the best measured archive.
Definition qd_meta.py:190
_offer(self, archive, item, descriptors)
Definition qd_meta.py:159
_inner(self, projection, snapshot, evaluate)
Definition qd_meta.py:168
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405