# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare novelty ES, Q-learning for operator selection, and deep-archive allocation. """Run three small, seeded search comparisons and report JSON lines.""" import argparse import json from dataclasses import asdict from itertools import pairwise from math import hypot, sqrt from qdpy.algorithms import (BayesianDeepQD, ConditionalConfiguration, IntegerVariable, MEES, NoveltyES, QQD, RealVariable) from qdpy.containers import Grid def maze_path(vector): """Stop a two-segment path at the first contact with a vertical wall.""" x, y = .05, .5 waypoints = ((x, y), tuple(vector[:2]), tuple(vector[2:])) for (a, b), (c, d) in pairwise(waypoints): for step in range(1, 33): t = step / 32 point = a + t * (c - a), b + t * (d - b) if .42 <= point[0] <= .58 and .25 <= point[1] <= .75: return x, y x, y = point return x, y def novelty_trial(seed, budget): """Compare a shared novelty history with a grid-based ES baseline.""" initial = ((.65, .45, .95, .5), (.6, .55, .95, .5)) for mode in ("ns-es", "nsr-es", "nsra-es", "me-es"): grid = Grid(shape=(10, 10), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,)) first_goal = None evaluations = 0 def evaluate(genome, rollout_seed=None): nonlocal first_goal, evaluations evaluations += 1 x, y = maze_path(genome) distance = hypot(x - .95, y - .5) if first_goal is None and distance < .1: first_goal = evaluations return 1. - distance / sqrt(2), (x, y) if mode == "me-es": search = MEES(grid, initial[0], pairs=3, sigma=.15, learning_rate=.08, ind_domain=(0., 1.), seed=seed) search.run(evaluate, budget) else: search = NoveltyES(initial, mode=mode, archive=grid, pairs=2, sigma=.15, learning_rate=.08, patience=4, weight_step=.2, ind_domain=(0., 1.), seed=seed) search.run(evaluate, budget) yield dict(method=mode, seed=seed, evaluations=evaluations, cells=len(grid), qd_score=grid.qd_score(), first_goal=first_goal, best_center=max((row.fitness.values[0] for row in grid), default=0.)) # Each operation has a duration on each of three machines. DURATIONS = ((3, 6, 5), (4, 2, 6), (5, 4, 3), (2, 5, 6), (6, 3, 4), (4, 6, 2), (3, 5, 4), (6, 4, 3)) JOBS = tuple(job for job in range(4) for _ in range(2)) OPERATIONS = len(DURATIONS) def sample_schedule(rng): """Sample an operation order and a machine choice for each operation.""" return tuple(map(int, rng.permutation(JOBS))) + tuple(map(int, rng.integers(3, size=OPERATIONS))) def swap_jobs(genome, rng): """Swap two positions in the dispatch order while retaining machine assignments.""" a, b = map(int, rng.choice(OPERATIONS, size=2, replace=False)) proposal = list(genome) proposal[a], proposal[b] = proposal[b], proposal[a] return proposal def change_machine(genome, rng): """Reassign one operation to another machine.""" index = OPERATIONS + int(rng.integers(OPERATIONS)) proposal = list(genome) proposal[index] = (proposal[index] + int(rng.integers(1, 3))) % 3 return proposal def evaluate_schedule(genome, seed): """Decode job precedence and score energy, transports, and idle periods.""" completed = [0] * len(set(JOBS)) job_finish = completed.copy() previous_machine = [-1] * len(completed) machine_finish = [0] * 3 active_energy = idle_energy = moves = idle_periods = 0 for job in genome[:OPERATIONS]: index = 2 * job + completed[job] machine = genome[OPERATIONS + index] move = completed[job] > 0 and previous_machine[job] != machine start = max(job_finish[job] + move, machine_finish[machine]) idle = start - machine_finish[machine] duration = DURATIONS[index][machine] moves += move idle_periods += idle > 0 active_energy += (2 + machine) * duration idle_energy += idle job_finish[job] = machine_finish[machine] = start + duration previous_machine[job] = machine completed[job] += 1 return active_energy + 4 * moves + idle_energy, (moves, idle_periods) def scheduling_trial(seed, budget): """Compare tabular selection, uniform selection, and UCB1 on the same operators.""" for mode in ("q-learning", "uniform", "bandit"): grid = Grid(shape=(5, 9), features_domain=((-0.5, 4.5), (-0.5, 8.5)), fitness_domain=((0., 400.),), fitness_weights=(-1.,)) search = QQD(grid, sample=sample_schedule, operators={"swap": swap_jobs, "machine": change_machine}, batch_size=6, initial_samples=12, controller=mode, seed=seed) stats = search.run(evaluate_schedule, budget) yield dict(method=mode, seed=seed, cells=len(grid), qd_score=grid.qd_score(), **asdict(stats), best_energy=min((row.fitness.values[0] for row in grid), default=None)) def depth_trial(seed, budget): """Compare competitive and equal-budget acquisition on three frame configurations.""" variables = {"span": RealVariable(0., 1.), "rise": RealVariable(0., 1.), "layers": IntegerVariable(1, 3)} configurations = tuple(ConditionalConfiguration({"frame": frame}, active, ("load",)) for frame, active in ( ("solid", ("span", "rise")), ("laminated", tuple(variables)), ("ribbed", tuple(variables)), )) for mode in ("competitive", "equal"): grid = Grid(shape=(6, 6), features_domain=((0., 1.),) * 2, fitness_domain=((0., 2.),), fitness_weights=(1.,)) search = BayesianDeepQD(grid, budget, variables, configurations=configurations, batch_size=5, initial_samples=2, surrogate_budget=24, quality_floor=0., allocation=mode, seed=seed) attempts = [0] * len(configurations) def evaluate(genome): branch = genome[0] attempts[branch] += 1 design = search.decode(genome) x, y = design["span"], design["rise"] layers = design.get("layers", 1) bonus = (0., .25 - .06 * (layers - 2)**2, .12 - .04 * (layers - 3)**2)[branch] quality = 1. - .4 * (x - .32)**2 - .45 * (y - .7)**2 + bonus return (quality,), (x, y), {"load": x + .6 * y - (1.05 + .1 * layers)} search.optimise(evaluate) yield dict(method=mode, seed=seed, evaluations=sum(attempts), predictions=search.surrogate_evaluations, attempts=attempts, layers=search.deep_archive.configuration_counts, cells=len(grid), qd_score=grid.qd_score()) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("task", choices=("maze", "schedule", "depth")) parser.add_argument("--budget", type=int) parser.add_argument("--seeds", type=int, nargs="+", default=[11, 22, 33]) args = parser.parse_args() trial, default = {"maze": (novelty_trial, 302), "schedule": (scheduling_trial, 300), "depth": (depth_trial, 83)}[args.task] for seed in args.seeds: for metrics in trial(seed, default if args.budget is None else args.budget): print(json.dumps(metrics, sort_keys=True))