QDpy
Loading...
Searching...
No Matches
multi_decoder.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Illuminate solutions produced by alternative decoders of the same genome."""
7
8from dataclasses import dataclass
9
10import numpy as np
11
12from ._population import _attempt_budget
13from .monte_carlo import _Arm, _ucb
14from .task_search import _measurement, _offer, _validate_grid
15
16__all__ = ["MultiDecoderResult", "multi_decoder_map_elites"]
17
18
19
20@dataclass(frozen=True)
22 """An archive genome is the decoder index followed by the original genotype."""
23
24 archive: object
25 proposals: int
26 decoder_calls: tuple[int, ...]
27 objective_calls: int
28 failed_decodes: int
29 emitter_calls: tuple[int, ...]
30 emitter_rewards: tuple[float, ...]
31
32
33
46def multi_decoder_map_elites(archive, evaluate, *, sample, emitters, decoders, budget, initial_samples=8,
47 rule="round_robin", exploration=1., epsilon=.3, seed=0):
48 """Try each decoder on the emitted genome and reward successful admissions.
49
50 Each decode consumes a budget slot, including a refusal to decode.
51 Rotate decoder order each proposal. Each arm earns the fraction of
52 attempted decodings that filled or improved a cell. The decoder
53 index prefixes archived genomes to preserve alternative phenotypes.
54 """
55 _validate_grid(archive)
56 emitters, decoders = tuple(emitters), tuple(decoders)
57 if not emitters or not decoders or not all(map(callable, (sample, evaluate, *emitters, *decoders))):
58 raise ValueError("Provide callable sampling, evaluation, emitters, and decoders.")
59 if rule not in ("round_robin", "ucb1", "decaying_epsilon") or not (
60 0 <= exploration < np.inf and 0 <= epsilon <= 1):
61 raise ValueError("Use a valid emitter rule and finite exploration parameters.")
62 budget, initial = _attempt_budget(budget), _attempt_budget(initial_samples)
63 if archive.fitness_weights is None:
64 archive._set_fitness_weights((1.,))
65 rng = np.random.default_rng(seed)
66 arms = [_Arm() for _ in emitters]
67 calls = [0] * len(decoders)
68 proposals = objective = failed = emitted = 0
69 while budget:
70 arm = None
71 if proposals < initial or not archive:
72 genome = tuple(sample(rng))
73 else:
74 if rule == "round_robin":
75 arm = emitted % len(arms)
76 elif rule == "ucb1":
77 values = np.asarray([_ucb(state, emitted, exploration) for state in arms])
78 arm = int(rng.choice(np.flatnonzero(values == values.max())))
79 elif emitted < len(arms):
80 arm = emitted
81 elif rng.random() < epsilon / np.sqrt(1. + emitted):
82 arm = int(rng.integers(len(arms)))
83 else:
84 means = np.asarray([state.successes / state.draws for state in arms])
85 arm = int(rng.choice(np.flatnonzero(means == means.max())))
86 parent = tuple(archive[int(rng.integers(len(archive)))][1:])
87 genome = tuple(emitters[arm](parent, rng))
88 emitted += 1
89 spent = min(budget, len(decoders))
90 before = archive.nb_added
91 for offset in range(spent):
92 slot = (proposals + offset) % len(decoders)
93 calls[slot] += 1
94 phenotype = decoders[slot](genome)
95 if phenotype is None:
96 failed += 1
97 continue
98 measurement = evaluate(phenotype)
99 objective += 1
100 if measurement is not None:
101 quality, descriptor = measurement
102 _offer(archive, _measurement(archive, ((quality,), descriptor), (slot, *genome)))
103 if arm is not None:
104 arms[arm].draws += 1
105 arms[arm].successes += (archive.nb_added - before) / spent
106 proposals += 1
107 budget -= spent
108 return MultiDecoderResult(archive, proposals, tuple(calls), objective, failed,
109 tuple(arm.draws for arm in arms), tuple(arm.successes for arm in arms))
Archive and separate proposal, decoding, and objective measurement budgets.