QDpy
Loading...
Searching...
No Matches
qed.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Quality-Environment-Diversity with caller-provided environment generation."""
7
8from dataclasses import dataclass
9from operator import index
10
11import numpy as np
12
13from qdpy.containers import Grid
14from qdpy.phenotype import Individual
15
16from .task_search import _measurement, _offer, _validate_grid
17
18__all__ = ["QEDResult", "quality_environment_diversity"]
19
20
22 """Keep the identity of a trial even when its genome is measured again."""
23
24 __eq__ = object.__eq__
25 __ne__ = object.__ne__
26 __hash__ = object.__hash__
27
28
29
30@dataclass(frozen=True)
32 """Return the native archive and counts of trials, failures, and admissions."""
33
34 archive: Grid
35 evaluations: int
36 failures: int
37 out_of_domain: int
38 updates: int
39
40
41
43def quality_environment_diversity(archive, evaluate, *, sample_environment, describe_environment,
44 sample, mutate, budget, initial_samples=16, seed=0):
45 """Generate one training environment per candidate and retain its best trials.
46
47 The report grid uses environmental features such as friction or sensor
48 noise. Separate random streams for environments, variation, and rollout
49 seeds make the sequence of training conditions independent of parent
50 selection. Export the native archive or pass it to MBOA for measured
51 adaptation to new conditions.
52
53 :param archive: Empty parentless best-only Grid or CVTGrid with one objective.
54 Set fitness_weights explicitly to choose the objective direction.
55 :param evaluate: Callable (genome, environment, rollout_seed) returning
56 one finite scalar fitness or None for a failed trial.
57 :param sample_environment: Callable (rng) drawing one environment specification.
58 :param describe_environment: Callable (environment) returning its finite grid coordinates.
59 :param sample: Callable (rng) returning an initial controller genome iterable.
60 :param mutate: Callable (genome, rng) returning the next controller genome.
61 Treat genome elements as immutable.
62 :param budget: Total evaluator calls, including the initial phase.
63 :param initial_samples: Number of attempts before drawing parents from the archive.
64 :param seed: Seed for independent environment, controller, and rollout streams.
65 """
66 _validate_grid(archive)
67 if not all(callable(callback) for callback in (evaluate, sample_environment, describe_environment, sample, mutate)):
68 raise TypeError("Supply callable environment, controller, and evaluation functions.")
69 budget, initial_samples = index(budget), index(initial_samples)
70 if min(budget, initial_samples) < 0:
71 raise ValueError("budget and initial_samples must be nonnegative.")
72 environments, variation, rollouts = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
73 before = archive.nb_added
74 failures = out_of_domain = 0
75 for attempt in range(budget):
76 if attempt < initial_samples or not archive:
77 genome = tuple(sample(variation))
78 else:
79 parent = archive[int(variation.integers(len(archive)))]
80 genome = tuple(mutate(tuple(parent), variation))
81 environment = sample_environment(environments)
82 features = tuple(describe_environment(environment))
83 score = evaluate(genome, environment, int(rollouts.integers(2**32)))
84 if score is None:
85 failures += 1
86 continue
87 candidate, cell = _measurement(archive, ((score,), features), genome)
88 if cell is None:
89 out_of_domain += 1
90 continue
91 # Two trials of the same controller can differ in environment and
92 # fitness. Admit or replace on measured fitness, using trial identity.
93 trial = _EnvironmentTrial(genome, name=f"qed-{attempt}",
94 fitness=candidate.fitness, features=candidate.features, scores=candidate.scores)
95 _offer(archive, (trial, cell))
96 return QEDResult(archive, budget, failures, out_of_domain, archive.nb_added - before)
Report the environment repertoire and exact evaluation counts.
Definition qed.py:31