Source code for qdpy.algorithms.constrained

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Mixed-variable MAP-Elites with separate feasible and near-feasible elites.

"""Mixed-variable MAP-Elites with named inequality constraints."""

from collections.abc import Mapping
from dataclasses import dataclass
from math import fsum, isfinite
from numbers import Real
from operator import index
import random

from qdpy.base import registry
from qdpy.containers import Grid, CVTGrid
from .modern import _FixedGeneration, _positive_int

__all__ = ["RealVariable", "IntegerVariable", "CategoricalVariable", "ConstrainedMAPElites",
           "ConditionalConfiguration", "HiGeME"]


## @brief Describe a real coordinate with inclusive finite bounds.
[docs] @dataclass(frozen=True) class RealVariable: """Inclusive real interval. Equal endpoints fix the coordinate.""" lower: float upper: float def __post_init__(self): if not (isinstance(self.lower, Real) and isinstance(self.upper, Real)): raise TypeError("Real bounds must be numeric.") lower, upper = float(self.lower), float(self.upper) if not (isfinite(upper - lower) and lower <= upper): raise ValueError("Real bounds must be finite, ordered, and have a finite span.") object.__setattr__(self, "lower", lower) object.__setattr__(self, "upper", upper)
## @brief Describe an integer coordinate with inclusive bounds.
[docs] @dataclass(frozen=True) class IntegerVariable: """Inclusive integer interval. Equal endpoints fix the coordinate.""" lower: int upper: int def __post_init__(self): lower, upper = index(self.lower), index(self.upper) if lower > upper: raise ValueError("Integer bounds must be ordered.") object.__setattr__(self, "lower", lower) object.__setattr__(self, "upper", upper)
## @brief Define the labels represented by integer category indices.
[docs] @dataclass(frozen=True) class CategoricalVariable: """Ordered distinct hashable labels. A single label fixes the coordinate.""" choices: tuple def __post_init__(self): choices = tuple(self.choices) if not choices or len(choices) != len(set(choices)): raise ValueError("Supply at least one category and use distinct labels.") object.__setattr__(self, "choices", choices)
def _encoded_bounds(variable): if isinstance(variable, CategoricalVariable): return 0, len(variable.choices) - 1 return variable.lower, variable.upper def _decode_gene(value, variable, bounds): if isinstance(variable, RealVariable): if not isinstance(value, Real): raise TypeError("Real variables require numeric values.") value = float(value) else: value = index(value) if not bounds[0] <= value <= bounds[1]: raise ValueError("Genome coordinate lies outside its variable bounds.") return variable.choices[value] if isinstance(variable, CategoricalVariable) else value def _sample_gene(variable, bounds, rng): return rng.uniform(*bounds) if isinstance(variable, RealVariable) else rng.randint(*bounds) def _mutate_gene(value, variable, bounds, sigma, rng): lower, upper = bounds if isinstance(variable, RealVariable): unit_value = (value - lower) / (upper - lower) perturbed = min(1.0, max(0.0, rng.gauss(unit_value, sigma))) return min(upper, lower + perturbed * (upper - lower)) other = rng.randrange(lower, upper) return other + (other >= value) def _constraint_violation(individual, names): terms = [] for name in names: value = individual.scores.get(name) if not isinstance(value, Real) or not isfinite(value): raise ValueError(f"Constraint {name!r} needs a finite residual.") terms.append(max(0.0, value)) return fsum(terms) def _validate_grid(container): if (type(container) not in (Grid, CVTGrid) or container.fitness_domain is None or len(container.fitness_domain) != 1 or container.max_items_per_bin != 1 or container.discard_random_on_bin_overload or len(container)): raise ValueError("Supply an empty, best-only Grid or CVTGrid with one objective.") def _check_measurements(archive, individual): if not all(map(isfinite, archive.get_ind_fitness(individual).values)): raise ValueError("Constrained MAP-Elites requires a finite objective.") if not all(map(isfinite, archive.get_ind_features(individual))): raise ValueError("Constrained MAP-Elites requires finite descriptors.") archive._check_if_can_be_added(individual) archive.index_grid(individual) ## @brief Search for feasible elites with real, integer, and categorical coordinates.
[docs] @registry.register class ConstrainedMAPElites(_FixedGeneration): """Keep the best feasible solution in each cell of a fixed result grid. Return the native ``(fitness, descriptors, scores)`` tuple from an evaluator and include one finite residual per named constraint. A residual of zero is feasible. Candidate genomes contain numeric coordinates and category indices. Use ``decode()`` to recover labels. :param container: Empty one-elite Grid or CVTGrid with one objective. :param budget: Attempted evaluations per run. :param variables: RealVariable, IntegerVariable, or CategoricalVariable instances in genome order. :param constraint_names: Score names for inequality residuals g(x) <= 0. :param batch_size: Number of proposals before updating either archive. :param real_sigma: Gaussian mutation scale as a fraction of a real span. :param infeasible_parent_probability: Probability of drawing a near-feasible parent when both archives have entries. Zero selects feasible parents exclusively and samples randomly until a feasible result is available. :param optimisation_task: The usual single-objective direction or weight. """ _allows_no_constraints = False _variation_rng = random def __init__(self, container, budget, variables, *, constraint_names, batch_size=1, real_sigma=0.1, infeasible_parent_probability=0.5, optimisation_task="minimisation"): _validate_grid(container) self.variables = tuple(variables) if not self.variables or not all(isinstance(v, (RealVariable, IntegerVariable, CategoricalVariable)) for v in self.variables): raise ValueError("Supply one supported variable specification per coordinate.") names = (constraint_names,) if isinstance(constraint_names, str) else tuple(constraint_names) if ((not names and not self._allows_no_constraints) or not all(isinstance(name, str) and name for name in names) or len(set(names)) != len(names)): raise ValueError("Supply distinct, nonempty constraint score names.") if set(names).intersection(container.fitness_score_names): raise ValueError("Use separate score names for constraints and the objective.") if not (0 < real_sigma < float("inf") and 0 <= infeasible_parent_probability <= 1): raise ValueError("Supply a positive finite real_sigma and a parent probability in [0, 1].") self.constraint_names = names self.real_sigma = real_sigma self.infeasible_parent_probability = infeasible_parent_probability self._bounds = tuple(map(_encoded_bounds, self.variables)) self._mutable = tuple(i for i, (lower, upper) in enumerate(self._bounds) if lower < upper) super().__init__(container, _positive_int(budget, "budget"), dimension=len(self.variables), batch_size=_positive_int(batch_size, "batch_size"), optimisation_task=optimisation_task) def reinit(self): """Reset the search counters and near-feasible archive.""" super().reinit() self._infeasible = {} @property def infeasible_elites(self): """Return the lowest-violation candidate currently held in each cell.""" return {cell: candidate for cell, (_, candidate) in self._infeasible.items()} ## @brief Validate a numeric genome and translate category indices to labels.
[docs] def decode(self, candidate): """Return the coordinates with the original category labels restored.""" if len(candidate) != self.dimension: raise ValueError("Genome length must match the variable specifications.") return tuple(_decode_gene(value, variable, bounds) for value, variable, bounds in zip(candidate, self.variables, self._bounds))
def _select_parent(self, rng): probability = self.infeasible_parent_probability if probability and self._infeasible and (not self.container or rng.random() < probability): return rng.choice(tuple(self._infeasible.values()))[1] return rng.choice(self.container) if self.container else None def _internal_ask(self, base_ind): rng = self._variation_rng parent = self._select_parent(rng) if parent is None: base_ind[:] = [_sample_gene(variable, bounds, rng) for variable, bounds in zip(self.variables, self._bounds)] return base_ind base_ind[:] = parent if self._mutable: rate = 1 / len(self._mutable) selected = [i for i in self._mutable if rng.random() < rate] or [rng.choice(self._mutable)] for i in selected: base_ind[i] = _mutate_gene(parent[i], self.variables[i], self._bounds[i], self.real_sigma, rng) return base_ind def _violation(self, individual): return _constraint_violation(individual, self.constraint_names) def _check_candidate(self, individual): self.decode(individual) _check_measurements(self.container, individual) self._violation(individual) def _commit_generation(self, evaluated): archive = self.container admitted = set() for slot, candidate in enumerate(evaluated): if candidate is None: continue violation = self._violation(candidate) cell = archive.index_grid(candidate) if violation == 0: if self._offer_to_grid(candidate, cell): admitted.add(slot) else: fitness = archive.get_ind_fitness(candidate) rank = (violation, -(fitness.values[0] * fitness.weights[0])) if cell not in self._infeasible or rank < self._infeasible[cell][0]: self._infeasible[cell] = (rank, candidate) return admitted def best(self): """Return the best feasible individual or raise if the grid is empty.""" if not self.container: raise RuntimeError("Constrained MAP-Elites has no feasible result in its grid.") return super().best()
def _names(values, description): names = (values,) if isinstance(values, str) else tuple(values) if not all(isinstance(name, str) and name for name in names) or len(set(names)) != len(names): raise ValueError(f"Use distinct nonempty names for {description}.") return names ## @brief Declare the selectors, active genes, and constraint scores for one branch.
[docs] @dataclass(frozen=True) class ConditionalConfiguration: """One allowed set of selector values in HiGeME. :param selectors: Mapping or pairs of selector names and hashable labels. Names and values are copied into a tuple of pairs. :param active: Names from the shared variable schema visible in this branch. :param constraints: Names of required residual scores. A value at most zero satisfies the constraint. """ selectors: tuple active: tuple[str, ...] constraints: tuple[str, ...] = () def __post_init__(self): pairs = tuple(self.selectors.items() if isinstance(self.selectors, Mapping) else self.selectors) pairs = tuple((name, value) for name, value in pairs) _names((name for name, _ in pairs), "selectors") for _, value in pairs: hash(value) object.__setattr__(self, "selectors", pairs) object.__setattr__(self, "active", _names(self.active, "active variables")) object.__setattr__(self, "constraints", _names(self.constraints, "constraint scores"))
## @brief Search a union of conditional design spaces using hidden numeric genes.
[docs] @registry.register class HiGeME(_FixedGeneration): """Sample and mutate explicit configurations following Baraton et al. Each genome contains a configuration index followed by one numeric gene per variable in mapping order. Hidden genes retain their stored values when a branch deactivates them. Use decode() to obtain only selectors and active parameters. The evaluator returns native fitness, descriptors, and named constraint scores. :param container: Empty best-only Grid or CVTGrid with one objective. :param budget: Attempt budget including one initial sample per configuration. :param variables: Ordered mapping from names to mixed-variable specifications. :param configurations: Ordered sequence of ConditionalConfiguration objects. :param configuration_probability: Chance of drawing a whole configuration uniformly for an offspring. The draw may retain the current branch. :param gene_probability: Independent mutation probability of each active gene. :param real_sigma: Gaussian mutation scale in units of the real interval. :param seed: Seed for the search's private random number generator. :param batch_size: Number of candidates evaluated before archive feedback. :param optimisation_task: Single objective direction or weight. """ _requires_proposed_genome = True def __init__(self, container, budget, variables, *, configurations, configuration_probability=0.4, gene_probability=0.5, real_sigma=0.3, seed=0, batch_size=1, optimisation_task="minimisation"): _validate_grid(container) if not isinstance(variables, Mapping): raise TypeError("Supply a mapping from gene names to variable specifications.") self._gene_names = _names(variables, "variables") self.variables = tuple(variables.values()) if not all(isinstance(v, (RealVariable, IntegerVariable, CategoricalVariable)) for v in self.variables): raise ValueError("Use real, integer, or categorical variable specifications.") self.configurations = tuple(configurations) if not self.configurations or not all(isinstance(item, ConditionalConfiguration) for item in self.configurations): raise ValueError("Supply at least one ConditionalConfiguration.") signatures = {frozenset(config.selectors) for config in self.configurations} if len(signatures) != len(self.configurations): raise ValueError("Give each configuration distinct selector assignments.") names = set(self._gene_names) measurement_names = set(container.fitness_score_names) | set(container.features_score_names) for config in self.configurations: if names.intersection(name for name, _ in config.selectors) or not names.issuperset(config.active): raise ValueError("Selectors must be separate from the gene schema and active genes must exist.") if measurement_names.intersection(config.constraints): raise ValueError("Use separate names for constraints, objectives, and descriptors.") if not (0 <= configuration_probability <= 1 and 0 <= gene_probability <= 1 and 0 < real_sigma < float("inf")): raise ValueError("Use probabilities in [0, 1] and a finite positive real_sigma.") budget = _positive_int(budget, "budget") if budget < len(self.configurations): raise ValueError("Budget must cover one initial candidate per configuration.") self.configuration_probability = configuration_probability self.gene_probability = gene_probability self.real_sigma = real_sigma self.seed = index(seed) self._bounds = tuple(map(_encoded_bounds, self.variables)) self._active = tuple(tuple(i for i, name in enumerate(self._gene_names) if name in config.active) for config in self.configurations) super().__init__(container, budget, dimension=len(self.variables) + 1, batch_size=_positive_int(batch_size, "batch_size"), optimisation_task=optimisation_task) def reinit(self): """Reset the proposal stream and accounting.""" super().reinit() self._rng = random.Random(self.seed)
[docs] def ask_batch(self, size=None): """Issue a manual batch, shortening the default batch to fit the remaining budget.""" remaining = self.budget - self.nb_evaluations size = min(self.batch_size, remaining) if size is None else _positive_int(size, "size") if size <= 0 or size > remaining: raise ValueError("The batch must fit the remaining evaluation budget.") return super().ask_batch(size)
def _branch(self, candidate): if len(candidate) != self.dimension: raise ValueError("Genome length must match the conditional gene schema.") branch = index(candidate[0]) if not 0 <= branch < len(self.configurations): raise ValueError("Genome configuration index is out of range.") return branch ## @brief Decode a candidate into the design visible to the evaluator.
[docs] def decode(self, candidate): """Return selector labels and typed active gene values in a new mapping.""" branch = self._branch(candidate) values = [_decode_gene(value, variable, bounds) for value, variable, bounds in zip(candidate[1:], self.variables, self._bounds)] decoded = dict(self.configurations[branch].selectors) decoded.update((self._gene_names[i], values[i]) for i in self._active[branch]) return decoded
def _parent_pool(self): return self.container def _internal_ask(self, base_ind): count = len(self.configurations) parents = self._parent_pool() if self.nb_suggestions < count or not parents: branch = self.nb_suggestions if self.nb_suggestions < count else self._rng.randrange(count) base_ind[:] = [branch, *(_sample_gene(variable, bounds, self._rng) for variable, bounds in zip(self.variables, self._bounds))] return base_ind base_ind[:] = self._rng.choice(parents) if self._rng.random() < self.configuration_probability: base_ind[0] = self._rng.randrange(count) for i in self._active[base_ind[0]]: bounds = self._bounds[i] if bounds[0] < bounds[1] and self._rng.random() < self.gene_probability: base_ind[i + 1] = _mutate_gene(base_ind[i + 1], self.variables[i], bounds, self.real_sigma, self._rng) return base_ind def _check_candidate(self, individual): self.decode(individual) _check_measurements(self.container, individual) _constraint_violation(individual, self.configurations[individual[0]].constraints) def _commit_generation(self, evaluated): admitted = set() for slot, individual in enumerate(evaluated): if individual is not None: configuration = self.configurations[individual[0]] if _constraint_violation(individual, configuration.constraints) == 0: cell = self.container.index_grid(individual) if self._offer_to_grid(individual, cell): admitted.add(slot) return admitted