QDpy
Loading...
Searching...
No Matches
hierarchical.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Retain a repertoire of fine alternatives within each coarse niche."""
7
8from math import isfinite
9
10import numpy as np
11
12from .modern import _positive_int
13from .task_search import _measurement, _offer, _validate_grid
14
15__all__ = ["HierarchicalArchive", "HierarchicalMAPElites"]
16
17
18
20 """Use a fixed coarse geometry and one best-only archive per occupied niche.
21
22 :param coarse: Empty best-only Grid or CVTGrid. Its descriptors locate
23 a branch, and its fitness bounds and objective direction apply to
24 each branch. The geometry stays empty.
25 :param make_fine: Callback (coarse_index) constructing a fresh empty
26 best-only Grid or CVTGrid for that branch. Fine geometry and
27 capacity may differ across branches. Treat returned grids as
28 views when reading them through this archive.
29 """
30
31 def __init__(self, coarse, make_fine):
32 _validate_grid(coarse)
33 if not callable(make_fine):
34 raise TypeError("Supply a factory for fine archives.")
35 if coarse.fitness_weights is None:
36 coarse._set_fitness_weights((1.,))
37 self.coarse = coarse
38 self._make_fine = make_fine
39 self._branches = {}
40
41 @property
42 def subarchives(self):
43 """Return the occupied coarse indices and their fine archives."""
44 return dict(self._branches)
45
46 def __iter__(self):
47 for branch in self._branches.values():
48 yield from branch
49
50 def __len__(self):
51 return sum(map(len, self._branches.values()))
52
53
54 def index(self, descriptor):
55 """Return the coarse Grid or CVTGrid index."""
56 return self.coarse.index_grid(tuple(descriptor))
57
58
59 def alternatives(self, descriptor):
60 """Return the measured fine elites as a tuple, or an empty tuple for an empty branch."""
61 return tuple(self._branches.get(self.index(descriptor), ()))
62
63
64 def coarse_descriptor(self, elite):
65 """Return the coarse descriptor stored when this elite was measured."""
66 return elite._hierarchical_descriptor
67
68
69 def query(self, bounds):
70 """Return alternatives matching one (lower, upper) pair per coarse axis."""
71 bounds = tuple(tuple(map(float, pair)) for pair in bounds)
72 if (len(bounds) != len(self.coarse.features_domain)
73 or any(len(pair) != 2 or not all(map(isfinite, pair)) or pair[0] > pair[1] for pair in bounds)):
74 raise ValueError("Supply one finite inclusive interval per coarse descriptor.")
75 return tuple(elite for elite in self
76 if all(lower <= value <= upper for value, (lower, upper) in
77 zip(self.coarse_descriptor(elite), bounds)))
78
79 def _new_branch(self, index):
80 branch = self._make_fine(index)
81 _validate_grid(branch)
82 if (branch is self.coarse or id(branch) in {id(other) for other in self._branches.values()}
83 or tuple(branch.fitness_domain) != tuple(self.coarse.fitness_domain)
84 or branch.fitness_weights not in (None, self.coarse.fitness_weights)):
85 raise ValueError("Each branch needs its own grid and the coarse fitness domain and weights.")
86 branch._set_fitness_weights(self.coarse.fitness_weights)
87 return branch
88
89
90 def add(self, genome, fitness, coarse_descriptor, fine_descriptor):
91 """Return True if the candidate fills or improves a fine cell.
92
93 Genomes are immutable and hashable. Fine archive entries store
94 the original genome at index zero, its measured fine features,
95 and the coarse descriptor used to route it.
96 Measurements outside either descriptor domain are skipped.
97 """
98 hash(genome)
99 coarse_descriptor = tuple(coarse_descriptor)
100 _, index = _measurement(self.coarse, ((fitness,), coarse_descriptor), (genome,))
101 if index is None:
102 return False
103 branch = self._branches.get(index)
104 if branch is None:
105 branch = self._new_branch(index)
106 measurement = _measurement(branch, ((fitness,), fine_descriptor), (genome,))
107 measurement[0]._hierarchical_descriptor = tuple(map(float, coarse_descriptor))
108 previous = branch.nb_added
109 _offer(branch, measurement)
110 if branch.nb_added != previous:
111 self._branches[index] = branch
112 return True
113 return False
114
115
116 def sample(self, rng):
117 """Return an elite using a NumPy generator."""
118 if not self._branches:
119 raise ValueError("The hierarchy needs at least one elite to sample.")
120 branches = tuple(self._branches.values())
121 branch = branches[int(rng.integers(len(branches)))]
122 return branch[int(rng.integers(len(branch)))]
123
124
125
127 """Search with caller-defined initialization, mutation and evaluation.
128
129 :param archive: HierarchicalArchive, optionally seeded.
130 :param propose: Callback (rng) returning a new genome.
131 :param mutate: Callback (parent_genome, rng) returning an offspring.
132 :param random_fraction: Probability of drawing a fresh genome when
133 parents are available.
134 :param seed: Seed for parent selection and genome proposals.
135 """
136
137 def __init__(self, archive, *, propose, mutate, random_fraction=.1, seed=0):
138 if not isinstance(archive, HierarchicalArchive) or not callable(propose) or not callable(mutate):
139 raise TypeError("Supply a HierarchicalArchive and callable proposal and mutation.")
140 if not 0. <= random_fraction <= 1.:
141 raise ValueError("random_fraction must be in [0, 1].")
142 self.archive = archive
143 self._propose, self._mutate = propose, mutate
144 self._rng = np.random.default_rng(seed)
145 self._random_fraction = random_fraction
146 self.nb_evaluations = 0
147 self.nb_failures = 0
148
149
150 def run(self, evaluate, *, budget):
151 """Evaluate genomes for (fitness, coarse descriptor, fine descriptor).
152
153 A failed evaluation returned as None still consumes an attempt.
154 """
155 for _ in range(_positive_int(budget, "budget")):
156 if self.archive._branches and self._rng.random() >= self._random_fraction:
157 genome = self._mutate(self.archive.sample(self._rng)[0], self._rng)
158 else:
159 genome = self._propose(self._rng)
160 self.nb_evaluations += 1
161 result = evaluate(genome)
162 if result is None:
163 self.nb_failures += 1
164 else:
165 self.archive.add(genome, *result)
166 return self.archive
Route one measured genome to its coarse niche and local archive.
query(self, bounds)
Filter retained elites by inclusive coarse descriptor bounds.
sample(self, rng)
Select a branch uniformly, then sample a fine elite.
coarse_descriptor(self, elite)
Return exact coarse measurements associated with a fine elite.
add(self, genome, fitness, coarse_descriptor, fine_descriptor)
Try to admit a measured alternative at a coarse-to-fine path.
alternatives(self, descriptor)
Return alternatives for the coarse cell containing a requested descriptor.
index(self, descriptor)
Find the coarse niche for a descriptor vector.
Evolve a hierarchical repertoire with branch-uniform parent selection.
run(self, evaluate, *, budget)
Add an evaluation budget to the current repertoire.