QDpy
Loading...
Searching...
No Matches
new_qd_families.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run paired CPU comparisons and optionally export verified replay data."""
6
7import argparse
8import ast
9import json
10import random
11from collections import Counter
12from functools import lru_cache
13from heapq import heappop, heappush
14from itertools import combinations, count
15from pathlib import Path
16
17import numpy as np
18
19from qdpy.algorithms import (
20 AsyncQDHalving,
21 EliteReplay,
22 IsoLineMAPElites,
23 MagnitudeArchive,
24 MagnitudeGoExplore,
25 MedoidArchive,
26 MedoidMAPElites,
27 QDHyperband,
28 VariableConstraintMAPElites,
29)
30from qdpy.containers import Grid
31
32JOBS = ((2, 6, 3), (4, 10, 1), (3, 8, 4), (5, 12, 2), (2, 4, 1), (3, 16, 2))
33STRATEGIES = ("direct", "compensate", "split")
34PROBLEMS = {"17+19": (17, 19), "24+29": (24, 29), "37+48": (37, 48)}
35FIDELITIES = (1, 3, 9)
36
37
38def make_grid(bins):
39 """Use unit descriptor bounds and a common quality scale."""
40 return Grid(shape=(bins,), features_domain=((0., 1.),), fitness_domain=((0., 1.),),
41 fitness_weights=(1.,))
42
43
44def permutation(rng):
45 """Draw a permutation of all jobs."""
46 return tuple(map(int, rng.permutation(len(JOBS))))
47
48
49def swap(parent, rng):
50 """Swap two distinct jobs."""
51 first, second = rng.choice(len(parent), 2, replace=False)
52 child = list(parent)
53 child[first], child[second] = child[second], child[first]
54 return tuple(child)
55
56
57def schedule(order):
58 """Measure weighted tardiness and the completion times of two jobs."""
59 clock, tardiness = 0, 0
60 completed = {}
61 for job in order:
62 duration, due, weight = JOBS[job]
63 clock += duration
64 completed[job] = clock
65 tardiness += weight * max(0, clock - due)
66 quality = 1. / (1. + tardiness / 20)
67 return quality, ((order[0] + .5) / len(JOBS),), {
68 "completion_0": completed[0], "completion_4": completed[4]}
69
70
71def constraints_comparison(seed, budget):
72 """Measure coverage across a deadline change with or without retained alternatives."""
73 rows = []
74 initial, final = {"completion_0": (None, 13)}, {"completion_0": (None, 9), "completion_4": (None, 9)}
75 for method, history in (("history", 3 * budget), ("elite-only", 0), ("restart", 0)):
76 search = VariableConstraintMAPElites(make_grid(len(JOBS)), score_names=tuple(final),
77 constraints=final if method == "restart" else initial,
78 history_size=history, propose=permutation, mutate=swap, seed=seed)
79 if method != "restart":
80 search.run(schedule, budget=3 * budget)
81 search.set_constraints(final)
82 initial_cells = len(search.archive)
83 recovery = 0 if initial_cells == len(JOBS) else None
84 for step in range(1, budget + 1):
85 search.run(schedule, budget=1)
86 if recovery is None and len(search.archive) == len(JOBS):
87 recovery = step
88 rows.append({
89 "task": "constraints", "method": method, "seed": seed, "immediate_cells": initial_cells,
90 "calls_to_full_coverage": recovery, "final_cells": len(search.archive),
91 "final_qd": search.archive.qd_score(), "pre_change_calls": 0 if method == "restart" else 3 * budget,
92 "post_change_calls": budget,
93 })
94 return rows
95
96
97@lru_cache(maxsize=8192)
98def kendall(first, second):
99 """Count pairs of jobs whose relative order differs."""
100 positions = {job: i for i, job in enumerate(second)}
101 return sum(positions[a] > positions[b] for a, b in combinations(first, 2))
102
103
104def magnitude_comparison(seed, budget):
105 """Compare internal niches by scoring their elites on a shared projection."""
106 rng = np.random.default_rng(2026)
107 panel = tuple(permutation(rng) for _ in range(30))
108 medoids = MedoidArchive.fit(panel, 12, kendall)
109 ranked = MagnitudeArchive.from_reference(panel, kendall, count=6, rank=2, capacity=12)
110 rows = []
111 for method in ("medoids", "ranked-uniform", "ranked-magnitude"):
112 if method == "medoids":
113 search = MedoidMAPElites(medoids, propose=permutation, mutate=swap, seed=seed)
114 else:
115 archive = MagnitudeArchive(ranked.landmarks, kendall, rank=2, capacity=12)
116 search = MagnitudeGoExplore(archive, propose=permutation, mutate=swap, seed=seed,
117 selection="uniform" if method == "ranked-uniform" else "magnitude")
118 archive = search.optimise(lambda order: (schedule(order)[0], order), budget=budget)
119 common = {}
120 for elite in archive:
121 key = (elite.genome[0], elite.genome[1] % 2)
122 common[key] = max(common.get(key, 0.), elite.fitness)
123 distances = [kendall(a.descriptor, b.descriptor) for a, b in combinations(archive, 2)]
124 rows.append({
125 "task": "magnitude", "method": method, "seed": seed, "evaluations": search.nb_evaluations,
126 "projected_cells": len(common), "projected_qd": sum(common.values()), "retained": len(archive),
127 "mean_kendall": float(np.mean(distances)) if distances else 0.,
128 })
129 return rows
130
131
132def fidelity_measure(genome, fidelity):
133 """Measure a niche-dependent objective with shifted low-fidelity optima."""
134 x, y = genome
135 target = .15 + .7 * np.cos(np.pi * x) ** 2
136 bias = .25 * (1 - fidelity / FIDELITIES[-1])
137 quality = .35 + .65 * np.exp(-((y - target - bias) * 7.) ** 2)
138 return float(quality), (float(np.clip(x - .2 * bias, 0., 1.)),)
139
140
141def duration(genome, fidelity):
142 """Give candidates in the first three of eight niches longer worker durations."""
143 x, y = genome
144 return fidelity * (1 + 4 * int(x < .375) + int(y > .7))
145
146
147def simulate(ask, tell, archive, workers):
148 """Replay a deterministic parallel completion schedule with virtual worker ticks."""
149 serial = count()
150 now = 0
151 jobs, trace = [], [(0, 0.)]
152 while True:
153 while len(jobs) < workers and (job := ask()) is not None:
154 ticket, genome, fidelity = job
155 heappush(jobs, (now + duration(genome, fidelity), next(serial), ticket, genome, fidelity))
156 if not jobs:
157 return trace
158 now, _, ticket, genome, fidelity = heappop(jobs)
159 tell(ticket, fidelity_measure(genome, fidelity))
160 trace.append((now, archive.qd_score()))
161
162
163def fidelity_comparison(seed, budget):
164 """Compare methods under one shared cost ceiling and four-worker model."""
165 workers = 4
166
167 def summary(method, archive, spent, trace):
168 early = [quality for tick, quality in trace if tick <= 100]
169 return {
170 "task": "fidelity", "method": method, "seed": seed, "ceiling": budget, "spent": spent,
171 "cells": len(archive), "slow_cells": sum(int(archive.index_grid(elite)[0] < 3) for elite in archive),
172 "final_qd": archive.qd_score(), "worker_ticks": trace[-1][0] if trace else None,
173 "qd_at_tick_100": early[-1] if early else None, "trace": trace or None,
174 }
175
176 def async_trial(method, late_fraction):
177 archive = make_grid(8)
178 halving = AsyncQDHalving(archive, 2, FIDELITIES, budget=budget, seed=seed, late_fraction=late_fraction)
179
180 def ask_fidelity():
181 request = halving.ask()
182 return (request, request.genome, request.fidelity) if request else None
183
184 trace = simulate(ask_fidelity, halving.tell, archive, workers)
185 return summary(method, archive, halving.spent, trace)
186
187 rows = [async_trial("async-halving", .25), async_trial("async-unreserved", 0.)]
188
189 archive = make_grid(8)
190 halving = QDHyperband(archive, 2, FIDELITIES, seed=seed)
191 halving.run(fidelity_measure, budget)
192 rows.append(summary("qdHB", archive, halving.spent, ()))
193
194 random.seed(seed)
195 np.random.seed(seed)
196 archive = make_grid(8)
197 full_trials = budget // FIDELITIES[-1]
198 full = IsoLineMAPElites(archive, full_trials, 2, optimisation_task="maximisation",
199 batch_size=workers, iso_sigma=.12)
200
201 def ask_full():
202 if full.nb_suggestions < full_trials:
203 candidate = full.ask()
204 return candidate, tuple(candidate), FIDELITIES[-1]
205 return None
206
207 def tell_full(candidate, result):
208 score, descriptor = result
209 full.tell(candidate, fitness=(score,), features=descriptor)
210
211 trace = simulate(ask_full, tell_full, archive, workers)
212 rows.append(summary("async-map-elites", archive, full.nb_evaluations * FIDELITIES[-1], trace))
213 return rows
214
215
216def arithmetic_proposal(problem, target, parent, rng):
217 """Emulate a proposer that favors direct sums and sometimes misses its target."""
218 strategy = target[0] if target is not None and rng.random() < .8 else rng.choice(
219 STRATEGIES, p=(.93, .05, .02))
220 a, b = PROBLEMS[problem]
221 if rng.random() < .15:
222 b += 1
223 offset = int(rng.integers(1, 10))
224 if strategy == "compensate":
225 return f"({a}+{b + offset})-{offset}"
226 if strategy == "split":
227 return f"{a}+({b - offset}+{offset})"
228 return f"{a}+{b}"
229
230
231def arithmetic_verifier(problem, solution):
232 """Check a small integer expression and label its achieved strategy independently."""
233 def value(node):
234 if isinstance(node, ast.Constant) and type(node.value) is int:
235 return node.value
236 if isinstance(node, ast.BinOp):
237 if isinstance(node.op, ast.Add):
238 return value(node.left) + value(node.right)
239 if isinstance(node.op, ast.Sub):
240 return value(node.left) - value(node.right)
241 raise ValueError("Only integer addition and subtraction are allowed.")
242
243 try:
244 tree = ast.parse(solution, mode="eval").body
245 if value(tree) != sum(PROBLEMS[problem]):
246 return None
247 except (SyntaxError, ValueError):
248 return None
249 if isinstance(tree, ast.BinOp):
250 if isinstance(tree.op, ast.Sub) and isinstance(tree.left, ast.BinOp):
251 return "compensate"
252 if isinstance(tree.op, ast.Add):
253 return "split" if isinstance(tree.right, ast.BinOp) else "direct"
254 return None
255
256
257def replay_comparison(seed, budget, export=None):
258 """Compare verified strategy coverage at the same proposal budget."""
259 rows = []
260 for guided in (True, False):
261 search = EliteReplay(dict.fromkeys(PROBLEMS, STRATEGIES), seed=seed)
262 dataset = search.run(arithmetic_proposal, arithmetic_verifier, budget=budget, guided=guided)
263 if export is not None and guided:
264 dataset.save(export)
265 spread = Counter(entry.problem for entry in dataset.entries)
266 stats = search.stats
267 rows.append({
268 "task": "replay", "method": "guided" if guided else "independent", "seed": seed,
269 "proposals": stats.proposals, "verifications": stats.verifications,
270 "correct": stats.verified, "strategies": len(dataset), "per_problem": dict(spread),
271 })
272 return rows
273
274
275def main():
276 """Run a single workload or all four and write their per-seed results."""
277 workloads = {"constraints": (constraints_comparison, 32), "magnitude": (magnitude_comparison, 128),
278 "fidelity": (fidelity_comparison, 216), "replay": (replay_comparison, 48)}
279 parser = argparse.ArgumentParser(description=__doc__)
280 parser.add_argument("task", choices=(*workloads, "all"))
281 parser.add_argument("--budget", type=int, help="Override the selected workload's native budget.")
282 parser.add_argument("--seeds", type=int, nargs="+", default=[11, 12, 13, 14, 15])
283 parser.add_argument("--output", type=Path, help="Write comparison rows as JSONL.")
284 parser.add_argument("--replay-out", type=Path, help="Export the first seed's guided replay data.")
285 args = parser.parse_args()
286 tasks = workloads if args.task == "all" else (args.task,)
287 if args.budget is not None and (args.budget < 1 or "fidelity" in tasks and args.budget < FIDELITIES[-1]):
288 parser.error("Use a positive budget of at least 9 when running fidelity.")
289 if args.replay_out is not None and "replay" not in tasks:
290 parser.error("--replay-out requires the replay workload.")
291 results = []
292 for task in tasks:
293 compare, default = workloads[task]
294 for idx, seed in enumerate(args.seeds):
295 options = {"export": args.replay_out} if task == "replay" and idx == 0 else {}
296 results.extend(compare(seed, args.budget or default, **options))
297 report = "".join(json.dumps(row, sort_keys=True) + "\n" for row in results)
298 if args.output:
299 args.output.write_text(report, encoding="utf-8")
300 else:
301 print(report, end="")
302
303
304if __name__ == "__main__":
305 main()