# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Maintain stepping stones for combinations of subtasks.
# @see https://arxiv.org/abs/1807.03392
"""Combinatorial multiobjective evolution over bounded subtask populations."""
from dataclasses import dataclass
from itertools import combinations
from operator import index
from types import MappingProxyType
import numpy as np
from scipy.spatial.distance import cdist
from .evolvability_es import _pareto_utilities
from .modern import _positive_int
__all__ = ["CMOEA", "CMOEARecord", "CMOEAStats"]
def _choose_subsets(count, cap, rng):
if count <= cap.bit_length() and (1 << count) - 1 <= cap:
return tuple(subset for size in range(1, count + 1) for subset in combinations(range(count), size))
full = tuple(range(count))
subsets = dict.fromkeys((*((idx,) for idx in full), full))
if cap < len(subsets):
raise ValueError("max_bins must cover all singleton subtasks and the full combination.")
while len(subsets) < cap:
subset = tuple(np.flatnonzero(rng.integers(0, 2, count)).tolist())
if subset:
subsets.setdefault(subset, None)
return tuple(subsets)
## @brief One evaluated genotype with every task score and its diversity descriptor.
[docs]
@dataclass(frozen=True)
class CMOEARecord:
"""Store one measurement that can participate in multiple populations."""
genome: tuple
task_scores: tuple[float, ...]
descriptor: tuple[float, ...]
## @brief Cumulative evaluator attempts, failed evaluations, and committed generations.
[docs]
@dataclass(frozen=True)
class CMOEAStats:
"""Count each candidate once even when it competes in every bin."""
evaluations: int
failures: int
generations: int
## @brief Preserve solutions to task combinations via local nondominated survival.
[docs]
class CMOEA:
"""Combine task fitness and within-bin behavioral diversity.
Every evaluated offspring competes in each bin using its original
vector of task scores. Survival uses NSGA-II front ranks and
crowding for the aggregate task score and mean behavioral distance.
Parent sampling is uniform over occupied bins and then their members.
:param task_count: Number of task scores returned per evaluation.
:param sample: Callable (rng) returning an initial genome iterable.
:param mutate: Callable (genome, rng) returning an offspring genome.
Treat genome elements as immutable.
:param bin_capacity: Maximum number of survivors in each task subset.
:param batch_size: New candidate evaluations before the next competition.
:param max_bins: Cap on automatically generated subsets, defaulting
to max(64, 2 * task_count). Large families retain all singletons,
the full task, and a seeded selection of other subsets.
:param subsets: Optional explicit collection of task index subsets.
Include the full task subset. This overrides automatic bin selection.
:param aggregate: "mean" or "product" for fitness within each subset.
:param seed: Seed for selection, variation, and evaluator seeds.
"""
def __init__(self, task_count, *, sample, mutate, bin_capacity=8, batch_size=16,
max_bins=None, subsets=None, aggregate="mean", seed=0):
self.task_count = _positive_int(task_count, "task_count")
self._capacity = _positive_int(bin_capacity, "bin_capacity")
self._batch_size = _positive_int(batch_size, "batch_size")
if not callable(sample) or not callable(mutate):
raise TypeError("sample and mutate must be callable.")
if aggregate not in ("mean", "product"):
raise ValueError("Choose 'mean' or 'product' task-score aggregation.")
self._aggregate = aggregate
self._sample, self._mutate = sample, mutate
geometry, self._selection, self._variation, self._evaluation = map(
np.random.default_rng, np.random.SeedSequence(seed).spawn(4))
self._full = tuple(range(self.task_count))
if subsets is None:
cap = max(64, 2 * self.task_count) if max_bins is None else _positive_int(max_bins, "max_bins")
subsets = _choose_subsets(self.task_count, cap, geometry)
else:
subsets = tuple(tuple(sorted(index(task) for task in subset)) for subset in subsets)
if (self._full not in subsets or len(set(subsets)) != len(subsets)
or any(not subset or len(set(subset)) != len(subset)
or subset[0] < 0 or subset[-1] >= self.task_count for subset in subsets)):
raise ValueError("Use distinct nonempty task subsets in range, including the full subset.")
self._bins = dict.fromkeys(subsets, ())
self._evaluations = self._failures = self._generations = 0
self._descriptor_size = None
## @brief Return immutable populations indexed by sorted tuples of task indices.
@property
def bins(self):
"""Return a read-only live view of each subset and its survivors."""
return MappingProxyType(self._bins)
## @brief Return the highest-scoring survivor for all subtasks.
@property
def best(self):
"""Return the best measured candidate in the full subset, or None."""
return max(self._bins[self._full], key=lambda row: self._fitness(np.asarray(row.task_scores)), default=None)
@property
def stats(self):
"""Return cumulative attempts, failures, and generations."""
return CMOEAStats(self._evaluations, self._failures, self._generations)
def _fitness(self, scores):
if self._aggregate == "mean":
return scores.mean(axis=-1)
# Log scores have the same ordering as products and avoid underflow.
with np.errstate(divide="ignore"):
return np.log(scores).sum(axis=-1)
def _measure(self, evaluate, genome):
self._evaluations += 1
result = evaluate(genome, int(self._evaluation.integers(2**32)))
if result is None:
self._failures += 1
return None
scores, descriptor = (np.asarray(row, dtype=float) for row in result)
if scores.shape != (self.task_count,) or not np.all((scores >= 0.) & (scores <= 1.)):
raise ValueError("Return one normalized task score in [0, 1] per task.")
if descriptor.ndim != 1 or not len(descriptor) or not np.isfinite(descriptor).all():
raise ValueError("Return a nonempty finite behavioral descriptor.")
if self._descriptor_size is None:
self._descriptor_size = len(descriptor)
elif len(descriptor) != self._descriptor_size:
raise ValueError("Descriptor dimensions must remain fixed throughout the search.")
return CMOEARecord(genome, tuple(scores), tuple(descriptor))
def _survive(self, candidates, subset):
if len(candidates) <= self._capacity:
return candidates
scores = np.asarray([row.task_scores for row in candidates])[:, subset]
quality = self._fitness(scores)
if self._aggregate == "product":
# A common product scaling preserves crowding distances while
# retaining precision when every absolute product is tiny.
best = quality.max()
quality = np.exp(quality - best) if np.isfinite(best) else np.zeros_like(quality)
descriptors = np.asarray([row.descriptor for row in candidates])
descriptors /= np.abs(descriptors).max() or 1.
diversity = cdist(descriptors, descriptors).sum(axis=1) / (len(candidates) - 1)
utilities = _pareto_utilities(quality, diversity)
survivors = np.argsort(-utilities, kind="stable")[:self._capacity]
return tuple(candidates[int(slot)] for slot in survivors)
## @brief Spend additional evaluator attempts and commit surviving task populations.
# @param evaluate Callable (genome, rollout_seed) returning (task_scores, descriptor) or None.
# @param budget Additional candidate calls including failed slots.
# @return Cumulative CMOEAStats.
[docs]
def run(self, evaluate, budget):
"""Use all requested attempts, including a shorter final generation."""
budget = index(budget)
if budget < 0:
raise ValueError("budget must be nonnegative.")
for start in range(0, budget, self._batch_size):
parents = [members for members in self._bins.values() if members]
measured = []
for _ in range(min(budget - start, self._batch_size)):
if parents:
source = parents[int(self._selection.integers(len(parents)))]
parent = source[int(self._selection.integers(len(source)))]
genome = tuple(self._mutate(parent.genome, self._variation))
else:
genome = tuple(self._sample(self._variation))
record = self._measure(evaluate, genome)
if record is not None:
measured.append(record)
if measured:
children = tuple(measured)
for subset, members in self._bins.items():
self._bins[subset] = self._survive(members + children, subset)
self._generations += 1
return self.stats