# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Many-objective Optimization via Voting for Elites.
# @see https://doi.org/10.1145/3583133.3590693
"""An archive with one majority-vote champion per objective subset."""
from dataclasses import dataclass
from operator import index
import numpy as np
from ._population import _attempt_budget, _finite_vector
from .modern import _positive_int
__all__ = ["MOVE", "MOVEEntry", "MOVEStats"]
## @brief An evaluated candidate, shared by every slot it wins.
[docs]
@dataclass(frozen=True)
class MOVEEntry:
"""Store raw objective values and lineage back to the breeding slot."""
genome: tuple
objectives: tuple[float, ...]
evaluation_id: int
parent_id: int | None
parent_slot: int | None
## @brief Cumulative candidate costs and slot replacements.
[docs]
@dataclass(frozen=True)
class MOVEStats:
"""Count each evaluation once even if it replaces several champions."""
evaluations: int
failures: int
generations: int
replacements: int
goal_switches: int
## @brief Breed one child per slot and compare it against all slots by strict majority.
[docs]
class MOVE:
"""Run Dean and Cheney's MOVE with caller-supplied genomes and objective functions.
The initial population assigns one candidate to each slot. Within a
generation, all offspring use the incumbent snapshot, then compete
in slot order. Each objective casts a vote only for a strict
improvement. Slots keep their incumbent on a tied or losing vote.
:param objective_count: Number of values returned by the evaluator.
:param sample: Callable (rng) returning a genome iterable.
:param mutate: Callable (parent_genome, rng) returning an offspring iterable.
:param slots: Number of independently sampled subsets if subsets is omitted.
:param subset_size: Number of distinct indices per sampled subset.
Defaults to five or the full objective count, whichever is smaller.
:param subsets: Optional explicit nonempty objective index subsets in slot order.
:param maximize: One Boolean direction for all objectives or one per objective.
:param seed: Seed for geometry, variation, and independent evaluations.
"""
def __init__(self, objective_count, *, sample, mutate, slots=50, subset_size=None,
subsets=None, maximize=True, seed=0):
count = _positive_int(objective_count, "objective_count")
if not callable(sample) or not callable(mutate):
raise TypeError("sample and mutate must be callable.")
geometry, self._variation, self._evaluation = map(
np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
if subsets is None:
size = min(5, count) if subset_size is None else _positive_int(subset_size, "subset_size")
if size > count:
raise ValueError("subset_size cannot exceed objective_count.")
subsets = (geometry.choice(count, size, replace=False) for _ in range(_positive_int(slots, "slots")))
self._subsets = tuple(tuple(sorted(map(index, subset))) for subset in subsets)
if not self._subsets or any(not s or s[0] < 0 or s[-1] >= count or len(set(s)) != len(s)
for s in self._subsets):
raise ValueError("Each slot needs distinct objective indices in range.")
directions = np.asarray(maximize)
if directions.dtype.kind != "b" or directions.shape not in ((), (count,)):
raise ValueError("maximize must supply a Boolean or one Boolean per objective.")
self._directions = np.broadcast_to(directions, (count,))
self._sample, self._mutate = sample, mutate
self._champions = [None] * len(self._subsets)
self._parents = None
self._position = 0
self._evaluations = self._failures = self._generations = self._replacements = self._switches = 0
@property
def subsets(self):
"""Return the objective indices in each slot, including repeated subsets."""
return self._subsets
@property
def champions(self):
"""Return the current champions in slot order, with None for empty slots."""
return tuple(self._champions)
@property
def stats(self):
"""Return cumulative telemetry."""
return MOVEStats(self._evaluations, self._failures, self._generations, self._replacements, self._switches)
def _compete(self, child, slot, source):
incumbent = self._champions[slot]
if incumbent is not None:
subset = self._subsets[slot]
votes = sum((child.objectives[i] > incumbent.objectives[i]) if self._directions[i]
else (child.objectives[i] < incumbent.objectives[i]) for i in subset)
if votes * 2 <= len(subset):
return
self._champions[slot] = child
self._replacements += 1
self._switches += source is not None and source != slot
## @brief Evaluate complete or partial generations in deterministic slot order.
# @param evaluate Callable (genome, seed) returning the objective vector or None.
# @param budget Additional evaluator attempts.
# @return Cumulative MOVEStats.
[docs]
def run(self, evaluate, budget):
"""Spend the additional budget. A subsequent call continues the current generation."""
for _ in range(_attempt_budget(budget)):
slot = self._position
parent = None if self._parents is None else self._parents[slot]
genome = tuple(self._sample(self._variation) if parent is None
else self._mutate(parent.genome, self._variation))
self._evaluations += 1
objectives = evaluate(genome, int(self._evaluation.integers(2**32)))
if objectives is None:
self._failures += 1
else:
values = _finite_vector(objectives, "Objectives", len(self._directions))
child = MOVEEntry(genome, values, self._evaluations, None if parent is None else parent.evaluation_id,
None if parent is None else slot)
if self._parents is None:
self._champions[slot] = child
else:
for target in range(len(self._subsets)):
self._compete(child, target, child.parent_slot)
self._position += 1
if self._position == len(self._subsets):
self._generations += self._parents is not None
self._parents, self._position = self.champions, 0
return self.stats