Source code for qdpy.algorithms.feasible_mome
# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Multi-Objective MAP-Elites with separate feasibility and objective competition.
"""Store feasible local Pareto fronts and breed near-feasible candidates independently."""
from math import isfinite
import random
import numpy as np
from qdpy.base import registry
from qdpy.containers import ParetoGrid
from qdpy.tools import iso_line_dd
from .constrained import _constraint_violation, _names
from .modern import MOME
__all__ = ["FeasibleMOME"]
## @brief Evolve feasible Pareto fronts and preserve a least-violation breeder per cell.
[docs]
@registry.register
class FeasibleMOME(MOME):
"""Apply explicit inequalities to MOME without changing its objective weights.
Evaluators return fitness, descriptors, and named constraint scores.
Each residual g(x) must be finite, with g(x) <= 0 denoting feasibility.
Only feasible candidates enter the reporting ParetoGrid. Infeasible
candidates compete by the sum of their positive residuals in a
separate slot per cell. Scale residuals in the evaluator when units differ.
:param container: Empty ParetoGrid for feasible trade-offs.
:param budget: Exact evaluation attempts.
:param dimension: Number of real-valued genome coordinates.
:param batch_size: Number of proposals before committing feedback.
:param constraint_names: Score names holding the inequality residuals.
:param infeasible_parent_probability: Chance of drawing a least-violation
breeder when both pools have entries. Zero disables these parents.
:param seed: Private mutation, selection, and truncation seed.
:param kwargs: MOME settings, including decision bounds and variation scales.
"""
_requires_proposed_genome = True
def __init__(self, container, budget, dimension, batch_size=1, *,
constraint_names, infeasible_parent_probability=.25, seed=0, **kwargs):
if not isinstance(container, ParetoGrid):
raise ValueError("FeasibleMOME requires a ParetoGrid.")
names = _names(constraint_names, "constraint scores")
if not names or set(names).intersection((*container.fitness_score_names, *container.features_score_names)):
raise ValueError("Supply separate, nonempty constraint score names.")
if len(container):
raise ValueError("FeasibleMOME starts with an empty ParetoGrid.")
if not 0. <= infeasible_parent_probability <= 1.:
raise ValueError("infeasible_parent_probability must be in [0, 1].")
self.constraint_names = names
self.infeasible_parent_probability = infeasible_parent_probability
self.seed = seed
super().__init__(container, budget, dimension, batch_size, **kwargs)
if not isfinite(self.ind_domain[1] - self.ind_domain[0]):
raise ValueError("Provide decision bounds with a finite span.")
def reinit(self):
"""Reset the proposal stream and auxiliary breeding slots."""
super().reinit()
self._rng = np.random.default_rng(self.seed)
self._truncation_rng = random.Random(None if self.seed is None else int(self.seed))
self._infeasible = {}
@property
def infeasible_elites(self):
"""Return an independent mapping of cells to their least-violation breeders."""
return {cell: candidate for cell, (_, candidate) in self._infeasible.items()}
def _start_fixed_batch(self, size):
super()._start_fixed_batch(size)
self._auxiliary = (tuple(candidate for _, candidate in self._infeasible.values())
if self.infeasible_parent_probability else ())
def _parent(self):
if self._auxiliary and (not self._occupied or self._rng.random() < self.infeasible_parent_probability):
return self._auxiliary[self._rng.integers(len(self._auxiliary))]
front = self._occupied[self._rng.integers(len(self._occupied))]
return front[self._rng.integers(len(front))]
def _internal_ask(self, base_ind):
if self._occupied or self._auxiliary:
base_ind[:] = iso_line_dd(self._parent(), self._parent(), iso_sigma=self.iso_sigma,
line_sigma=self.line_sigma, bounds=self.ind_domain, rng=self._rng)
else:
base_ind[:] = self._rng.uniform(*self.ind_domain, size=self.dimension)
return base_ind
def _check_candidate(self, individual):
super()._check_candidate(individual)
if not isfinite(_constraint_violation(individual, self.constraint_names)):
raise ValueError("The aggregate constraint violation must be finite.")
def _commit_generation(self, evaluated):
feasible = []
for candidate in evaluated:
if candidate is None:
continue
violation = _constraint_violation(candidate, self.constraint_names)
if violation == 0.:
feasible.append(candidate)
else:
cell = self.container.index_grid(candidate)
previous = self._infeasible.get(cell)
if previous is None or violation < previous[0]:
self._infeasible[cell] = violation, candidate
admitted = self.container._merge_fronts(feasible, truncation_rng=self._truncation_rng)
return {slot for slot, candidate in enumerate(evaluated) if id(candidate) in admitted}