QDpy
Loading...
Searching...
No Matches
autoqd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Compare AutoQD, a frozen projection, and fixed descriptors at equal budgets."""
6
7from argparse import ArgumentParser
8import json
9from time import perf_counter
10
11import numpy as np
12
13from qdpy.algorithms import CMAMAE, autoqd_search
14from qdpy.containers import Grid
15from qdpy.phenotype import Features, Fitness, Individual
16
17
18HORIZON = 20
19ROLLOUTS = 2
20DOMAIN = ((-1.2, 1.2),) * 2
21
22
23def make_archive():
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.,))
26
27
28
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:],
33 -1, 1)
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
41
42
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)
46
47
48def _record(method, archive, seed, attempts, rollouts, trajectory_steps, seconds, **metadata):
49 held_out = make_archive()
50 for elite in 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)
59
60
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,
64 ind_domain=(-1., 1.))
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)
72
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))
81 feedback = []
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)
89
90
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))