QDpy
Loading...
Searching...
No Matches
come.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Search two component descriptor spaces with adaptive partner selection."""
7
8from dataclasses import dataclass
9
10import numpy as np
11
12from qdpy.containers import Grid
13from qdpy.phenotype import Features, Fitness, Individual
14from .modern import _positive_int
15
16__all__ = ["CoME", "CoMEStats"]
17
18
19
20@dataclass(frozen=True)
22 """Count complete pair evaluations, evaluated generations, and archive insertions.
23
24 :ivar evaluations: Number of complete pairs scored, including initialization.
25 :ivar generations: Number of batches committed.
26 :ivar archive_updates: Number of successful insertions into either archive.
27 """
28
29 evaluations: int
30 generations: int
31 archive_updates: int
32
33
34
35class CoME:
36 """Mutate one component and evaluate it with neighbors of a chosen partner cell.
37
38 The two rectangular grids have identical shapes. Each is indexed by one
39 component's descriptors and stores the complete pair and its measured
40 fitness. Each archive competes independently. Partner selection reads
41 that side's component from the pair at the chosen cell.
42
43 :param archives: Two distinct empty, parentless, best-only grids with the
44 same shape and the same finite, nonzero scalar fitness weight.
45 :param initialize: Two callbacks returning a component given the Generator.
46 :param mutations: Two callbacks taking (component, rng) and returning a component.
47 :param descriptors: Two callbacks taking a component and returning its finite,
48 in-bounds descriptor vector. Components are immutable and hashable.
49 :param evaluate: Callback returning scalar fitness from a complete pair.
50 :param coupling: One of "local-best", "global-best", "identity", "center", or "random".
51 :param partners: Maximum number of distinct neighbor cells sampled per mutation.
52 :param radius: Strict Euclidean radius in cell-index units around the partner cell.
53 :param initial_samples: Number of independently initialized pairs to score.
54 :param batch_size: Maximum number of scored pairs between archive updates.
55 :param seed: Private proposal seed.
56 """
57
58 def __init__(self, archives, *, initialize, mutations, descriptors, evaluate,
59 coupling="local-best", partners=2, radius=2., initial_samples=8,
60 batch_size=16, seed=0):
61 self.archives = tuple(archives)
62 self._initializers, self._mutations, self._descriptors = map(tuple, (initialize, mutations, descriptors))
63 if (len(self.archives) != 2 or self.archives[0] is self.archives[1]
64 or any(type(grid) is not Grid or grid.parents or len(grid)
65 or grid.max_items_per_bin != 1 or grid.discard_random_on_bin_overload
66 or grid.fitness_score_names or grid.features_score_names
67 or len(grid.fitness_domain or ()) != 1 or len(grid.fitness_weights or ()) != 1
68 or not np.isfinite(grid.fitness_weights[0]) or not grid.fitness_weights[0]
69 for grid in self.archives)):
70 raise ValueError("Supply two empty, parentless, native best-only grids with signed fitness.")
71 first, second = self.archives
72 if (first.shape != second.shape or first.fitness_weights != second.fitness_weights
73 or first.fitness_domain != second.fitness_domain):
74 raise ValueError("The two grids need matching shapes, objective directions, and fitness bounds.")
75 if (any(len(callbacks) != 2 for callbacks in (self._initializers, self._mutations, self._descriptors))
76 or not all(map(callable, (*self._initializers, *self._mutations, *self._descriptors, evaluate)))):
77 raise ValueError("Provide one initializer, mutation, and descriptor callback per component.")
78 if coupling not in ("local-best", "global-best", "identity", "center", "random"):
79 raise ValueError("Unknown CoME coupling strategy.")
80 if not 0. < radius < np.inf:
81 raise ValueError("radius must be finite and positive.")
82 self._weight = first.fitness_weights[0]
83 self._evaluate, self.coupling, self.radius = evaluate, coupling, radius
84 self.partners = _positive_int(partners, "partners")
85 self.initial_samples = _positive_int(initial_samples, "initial_samples")
86 self.batch_size = _positive_int(batch_size, "batch_size")
87 self._rng = np.random.default_rng(seed)
88 self._local = ({}, {})
89 self._global = None
90 self._initial_evaluations = self._next_side = 0
91
92 def _describe(self, side, part):
93 hash(part)
94 features = tuple(map(float, self._descriptors[side](part)))
95 grid = self.archives[side]
96 if (len(features) != len(grid.shape) or not np.isfinite(features).all()
97 or not grid.in_bounds(features, grid.features_domain)):
98 raise ValueError("Use finite component descriptors within the corresponding grid bounds.")
99 return features, grid.index_grid(features)
100
101 def _partner_indices(self, side, source_cell, partner_cells, count):
102 if self.coupling == "random":
103 center = partner_cells[self._rng.integers(len(partner_cells))]
104 else:
105 target = source_cell
106 if self.coupling == "center":
107 target = tuple((n - 1) // 2 for n in self.archives[1 - side].shape)
108 elif self.coupling == "global-best" and self._global is not None:
109 target = self._global[1][1 - side]
110 elif self.coupling == "local-best" and source_cell in self._local[side]:
111 target = self._local[side][source_cell][1]
112 distances = np.sum((partner_cells - target) ** 2, axis=1)
113 center = partner_cells[self._rng.choice(np.flatnonzero(distances == distances.min()))]
114 distances = np.linalg.norm(partner_cells - center, axis=1)
115 nearby = np.flatnonzero(distances < self.radius)
116 return self._rng.choice(nearby, min(count, len(nearby)), replace=False)
117
118 def _offspring(self, size):
119 entries = [tuple((grid.index_grid(item), item) for item in grid) for grid in self.archives]
120 cells = [np.asarray([cell for cell, _ in side]) for side in entries]
121 produced = 0
122 while produced < size:
123 side = self._next_side
124 self._next_side = 1 - side
125 source = entries[side]
126 parent = source[self._rng.integers(len(source))][1][side]
127 part = self._mutations[side](parent, self._rng)
128 features, cell = self._describe(side, part)
129 indices = self._partner_indices(side, cell, cells[1 - side], min(self.partners, size - produced))
130 for index in indices:
131 other_cell, other = entries[1 - side][index]
132 records = ((part, features, cell), (other[1 - side], tuple(other.features), other_cell))
133 produced += 1
134 yield records if side == 0 else records[::-1]
135
136 def _commit(self, measured):
137 updates = 0
138 for records, quality in measured:
139 parts, descriptors, cells = zip(*records)
140 signed = self._weight * quality
141 if self.coupling == "global-best" and (self._global is None or signed > self._global[0]):
142 self._global = signed, cells
143 for side, (grid, features, cell) in enumerate(zip(self.archives, descriptors, cells)):
144 if self.coupling == "local-best":
145 previous = self._local[side].get(cell)
146 if previous is None or signed > previous[0]:
147 self._local[side][cell] = signed, cells[1 - side]
148 if grid.free or grid.solutions[cell]:
149 elite = Individual(list(parts), fitness=Fitness((quality,), weights=(self._weight,)),
150 features=Features(features))
151 updates += grid.add(elite) is not None
152 return updates
153
154
155 def run(self, budget):
156 """Continue from the live archives and coupling maps for budget pair evaluations."""
157 budget = _positive_int(budget, "budget")
158 evaluations = generations = updates = 0
159 while evaluations < budget:
160 size = min(self.batch_size, budget - evaluations)
161 if self._initial_evaluations < self.initial_samples or not all(map(len, self.archives)):
162 remaining_warmup = self.initial_samples - self._initial_evaluations
163 if remaining_warmup > 0:
164 size = min(size, remaining_warmup)
165 proposals = (tuple((part, *self._describe(side, part)) for side, part in enumerate(parts))
166 for parts in (tuple(init(self._rng) for init in self._initializers) for _ in range(size)))
167 initializing = True
168 else:
169 proposals = self._offspring(size)
170 initializing = False
171 measured = []
172 for records in proposals:
173 quality = float(self._evaluate(tuple(record[0] for record in records)))
174 if not np.isfinite(quality):
175 raise ValueError("CoME needs finite pair fitness.")
176 if self.archives[0].in_bounds((quality,), self.archives[0].fitness_domain):
177 measured.append((records, quality))
178 updates += self._commit(measured)
179 self._initial_evaluations += size if initializing else 0
180 evaluations += size
181 generations += 1
182 return CoMEStats(evaluations, generations, updates)
Counts from one CoME run call.
Definition come.py:21
Coevolve two specialized archives using separate coupling maps.
Definition come.py:35
run(self, budget)
Score exactly the requested number of complete pairs.
Definition come.py:155
_partner_indices(self, side, source_cell, partner_cells, count)
Definition come.py:101
_commit(self, measured)
Definition come.py:136
_describe(self, side, part)
Definition come.py:92
_offspring(self, size)
Definition come.py:118
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405