Source code for qdpy.algorithms.innovation_engine

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Keep a champion per classifier output and track switches between their lineages.
# @see https://doi.org/10.1162/EVCO_a_00189

"""Classifier-guided illumination with one score per goal class."""

from copy import deepcopy
from dataclasses import dataclass
from operator import index

import numpy as np

from ..genealogy import GoalSwitch
from ..lineage import LineageNode

__all__ = ["ClassChampion", "ClassifierIlluminationResult", "classifier_illumination"]


## @brief A class's best candidate and its proposal identity.
[docs] @dataclass(frozen=True) class ClassChampion: """Store a candidate's score for this class and the corresponding lineage ID.""" candidate: object score: float lineage_id: int
## @brief Champions and observed goal switches from a fixed-budget run.
[docs] @dataclass(frozen=True) class ClassifierIlluminationResult: """Return champions in class order, genealogy, and evaluation counters.""" champions: tuple[ClassChampion, ...] nodes: dict[int, LineageNode] switches: tuple[GoalSwitch, ...] evaluations: int champion_updates: int
## @brief Evolve a shared set of candidates against all classifier outputs.
[docs] def classifier_illumination(initialise, mutate, classify, *, classes, budget, initial_samples=1, seed=0): """Run the fixed-class MAP-Elites variant of an Innovation Engine. ``initialise(rng)`` returns a candidate, and ``mutate(candidate, rng)`` varies a copy of one uniformly sampled class champion. ``classify(candidate)`` returns one finite score per class in a stable order. Each evaluation competes independently against all class champions. An accepted update in a class other than the sampled parent class is one goal switch. The callbacks define the representation, renderer, and classifier. Candidates can win several classes in one call, which counts as one evaluation. Ties retain the earlier champion. Scores are maximized. """ classes, budget, initial_samples = index(classes), index(budget), index(initial_samples) if classes < 1 or not 1 <= initial_samples <= budget: raise ValueError("Use positive class and budget counts with initial_samples within the budget.") rng = np.random.default_rng(seed) champions = [None] * classes nodes, switches = {}, [] updates = 0 for proposal in range(budget): parent_class = None parents = () if proposal < initial_samples: candidate = initialise(rng) else: parent_class = int(rng.integers(classes)) champion = champions[parent_class] parents = (champion.lineage_id,) candidate = mutate(deepcopy(champion.candidate), rng) scores = np.asarray(classify(candidate), dtype=float) if scores.shape != (classes,) or not np.isfinite(scores).all(): raise ValueError("The classifier must return one finite score per class.") improvements = [label for label, score in enumerate(scores) if champions[label] is None or score > champions[label].score] if improvements: retained = deepcopy(candidate) for label in improvements: champions[label] = ClassChampion(retained, float(scores[label]), proposal) if parent_class is not None and label != parent_class: switches.append(GoalSwitch(parents[0], proposal, parent_class, label)) updates += len(improvements) operator = "initialise" if not parents else "mutation" status = "accepted" if improvements else "rejected" nodes[proposal] = LineageNode(proposal, parents, operator, proposal + 1, status, proposal + 1) return ClassifierIlluminationResult(tuple(champions), nodes, tuple(switches), budget, updates)