5"""Mixed-variable MAP-Elites with named inequality constraints."""
7from collections.abc
import Mapping
8from dataclasses
import dataclass
9from math
import fsum, isfinite
10from numbers
import Real
11from operator
import index
16from .modern
import _FixedGeneration, _positive_int
18__all__ = [
"RealVariable",
"IntegerVariable",
"CategoricalVariable",
"ConstrainedMAPElites",
19 "ConditionalConfiguration",
"HiGeME"]
23@dataclass(frozen=True)
25 """Inclusive real interval. Equal endpoints fix the coordinate."""
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)
41@dataclass(frozen=True)
43 """Inclusive integer interval. Equal endpoints fix the coordinate."""
48 def __post_init__(self):
49 lower, upper = index(self.lower), index(self.upper)
51 raise ValueError(
"Integer bounds must be ordered.")
52 object.__setattr__(self,
"lower", lower)
53 object.__setattr__(self,
"upper", upper)
57@dataclass(frozen=True)
59 """Ordered distinct hashable labels. A single label fixes the coordinate."""
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)
70def _encoded_bounds(variable):
71 if isinstance(variable, CategoricalVariable):
72 return 0, len(variable.choices) - 1
73 return variable.lower, variable.upper
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.")
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
88def _sample_gene(variable, bounds, rng):
89 return rng.uniform(*bounds)
if isinstance(variable, RealVariable)
else rng.randint(*bounds)
92def _mutate_gene(value, variable, bounds, sigma, rng):
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)
102def _constraint_violation(individual, 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))
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.")
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)
131 """Keep the best feasible solution in each cell of a fixed result grid.
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.
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.
151 _allows_no_constraints =
False
152 _variation_rng = random
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)
158 if not self.
variables or not all(isinstance(v, (RealVariable, IntegerVariable, CategoricalVariable))
160 raise ValueError(
"Supply one supported variable specification per coordinate.")
161 names = (constraint_names,)
if isinstance(constraint_names, str)
else tuple(constraint_names)
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].")
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)
178 """Reset the search counters and near-feasible archive."""
184 """Return the lowest-violation candidate currently held in each cell."""
185 return {cell: candidate
for cell, (_, candidate)
in self.
_infeasible.items()}
189 """Return the coordinates with the original category labels restored."""
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))
195 def _select_parent(self, rng):
198 return rng.choice(tuple(self.
_infeasible.values()))[1]
205 base_ind[:] = [_sample_gene(variable, bounds, rng)
212 selected = [i
for i
in self.
_mutable if rng.random() < rate]
or [rng.choice(self.
_mutable)]
217 def _violation(self, individual):
220 def _check_candidate(self, individual):
222 _check_measurements(self.
container, individual)
228 for slot, candidate
in enumerate(evaluated):
229 if candidate
is None:
232 cell = archive.index_grid(candidate)
237 fitness = archive.get_ind_fitness(candidate)
238 rank = (violation, -(fitness.values[0] * fitness.weights[0]))
244 """Return the best feasible individual or raise if the grid is empty."""
246 raise RuntimeError(
"Constrained MAP-Elites has no feasible result in its grid.")
247 return super().
best()
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}.")
258@dataclass(frozen=True)
260 """One allowed set of selector values in HiGeME.
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.
270 active: tuple[str, ...]
271 constraints: tuple[str, ...] = ()
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:
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"))
287 """Sample and mutate explicit configurations following Baraton et al.
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.
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.
308 _requires_proposed_genome =
True
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.")
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.")
320 if not self.
configurations or not all(isinstance(item, ConditionalConfiguration)
322 raise ValueError(
"Supply at least one ConditionalConfiguration.")
323 signatures = {frozenset(config.selectors)
for config
in self.
configurations}
325 raise ValueError(
"Give each configuration distinct selector assignments.")
327 measurement_names = set(container.fitness_score_names) | set(container.features_score_names)
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")
337 raise ValueError(
"Budget must cover one initial candidate per configuration.")
341 self.
seed = index(seed)
343 self.
_active = tuple(tuple(i
for i, name
in enumerate(self.
_gene_names)
if name
in config.active)
345 super().__init__(container, budget, dimension=len(self.
variables) + 1,
346 batch_size=_positive_int(batch_size,
"batch_size"), optimisation_task=optimisation_task)
349 """Reset the proposal stream and accounting."""
351 self.
_rng = random.Random(self.
seed)
354 """Issue a manual batch, shortening the default batch to fit the remaining budget."""
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.")
361 def _branch(self, candidate):
363 raise ValueError(
"Genome length must match the conditional gene schema.")
364 branch = index(candidate[0])
366 raise ValueError(
"Genome configuration index is out of range.")
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)]
379 def _parent_pool(self):
387 base_ind[:] = [branch, *(_sample_gene(variable, bounds, self.
_rng)
391 base_ind[:] = self.
_rng.choice(parents)
393 base_ind[0] = self.
_rng.randrange(count)
394 for i
in self.
_active[base_ind[0]]:
400 def _check_candidate(self, individual):
402 _check_measurements(self.
container, individual)
403 _constraint_violation(individual, self.
configurations[individual[0]].constraints)
407 for slot, individual
in enumerate(evaluated):
408 if individual
is not None:
410 if _constraint_violation(individual, configuration.constraints) == 0:
411 cell = self.
container.index_grid(individual)
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.
_internal_ask(self, base_ind)
decode(self, candidate)
Validate a numeric genome and translate category indices to labels.
_commit_generation(self, evaluated)
_violation(self, individual)
infeasible_parent_probability
bool _allows_no_constraints
_select_parent(self, rng)
Search a union of conditional design spaces using hidden numeric genes.
decode(self, candidate)
Decode a candidate into the design visible to the evaluator.
_internal_ask(self, base_ind)
_commit_generation(self, evaluated)
ask_batch(self, size=None)
configuration_probability
Describe an integer coordinate with inclusive bounds.
Describe a real coordinate with inclusive finite bounds.
_offer_to_grid(self, individual, cell)