QDpy
Loading...
Searching...
No Matches
deep_voronoi_occupancy.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Seeded CPU comparisons for Deep QD, Voronoi-Elites and occupancy CVT-MAP-Elites."""
6
7import argparse
8import json
9import random
10from time import perf_counter
11
12import numpy as np
13from scipy.spatial.distance import pdist, squareform
14
15from qdpy.algorithms import (ConditionalConfiguration, DeepQD, DominatedNoveltySearch, HiGeME,
16 IntegerVariable, OccupancyHistogram, OccupancyMAPElites, RealVariable,
17 TraceElites, VoronoiElites, autoqd_search)
18from qdpy.containers import Grid, TraceArchive, VoronoiArchive
19from qdpy.phenotype import Features, Fitness, Individual
20from qdpy.tools import iso_line_dd
21
22
23def _grid(shape, bounds=(0., 1.)):
24 return Grid(shape=shape, features_domain=(bounds,) * len(shape),
25 fitness_domain=((0., 2.),), fitness_weights=(1.,))
26
27
28def _offer(grid, genome, value, features):
29 grid.add(Individual(list(genome), fitness=Fitness((value,), weights=(1.,)), features=Features(features)))
30
31
32_LAYOUTS = (
33 ConditionalConfiguration({"layout": "sheet"}, ("span", "gauge"), ("buckling",)),
34 ConditionalConfiguration({"layout": "ribbed"}, ("span", "gauge", "ribs"), ("stock",)),
35 ConditionalConfiguration({"layout": "laminate"}, ("span", "gauge", "binder"), ("available",)),
36)
37_VARIABLES = {"span": RealVariable(0., 1.), "gauge": RealVariable(0., 1.),
38 "ribs": IntegerVariable(1, 5), "binder": RealVariable(0., 1.)}
39
40
41def _panel(design):
42 span, gauge = design["span"], design["gauge"]
43 if design["layout"] == "sheet":
44 value = 1.82 - .18 * span - .4 * (gauge - .45)**2
45 residuals = {"buckling": span - .86}
46 elif design["layout"] == "ribbed":
47 value = 1.68 - .16 * (1. - span) - .3 * (gauge - .62)**2 - .009 * (design["ribs"] - 3)**2
48 residuals = {"stock": .12 - span}
49 else:
50 value = 1.57 - .2 * (span - .65)**2 - .4 * (gauge - .25)**2 - .12 * (design["binder"] - .5)**2
51 residuals = {"available": .21 - span}
52 return (value,), (span,), residuals
53
54
55
56def deep_trial(seed, budget):
57 """Use the same three feasible design families and the same measured budget."""
58 for cls, method in ((HiGeME, "higeme"), (DeepQD, "deep-qd")):
59 start = perf_counter()
60 grid = _grid((12,))
61 search = cls(grid, budget, _VARIABLES, configurations=_LAYOUTS,
62 batch_size=8, optimisation_task="maximisation", seed=seed)
63
64 def evaluate(genome):
65 return _panel(search.decode(genome))
66
67 search.optimise(evaluate)
68 counts = (search.deep_archive.configuration_counts if method == "deep-qd"
69 else tuple(sum(ind[0] == branch for ind in grid) for branch in range(len(_LAYOUTS))))
70 yield dict(study="deep", method=method, seed=seed, evaluations=search.nb_evaluations,
71 cells=grid.filled_bins, configuration_counts=counts, retained=sum(counts),
72 mean_configurations=sum(counts) / len(grid), best_cell_qd=grid.qd_score(False),
73 elapsed_s=perf_counter() - start)
74
75
76def _islands(genome):
77 x, y, alpha, beta = genome
78 descriptor = (.48 * x + .52 * (alpha >= .5), y)
79 peaks = [.5 + 1.4 * np.exp(-8 * ((x - u)**2 + (y - v)**2)) for u, v in ((.25, .8), (.8, .3))]
80 return (float(max(peaks) - .27 * (beta - .4)**2),), descriptor
81
82
83
84def voronoi_trial(seed, budget, capacity):
85 """Give both methods the same Gaussian variation scale and archive capacity."""
86 domain = ((0., 1.),) * 2
87 for method in ("voronoi", "dns"):
88 random.seed(seed)
89 np.random.seed(seed)
90 start = perf_counter()
91 if method == "voronoi":
92 archive = VoronoiArchive(capacity, features_domain=domain, fitness_domain=((0., 2.),),
93 storage_type="orderedset")
94 search = VoronoiElites(archive, budget, 4, batch_size=8, initial_samples=8, sigma=.08, seed=seed)
95 else:
96 search = DominatedNoveltySearch(budget, 4, capacity, 8, iso_sigma=.08, line_sigma=0.,
97 fitness_domain=((0., 2.),), optimisation_task="maximisation")
98 search.optimise(_islands, batch_mode=True)
99 archive = search.container
100 report = _grid((8, 8))
101 for elite in archive:
102 report.add(elite)
103 near = None
104 if len(archive) > 1:
105 distances = squareform(pdist([ind.features.values for ind in archive]))
106 np.fill_diagonal(distances, np.inf)
107 near = float(distances.min(axis=1).mean())
108 yield dict(study="voronoi", method=method, seed=seed, evaluations=search.nb_evaluations,
109 capacity=capacity, retained=len(archive), reporting_cells=report.filled_bins,
110 qd_score=report.qd_score(False), mean_nearest_distance=near,
111 elapsed_s=perf_counter() - start)
112
113
114
115def capacity_trial(seed, offers):
116 """Preload the archive before timing a fixed stream of new candidates."""
117 for capacity in (32, 128, 512):
118 rng = np.random.default_rng(seed)
119 archive = VoronoiArchive(capacity, features_domain=((0., 1.),) * 2, storage_type="orderedset")
120 points = rng.random((capacity + offers, 3))
121 candidates = [Individual((i,), fitness=Fitness((float(z),), weights=(1.,)), features=Features((x, y)))
122 for i, (x, y, z) in enumerate(points)]
123 for candidate in candidates[:capacity]:
124 archive.add(candidate)
125 start = perf_counter()
126 for candidate in candidates[capacity:]:
127 archive.add(candidate)
128 elapsed = perf_counter() - start
129 yield dict(study="capacity", method="voronoi", seed=seed, capacity=capacity,
130 offers=offers, admitted=archive.nb_added - capacity, elapsed_s=elapsed,
131 microseconds_per_offer=elapsed / offers * 1e6)
132
133
134
135def navigate(genome):
136 """Return a scalar navigation score and a trajectory of 25 positions."""
137 end_x, end_y, turn, pace = genome
138 t = np.linspace(0., 1., 25)[:, None]**(.65 + 1.5 * pace)
139 path = ((1. - t)**2 * [.08, .5] + 2 * t * (1. - t) * [.52, turn]
140 + t**2 * [end_x, end_y])
141 x, y = path.T
142 hits = np.flatnonzero((.38 <= x) & (x <= .64) & (.43 <= y) & (y <= .57))
143 if hits.size:
144 path[hits[0]:] = path[hits[0] - 1]
145 error = np.square(path[-1] - [.9, .54]).sum()
146 return float(.3 + 1.6 * np.exp(-5 * error) - .22 * bool(hits.size)), path
147
148
149def _endpoint_archive(evaluate, geometry, seed, budget):
150 rng = np.random.default_rng(seed)
151 for step in range(budget):
152 if step < 16 or not len(geometry):
153 point = rng.random(4)
154 else:
155 first, second = rng.integers(len(geometry), size=2)
156 point = iso_line_dd(geometry[first], geometry[second], bounds=(0., 1.), rng=rng)
157 fitness, path = evaluate(point)
158 _offer(geometry, point, fitness, path[-1])
159 return geometry
160
161
162
163def occupancy_trial(seed, budget, with_autoqd=False):
164 """Share real evaluation budgets and audit the retained measured paths."""
165 reference = np.random.default_rng(119).random((512, 2))
166 histogram = OccupancyHistogram.fit(reference, 12, seed=119)
167 methods = ("occupancy", "endpoint", "trace") + (("autoqd",) if with_autoqd else ())
168 for method in methods:
169 calls, observations = 0, {}
170
171 def evaluate(genome):
172 nonlocal calls
173 calls += 1
174 fitness, path = navigate(genome)
175 observations[tuple(genome)] = (fitness, path)
176 return fitness, path
177
178 start = perf_counter()
179 if method == "occupancy":
180 archive = histogram.make_archive(64, fitness_domain=(0., 2.), seed=seed)
181 search = OccupancyMAPElites(archive, budget, 4, histogram=histogram, seed=seed)
182 search.optimise(evaluate)
183 elif method == "endpoint":
184 archive = _endpoint_archive(evaluate, _grid((8, 8)), seed, budget)
185 elif method == "trace":
186 archive = TraceArchive(_grid((8, 8)))
187 TraceElites(archive, 4, iso_sigma=.01, seed=seed).run(evaluate, budget)
188 else:
189 def evaluate_autoqd(genome, _seed):
190 score, path = evaluate(genome)
191 return score, [path]
192
193 archive = autoqd_search(evaluate_autoqd, _grid((8, 8), (-1.2, 1.2)),
194 budget=budget, x0=[.5] * 4, sigma0=.2, threshold_min=0.,
195 trajectory_width=2, batch_size=8, embedding_dim=16,
196 update_interval=5, ind_domain=(0., 1.), seed=seed).archive
197 endpoints = _grid((8, 8))
198 paths = TraceArchive(_grid((8, 8)))
199 genomes = {elite.genome if method == "trace" else tuple(elite) for elite in archive}
200 # Keep tie handling independent of hash ordering during rebinning.
201 for genome in sorted(genomes):
202 value, path = observations[genome]
203 _offer(endpoints, genome, value, path[-1])
204 paths.add(genome, value, path)
205 best = max(observations[genome][0] for genome in genomes)
206 yield dict(study="occupancy", method=method, seed=seed, evaluations=calls, trajectory_steps=calls * 25,
207 retained=len(genomes), search_cells=archive.filled_bins, endpoint_cells=endpoints.filled_bins,
208 trace_cells=paths.filled_bins, endpoint_qd=endpoints.qd_score(False), best=best,
209 elapsed_s=perf_counter() - start)
210
211
212def main():
213 parser = argparse.ArgumentParser(description=__doc__)
214 parser.add_argument("method", choices=("deep", "voronoi", "capacity", "occupancy"))
215 parser.add_argument("--budget", type=int, help="Evaluation budget or number of timed offers")
216 parser.add_argument("--capacity", type=int, default=32, help="Archive capacity for the Voronoi search comparison")
217 parser.add_argument("--seeds", nargs="+", type=int, default=[7, 13, 23])
218 parser.add_argument("--with-autoqd", action="store_true", help="Include AutoQD using the optional cma extra")
219 args = parser.parse_args()
220 minimum = 3 if args.method == "deep" else 1
221 if args.capacity < 1 or (args.budget is not None and args.budget < minimum):
222 parser.error(f"Use a positive capacity and a budget of at least {minimum} for {args.method}.")
223 if args.with_autoqd and args.method != "occupancy":
224 parser.error("--with-autoqd is available with occupancy.")
225 for seed in args.seeds:
226 if args.method == "deep":
227 trial = deep_trial(seed, args.budget or 480)
228 elif args.method == "voronoi":
229 trial = voronoi_trial(seed, args.budget or 400, args.capacity)
230 elif args.method == "capacity":
231 trial = capacity_trial(seed, args.budget or 128)
232 else:
233 trial = occupancy_trial(seed, args.budget or 320, args.with_autoqd)
234 for row in trial:
235 print(json.dumps(row, allow_nan=False))
236
237
238if __name__ == "__main__":
239 main()