5"""Run three small, seeded search comparisons and report JSON lines."""
9from dataclasses
import asdict
10from itertools
import pairwise
11from math
import hypot, sqrt
13from qdpy.algorithms import (BayesianDeepQD, ConditionalConfiguration, IntegerVariable,
14 MEES, NoveltyES, QQD, RealVariable)
19 """Stop a two-segment path at the first contact with a vertical wall."""
21 waypoints = ((x, y), tuple(vector[:2]), tuple(vector[2:]))
22 for (a, b), (c, d)
in pairwise(waypoints):
23 for step
in range(1, 33):
25 point = a + t * (c - a), b + t * (d - b)
26 if .42 <= point[0] <= .58
and .25 <= point[1] <= .75:
32def novelty_trial(seed, budget):
33 """Compare a shared novelty history with a grid-based ES baseline."""
34 initial = ((.65, .45, .95, .5), (.6, .55, .95, .5))
35 for mode
in (
"ns-es",
"nsr-es",
"nsra-es",
"me-es"):
36 grid = Grid(shape=(10, 10), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),),
37 fitness_weights=(1.,))
41 def evaluate(genome, rollout_seed=None):
42 nonlocal first_goal, evaluations
44 x, y = maze_path(genome)
45 distance = hypot(x - .95, y - .5)
46 if first_goal
is None and distance < .1:
47 first_goal = evaluations
48 return 1. - distance / sqrt(2), (x, y)
51 search = MEES(grid, initial[0], pairs=3, sigma=.15, learning_rate=.08, ind_domain=(0., 1.), seed=seed)
52 search.run(evaluate, budget)
54 search = NoveltyES(initial, mode=mode, archive=grid, pairs=2, sigma=.15, learning_rate=.08,
55 patience=4, weight_step=.2, ind_domain=(0., 1.), seed=seed)
56 search.run(evaluate, budget)
57 yield dict(method=mode, seed=seed, evaluations=evaluations, cells=len(grid),
58 qd_score=grid.qd_score(), first_goal=first_goal,
59 best_center=max((row.fitness.values[0]
for row
in grid), default=0.))
63DURATIONS = ((3, 6, 5), (4, 2, 6), (5, 4, 3), (2, 5, 6), (6, 3, 4), (4, 6, 2), (3, 5, 4), (6, 4, 3))
64JOBS = tuple(job
for job
in range(4)
for _
in range(2))
65OPERATIONS = len(DURATIONS)
68def sample_schedule(rng):
69 """Sample an operation order and a machine choice for each operation."""
70 return tuple(map(int, rng.permutation(JOBS))) + tuple(map(int, rng.integers(3, size=OPERATIONS)))
73def swap_jobs(genome, rng):
74 """Swap two positions in the dispatch order while retaining machine assignments."""
75 a, b = map(int, rng.choice(OPERATIONS, size=2, replace=
False))
76 proposal = list(genome)
77 proposal[a], proposal[b] = proposal[b], proposal[a]
81def change_machine(genome, rng):
82 """Reassign one operation to another machine."""
83 index = OPERATIONS + int(rng.integers(OPERATIONS))
84 proposal = list(genome)
85 proposal[index] = (proposal[index] + int(rng.integers(1, 3))) % 3
89def evaluate_schedule(genome, seed):
90 """Decode job precedence and score energy, transports, and idle periods."""
91 completed = [0] * len(set(JOBS))
92 job_finish = completed.copy()
93 previous_machine = [-1] * len(completed)
94 machine_finish = [0] * 3
95 active_energy = idle_energy = moves = idle_periods = 0
96 for job
in genome[:OPERATIONS]:
97 index = 2 * job + completed[job]
98 machine = genome[OPERATIONS + index]
99 move = completed[job] > 0
and previous_machine[job] != machine
100 start = max(job_finish[job] + move, machine_finish[machine])
101 idle = start - machine_finish[machine]
102 duration = DURATIONS[index][machine]
104 idle_periods += idle > 0
105 active_energy += (2 + machine) * duration
107 job_finish[job] = machine_finish[machine] = start + duration
108 previous_machine[job] = machine
110 return active_energy + 4 * moves + idle_energy, (moves, idle_periods)
113def scheduling_trial(seed, budget):
114 """Compare tabular selection, uniform selection, and UCB1 on the same operators."""
115 for mode
in (
"q-learning",
"uniform",
"bandit"):
116 grid = Grid(shape=(5, 9), features_domain=((-0.5, 4.5), (-0.5, 8.5)),
117 fitness_domain=((0., 400.),), fitness_weights=(-1.,))
118 search = QQD(grid, sample=sample_schedule, operators={
"swap": swap_jobs,
"machine": change_machine},
119 batch_size=6, initial_samples=12, controller=mode, seed=seed)
120 stats = search.run(evaluate_schedule, budget)
121 yield dict(method=mode, seed=seed, cells=len(grid), qd_score=grid.qd_score(), **asdict(stats),
122 best_energy=min((row.fitness.values[0]
for row
in grid), default=
None))
125def depth_trial(seed, budget):
126 """Compare competitive and equal-budget acquisition on three frame configurations."""
127 variables = {
"span": RealVariable(0., 1.),
"rise": RealVariable(0., 1.),
"layers": IntegerVariable(1, 3)}
128 configurations = tuple(ConditionalConfiguration({
"frame": frame}, active, (
"load",))
for frame, active
in (
129 (
"solid", (
"span",
"rise")), (
"laminated", tuple(variables)), (
"ribbed", tuple(variables)),
131 for mode
in (
"competitive",
"equal"):
132 grid = Grid(shape=(6, 6), features_domain=((0., 1.),) * 2, fitness_domain=((0., 2.),),
133 fitness_weights=(1.,))
134 search = BayesianDeepQD(grid, budget, variables, configurations=configurations, batch_size=5,
135 initial_samples=2, surrogate_budget=24, quality_floor=0., allocation=mode, seed=seed)
136 attempts = [0] * len(configurations)
138 def evaluate(genome):
140 attempts[branch] += 1
141 design = search.decode(genome)
142 x, y = design[
"span"], design[
"rise"]
143 layers = design.get(
"layers", 1)
144 bonus = (0., .25 - .06 * (layers - 2)**2, .12 - .04 * (layers - 3)**2)[branch]
145 quality = 1. - .4 * (x - .32)**2 - .45 * (y - .7)**2 + bonus
146 return (quality,), (x, y), {
"load": x + .6 * y - (1.05 + .1 * layers)}
148 search.optimise(evaluate)
149 yield dict(method=mode, seed=seed, evaluations=sum(attempts), predictions=search.surrogate_evaluations,
150 attempts=attempts, layers=search.deep_archive.configuration_counts, cells=len(grid),
151 qd_score=grid.qd_score())
154if __name__ ==
"__main__":
155 parser = argparse.ArgumentParser(description=__doc__)
156 parser.add_argument(
"task", choices=(
"maze",
"schedule",
"depth"))
157 parser.add_argument(
"--budget", type=int)
158 parser.add_argument(
"--seeds", type=int, nargs=
"+", default=[11, 22, 33])
159 args = parser.parse_args()
160 trial, default = {
"maze": (novelty_trial, 302),
"schedule": (scheduling_trial, 300),
161 "depth": (depth_trial, 83)}[args.task]
162 for seed
in args.seeds:
163 for metrics
in trial(seed, default
if args.budget
is None else args.budget):
164 print(json.dumps(metrics, sort_keys=
True))