QDpy
Loading...
Searching...
No Matches
residual_window_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run seeded comparisons and write one JSON object per method and seed."""
6
7import argparse
8import json
9from collections import defaultdict
10from dataclasses import asdict
11from itertools import pairwise, product
12from math import dist, sqrt
13
14import numpy as np
15from scipy.spatial.distance import cdist
16
17from qdpy.algorithms import GSEMOD, MultiDescriptorMAPElites, RealVariable, VoronoiElites, WindowedMAPElites
18from qdpy.containers import Grid, VoronoiArchive
19from qdpy.symbolic import Expression, residual_symbolic_regression
20
21
22def maze(genome):
23 """Return four route samples and the final location of a two-segment navigation plan."""
24 start, goal = (.05, .5), (.95, .5)
25 route = [start]
26 for first, last in pairwise((start, genome[:2], genome[2:])):
27 for step in range(1, 17):
28 point = tuple(a + (b - a) * (step / 16) for a, b in zip(first, last))
29 if .42 <= point[0] <= .58 and .22 <= point[1] <= .78:
30 break
31 route.append(point)
32 else:
33 continue
34 break
35 route.extend([route[-1]] * (33 - len(route)))
36 features = tuple(value for i in (8, 16, 24, 32) for value in route[i])
37 return 1. - dist(route[-1], goal) / sqrt(2.), route[-1], features
38
39
40def report_grid():
41 """Use shared geometry for comparing search archives."""
42 return Grid(shape=(12, 12), features_domain=((0., 1.),) * 2,
43 fitness_domain=((0., 1.),), fitness_weights=(1.,))
44
45
46def voronoi_trial(seed, budget):
47 """Compare Voronoi-Elites with and without extinction on a wall maze."""
48 for method in ("ordinary", "extinction"):
49 archive = VoronoiArchive(28, features_domain=((0., 1.),) * 8, fitness_domain=((0., 1.),))
50 kwargs = {} if method == "ordinary" else dict(extinction_period=5, extinction_size=9)
51 search = VoronoiElites(archive, budget, 4, initial_samples=32, batch_size=16, sigma=.095, seed=seed, **kwargs)
52 calls, first_goal = 0, None
53
54 def evaluate(genome):
55 nonlocal calls, first_goal
56 reward, endpoint, trajectory = maze(genome)
57 calls += 1
58 if dist(endpoint, (.95, .5)) < .09 and first_goal is None:
59 first_goal = calls
60 return (reward,), trajectory
61
62 search.optimise(evaluate)
63 cells = {}
64 geometry = report_grid()
65 for row in archive:
66 cell = geometry.index_grid(row.features.values[-2:])
67 cells[cell] = max(cells.get(cell, 0.), row.fitness.values[0])
68 yield dict(method=method, seed=seed, evaluations=calls, first_goal=first_goal, survivors=len(archive),
69 cells=len(cells), qd_score=sum(cells.values()), best=archive.best.fitness.values[0],
70 extinctions=search.extinctions, pruned=search.pruned)
71
72
73def descriptor_trial(seed, budget):
74 """Use maze trajectories for parent selection and endpoints for archive admission."""
75 for method in ("uniform", "novelty", "surprise", "blend", "pareto"):
76 archive = report_grid()
77 search = MultiDescriptorMAPElites(archive, budget, 4, selection_size=8, mode=method, neighbors=6,
78 clusters=7, batch_size=16, iso_sigma=.085, seed=seed)
79
80 def evaluate(genome):
81 quality, endpoint, trajectory = maze(genome)
82 return (quality,), endpoint, {"selection": trajectory}
83
84 search.optimise(evaluate)
85 points = np.array([row.scores["selection"] for row in archive])
86 distances = cdist(points, points)
87 np.fill_diagonal(distances, np.inf)
88 mean_gap = float(distances.min(axis=1).mean()) if len(points) > 1 else 0.
89 yield dict(method=method, seed=seed, evaluations=search.nb_evaluations, cells=len(archive),
90 qd_score=archive.qd_score(), trajectory_gap=mean_gap,
91 best=archive.best.fitness.values[0], forecasts=search.forecasts)
92
93
94def window_trial(seed, budget):
95 """Compare global search with two displays for a fixed scripted preference."""
96 target = (.82, .22)
97
98 def preference(point):
99 return 1. - dist(point, target) / sqrt(2.)
100
101 def evaluate(genome):
102 x, y = genome
103 return (1. - .2 * dist(genome, (.45, .43)),), (x, y), {"clearance": x + y - 1.18}
104
105 def chooser(panel):
106 return max(range(len(panel)), key=lambda i: preference(panel[i].features.values))
107
108 def advance(search, attempts):
109 for offset in range(0, attempts, search.batch_size):
110 batch = search.ask_batch(min(search.batch_size, attempts - offset))
111 search.tell_batch([evaluate(genome) for genome in batch])
112
113 for method in ("global", "corners", "medoids"):
114 archive = report_grid()
115 search = WindowedMAPElites(archive, budget, (RealVariable(0., 1.),) * 2, constraint_names="clearance",
116 window_radius=(.20, .20), batch_size=12, real_sigma=.085,
117 optimisation_task="maximisation", seed=seed)
118 initial = min(budget, 60)
119 advance(search, initial)
120 selected = []
121 for left in range(initial, budget, 36):
122 elite = search.choose(chooser, sampling="medoids" if method == "global" else method)
123 if elite is not None:
124 selected.append(preference(elite.features.values))
125 if method == "global":
126 search.focus(None)
127 advance(search, min(36, budget - left))
128 scores = [preference(row.features.values) for row in archive]
129 yield dict(method=method, seed=seed, evaluations=search.nb_evaluations, cells=len(archive),
130 qd_score=archive.qd_score(), best_preference=max(scores, default=None),
131 mean_preference=float(np.mean(scores)) if scores else None,
132 mean_choice=float(np.mean(selected)) if selected else None,
133 target_cells=sum(value >= .91 for value in scores), choices=len(selected))
134
135
136def lotz_k(bits, k):
137 """Compute the three maximization objectives of the LOTZ-k benchmark."""
138 leading = next((i for i, bit in enumerate(bits) if not bit), len(bits))
139 trailing = next((i for i, bit in enumerate(reversed(bits)) if bit), len(bits))
140 total = leading + trailing
141 return leading, trailing, (len(bits) + 1 - total if total >= len(bits) - k else 0)
142
143
144def binary_trial(seed, budget):
145 """Compare both imbalance measures and ordinary GSEMO on LOTZ-k."""
146 dimension, k = 10, 4
147 front = defaultdict(list)
148 for bits in product(range(2), repeat=dimension):
149 scores = lotz_k(bits, k)
150 if scores[-1]:
151 front[scores].append(bits)
152 choices = [np.asarray(rows) for rows in front.values()]
153 forced_one = sum(rows.min(axis=0) for rows in choices)
154 forced_zero = sum(1 - rows.max(axis=0) for rows in choices)
155 free = len(front) - forced_one - forced_zero
156 minimum = int(np.maximum(abs(forced_one - forced_zero) - free, len(front) % 2).sum())
157 for method in ("none", "total", "lexicographic"):
158 search = GSEMOD(dimension, diversity=method, seed=seed)
159 stats = search.run(lambda bits, rollout_seed: lotz_k(bits, k), budget)
160 found = sum(row.objectives in front for row in search.population)
161 yield dict(method=method, seed=seed, **asdict(stats), total_imbalance=stats.total_imbalance,
162 front_found=found, front_size=len(front), minimum_imbalance=minimum)
163
164
165def residual_trial(seed, budget):
166 """Fit a mixture of opposing lines and score both regimes on fresh points."""
167 rng = np.random.default_rng(seed)
168 x = np.tile(np.linspace(.22, 1.9, 26), 2)[:, None]
169 y = np.concatenate((1.08 * x[:26, 0], -.92 * x[26:, 0])) + rng.normal(0., .025, size=len(x))
170 groups = np.repeat((0, 1), 26)
171 test = np.linspace(.24, 1.86, 32)[:, None]
172 references = (1.08 * test[:, 0], -.92 * test[:, 0])
173 for method in ("structural", "residual"):
174 result = residual_symbolic_regression(
175 x, y, groups=groups, layout=method, budget=budget, fit_evaluations=23, operators=("add", "sub", "mul"),
176 max_nodes=8, max_depth=3, cma_population=5, fit_sigma=1.15, seed=seed,
177 initial_expressions=(Expression.variable(0),),
178 )
179 errors = [min(row.model.rmse(test, target) for row in result.elites) for target in references]
180 yield dict(method=method, seed=seed, **asdict(result.stats), elite_count=len(result.elites),
181 best_robust_loss=result.best.loss, held_out_rmse=errors,
182 recovered_regimes=sum(error <= .12 for error in errors))
183
184
185if __name__ == "__main__":
186 cases = {"voronoi": (voronoi_trial, 704), "descriptors": (descriptor_trial, 480),
187 "window": (window_trial, 276), "binary": (binary_trial, 1800), "residual": (residual_trial, 48)}
188 parser = argparse.ArgumentParser(description=__doc__)
189 parser.add_argument("task", choices=cases)
190 parser.add_argument("--budget", type=int)
191 parser.add_argument("--seeds", nargs="+", type=int, default=[11, 22, 33])
192 args = parser.parse_args()
193 if args.budget is not None and args.budget < 1:
194 parser.error("--budget must be positive")
195 trial, default = cases[args.task]
196 for seed in args.seeds:
197 for record in trial(seed, default if args.budget is None else args.budget):
198 print(json.dumps(record, sort_keys=True))