5"""Compare AutoQD, a frozen projection, and fixed descriptors at equal budgets."""
7from argparse
import ArgumentParser
9from time
import perf_counter
20DOMAIN = ((-1.2, 1.2),) * 2
24 """Use the same shape for all searches and for held-out comparison."""
25 return Grid(shape=(8, 8), features_domain=DOMAIN, fitness_domain=((0., 1.),), fitness_weights=(1.,))
29def evaluate(genome, seed):
30 """Return mean quality and flattened state-action trajectories."""
31 genome = np.asarray(genome)
32 controls = np.clip(genome[:2] + np.sin(np.linspace(0, 2 * np.pi, HORIZON))[:,
None] * genome[2:],
34 starts = np.random.default_rng(seed).uniform(-0.04, 0.04, size=(ROLLOUTS, 2))
35 displacement = controls / HORIZON
36 traveled = np.vstack((np.zeros(2), np.cumsum(displacement, axis=0)[:-1]))
37 trajectories = tuple(np.column_stack((start + traveled, controls))
for start
in starts)
38 error = np.square(controls - [0.45, -0.25]).mean()
39 steer_cost = np.square(np.diff(controls, axis=0)).mean()
40 return 1 - 0.2 * float(error) - 0.05 * float(steer_cost), trajectories
43def endpoint(trajectories):
44 """Report final positions on the shared evaluation grid."""
45 return np.mean([trial[0, :2] + trial[:, 2:].mean(axis=0)
for trial
in trajectories], axis=0)
48def _record(method, archive, seed, attempts, rollouts, trajectory_steps, seconds, **metadata):
49 held_out = make_archive()
51 fitness, trajectories = evaluate(elite, 100_000 + seed)
52 held_out.add(Individual(elite, fitness=Fitness((fitness,), weights=(1.,)),
53 features=Features(endpoint(trajectories))))
54 return dict(method=method, seed=seed, attempts=attempts, rollouts=rollouts,
55 trajectory_steps=trajectory_steps, seconds=seconds, search_cells=archive.filled_bins,
56 held_out_steps=len(archive) * ROLLOUTS * HORIZON,
57 held_out_coverage=held_out.filled_bins / 64,
58 held_out_qd_score=held_out.qd_score(normalized=
False), **metadata)
61def comparison(budget, seed):
62 """Run the three variants and remeasure their elites in one reporting geometry."""
63 settings = dict(budget=budget, x0=(0.,) * 4, sigma0=0.5, threshold_min=0., batch_size=16,
65 for method, interval
in ((
"autoqd", 4), (
"frozen-projection",
None)):
66 start = perf_counter()
67 result = autoqd_search(evaluate, make_archive(), trajectory_width=4, gamma=0.91, bandwidth=0.5,
68 update_interval=interval, seed=seed, **settings)
69 yield _record(method, result.archive, seed, result.attempts, result.rollouts, result.trajectory_steps,
70 perf_counter() - start, rebuilds=result.rebuilds, skipped_rebuilds=result.skipped_rebuilds,
71 boundary_evaluations=result.boundary_evaluations, failures=result.failures)
73 start = perf_counter()
74 _, evaluation_seed, emitter_seed = np.random.SeedSequence(seed).spawn(3)
75 rng = np.random.default_rng(evaluation_seed)
76 cma_seed = int(np.random.default_rng(emitter_seed).integers(2**32))
77 archive = make_archive()
78 search = CMAMAE(archive, seed=cma_seed, optimisation_task=
"maximisation", **settings)
79 for offset
in range(0, budget, search.batch_size):
80 batch = search.ask_batch(min(search.batch_size, budget - offset))
82 for candidate
in batch:
83 fitness, trajectories = evaluate(candidate, int(rng.integers(2**32)))
84 feedback.append(((fitness,), endpoint(trajectories)))
85 search.tell_batch(feedback)
86 attempts = search.nb_evaluations
87 yield _record(
"fixed-descriptors", archive, seed, attempts, attempts * ROLLOUTS,
88 attempts * ROLLOUTS * HORIZON, perf_counter() - start)
91if __name__ ==
"__main__":
92 parser = ArgumentParser(description=__doc__)
93 parser.add_argument(
"--budget", type=int, default=512)
94 parser.add_argument(
"--seeds", nargs=
"+", type=int, default=[11, 29, 47])
95 options = parser.parse_args()
96 for seed
in options.seeds:
97 for row
in comparison(options.budget, seed):
98 print(json.dumps(row, sort_keys=
True, allow_nan=
False))