QDpy
Loading...
Searching...
No Matches
multi_encoding.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Use multiple genotype representations in one phenotype archive."""
7
8from collections.abc import Callable, Iterable
9from dataclasses import dataclass
10from operator import index
11
12import numpy as np
13
14from ._population import _attempt_budget
15from .task_search import _measurement, _offer, _validate_grid
16
17__all__ = ["GenomeEncoding", "MultiEncodingMAPElites", "MultiEncodingStats"]
18
19
20
21@dataclass(frozen=True)
23 """The genotype is a sequence. The decoded phenotype can be any object."""
24
25 name: str
26 sample: Callable[[np.random.Generator], Iterable]
27 mutate: Callable[[tuple, np.random.Generator], Iterable]
28 decode: Callable[[tuple], object]
29
30
31
32@dataclass(frozen=True)
34 """Counter tuples follow the configured encoding order."""
35
36 proposals: tuple[int, ...]
37 failed_decodes: tuple[int, ...]
38 objective_calls: tuple[int, ...]
39 admissions: tuple[int, ...]
40
41
42
44 """Sample each encoding evenly, then mutate uniformly drawn archive elites.
45
46 Archived genotypes start with the zero-based encoding index, followed by
47 the encoding's genome. All encodings compete in the same descriptor cells.
48 """
49
50
54 def __init__(self, archive, encodings, *, initial_samples=8, seed=0):
55 _validate_grid(archive)
56 encodings = tuple(encodings)
57 if not encodings or any(
58 not isinstance(encoding, GenomeEncoding) or not isinstance(encoding.name, str)
59 or not encoding.name or not all(map(callable, (encoding.sample, encoding.mutate, encoding.decode)))
60 for encoding in encodings):
61 raise ValueError("Supply named encodings with sampling, mutation, and decoding callables.")
62 if len({encoding.name for encoding in encodings}) != len(encodings):
63 raise ValueError("Encoding names must be unique.")
64 self._initial = _attempt_budget(initial_samples) * len(encodings)
65 self._rng = np.random.default_rng(seed)
66 self.archive, self.encodings = archive, encodings
67 if archive.fitness_weights is None:
68 archive._set_fitness_weights((1.,))
69 self._proposed = 0
70 self._proposals = [0] * len(encodings)
71 self._failures = [0] * len(encodings)
72 self._objectives = [0] * len(encodings)
73 self._admissions = [0] * len(encodings)
74
75
76 @property
77 def stats(self):
78 return MultiEncodingStats(tuple(self._proposals), tuple(self._failures),
79 tuple(self._objectives), tuple(self._admissions))
80
81
82 def decode(self, elite):
83 slot = index(elite[0])
84 if not 0 <= slot < len(self.encodings):
85 raise ValueError("Elite has an invalid encoding index.")
86 return self.encodings[slot].decode(tuple(elite[1:]))
87
88
91 def run(self, evaluate, budget):
92 if not callable(evaluate):
93 raise ValueError("evaluate must be callable.")
94 for _ in range(_attempt_budget(budget)):
95 if self._proposed < self._initial or not self.archive:
96 slot = self._proposed % len(self.encodings)
97 genome = tuple(self.encodings[slot].sample(self._rng))
98 else:
99 slot, *parent = self.archive[int(self._rng.integers(len(self.archive)))]
100 genome = tuple(self.encodings[slot].mutate(tuple(parent), self._rng))
101 self._proposed += 1
102 self._proposals[slot] += 1
103 phenotype = self.encodings[slot].decode(genome)
104 if phenotype is None:
105 self._failures[slot] += 1
106 continue
107 self._objectives[slot] += 1
108 measurement = evaluate(phenotype)
109 if measurement is not None:
110 quality, descriptors = measurement
111 before = self.archive.nb_added
112 _offer(self.archive, _measurement(self.archive, ((quality,), descriptors), (slot, *genome)))
113 self._admissions[slot] += self.archive.nb_added - before
114 return self.stats
Sampling, mutation, and decoding for one representation.
Illuminate a shared phenotype space with several genotype encodings.
__init__(self, archive, encodings, *, initial_samples=8, seed=0)
decode(self, elite)
Decode an individual from this archive, without recording an objective call.
run(self, evaluate, budget)
Spend a budget of proposal attempts and return cumulative counters.
stats(self)
Cumulative counters from all runs.
Cumulative proposals, failed decodes, objective calls, and admissions by encoding.