6"""Run matched trajectory, continuous-control, and Bayesian QD pilots."""
10from pathlib
import Path
11from time
import perf_counter
15from qdpy.algorithms import (AuroraXCon, BOPElites, MCBOElites, OccupancyHistogram, OccupancyMAPElites,
16 PathSignature, PathSignatureMAPElites)
21 order, width, height, gate, exit_ = genome
22 width, height = .4 + .56 * width, .4 + .56 * height
23 path = np.array([[0., 0.], [width, 0.], [width, height], [0., height], [0., 0.]])
27 trap = .69 - .45 * (order - .12)**2 - .2 * abs(width - .82) - .15 * abs(height - .72)
28 gate_error = np.linalg.norm([order - .82, gate - .72, exit_ - .78])
29 reward = (1. - .75 * gate_error - .1 * abs(width - .73)
if reverse
and gate_error < .17
30 else .5 * trap
if reverse
else trap)
31 cell = (int(reverse), min(2, int((width - .4) / .56 * 3)), min(2, int((height - .4) / .56 * 3)))
32 return float(reward), path, cell
35def _trajectory(seed, budget, learned, *, selected=None):
36 methods = (
"endpoint",
"occupancy",
"path-signature")
38 methods += (
"aurora",
"aurora-con",
"aurora-x",
"aurora-xcon")
39 if selected
is not None:
40 methods = tuple(name
for name
in methods
if name
in selected)
41 signature = PathSignature(2)
42 ref = [_loop((order, x, y, .5, .5))[1]
for order
in (0., 1.)
43 for x
in (.07, .43, .87)
for y
in (.07, .43, .87)]
44 axis = np.linspace(0., 1., 5)
45 histogram = OccupancyHistogram([(x, y)
for x
in axis
for y
in axis])
46 occupancy_centers = np.unique([histogram.encode(path)
for path
in ref], axis=0)
47 cells = len(occupancy_centers)
50 calls, first = 0,
None
52 def evaluate(genome, _seed=None):
54 reward, path, cell = _loop(genome)
55 measurements[tuple(genome)] = reward, cell
57 if reward >= .85
and first
is None:
62 if name.startswith(
"aurora"):
63 loss =
"triplet" if name
in (
"aurora-con",
"aurora-xcon")
else "reconstruction"
64 period = 96
if name
in (
"aurora-x",
"aurora-xcon")
else 0
65 search = AuroraXCon(5, initial_samples=24, training_period=24, extinction_period=period,
66 radius=.075, capacity=48, target_size=12, size_gain=.1, epochs=4,
67 iso_sigma=.10, line_sigma=.2,
69 stats = search.run(evaluate, budget)
70 archive = search.archive
71 diagnostics = dict(refits=stats.refits, optim_updates=stats.optimizer_steps, radius=stats.novelty_radius,
72 prunings=stats.extinctions, pruned=stats.pruned)
74 options = dict(initial_samples=24, iso_sigma=.10, line_sigma=.2, seed=seed, batch_size=1)
75 if name ==
"occupancy":
76 archive = histogram.make_archive(cells, centroids=occupancy_centers, fitness_domain=(0., 1.))
77 search = OccupancyMAPElites(archive, budget, 5, histogram=histogram, **options)
80 if name ==
"endpoint":
81 encoder = PathSignature(2, order=1)
82 archive = CVTGrid(shape=cells, centroids=np.zeros((cells, 2)),
83 features_domain=((-1., 1.),) * 2, fitness_domain=((0., 1.),),
84 fitness_weights=(1.,))
86 archive = encoder.make_archive(ref, cells, fitness_domain=(0., 1.), seed=7)
87 search = PathSignatureMAPElites(archive, budget, 5, signature=encoder, **options)
88 search.optimise(evaluate)
89 live = np.zeros((2, 3, 3))
91 reward, cell = measurements[tuple(elite)]
92 live[cell] = max(live[cell], reward)
93 yield dict(task=
"trajectory", method=name, seed=seed, evaluations=calls,
94 best_return=max(reward
for reward, _
in measurements.values()), first_target=first,
95 active_size=len(archive), audited_cells=int(np.count_nonzero(live)),
96 audited_orders=int(np.count_nonzero(live.max(axis=(1, 2)))), audited_qd=float(live.sum()),
100def _control_factory():
101 import gymnasium
as gym
103 class Tracking(gym.Env):
104 """Track a moving target with bounded continuous acceleration."""
106 observation_space = gym.spaces.Box(-np.inf, np.inf, (3,), dtype=np.float32)
107 action_space = gym.spaces.Box(-1., 1., (1,), dtype=np.float32)
109 def reset(self, *, seed=None, options=None):
110 super().reset(seed=seed)
111 self.x, self.v = self.np_random.uniform(-.25, .25, size=2)
112 self.goal = self.np_random.choice([-.7, .7])
114 return np.array([self.x, self.v, self.goal], dtype=np.float32), {}
116 def step(self, action):
117 command = float(action[0])
118 self.v = .65 * self.v + .11 * command
121 reward = max(0., 1. - .55 * abs(self.x - self.goal) - .05 * command**2)
123 self.goal = -self.goal
124 return np.array([self.x, self.v, self.goal], dtype=np.float32), reward,
False, self.t == 12, {}
129def _control(seed, budget, batches):
130 from qdpy.rl import ASCIIME, PGAMAPElites, NeuralMAPElites, PolicyConfig, TD3Config
132 def features(episode):
133 return float(episode.observations[-1, 0]), float(np.abs(episode.actions).mean())
135 for name, batch
in [(
"neural", 1)] + [(name, size)
for size
in batches
for name
in (
"ascii",
"pga")]:
136 archive = Grid(shape=(10, 5), features_domain=((-4., 4.), (0., 1.)), fitness_domain=((0., 12.),),
137 fitness_weights=(1.,))
138 options = dict(descriptor=features, seed=seed, policy=PolicyConfig((16,)), max_episode_steps=12,
139 initial_policies=8, iso_sigma=.08, line_sigma=.2)
141 search = ASCIIME(_control_factory, archive, batch_size=batch, gradient_batch_size=min(8, batch),
142 gradient_steps=2, learning_rate=.05, **options)
144 td3 = TD3Config(learning_starts=96, batch_size=32, critic_hidden_sizes=(32, 32))
145 search = PGAMAPElites(_control_factory, archive, td3=td3, batch_size=batch, critic_steps=2,
146 pg_steps=2, **options)
148 search = NeuralMAPElites(_control_factory, archive, **options)
149 started = perf_counter()
150 stats = search.train(budget)
151 seconds = perf_counter() - started
152 actor = search.best_policy()
154 with _control_factory()
as env:
156 obs, _ = env.reset(seed=50000 + 100 * seed + i)
159 obs, reward, _, _, _ = env.step(actor.act(obs))
162 yield dict(task=
"control", method=name, seed=seed, batch_size=batch, steps=stats.env_steps,
163 measured_policies=stats.evaluated_policies, optimizer_steps=stats.optimizer_steps,
164 gradient_offspring=getattr(stats,
"ascii_offspring", getattr(stats,
"pg_offspring", 0)),
165 cells=len(archive), qd_score=archive.qd_score(normalized=
False), audit_steps=240,
166 audit_return=float(np.mean(audit)), seconds=seconds)
170 """Instrument the reference algorithm without changing its proposals."""
176 def _fit_models(self):
177 started = perf_counter()
178 models = super()._fit_models()
182 def _modelled_point(self):
183 started = perf_counter()
185 point = super()._modelled_point()
186 self.acquisition_seconds += perf_counter() - started - (self.
model_seconds - previous)
190def _bayesian(seed, budget):
191 def objective(genome):
193 a = np.clip(.7 * x + .3 * y + .08 * np.sin(6. * z), 0., 1.)
194 b = np.clip(.8 * z + .2 * x + .08 * np.sin(6. * y), 0., 1.)
195 value = 1. - .65 * (y - (.2 + .5 * np.sin(3. * x)**2))**2 - .2 * (z - .55)**2
196 return (float(value),), (float(a), float(b))
198 for name
in (
"mcbo",
"bop"):
199 archive =
Grid(shape=(7, 7), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),),
200 fitness_weights=(1.,))
201 options = dict(seed=seed, initial_samples=8, candidate_pool=32, quality_floor=0.)
203 search =
MCBOElites(archive, budget, 3, (0., 1.), inducing_points=24, posterior_samples=128,
204 noise=.003, **options)
206 search =
_TimedBOP(archive, budget, 3, (0., 1.), restarts=1, **options)
207 evaluator_seconds = 0.
208 started = perf_counter()
209 checkpoints, to_target = {},
None
210 for _
in range(budget):
211 point, = search.ask_batch()
212 before = perf_counter()
213 result = objective(point)
214 evaluator_seconds += perf_counter() - before
215 search.tell_batch([result])
216 qd_score = archive.qd_score(normalized=
False)
217 if to_target
is None and qd_score >= 18:
218 to_target = dict(evaluations=search.nb_evaluations, seconds=perf_counter() - started)
219 if search.nb_evaluations
in (32, 64, 128):
220 checkpoints[str(search.nb_evaluations)] = qd_score
221 total = perf_counter() - started
222 timing = search.stats
if name ==
"mcbo" else search
223 yield dict(task=
"bayesian", method=name, seed=seed, evaluations=search.nb_evaluations,
224 cells=len(archive), qd_score=archive.qd_score(normalized=
False), checkpoints=checkpoints,
226 model_seconds=timing.model_seconds, acquisition_seconds=timing.acquisition_seconds,
227 evaluator_seconds=evaluator_seconds, seconds=total)
232 """Use explicit seeds and a budget in evaluator calls or environment steps."""
233 parser = argparse.ArgumentParser(description=__doc__)
234 parser.add_argument(
"task", choices=(
"trajectory",
"aurora",
"control",
"bayesian",
"all"))
235 parser.add_argument(
"--seeds", nargs=
"+", type=int, default=[7, 13, 23])
236 parser.add_argument(
"--budget", type=int)
237 parser.add_argument(
"--batch-sizes", nargs=
"+", type=int, default=[4, 16])
238 parser.add_argument(
"--output", type=Path)
239 args = parser.parse_args()
240 if args.budget
is not None and (args.task ==
"all" or args.budget < (12
if args.task ==
"control" else
241 24
if args.task ==
"aurora" else 1)):
242 parser.error(
"Use a single task and enough budget for its initialization.")
243 if any(size < 2
for size
in args.batch_sizes):
244 parser.error(
"Use batch sizes of at least two.")
245 experiments = {
"trajectory": (_trajectory, 384, (
False,)),
"aurora": (_trajectory, 384, (
True,)),
246 "control": (_control, 2304, (args.batch_sizes,)),
"bayesian": (_bayesian, 128, ())}
247 selected = (
"aurora",
"control",
"bayesian")
if args.task ==
"all" else (args.task,)
249 for task
in selected:
250 function, default, options = experiments[task]
251 for seed
in args.seeds:
252 for row
in function(seed, args.budget
or default, *options):
253 line = json.dumps(row, sort_keys=
True, allow_nan=
False)
257 args.output.parent.mkdir(parents=
True, exist_ok=
True)
258 args.output.write_text(
"\n".join(lines) +
"\n", encoding=
"utf-8")
261if __name__ ==
"__main__":
Select one genuine evaluation with expected joint improvement of elites.
Optimize sampled expected improvement over actual descriptor cells.