5"""Run four seeded comparisons using the base QDpy installation."""
10from dataclasses
import asdict
14from qdpy.algorithms import BOPElites, CoME, MEliTA, MOLE, QDHeuristicDesign, SPHEN
18def design_grid(shape, bounds=(0., 1.), direction=1., fitness=(0., 2.)):
19 """Make a fixed best-only grid with a native scalar objective."""
20 return Grid(shape=shape, features_domain=(bounds,) * len(shape),
21 fitness_domain=(fitness,), fitness_weights=(direction,))
24def component_trial(seed, budget):
25 """Search complementary layout and controller settings under the same pair budget."""
26 for name
in (
"CoME",
"joint MAP-Elites",
"MEliTA"):
28 pair_grid = design_grid((7, 7))
31 layout, controller = parts
32 target = .9 - .8 * layout + .05 * np.sin(6. * layout)
33 value = 1. - .85 * (target - controller) ** 2 - .1 * (layout - .55) ** 2
34 cell = pair_grid.index_grid(parts)
35 occupied[cell] = max(value, occupied.get(cell, 0.))
38 def mutate(value, rng):
39 return float(np.clip(value + rng.normal(0., .12), 0., 1.))
42 grids = (design_grid((7,)), design_grid((7,)))
43 search = CoME(grids, initialize=(
lambda rng: float(rng.random()),) * 2,
44 mutations=(mutate, mutate), descriptors=(
lambda part: (part,),) * 2,
45 evaluate=quality, radius=2., partners=2, initial_samples=8, seed=seed)
46 evaluations = search.run(budget).evaluations
47 retained = {tuple(item)
for grid
in grids
for item
in grid}
50 pair_grid, initialize=
lambda rng: tuple(rng.random(2)), coherence=quality,
51 mutations=(
lambda parts, rng: mutate(parts[0], rng),
lambda parts, rng: mutate(parts[1], rng)),
52 descriptors=(float, float), transverse=name ==
"MEliTA", seed=seed,
54 evaluations = search.run(budget).assessments
55 retained = {tuple(item)
for item
in pair_grid}
56 cells = {pair_grid.index_grid(pair)
for pair
in retained}
57 yield dict(method=name, seed=seed, evaluations=evaluations,
58 evaluated_pair_cells=len(occupied), retained_pair_cells=len(cells),
59 component_cells=[len({cell[side]
for cell
in cells})
for side
in range(2)],
60 best_quality=max(occupied.values()), evaluated_qd_score=sum(occupied.values()))
64 """Measure coupled descriptors and a nonlinear synthetic fitness."""
66 first = .15 + .68 * x + .10 * np.sin(7. * y)
67 second = .09 + .72 * y + .12 * np.sin(9. * x) ** 2
68 quality = 1. + .2 * np.cos(8. * (x - y)) - .4 * (x - .65) ** 2 - .25 * (y - .4) ** 2
69 return (float(quality),), (float(first), float(second))
72def surrogate_trial(seed, budget):
73 """Compare a posterior-mean acquisition map with probabilistic cell assignment."""
74 for kind
in (SPHEN, BOPElites):
75 grid = design_grid((6, 6))
77 search = kind(grid, budget, 2, seed=seed, initial_samples=8, surrogate_budget=96, batch_size=4)
79 search = kind(grid, budget, 2, (0., 1.), 0., seed=seed, initial_samples=8,
80 candidate_pool=32, restarts=1, optimisation_task=
"maximisation")
81 search.optimise(black_box)
82 row = dict(method=kind.__name__, seed=seed, evaluations=search.nb_evaluations,
83 cells=grid.filled_bins, qd_score=float(sum(item.fitness.values[0]
for item
in grid)),
84 best_quality=grid.best.fitness.values[0])
86 predicted = search.prediction_map(192, seed=seed)
87 row.update(prediction_checks=search.prediction_checks, misclassified=search.misclassified,
88 surrogate_evaluations=search.surrogate_evaluations, prediction_budget=192,
89 predicted_cells=len(predicted))
94 """Return two costs and a Jacobian with efficient line segments at y = ±0.6."""
97 return ((x + .8) ** 2 + well ** 2, (x - .8) ** 2 + well ** 2), (
98 (2 * (x + .8), 4 * y * well), (2 * (x - .8), 4 * y * well),
102def landscape_trial(seed, budget):
103 """Compare the traced decision-space curves to their analytic coordinates."""
104 rng = np.random.default_rng(seed)
105 starts = [(float(rng.uniform(-.2, .2)), float(sign * rng.uniform(.72, .9)))
for sign
in (1, -1)]
106 result = MOLE(((-1., 1.),) * 2, step_size=.1).run(two_curves, starts, budget)
107 curves = [np.asarray([item.genome
for item
in trace])
for trace
in result.sets]
108 return [dict(method=
"MOLE", seed=seed, evaluations=result.evaluations, curves=len(curves),
109 points=[len(curve)
for curve
in curves], spans=[float(np.ptp(curve[:, 0]))
for curve
in curves],
110 max_curve_error=max((float(np.max(np.abs(np.abs(curve[:, 1]) - .6)))
for curve
in curves),
112 transitions=len(result.transitions))]
115def schedule_cost(rule, case):
116 """Score a deterministic single-machine schedule under a weighted tardiness cost."""
117 times, due, preference = case
120 order = np.argsort(a * times / times.mean() + b * due / due.mean(), kind=
"stable")
121 completion = np.cumsum(times[order])
122 tardiness = np.maximum(completion - due[order], 0.)
123 return float(((1. - preference) * completion.mean() + preference * tardiness.mean()) / times.sum())
126def schedule_structure(rule):
127 """Extract feature counts from the syntax of a two-term scheduling rule."""
129 terms = [
"duration"] * a + [
"due_date"] * b
130 tree = ast.parse(
" + ".join(terms), mode=
"eval")
131 names = [node.id
for node
in ast.walk(tree)
if isinstance(node, ast.Name)]
132 return names.count(
"duration"), names.count(
"due_date")
135def propose_schedule(parent, attribution, rng):
136 """Use structural attribution to bias which term changes in a scheduling rule."""
137 magnitudes = np.abs(attribution) + .1
138 axis = int(rng.choice(2, p=magnitudes / magnitudes.sum()))
140 rule[axis] = int(np.clip(rule[axis] + rng.choice((-2, -1, 1, 2)), 0, 9))
141 return tuple(rule)
if any(rule)
else None
144def _cases(rng, count):
145 for i
in range(count):
146 durations = rng.integers(1, 16, size=12)
147 deadlines = rng.uniform(.06, .75, size=12) * durations.sum()
148 yield durations, deadlines, (0., .5, 1.)[i % 3]
151def scheduling_trial(seed, budget):
152 """Build one repertoire and compare two selectors on a disjoint test panel."""
153 train_rng, test_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
154 training, held_out = tuple(_cases(train_rng, 12)), tuple(_cases(test_rng, 30))
155 grid = design_grid((7, 7), (-1., 1.), -1., (0., 1.))
156 search = QDHeuristicDesign(
157 grid, structure=schedule_structure, propose=propose_schedule, evaluate=schedule_cost,
158 instance_features=
lambda case: (case[2],), descriptor_indices=(0, 1), neighbors=4, seed=seed,
160 stats = search.run([(8, 0), (0, 8), (4, 4), (7, 1)], training, budget)
161 for label, select
in ((
"instance selector", search.select), (
"single best",
lambda case: grid.best[0])):
162 selected = [select(case)
for case
in held_out]
163 mean_cost = float(np.mean([schedule_cost(rule, case)
for rule, case
in zip(selected, held_out)]))
164 yield dict(method=label, seed=seed, **asdict(stats), cells=grid.filled_bins,
165 held_out_evaluations=len(held_out), held_out_cost=mean_cost, selected_rules=len(set(selected)))
168if __name__ ==
"__main__":
169 trials = {
"components": (component_trial, 160),
"surrogate": (surrogate_trial, 64),
170 "landscape": (landscape_trial, 512),
"scheduling": (scheduling_trial, 360)}
171 parser = argparse.ArgumentParser(description=__doc__)
172 parser.add_argument(
"task", choices=trials)
173 parser.add_argument(
"--budget", type=int)
174 parser.add_argument(
"--seeds", type=int, nargs=
"+", default=[11, 22, 33])
175 args = parser.parse_args()
176 trial, default_budget = trials[args.task]
177 budget = default_budget
if args.budget
is None else args.budget
178 for seed
in args.seeds:
179 for row
in trial(seed, budget):
180 print(json.dumps(row, sort_keys=
True))