# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Illuminate an archive of controllers by their sampled training environments.
# @see https://arxiv.org/abs/2003.02341
"""Quality-Environment-Diversity with caller-provided environment generation."""
from dataclasses import dataclass
from operator import index
import numpy as np
from qdpy.containers import Grid
from qdpy.phenotype import Individual
from .task_search import _measurement, _offer, _validate_grid
__all__ = ["QEDResult", "quality_environment_diversity"]
class _EnvironmentTrial(Individual):
"""Keep the identity of a trial even when its genome is measured again."""
__eq__ = object.__eq__
__ne__ = object.__ne__
__hash__ = object.__hash__
## @brief Report the environment repertoire and exact evaluation counts.
[docs]
@dataclass(frozen=True)
class QEDResult:
"""Return the native archive and counts of trials, failures, and admissions."""
archive: Grid
evaluations: int
failures: int
out_of_domain: int
updates: int
## @brief Run MAP-Elites using training environment coordinates as descriptors.
# @return QEDResult with the supplied archive and the number of complete trials.
[docs]
def quality_environment_diversity(archive, evaluate, *, sample_environment, describe_environment,
sample, mutate, budget, initial_samples=16, seed=0):
"""Generate one training environment per candidate and retain its best trials.
The report grid uses environmental features such as friction or sensor
noise. Separate random streams for environments, variation, and rollout
seeds make the sequence of training conditions independent of parent
selection. Export the native archive or pass it to MBOA for measured
adaptation to new conditions.
:param archive: Empty parentless best-only Grid or CVTGrid with one objective.
Set fitness_weights explicitly to choose the objective direction.
:param evaluate: Callable (genome, environment, rollout_seed) returning
one finite scalar fitness or None for a failed trial.
:param sample_environment: Callable (rng) drawing one environment specification.
:param describe_environment: Callable (environment) returning its finite grid coordinates.
:param sample: Callable (rng) returning an initial controller genome iterable.
:param mutate: Callable (genome, rng) returning the next controller genome.
Treat genome elements as immutable.
:param budget: Total evaluator calls, including the initial phase.
:param initial_samples: Number of attempts before drawing parents from the archive.
:param seed: Seed for independent environment, controller, and rollout streams.
"""
_validate_grid(archive)
if not all(callable(callback) for callback in (evaluate, sample_environment, describe_environment, sample, mutate)):
raise TypeError("Supply callable environment, controller, and evaluation functions.")
budget, initial_samples = index(budget), index(initial_samples)
if min(budget, initial_samples) < 0:
raise ValueError("budget and initial_samples must be nonnegative.")
environments, variation, rollouts = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
before = archive.nb_added
failures = out_of_domain = 0
for attempt in range(budget):
if attempt < initial_samples or not archive:
genome = tuple(sample(variation))
else:
parent = archive[int(variation.integers(len(archive)))]
genome = tuple(mutate(tuple(parent), variation))
environment = sample_environment(environments)
features = tuple(describe_environment(environment))
score = evaluate(genome, environment, int(rollouts.integers(2**32)))
if score is None:
failures += 1
continue
candidate, cell = _measurement(archive, ((score,), features), genome)
if cell is None:
out_of_domain += 1
continue
# Two trials of the same controller can differ in environment and
# fitness. Admit or replace on measured fitness, using trial identity.
trial = _EnvironmentTrial(genome, name=f"qed-{attempt}",
fitness=candidate.fitness, features=candidate.features, scores=candidate.scores)
_offer(archive, (trial, cell))
return QEDResult(archive, budget, failures, out_of_domain, archive.nb_added - before)