QDpy
Loading...
Searching...
No Matches
metric_peer_search.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run four small matched-budget comparisons on a CPU."""
6
7import argparse
8from functools import lru_cache
9from itertools import permutations
10import json
11from math import fsum
12
13import numpy as np
14from sklearn.cluster import KMeans
15
16from qdpy.algorithms import (CMAMEGA, DecentralizedMAPElites, EntropyTourSearch, GradientEvaluation,
17 MedoidArchive, MedoidMAPElites, NOAH, tour_segment_entropy)
18from qdpy.containers import CVTGrid, Grid
19from qdpy.phenotype import Features, Fitness, Individual
20
21
22def jaccard(first, second):
23 """Return Jaccard distance between two feature sets, including empty sets."""
24 return 1. - len(first & second) / len(first | second) if first or second else 0.
25
26
27def propose_set(rng):
28 """Sample a group of two to five elements."""
29 return frozenset(map(int, rng.choice(10, int(rng.integers(2, 6)), replace=False)))
30
31
32def mutate_set(parent, rng):
33 """Toggle one group member within the allowed size range."""
34 element = int(rng.integers(10))
35 child = parent ^ {element}
36 return child if 2 <= len(child) <= 5 else parent
37
38
39def evaluate_set(group):
40 """Score benefits and size on a common scale."""
41 quality = sum(1. + .2 * (element % 5) for element in group) / (2. + len(group))
42 return quality, group
43
44
45def _encode_set(group):
46 return tuple(float(element in group) for element in range(10))
47
48
49def medoid_trial(seed, budget):
50 """Compare equal-size niches with a held-out Jaccard target panel."""
51 panel = np.random.default_rng(701)
52 reference = [propose_set(panel) for _ in range(120)]
53 audit = [propose_set(panel) for _ in range(128)]
54 centroids = KMeans(n_clusters=12, n_init=3, random_state=701).fit([_encode_set(ref) for ref in reference])
55
56 def measured(group):
57 quality, _ = evaluate_set(group)
58 return Individual(sorted(group), fitness=Fitness((quality,), weights=(1.,)),
59 features=Features(_encode_set(group)))
60
61 for initial in sorted({1, min(16, budget)}):
62 nearest = MedoidArchive.fit(reference, 12, jaccard)
63 grid = CVTGrid(shape=12, features_domain=((0., 1.),) * 10, fitness_domain=((0., 2.),),
64 fitness_weights=(1.,), centroids=np.clip(centroids.cluster_centers_, 0., 1.))
65 init_rng = np.random.default_rng(seed)
66 for _ in range(initial):
67 group = propose_set(init_rng)
68 candidate = measured(group)
69 grid.add(candidate)
70 nearest.add(group, candidate.fitness.values[0], group)
71 if budget > initial:
72 search = MedoidMAPElites(nearest, propose=propose_set, mutate=mutate_set, seed=seed)
73 search.optimise(evaluate_set, budget=budget - initial)
74 rng = np.random.default_rng(seed)
75 for _ in range(budget - initial):
76 group = mutate_set(frozenset(grid[rng.integers(len(grid))]), rng)
77 grid.add(measured(group))
78 elites = (("Medoid MAP-Elites", [(item.descriptor, item.fitness) for item in nearest]),
79 ("Euclidean CVT", [(frozenset(item), item.fitness.values[0]) for item in grid]))
80 for label, entries in elites:
81 distances = [min(jaccard(target, group) for group, _ in entries) for target in audit]
82 yield dict(method=label, seed=seed, evaluations=budget, initial=initial, cells=len(entries),
83 audit_exact_matches=sum(distance == 0. for distance in distances),
84 audit_mean_distance=float(np.mean(distances)),
85 mean_quality=float(np.mean([quality for _, quality in entries])))
86
87
88def peer_grid():
89 """A shared reporting geometry for all decentralized peers."""
90 return Grid(shape=(24,), features_domain=((0., 1.),), fitness_domain=((0., 1.),), fitness_weights=(1.,))
91
92
93def peer_proposal(peer, rng):
94 """Start each peer in a different portion of the descriptor domain."""
95 return ((peer + .5) / 6., float(rng.random()))
96
97
98def peer_mutation(peer, parent, rng):
99 """Vary position and quality coordinates with a private draw."""
100 return tuple(np.clip(np.asarray(parent) + rng.normal(0., .045, size=2), 0., 1.))
101
102
103def peer_measurement(genome):
104 """Reward the ridge of a synthetic landscape across the descriptor axis."""
105 x, y = genome
106 target = .5 + .4 * np.sin(3 * np.pi * x)
107 return (1. - (target - y) ** 2,), (x,)
108
109
110def peer_trial(seed, budget):
111 """Compare ring, complete, and local-only search with matched evaluator budgets."""
112 for label, topology, messages in (("Ring", "ring", 48), ("Complete", "complete", 48), ("Isolated", "ring", 0)):
113 search = DecentralizedMAPElites(peer_grid(), 6, propose=peer_proposal, mutate=peer_mutation,
114 topology=topology, local_batch_size=2, exchange_period=3, seed=seed)
115 union = search.optimise(peer_measurement, budget=budget, message_budget=messages)
116 yield dict(method=label, seed=seed, evaluations=search.nb_evaluations,
117 messages=search.messages, migrants_admitted=search.migrant_admissions,
118 local_mean_cells=float(np.mean([archive.filled_bins for archive in search.archives])),
119 union_cells=union.filled_bins, union_qd_score=float(sum(item.fitness.values[0] for item in union)))
120
121
122_CURVATURE = np.geomspace(1., .0001, 12)
123_TARGET = np.linspace(-.55, .2, 12)
124
125
126def gradient_design(genome):
127 """Return exact derivatives for an anisotropic objective and two behavior axes."""
128 x = np.asarray(genome)
129 difference = x - _TARGET
130 quality = 1. - .23 * (_CURVATURE @ difference ** 2)
131 descriptors = np.tanh([4. * x[0] + .2 * x[1], .25 * x[1] + .06 * x[2]])
132 jacobian = np.zeros((3, len(x)))
133 jacobian[0] = -.46 * _CURVATURE * difference
134 jacobian[1, :2] = (1. - descriptors[0] ** 2) * np.array([4., .2])
135 jacobian[2, 1:3] = (1. - descriptors[1] ** 2) * np.array([.25, .06])
136 return GradientEvaluation(float(quality), descriptors, jacobian)
137
138
139def gradient_measurement(genome):
140 """Score the same objective and descriptors without computing a Jacobian."""
141 x = np.asarray(genome)
142 quality = 1. - .23 * (_CURVATURE @ (x - _TARGET) ** 2)
143 return (float(quality),), tuple(np.tanh([4. * x[0] + .2 * x[1], .25 * x[1] + .06 * x[2]]))
144
145
146def gradient_trial(seed, budget):
147 """Isolate Adam using the same branching and admission in both variants."""
148 for optimizer in ("adam", "gradient"):
149 grid = Grid(shape=(10, 8), features_domain=((-1., 1.), (-.31, .31)),
150 fitness_domain=((-1., 1.),), fitness_weights=(1.,))
151 search = CMAMEGA(grid, budget, np.zeros(12), .18, 8, gradient_evaluate=gradient_design,
152 centre_optimizer=optimizer, step_size=.12, ind_domain=(-1., 1.), seed=seed)
153 search.optimise(gradient_measurement)
154 yield dict(method=f"CMA-MEGA ({optimizer})", seed=seed, evaluations=search.nb_evaluations,
155 gradient_calls=search.gradient_evaluations, cells=grid.filled_bins,
156 qd_score=float(sum(item.fitness.values[0] for item in grid)))
157
158
159@lru_cache
160def routing_case():
161 """Compute the exact optimum of a small symmetric instance outside the search budget."""
162 points = np.array([[0., 0.], [1.1, .1], [2.03, .2], [3.02, .04], [3.05, 1.13],
163 [2.25, 1.08], [1.05, .95], [.02, 1.02]])
164 matrix = np.linalg.norm(points[:, None] - points, axis=2)
165 tours = [(0, *suffix) for suffix in permutations(range(1, len(points))) if suffix[0] < suffix[-1]]
166 optimum = min(tours, key=lambda tour: tour_cost(matrix, tour))
167 return matrix, optimum, len(tours)
168
169
170def tour_cost(matrix, tour):
171 """Sum the costs of the cyclic tour including the closing edge."""
172 return fsum(matrix[first, second] for first, second in zip(tour, tour[1:] + tour[:1]))
173
174
175def _edges(tour):
176 return frozenset(frozenset(pair) for pair in zip(tour, tour[1:] + tour[:1]))
177
178
179def _edge_distance(first, second):
180 return 1. - len(_edges(first) & _edges(second)) / len(first)
181
182
183def tours_trial(seed, budget):
184 """Compare feasible portfolios using segment entropy on every method."""
185 matrix, start, setup_calls = routing_case()
186 limit = 1.27 * tour_cost(matrix, start)
187 capacity = 8
188 evolution = EntropyTourSearch(matrix, limit, capacity, segment_length=3, seed=seed)
189 entropy = evolution.run([start], budget=budget)
190 comparison = NOAH(capacity, barrier=limit, seed=seed, diversity_scale=2.).run(
191 lambda tour: tour_cost(matrix, tour), budget=budget, propose=lambda rng: start,
192 mutate=evolution._two_opt, distance=_edge_distance,
193 )
194 rng = np.random.default_rng(seed)
195 grid = Grid(shape=(len(start) + 1,), features_domain=((0., 1.),),
196 fitness_domain=((0., float(len(start) * matrix.max())),), fitness_weights=(-1.,))
197 for index in range(budget):
198 parent = start if index == 0 else tuple(grid[rng.integers(len(grid))])
199 candidate = start if index == 0 else evolution._two_opt(parent, rng)
200 value = tour_cost(matrix, candidate)
201 grid.add(Individual(candidate, fitness=Fitness((value,), weights=(-1.,)),
202 features=Features((_edge_distance(start, candidate),))))
203 filtered = sorted((item for item in grid if item.fitness.values[0] <= limit), key=lambda item: item.fitness.values)
204 selections = (("Entropy tour search", [(item.tour, item.cost) for item in entropy.tours]),
205 ("NOAH", [(item.genome, item.fitness) for item in comparison.acceptable]),
206 ("Filtered MAP-Elites", [(tuple(item), item.fitness.values[0]) for item in filtered[:capacity]]))
207 for label, selected in selections:
208 costs = [cost for _, cost in selected]
209 yield dict(method=label, seed=seed, evaluations=budget, shared_setup_calls=setup_calls,
210 count=len(selected), entropy=tour_segment_entropy([tour for tour, _ in selected]), cost_limit=limit,
211 mean_cost=float(np.mean(costs)) if costs else None,
212 worst_cost=max(costs) if costs else None)
213
214
215if __name__ == "__main__":
216 trials = {"medoid": (medoid_trial, 192), "peers": (peer_trial, 240), "gradient": (gradient_trial, 360),
217 "tours": (tours_trial, 320)}
218 parser = argparse.ArgumentParser(description=__doc__)
219 parser.add_argument("task", choices=trials)
220 parser.add_argument("--budget", type=int)
221 parser.add_argument("--seeds", nargs="+", type=int, default=[11, 22, 33])
222 args = parser.parse_args()
223 method, default_budget = trials[args.task]
224 budget = default_budget if args.budget is None else args.budget
225 if budget < 1:
226 parser.error("budget must be positive")
227 for seed in args.seeds:
228 for record in method(seed, budget):
229 print(json.dumps(record, allow_nan=False, sort_keys=True))