QDpy
Loading...
Searching...
No Matches
constrained.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Mixed-variable MAP-Elites with named inequality constraints."""
6
7from collections.abc import Mapping
8from dataclasses import dataclass
9from math import fsum, isfinite
10from numbers import Real
11from operator import index
12import random
13
14from qdpy.base import registry
15from qdpy.containers import Grid, CVTGrid
16from .modern import _FixedGeneration, _positive_int
17
18__all__ = ["RealVariable", "IntegerVariable", "CategoricalVariable", "ConstrainedMAPElites",
19 "ConditionalConfiguration", "HiGeME"]
20
21
22
23@dataclass(frozen=True)
25 """Inclusive real interval. Equal endpoints fix the coordinate."""
26
27 lower: float
28 upper: float
29
30 def __post_init__(self):
31 if not (isinstance(self.lower, Real) and isinstance(self.upper, Real)):
32 raise TypeError("Real bounds must be numeric.")
33 lower, upper = float(self.lower), float(self.upper)
34 if not (isfinite(upper - lower) and lower <= upper):
35 raise ValueError("Real bounds must be finite, ordered, and have a finite span.")
36 object.__setattr__(self, "lower", lower)
37 object.__setattr__(self, "upper", upper)
38
39
40
41@dataclass(frozen=True)
43 """Inclusive integer interval. Equal endpoints fix the coordinate."""
44
45 lower: int
46 upper: int
47
48 def __post_init__(self):
49 lower, upper = index(self.lower), index(self.upper)
50 if lower > upper:
51 raise ValueError("Integer bounds must be ordered.")
52 object.__setattr__(self, "lower", lower)
53 object.__setattr__(self, "upper", upper)
54
55
56
57@dataclass(frozen=True)
59 """Ordered distinct hashable labels. A single label fixes the coordinate."""
60
61 choices: tuple
62
63 def __post_init__(self):
64 choices = tuple(self.choices)
65 if not choices or len(choices) != len(set(choices)):
66 raise ValueError("Supply at least one category and use distinct labels.")
67 object.__setattr__(self, "choices", choices)
68
69
70def _encoded_bounds(variable):
71 if isinstance(variable, CategoricalVariable):
72 return 0, len(variable.choices) - 1
73 return variable.lower, variable.upper
74
75
76def _decode_gene(value, variable, bounds):
77 if isinstance(variable, RealVariable):
78 if not isinstance(value, Real):
79 raise TypeError("Real variables require numeric values.")
80 value = float(value)
81 else:
82 value = index(value)
83 if not bounds[0] <= value <= bounds[1]:
84 raise ValueError("Genome coordinate lies outside its variable bounds.")
85 return variable.choices[value] if isinstance(variable, CategoricalVariable) else value
86
87
88def _sample_gene(variable, bounds, rng):
89 return rng.uniform(*bounds) if isinstance(variable, RealVariable) else rng.randint(*bounds)
90
91
92def _mutate_gene(value, variable, bounds, sigma, rng):
93 lower, upper = bounds
94 if isinstance(variable, RealVariable):
95 unit_value = (value - lower) / (upper - lower)
96 perturbed = min(1.0, max(0.0, rng.gauss(unit_value, sigma)))
97 return min(upper, lower + perturbed * (upper - lower))
98 other = rng.randrange(lower, upper)
99 return other + (other >= value)
100
101
102def _constraint_violation(individual, names):
103 terms = []
104 for name in names:
105 value = individual.scores.get(name)
106 if not isinstance(value, Real) or not isfinite(value):
107 raise ValueError(f"Constraint {name!r} needs a finite residual.")
108 terms.append(max(0.0, value))
109 return fsum(terms)
110
111
112def _validate_grid(container):
113 if (type(container) not in (Grid, CVTGrid) or container.fitness_domain is None
114 or len(container.fitness_domain) != 1 or container.max_items_per_bin != 1
115 or container.discard_random_on_bin_overload or len(container)):
116 raise ValueError("Supply an empty, best-only Grid or CVTGrid with one objective.")
117
118
119def _check_measurements(archive, individual):
120 if not all(map(isfinite, archive.get_ind_fitness(individual).values)):
121 raise ValueError("Constrained MAP-Elites requires a finite objective.")
122 if not all(map(isfinite, archive.get_ind_features(individual))):
123 raise ValueError("Constrained MAP-Elites requires finite descriptors.")
124 archive._check_if_can_be_added(individual)
125 archive.index_grid(individual)
126
127
128
129@registry.register
131 """Keep the best feasible solution in each cell of a fixed result grid.
132
133 Return the native ``(fitness, descriptors, scores)`` tuple from an
134 evaluator and include one finite residual per named constraint. A
135 residual of zero is feasible. Candidate genomes contain numeric
136 coordinates and category indices. Use ``decode()`` to recover labels.
137
138 :param container: Empty one-elite Grid or CVTGrid with one objective.
139 :param budget: Attempted evaluations per run.
140 :param variables: RealVariable, IntegerVariable, or CategoricalVariable
141 instances in genome order.
142 :param constraint_names: Score names for inequality residuals g(x) <= 0.
143 :param batch_size: Number of proposals before updating either archive.
144 :param real_sigma: Gaussian mutation scale as a fraction of a real span.
145 :param infeasible_parent_probability: Probability of drawing a near-feasible
146 parent when both archives have entries. Zero selects feasible parents
147 exclusively and samples randomly until a feasible result is available.
148 :param optimisation_task: The usual single-objective direction or weight.
149 """
150
151 _allows_no_constraints = False
152 _variation_rng = random
153
154 def __init__(self, container, budget, variables, *, constraint_names, batch_size=1,
155 real_sigma=0.1, infeasible_parent_probability=0.5, optimisation_task="minimisation"):
156 _validate_grid(container)
157 self.variables = tuple(variables)
158 if not self.variables or not all(isinstance(v, (RealVariable, IntegerVariable, CategoricalVariable))
159 for v in self.variables):
160 raise ValueError("Supply one supported variable specification per coordinate.")
161 names = (constraint_names,) if isinstance(constraint_names, str) else tuple(constraint_names)
162 if ((not names and not self._allows_no_constraints)
163 or not all(isinstance(name, str) and name for name in names) or len(set(names)) != len(names)):
164 raise ValueError("Supply distinct, nonempty constraint score names.")
165 if set(names).intersection(container.fitness_score_names):
166 raise ValueError("Use separate score names for constraints and the objective.")
167 if not (0 < real_sigma < float("inf") and 0 <= infeasible_parent_probability <= 1):
168 raise ValueError("Supply a positive finite real_sigma and a parent probability in [0, 1].")
169 self.constraint_names = names
170 self.real_sigma = real_sigma
171 self.infeasible_parent_probability = infeasible_parent_probability
172 self._bounds = tuple(map(_encoded_bounds, self.variables))
173 self._mutable = tuple(i for i, (lower, upper) in enumerate(self._bounds) if lower < upper)
174 super().__init__(container, _positive_int(budget, "budget"), dimension=len(self.variables),
175 batch_size=_positive_int(batch_size, "batch_size"), optimisation_task=optimisation_task)
176
177 def reinit(self):
178 """Reset the search counters and near-feasible archive."""
179 super().reinit()
180 self._infeasible = {}
181
182 @property
184 """Return the lowest-violation candidate currently held in each cell."""
185 return {cell: candidate for cell, (_, candidate) in self._infeasible.items()}
186
187
188 def decode(self, candidate):
189 """Return the coordinates with the original category labels restored."""
190 if len(candidate) != self.dimension:
191 raise ValueError("Genome length must match the variable specifications.")
192 return tuple(_decode_gene(value, variable, bounds)
193 for value, variable, bounds in zip(candidate, self.variables, self._bounds))
194
195 def _select_parent(self, rng):
196 probability = self.infeasible_parent_probability
197 if probability and self._infeasible and (not self.container or rng.random() < probability):
198 return rng.choice(tuple(self._infeasible.values()))[1]
199 return rng.choice(self.container) if self.container else None
200
201 def _internal_ask(self, base_ind):
202 rng = self._variation_rng
203 parent = self._select_parent(rng)
204 if parent is None:
205 base_ind[:] = [_sample_gene(variable, bounds, rng)
206 for variable, bounds in zip(self.variables, self._bounds)]
207 return base_ind
208
209 base_ind[:] = parent
210 if self._mutable:
211 rate = 1 / len(self._mutable)
212 selected = [i for i in self._mutable if rng.random() < rate] or [rng.choice(self._mutable)]
213 for i in selected:
214 base_ind[i] = _mutate_gene(parent[i], self.variables[i], self._bounds[i], self.real_sigma, rng)
215 return base_ind
216
217 def _violation(self, individual):
218 return _constraint_violation(individual, self.constraint_names)
219
220 def _check_candidate(self, individual):
221 self.decode(individual)
222 _check_measurements(self.container, individual)
223 self._violation(individual)
224
225 def _commit_generation(self, evaluated):
226 archive = self.container
227 admitted = set()
228 for slot, candidate in enumerate(evaluated):
229 if candidate is None:
230 continue
231 violation = self._violation(candidate)
232 cell = archive.index_grid(candidate)
233 if violation == 0:
234 if self._offer_to_grid(candidate, cell):
235 admitted.add(slot)
236 else:
237 fitness = archive.get_ind_fitness(candidate)
238 rank = (violation, -(fitness.values[0] * fitness.weights[0]))
239 if cell not in self._infeasible or rank < self._infeasible[cell][0]:
240 self._infeasible[cell] = (rank, candidate)
241 return admitted
242
243 def best(self):
244 """Return the best feasible individual or raise if the grid is empty."""
245 if not self.container:
246 raise RuntimeError("Constrained MAP-Elites has no feasible result in its grid.")
247 return super().best()
248
249
250def _names(values, description):
251 names = (values,) if isinstance(values, str) else tuple(values)
252 if not all(isinstance(name, str) and name for name in names) or len(set(names)) != len(names):
253 raise ValueError(f"Use distinct nonempty names for {description}.")
254 return names
255
256
257
258@dataclass(frozen=True)
260 """One allowed set of selector values in HiGeME.
261
262 :param selectors: Mapping or pairs of selector names and hashable labels.
263 Names and values are copied into a tuple of pairs.
264 :param active: Names from the shared variable schema visible in this branch.
265 :param constraints: Names of required residual scores. A value at most zero
266 satisfies the constraint.
267 """
268
269 selectors: tuple
270 active: tuple[str, ...]
271 constraints: tuple[str, ...] = ()
272
273 def __post_init__(self):
274 pairs = tuple(self.selectors.items() if isinstance(self.selectors, Mapping) else self.selectors)
275 pairs = tuple((name, value) for name, value in pairs)
276 _names((name for name, _ in pairs), "selectors")
277 for _, value in pairs:
278 hash(value)
279 object.__setattr__(self, "selectors", pairs)
280 object.__setattr__(self, "active", _names(self.active, "active variables"))
281 object.__setattr__(self, "constraints", _names(self.constraints, "constraint scores"))
282
283
284
285@registry.register
287 """Sample and mutate explicit configurations following Baraton et al.
288
289 Each genome contains a configuration index followed by one numeric gene
290 per variable in mapping order. Hidden genes retain their stored values
291 when a branch deactivates them. Use decode() to obtain only selectors and
292 active parameters. The evaluator returns native fitness, descriptors,
293 and named constraint scores.
294
295 :param container: Empty best-only Grid or CVTGrid with one objective.
296 :param budget: Attempt budget including one initial sample per configuration.
297 :param variables: Ordered mapping from names to mixed-variable specifications.
298 :param configurations: Ordered sequence of ConditionalConfiguration objects.
299 :param configuration_probability: Chance of drawing a whole configuration
300 uniformly for an offspring. The draw may retain the current branch.
301 :param gene_probability: Independent mutation probability of each active gene.
302 :param real_sigma: Gaussian mutation scale in units of the real interval.
303 :param seed: Seed for the search's private random number generator.
304 :param batch_size: Number of candidates evaluated before archive feedback.
305 :param optimisation_task: Single objective direction or weight.
306 """
307
308 _requires_proposed_genome = True
309
310 def __init__(self, container, budget, variables, *, configurations, configuration_probability=0.4,
311 gene_probability=0.5, real_sigma=0.3, seed=0, batch_size=1, optimisation_task="minimisation"):
312 _validate_grid(container)
313 if not isinstance(variables, Mapping):
314 raise TypeError("Supply a mapping from gene names to variable specifications.")
315 self._gene_names = _names(variables, "variables")
316 self.variables = tuple(variables.values())
317 if not all(isinstance(v, (RealVariable, IntegerVariable, CategoricalVariable)) for v in self.variables):
318 raise ValueError("Use real, integer, or categorical variable specifications.")
319 self.configurations = tuple(configurations)
320 if not self.configurations or not all(isinstance(item, ConditionalConfiguration)
321 for item in self.configurations):
322 raise ValueError("Supply at least one ConditionalConfiguration.")
323 signatures = {frozenset(config.selectors) for config in self.configurations}
324 if len(signatures) != len(self.configurations):
325 raise ValueError("Give each configuration distinct selector assignments.")
326 names = set(self._gene_names)
327 measurement_names = set(container.fitness_score_names) | set(container.features_score_names)
328 for config in self.configurations:
329 if names.intersection(name for name, _ in config.selectors) or not names.issuperset(config.active):
330 raise ValueError("Selectors must be separate from the gene schema and active genes must exist.")
331 if measurement_names.intersection(config.constraints):
332 raise ValueError("Use separate names for constraints, objectives, and descriptors.")
333 if not (0 <= configuration_probability <= 1 and 0 <= gene_probability <= 1 and 0 < real_sigma < float("inf")):
334 raise ValueError("Use probabilities in [0, 1] and a finite positive real_sigma.")
335 budget = _positive_int(budget, "budget")
336 if budget < len(self.configurations):
337 raise ValueError("Budget must cover one initial candidate per configuration.")
338 self.configuration_probability = configuration_probability
339 self.gene_probability = gene_probability
340 self.real_sigma = real_sigma
341 self.seed = index(seed)
342 self._bounds = tuple(map(_encoded_bounds, self.variables))
343 self._active = tuple(tuple(i for i, name in enumerate(self._gene_names) if name in config.active)
344 for config in self.configurations)
345 super().__init__(container, budget, dimension=len(self.variables) + 1,
346 batch_size=_positive_int(batch_size, "batch_size"), optimisation_task=optimisation_task)
347
348 def reinit(self):
349 """Reset the proposal stream and accounting."""
350 super().reinit()
351 self._rng = random.Random(self.seed)
352
353 def ask_batch(self, size=None):
354 """Issue a manual batch, shortening the default batch to fit the remaining budget."""
355 remaining = self.budget - self.nb_evaluations
356 size = min(self.batch_size, remaining) if size is None else _positive_int(size, "size")
357 if size <= 0 or size > remaining:
358 raise ValueError("The batch must fit the remaining evaluation budget.")
359 return super().ask_batch(size)
360
361 def _branch(self, candidate):
362 if len(candidate) != self.dimension:
363 raise ValueError("Genome length must match the conditional gene schema.")
364 branch = index(candidate[0])
365 if not 0 <= branch < len(self.configurations):
366 raise ValueError("Genome configuration index is out of range.")
367 return branch
368
369
370 def decode(self, candidate):
371 """Return selector labels and typed active gene values in a new mapping."""
372 branch = self._branch(candidate)
373 values = [_decode_gene(value, variable, bounds)
374 for value, variable, bounds in zip(candidate[1:], self.variables, self._bounds)]
375 decoded = dict(self.configurations[branch].selectors)
376 decoded.update((self._gene_names[i], values[i]) for i in self._active[branch])
377 return decoded
378
379 def _parent_pool(self):
380 return self.container
381
382 def _internal_ask(self, base_ind):
383 count = len(self.configurations)
384 parents = self._parent_pool()
385 if self.nb_suggestions < count or not parents:
386 branch = self.nb_suggestions if self.nb_suggestions < count else self._rng.randrange(count)
387 base_ind[:] = [branch, *(_sample_gene(variable, bounds, self._rng)
388 for variable, bounds in zip(self.variables, self._bounds))]
389 return base_ind
390
391 base_ind[:] = self._rng.choice(parents)
392 if self._rng.random() < self.configuration_probability:
393 base_ind[0] = self._rng.randrange(count)
394 for i in self._active[base_ind[0]]:
395 bounds = self._bounds[i]
396 if bounds[0] < bounds[1] and self._rng.random() < self.gene_probability:
397 base_ind[i + 1] = _mutate_gene(base_ind[i + 1], self.variables[i], bounds, self.real_sigma, self._rng)
398 return base_ind
399
400 def _check_candidate(self, individual):
401 self.decode(individual)
402 _check_measurements(self.container, individual)
403 _constraint_violation(individual, self.configurations[individual[0]].constraints)
404
405 def _commit_generation(self, evaluated):
406 admitted = set()
407 for slot, individual in enumerate(evaluated):
408 if individual is not None:
409 configuration = self.configurations[individual[0]]
410 if _constraint_violation(individual, configuration.constraints) == 0:
411 cell = self.container.index_grid(individual)
412 if self._offer_to_grid(individual, cell):
413 admitted.add(slot)
414 return admitted
Define the labels represented by integer category indices.
Declare the selectors, active genes, and constraint scores for one branch.
Search for feasible elites with real, integer, and categorical coordinates.
decode(self, candidate)
Validate a numeric genome and translate category indices to labels.
Search a union of conditional design spaces using hidden numeric genes.
decode(self, candidate)
Decode a candidate into the design visible to the evaluator.
Describe an integer coordinate with inclusive bounds.
Describe a real coordinate with inclusive finite bounds.
_offer_to_grid(self, individual, cell)
Definition modern.py:228