# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Combinatorial MAP-Elites with several decoders and adaptive emitters.
# @see https://doi.org/10.1007/978-3-031-30229-9_3
"""Illuminate solutions produced by alternative decoders of the same genome."""
from dataclasses import dataclass
import numpy as np
from ._population import _attempt_budget
from .monte_carlo import _Arm, _ucb
from .task_search import _measurement, _offer, _validate_grid
__all__ = ["MultiDecoderResult", "multi_decoder_map_elites"]
## @brief Archive and separate proposal, decoding, and objective measurement budgets.
[docs]
@dataclass(frozen=True)
class MultiDecoderResult:
"""An archive genome is the decoder index followed by the original genotype."""
archive: object
proposals: int
decoder_calls: tuple[int, ...]
objective_calls: int
failed_decodes: int
emitter_calls: tuple[int, ...]
emitter_rewards: tuple[float, ...]
## @brief Generate offspring with round-robin or bandit emitters and decode them on a common grid.
# @param archive Empty parentless best-only Grid or CVTGrid.
# @param evaluate Callable (decoded) returning (scalar quality, descriptors), or None to reject.
# @param sample Callable (rng) returning an undecoded genome.
# @param emitters Ordered callables (parent, rng) returning an undecoded child genome.
# @param decoders Ordered callables (genome) returning a phenotype or None.
# @param budget Hard limit on decoder calls, including failures.
# @param initial_samples Number of proposals before selecting an emitter.
# @param rule Selection rule, "round_robin", "ucb1", or "decaying_epsilon".
# @param exploration Nonnegative UCB exploration coefficient.
# @param epsilon Initial exploration probability for decaying epsilon.
# @param seed Seed for parent selection and variation.
# @return MultiDecoderResult with the native archive and separate counters.
[docs]
def multi_decoder_map_elites(archive, evaluate, *, sample, emitters, decoders, budget, initial_samples=8,
rule="round_robin", exploration=1., epsilon=.3, seed=0):
"""Try each decoder on the emitted genome and reward successful admissions.
Each decode consumes a budget slot, including a refusal to decode.
Rotate decoder order each proposal. Each arm earns the fraction of
attempted decodings that filled or improved a cell. The decoder
index prefixes archived genomes to preserve alternative phenotypes.
"""
_validate_grid(archive)
emitters, decoders = tuple(emitters), tuple(decoders)
if not emitters or not decoders or not all(map(callable, (sample, evaluate, *emitters, *decoders))):
raise ValueError("Provide callable sampling, evaluation, emitters, and decoders.")
if rule not in ("round_robin", "ucb1", "decaying_epsilon") or not (
0 <= exploration < np.inf and 0 <= epsilon <= 1):
raise ValueError("Use a valid emitter rule and finite exploration parameters.")
budget, initial = _attempt_budget(budget), _attempt_budget(initial_samples)
if archive.fitness_weights is None:
archive._set_fitness_weights((1.,))
rng = np.random.default_rng(seed)
arms = [_Arm() for _ in emitters]
calls = [0] * len(decoders)
proposals = objective = failed = emitted = 0
while budget:
arm = None
if proposals < initial or not archive:
genome = tuple(sample(rng))
else:
if rule == "round_robin":
arm = emitted % len(arms)
elif rule == "ucb1":
values = np.asarray([_ucb(state, emitted, exploration) for state in arms])
arm = int(rng.choice(np.flatnonzero(values == values.max())))
elif emitted < len(arms):
arm = emitted
elif rng.random() < epsilon / np.sqrt(1. + emitted):
arm = int(rng.integers(len(arms)))
else:
means = np.asarray([state.successes / state.draws for state in arms])
arm = int(rng.choice(np.flatnonzero(means == means.max())))
parent = tuple(archive[int(rng.integers(len(archive)))][1:])
genome = tuple(emitters[arm](parent, rng))
emitted += 1
spent = min(budget, len(decoders))
before = archive.nb_added
for offset in range(spent):
slot = (proposals + offset) % len(decoders)
calls[slot] += 1
phenotype = decoders[slot](genome)
if phenotype is None:
failed += 1
continue
measurement = evaluate(phenotype)
objective += 1
if measurement is not None:
quality, descriptor = measurement
_offer(archive, _measurement(archive, ((quality,), descriptor), (slot, *genome)))
if arm is not None:
arms[arm].draws += 1
arms[arm].successes += (archive.nb_added - before) / spent
proposals += 1
budget -= spent
return MultiDecoderResult(archive, proposals, tuple(calls), objective, failed,
tuple(arm.draws for arm in arms), tuple(arm.successes for arm in arms))