36 """Mutate one component and evaluate it with neighbors of a chosen partner cell.
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.
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.
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):
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]
70 raise ValueError(
"Supply two empty, parentless, native best-only grids with signed fitness.")
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.")
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]
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)
92 def _describe(self, side, part):
94 features = tuple(map(float, self.
_descriptors[side](part)))
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)
101 def _partner_indices(self, side, source_cell, partner_cells, count):
103 center = partner_cells[self.
_rng.integers(len(partner_cells))]
107 target = tuple((n - 1) // 2
for n
in self.
archives[1 - side].shape)
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)
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]
122 while produced < size:
125 source = entries[side]
126 parent = source[self.
_rng.integers(len(source))][1][side]
128 features, cell = self.
_describe(side, part)
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))
134 yield records
if side == 0
else records[::-1]
136 def _commit(self, measured):
138 for records, quality
in measured:
139 parts, descriptors, cells = zip(*records)
140 signed = self.
_weight * quality
143 for side, (grid, features, cell)
in enumerate(zip(self.
archives, descriptors, cells)):
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]:
151 updates += grid.add(elite)
is not None
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)
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)))
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.")
177 measured.append((records, quality))
178 updates += self.
_commit(measured)
182 return CoMEStats(evaluations, generations, updates)