# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare four QD workflows on scheduling, fidelity ladders, and arithmetic. """Run paired CPU comparisons and optionally export verified replay data.""" import argparse import ast import json import random from collections import Counter from functools import lru_cache from heapq import heappop, heappush from itertools import combinations, count from pathlib import Path import numpy as np from qdpy.algorithms import ( AsyncQDHalving, EliteReplay, IsoLineMAPElites, MagnitudeArchive, MagnitudeGoExplore, MedoidArchive, MedoidMAPElites, QDHyperband, VariableConstraintMAPElites, ) from qdpy.containers import Grid JOBS = ((2, 6, 3), (4, 10, 1), (3, 8, 4), (5, 12, 2), (2, 4, 1), (3, 16, 2)) STRATEGIES = ("direct", "compensate", "split") PROBLEMS = {"17+19": (17, 19), "24+29": (24, 29), "37+48": (37, 48)} FIDELITIES = (1, 3, 9) def make_grid(bins): """Use unit descriptor bounds and a common quality scale.""" return Grid(shape=(bins,), features_domain=((0., 1.),), fitness_domain=((0., 1.),), fitness_weights=(1.,)) def permutation(rng): """Draw a permutation of all jobs.""" return tuple(map(int, rng.permutation(len(JOBS)))) def swap(parent, rng): """Swap two distinct jobs.""" first, second = rng.choice(len(parent), 2, replace=False) child = list(parent) child[first], child[second] = child[second], child[first] return tuple(child) def schedule(order): """Measure weighted tardiness and the completion times of two jobs.""" clock, tardiness = 0, 0 completed = {} for job in order: duration, due, weight = JOBS[job] clock += duration completed[job] = clock tardiness += weight * max(0, clock - due) quality = 1. / (1. + tardiness / 20) return quality, ((order[0] + .5) / len(JOBS),), { "completion_0": completed[0], "completion_4": completed[4]} def constraints_comparison(seed, budget): """Measure coverage across a deadline change with or without retained alternatives.""" rows = [] initial, final = {"completion_0": (None, 13)}, {"completion_0": (None, 9), "completion_4": (None, 9)} for method, history in (("history", 3 * budget), ("elite-only", 0), ("restart", 0)): search = VariableConstraintMAPElites(make_grid(len(JOBS)), score_names=tuple(final), constraints=final if method == "restart" else initial, history_size=history, propose=permutation, mutate=swap, seed=seed) if method != "restart": search.run(schedule, budget=3 * budget) search.set_constraints(final) initial_cells = len(search.archive) recovery = 0 if initial_cells == len(JOBS) else None for step in range(1, budget + 1): search.run(schedule, budget=1) if recovery is None and len(search.archive) == len(JOBS): recovery = step rows.append({ "task": "constraints", "method": method, "seed": seed, "immediate_cells": initial_cells, "calls_to_full_coverage": recovery, "final_cells": len(search.archive), "final_qd": search.archive.qd_score(), "pre_change_calls": 0 if method == "restart" else 3 * budget, "post_change_calls": budget, }) return rows @lru_cache(maxsize=8192) def kendall(first, second): """Count pairs of jobs whose relative order differs.""" positions = {job: i for i, job in enumerate(second)} return sum(positions[a] > positions[b] for a, b in combinations(first, 2)) def magnitude_comparison(seed, budget): """Compare internal niches by scoring their elites on a shared projection.""" rng = np.random.default_rng(2026) panel = tuple(permutation(rng) for _ in range(30)) medoids = MedoidArchive.fit(panel, 12, kendall) ranked = MagnitudeArchive.from_reference(panel, kendall, count=6, rank=2, capacity=12) rows = [] for method in ("medoids", "ranked-uniform", "ranked-magnitude"): if method == "medoids": search = MedoidMAPElites(medoids, propose=permutation, mutate=swap, seed=seed) else: archive = MagnitudeArchive(ranked.landmarks, kendall, rank=2, capacity=12) search = MagnitudeGoExplore(archive, propose=permutation, mutate=swap, seed=seed, selection="uniform" if method == "ranked-uniform" else "magnitude") archive = search.optimise(lambda order: (schedule(order)[0], order), budget=budget) common = {} for elite in archive: key = (elite.genome[0], elite.genome[1] % 2) common[key] = max(common.get(key, 0.), elite.fitness) distances = [kendall(a.descriptor, b.descriptor) for a, b in combinations(archive, 2)] rows.append({ "task": "magnitude", "method": method, "seed": seed, "evaluations": search.nb_evaluations, "projected_cells": len(common), "projected_qd": sum(common.values()), "retained": len(archive), "mean_kendall": float(np.mean(distances)) if distances else 0., }) return rows def fidelity_measure(genome, fidelity): """Measure a niche-dependent objective with shifted low-fidelity optima.""" x, y = genome target = .15 + .7 * np.cos(np.pi * x) ** 2 bias = .25 * (1 - fidelity / FIDELITIES[-1]) quality = .35 + .65 * np.exp(-((y - target - bias) * 7.) ** 2) return float(quality), (float(np.clip(x - .2 * bias, 0., 1.)),) def duration(genome, fidelity): """Give candidates in the first three of eight niches longer worker durations.""" x, y = genome return fidelity * (1 + 4 * int(x < .375) + int(y > .7)) def simulate(ask, tell, archive, workers): """Replay a deterministic parallel completion schedule with virtual worker ticks.""" serial = count() now = 0 jobs, trace = [], [(0, 0.)] while True: while len(jobs) < workers and (job := ask()) is not None: ticket, genome, fidelity = job heappush(jobs, (now + duration(genome, fidelity), next(serial), ticket, genome, fidelity)) if not jobs: return trace now, _, ticket, genome, fidelity = heappop(jobs) tell(ticket, fidelity_measure(genome, fidelity)) trace.append((now, archive.qd_score())) def fidelity_comparison(seed, budget): """Compare methods under one shared cost ceiling and four-worker model.""" workers = 4 def summary(method, archive, spent, trace): early = [quality for tick, quality in trace if tick <= 100] return { "task": "fidelity", "method": method, "seed": seed, "ceiling": budget, "spent": spent, "cells": len(archive), "slow_cells": sum(int(archive.index_grid(elite)[0] < 3) for elite in archive), "final_qd": archive.qd_score(), "worker_ticks": trace[-1][0] if trace else None, "qd_at_tick_100": early[-1] if early else None, "trace": trace or None, } def async_trial(method, late_fraction): archive = make_grid(8) halving = AsyncQDHalving(archive, 2, FIDELITIES, budget=budget, seed=seed, late_fraction=late_fraction) def ask_fidelity(): request = halving.ask() return (request, request.genome, request.fidelity) if request else None trace = simulate(ask_fidelity, halving.tell, archive, workers) return summary(method, archive, halving.spent, trace) rows = [async_trial("async-halving", .25), async_trial("async-unreserved", 0.)] archive = make_grid(8) halving = QDHyperband(archive, 2, FIDELITIES, seed=seed) halving.run(fidelity_measure, budget) rows.append(summary("qdHB", archive, halving.spent, ())) random.seed(seed) np.random.seed(seed) archive = make_grid(8) full_trials = budget // FIDELITIES[-1] full = IsoLineMAPElites(archive, full_trials, 2, optimisation_task="maximisation", batch_size=workers, iso_sigma=.12) def ask_full(): if full.nb_suggestions < full_trials: candidate = full.ask() return candidate, tuple(candidate), FIDELITIES[-1] return None def tell_full(candidate, result): score, descriptor = result full.tell(candidate, fitness=(score,), features=descriptor) trace = simulate(ask_full, tell_full, archive, workers) rows.append(summary("async-map-elites", archive, full.nb_evaluations * FIDELITIES[-1], trace)) return rows def arithmetic_proposal(problem, target, parent, rng): """Emulate a proposer that favors direct sums and sometimes misses its target.""" strategy = target[0] if target is not None and rng.random() < .8 else rng.choice( STRATEGIES, p=(.93, .05, .02)) a, b = PROBLEMS[problem] if rng.random() < .15: b += 1 offset = int(rng.integers(1, 10)) if strategy == "compensate": return f"({a}+{b + offset})-{offset}" if strategy == "split": return f"{a}+({b - offset}+{offset})" return f"{a}+{b}" def arithmetic_verifier(problem, solution): """Check a small integer expression and label its achieved strategy independently.""" def value(node): if isinstance(node, ast.Constant) and type(node.value) is int: return node.value if isinstance(node, ast.BinOp): if isinstance(node.op, ast.Add): return value(node.left) + value(node.right) if isinstance(node.op, ast.Sub): return value(node.left) - value(node.right) raise ValueError("Only integer addition and subtraction are allowed.") try: tree = ast.parse(solution, mode="eval").body if value(tree) != sum(PROBLEMS[problem]): return None except (SyntaxError, ValueError): return None if isinstance(tree, ast.BinOp): if isinstance(tree.op, ast.Sub) and isinstance(tree.left, ast.BinOp): return "compensate" if isinstance(tree.op, ast.Add): return "split" if isinstance(tree.right, ast.BinOp) else "direct" return None def replay_comparison(seed, budget, export=None): """Compare verified strategy coverage at the same proposal budget.""" rows = [] for guided in (True, False): search = EliteReplay(dict.fromkeys(PROBLEMS, STRATEGIES), seed=seed) dataset = search.run(arithmetic_proposal, arithmetic_verifier, budget=budget, guided=guided) if export is not None and guided: dataset.save(export) spread = Counter(entry.problem for entry in dataset.entries) stats = search.stats rows.append({ "task": "replay", "method": "guided" if guided else "independent", "seed": seed, "proposals": stats.proposals, "verifications": stats.verifications, "correct": stats.verified, "strategies": len(dataset), "per_problem": dict(spread), }) return rows def main(): """Run a single workload or all four and write their per-seed results.""" workloads = {"constraints": (constraints_comparison, 32), "magnitude": (magnitude_comparison, 128), "fidelity": (fidelity_comparison, 216), "replay": (replay_comparison, 48)} parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("task", choices=(*workloads, "all")) parser.add_argument("--budget", type=int, help="Override the selected workload's native budget.") parser.add_argument("--seeds", type=int, nargs="+", default=[11, 12, 13, 14, 15]) parser.add_argument("--output", type=Path, help="Write comparison rows as JSONL.") parser.add_argument("--replay-out", type=Path, help="Export the first seed's guided replay data.") args = parser.parse_args() tasks = workloads if args.task == "all" else (args.task,) if args.budget is not None and (args.budget < 1 or "fidelity" in tasks and args.budget < FIDELITIES[-1]): parser.error("Use a positive budget of at least 9 when running fidelity.") if args.replay_out is not None and "replay" not in tasks: parser.error("--replay-out requires the replay workload.") results = [] for task in tasks: compare, default = workloads[task] for idx, seed in enumerate(args.seeds): options = {"export": args.replay_out} if task == "replay" and idx == 0 else {} results.extend(compare(seed, args.budget or default, **options)) report = "".join(json.dumps(row, sort_keys=True) + "\n" for row in results) if args.output: args.output.write_text(report, encoding="utf-8") else: print(report, end="") if __name__ == "__main__": main()