# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief MAP-Elites for subset selection with exact cardinality cells.
# @see https://doi.org/10.1007/s00453-024-01254-z
"""Find good subsets across several cardinality budgets in one run."""
from collections.abc import Mapping
from dataclasses import dataclass
from math import isfinite
from operator import index
import numpy as np
from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from .modern import _positive_int
__all__ = ["CardinalityMAPElites", "CardinalitySearchStats", "BooleanConjunction",
"ConjunctionMAPElites", "ConjunctionSearchStats"]
def _cardinality_grid(max_items, fitness_domain, fitness_weight):
return Grid(shape=(max_items + 1,), features_domain=((-.5, max_items + .5),),
fitness_domain=(tuple(fitness_domain),), fitness_weights=(fitness_weight,))
def _cardinality_options(dimension, max_items, mutation_probability, fitness_weight):
dimension = _positive_int(dimension, "dimension")
limit = dimension if max_items is None else index(max_items)
probability = 1. / dimension if mutation_probability is None else mutation_probability
if not 0 <= limit <= dimension or not 0 < probability <= 1 or not isfinite(fitness_weight) or not fitness_weight:
raise ValueError("Use max_items in [0, dimension], a positive flip rate, and a signed fitness weight.")
return dimension, limit, probability
## @brief Candidate and objective counts for one subset-search run.
@dataclass(frozen=True)
class CardinalitySearchStats:
"""Rejected over-budget proposals spend proposal slots only."""
proposals: int
evaluations: int
over_limit: int
archive_updates: int
## @brief Use independent bit flips and keep the best solution for each subset size.
class CardinalityMAPElites:
"""Search bit vectors indexed by the number of selected coordinates.
The first measurement is the empty subset. Subsequent proposals flip
each bit independently with probability 1 / dimension by default.
The evaluator receives a tuple containing the indices of selected
items. Inspect the bit-vector elites through archive or use
best_at_most() to choose an option for one cardinality budget.
:param dimension: Number of items available for selection.
:param max_items: Largest allowed cardinality. Defaults to dimension.
:param mutation_probability: Optional independent per-bit flip probability.
:param fitness_domain: Closed interval of admissible raw objective values.
:param fitness_weight: Nonzero finite sign and magnitude of the objective.
:param seed: Private proposal seed.
"""
def __init__(self, dimension, *, max_items=None, mutation_probability=None,
fitness_domain=(-np.inf, np.inf), fitness_weight=1., seed=0):
self.dimension, self.max_items, self.mutation_probability = _cardinality_options(
dimension, max_items, mutation_probability, fitness_weight)
self.archive = _cardinality_grid(self.max_items, fitness_domain, fitness_weight)
self._weight = fitness_weight
self._rng = np.random.default_rng(seed)
## @brief Return selected item indices from one archived bit vector.
@staticmethod
def subset(individual):
"""Translate the binary genome to its sorted tuple of indices."""
return tuple(i for i, bit in enumerate(individual) if bit)
## @brief Return the highest-quality measured elite within a cardinality limit.
def best_at_most(self, max_items):
"""Return an archived Individual, or None when no measured option fits."""
limit = index(max_items)
if not 0 <= limit <= self.max_items:
raise ValueError("The requested limit must be in the configured cardinality range.")
return max((ind for ind in self.archive if ind.features.values[0] <= limit),
key=lambda ind: self._weight * ind.fitness.values[0], default=None)
## @brief Spend an objective budget and a separate proposal cap.
# @param evaluate Callable mapping an ordered tuple of selected indices to raw scalar fitness.
# @param budget Maximum objective evaluations, including repeated admissible subsets.
# @param proposal_limit Maximum mutation attempts. Defaults to ten times budget.
# @return CardinalitySearchStats with the costs and accepted updates.
def run(self, evaluate, budget, *, proposal_limit=None):
"""Continue search and keep exact-cardinality elites in native grid cells."""
budget = _positive_int(budget, "budget")
limit = 10 * budget if proposal_limit is None else _positive_int(proposal_limit, "proposal_limit")
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
proposals = evaluations = rejected = updates = 0
while proposals < limit and evaluations < budget:
proposals += 1
if not len(self.archive):
bits = np.zeros(self.dimension, dtype=bool)
else:
parent = self.archive[self._rng.integers(len(self.archive))]
bits = np.logical_xor(parent, self._rng.random(self.dimension) < self.mutation_probability)
subset = tuple(map(int, np.flatnonzero(bits)))
if len(subset) > self.max_items:
rejected += 1
continue
fitness = (float(evaluate(subset)),)
evaluations += 1
if not isfinite(fitness[0]):
raise ValueError("The objective must be finite.")
if self.archive.in_bounds(fitness, self.archive.fitness_domain):
elite = Individual(bits.astype(int).tolist(), fitness=Fitness(fitness, weights=(self._weight,)),
features=Features((len(subset),)))
updates += self.archive.add(elite) is not None
return CardinalitySearchStats(proposals, evaluations, rejected, updates)
## @brief Require all named binary literals in a subset-selection problem.
[docs]
@dataclass(frozen=True)
class BooleanConjunction:
"""Match a subset containing every required index and no excluded index."""
required: frozenset[int] = frozenset()
excluded: frozenset[int] = frozenset()
def __post_init__(self):
required = frozenset(map(index, self.required))
excluded = frozenset(map(index, self.excluded))
if required & excluded or any(i < 0 for i in required | excluded):
raise ValueError("Rule indices must be nonnegative and the two sets must be disjoint.")
object.__setattr__(self, "required", required)
object.__setattr__(self, "excluded", excluded)
## @brief Test a subset against all literals.
[docs]
def matches(self, subset):
"""Return whether all required indices and no excluded indices are selected."""
selected = set(subset)
return self.required <= selected and self.excluded.isdisjoint(selected)
## @brief Costs of a shared subset-search run.
[docs]
@dataclass(frozen=True)
class ConjunctionSearchStats:
"""Count measured subsets, rejected proposals, and updates across rule archives."""
proposals: int
evaluations: int
over_limit: int
unmatched: int
archive_updates: int
## @brief Route one measured binary subset into each matching cardinality archive.
# @see https://doi.org/10.1145/3638529.3654160
[docs]
class ConjunctionMAPElites:
"""Optimize overlapping subset problems with one objective evaluation per proposal.
Give each rule a named cardinality archive. Try the required
subset for every rule that still has an empty archive. Later
choose parents uniformly across occupied rule/cardinality cells. Use
independent bit flips and optional uniform crossover. A proposed
subset matching several rules may improve all their archives.
:param dimension: Number of available items.
:param rules: Mapping from nonempty names to BooleanConjunction objects.
:param max_items: Largest admissible subset size shared by the rules.
:param mutation_probability: Independent bit flip rate.
:param crossover_probability: Probability of choosing two parents and
mixing their bits before mutation.
:param fitness_domain: Closed interval of admissible raw objective values.
:param fitness_weight: Signed objective weight. Positive maximizes.
:param seed: Private variation seed.
"""
def __init__(self, dimension, rules, *, max_items=None, mutation_probability=None,
crossover_probability=0., fitness_domain=(-np.inf, np.inf), fitness_weight=1., seed=0):
if not isinstance(rules, Mapping) or not rules or any(
not isinstance(name, str) or not name or not isinstance(rule, BooleanConjunction)
for name, rule in rules.items()):
raise ValueError("Provide named BooleanConjunction rules.")
self.dimension, self.max_items, self.mutation_probability = _cardinality_options(
dimension, max_items, mutation_probability, fitness_weight)
if not 0. <= crossover_probability <= 1.:
raise ValueError("crossover_probability must lie in [0, 1].")
if any(len(rule.required) > self.max_items
or any(i >= self.dimension for i in rule.required | rule.excluded) for rule in rules.values()):
raise ValueError("Every rule must be feasible within the item and cardinality bounds.")
self._rules = dict(rules)
self.crossover_probability, self._weight = crossover_probability, fitness_weight
self._rng = np.random.default_rng(seed)
self._seeded = set()
fitness_domain = tuple(fitness_domain)
self.archives = {name: _cardinality_grid(self.max_items, fitness_domain, fitness_weight)
for name in self._rules}
def _propose(self):
for name, rule in self._rules.items():
if name not in self._seeded and not self.archives[name]:
self._seeded.add(name)
bits = np.zeros(self.dimension, dtype=bool)
bits[list(rule.required)] = True
return bits
parents = [entry for archive in self.archives.values() for entry in archive]
if not parents:
rules = tuple(self._rules.values())
rule = rules[self._rng.integers(len(rules))]
available = sorted(set(range(self.dimension)) - rule.required - rule.excluded)
count = self._rng.integers(min(len(available), self.max_items - len(rule.required)) + 1)
indices = self._rng.choice(available, size=count, replace=False).astype(int)
bits = np.zeros(self.dimension, dtype=bool)
bits[list(rule.required)] = bits[indices] = True
return bits
first = parents[int(self._rng.integers(len(parents)))]
if self.crossover_probability and self._rng.random() < self.crossover_probability:
second = parents[int(self._rng.integers(len(parents)))]
first = np.where(self._rng.random(self.dimension) < .5, first, second)
return np.logical_xor(first, self._rng.random(self.dimension) < self.mutation_probability)
## @brief Spend an additional objective budget and a separate proposal cap.
[docs]
def run(self, evaluate, budget, *, proposal_limit=None):
"""Call evaluate(subset) with sorted selected indices and return per-call counts."""
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
budget = _positive_int(budget, "budget")
limit = 10 * budget if proposal_limit is None else _positive_int(proposal_limit, "proposal_limit")
proposals = calls = over_limit = unmatched = updates = 0
while proposals < limit and calls < budget:
proposals += 1
bits = self._propose()
subset = tuple(map(int, np.flatnonzero(bits)))
if len(subset) > self.max_items:
over_limit += 1
continue
selected = set(subset)
matches = [self.archives[name] for name, rule in self._rules.items()
if rule.required <= selected and rule.excluded.isdisjoint(selected)]
if not matches:
unmatched += 1
continue
fitness = (float(evaluate(subset)),)
calls += 1
if not isfinite(fitness[0]):
raise ValueError("The objective must be finite.")
if matches[0].in_bounds(fitness, matches[0].fitness_domain):
genome = bits.astype(int).tolist()
for archive in matches:
elite = Individual(genome, fitness=Fitness(fitness, weights=(self._weight,)),
features=Features((len(subset),)))
updates += archive.add(elite) is not None
return ConjunctionSearchStats(proposals, calls, over_limit, unmatched, updates)