#!/usr/bin/env python3 # SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief CPU comparisons for trajectory descriptors, action crossover, and sparse GP acquisition. """Run matched trajectory, continuous-control, and Bayesian QD pilots.""" import argparse import json from pathlib import Path from time import perf_counter import numpy as np from qdpy.algorithms import (AuroraXCon, BOPElites, MCBOElites, OccupancyHistogram, OccupancyMAPElites, PathSignature, PathSignatureMAPElites) from qdpy.containers import CVTGrid, Grid def _loop(genome): order, width, height, gate, exit_ = genome width, height = .4 + .56 * width, .4 + .56 * height path = np.array([[0., 0.], [width, 0.], [width, height], [0., height], [0., 0.]]) reverse = order >= .5 if reverse: path = path[::-1] trap = .69 - .45 * (order - .12)**2 - .2 * abs(width - .82) - .15 * abs(height - .72) gate_error = np.linalg.norm([order - .82, gate - .72, exit_ - .78]) reward = (1. - .75 * gate_error - .1 * abs(width - .73) if reverse and gate_error < .17 else .5 * trap if reverse else trap) cell = (int(reverse), min(2, int((width - .4) / .56 * 3)), min(2, int((height - .4) / .56 * 3))) return float(reward), path, cell def _trajectory(seed, budget, learned, *, selected=None): methods = ("endpoint", "occupancy", "path-signature") if learned: methods += ("aurora", "aurora-con", "aurora-x", "aurora-xcon") if selected is not None: methods = tuple(name for name in methods if name in selected) signature = PathSignature(2) ref = [_loop((order, x, y, .5, .5))[1] for order in (0., 1.) for x in (.07, .43, .87) for y in (.07, .43, .87)] axis = np.linspace(0., 1., 5) histogram = OccupancyHistogram([(x, y) for x in axis for y in axis]) occupancy_centers = np.unique([histogram.encode(path) for path in ref], axis=0) cells = len(occupancy_centers) for name in methods: measurements = {} calls, first = 0, None def evaluate(genome, _seed=None): nonlocal first, calls reward, path, cell = _loop(genome) measurements[tuple(genome)] = reward, cell calls += 1 if reward >= .85 and first is None: first = calls return reward, path diagnostics = {} if name.startswith("aurora"): loss = "triplet" if name in ("aurora-con", "aurora-xcon") else "reconstruction" period = 96 if name in ("aurora-x", "aurora-xcon") else 0 search = AuroraXCon(5, initial_samples=24, training_period=24, extinction_period=period, radius=.075, capacity=48, target_size=12, size_gain=.1, epochs=4, iso_sigma=.10, line_sigma=.2, seed=seed, loss=loss) stats = search.run(evaluate, budget) archive = search.archive diagnostics = dict(refits=stats.refits, optim_updates=stats.optimizer_steps, radius=stats.novelty_radius, prunings=stats.extinctions, pruned=stats.pruned) else: options = dict(initial_samples=24, iso_sigma=.10, line_sigma=.2, seed=seed, batch_size=1) if name == "occupancy": archive = histogram.make_archive(cells, centroids=occupancy_centers, fitness_domain=(0., 1.)) search = OccupancyMAPElites(archive, budget, 5, histogram=histogram, **options) else: encoder = signature if name == "endpoint": encoder = PathSignature(2, order=1) archive = CVTGrid(shape=cells, centroids=np.zeros((cells, 2)), features_domain=((-1., 1.),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,)) else: archive = encoder.make_archive(ref, cells, fitness_domain=(0., 1.), seed=7) search = PathSignatureMAPElites(archive, budget, 5, signature=encoder, **options) search.optimise(evaluate) live = np.zeros((2, 3, 3)) for elite in archive: reward, cell = measurements[tuple(elite)] live[cell] = max(live[cell], reward) yield dict(task="trajectory", method=name, seed=seed, evaluations=calls, best_return=max(reward for reward, _ in measurements.values()), first_target=first, active_size=len(archive), audited_cells=int(np.count_nonzero(live)), audited_orders=int(np.count_nonzero(live.max(axis=(1, 2)))), audited_qd=float(live.sum()), **diagnostics) def _control_factory(): import gymnasium as gym class Tracking(gym.Env): """Track a moving target with bounded continuous acceleration.""" observation_space = gym.spaces.Box(-np.inf, np.inf, (3,), dtype=np.float32) action_space = gym.spaces.Box(-1., 1., (1,), dtype=np.float32) def reset(self, *, seed=None, options=None): super().reset(seed=seed) self.x, self.v = self.np_random.uniform(-.25, .25, size=2) self.goal = self.np_random.choice([-.7, .7]) self.t = 0 return np.array([self.x, self.v, self.goal], dtype=np.float32), {} def step(self, action): command = float(action[0]) self.v = .65 * self.v + .11 * command self.x += self.v self.t += 1 reward = max(0., 1. - .55 * abs(self.x - self.goal) - .05 * command**2) if self.t == 6: self.goal = -self.goal return np.array([self.x, self.v, self.goal], dtype=np.float32), reward, False, self.t == 12, {} return Tracking() def _control(seed, budget, batches): from qdpy.rl import ASCIIME, PGAMAPElites, NeuralMAPElites, PolicyConfig, TD3Config def features(episode): return float(episode.observations[-1, 0]), float(np.abs(episode.actions).mean()) for name, batch in [("neural", 1)] + [(name, size) for size in batches for name in ("ascii", "pga")]: archive = Grid(shape=(10, 5), features_domain=((-4., 4.), (0., 1.)), fitness_domain=((0., 12.),), fitness_weights=(1.,)) options = dict(descriptor=features, seed=seed, policy=PolicyConfig((16,)), max_episode_steps=12, initial_policies=8, iso_sigma=.08, line_sigma=.2) if name == "ascii": search = ASCIIME(_control_factory, archive, batch_size=batch, gradient_batch_size=min(8, batch), gradient_steps=2, learning_rate=.05, **options) elif name == "pga": td3 = TD3Config(learning_starts=96, batch_size=32, critic_hidden_sizes=(32, 32)) search = PGAMAPElites(_control_factory, archive, td3=td3, batch_size=batch, critic_steps=2, pg_steps=2, **options) else: search = NeuralMAPElites(_control_factory, archive, **options) started = perf_counter() stats = search.train(budget) seconds = perf_counter() - started actor = search.best_policy() audit = [] with _control_factory() as env: for i in range(20): obs, _ = env.reset(seed=50000 + 100 * seed + i) total = 0. for _ in range(12): obs, reward, _, _, _ = env.step(actor.act(obs)) total += reward audit.append(total) yield dict(task="control", method=name, seed=seed, batch_size=batch, steps=stats.env_steps, measured_policies=stats.evaluated_policies, optimizer_steps=stats.optimizer_steps, gradient_offspring=getattr(stats, "ascii_offspring", getattr(stats, "pg_offspring", 0)), cells=len(archive), qd_score=archive.qd_score(normalized=False), audit_steps=240, audit_return=float(np.mean(audit)), seconds=seconds) class _TimedBOP(BOPElites): """Instrument the reference algorithm without changing its proposals.""" def reinit(self): super().reinit() self.model_seconds = self.acquisition_seconds = 0. def _fit_models(self): started = perf_counter() models = super()._fit_models() self.model_seconds += perf_counter() - started return models def _modelled_point(self): started = perf_counter() previous = self.model_seconds point = super()._modelled_point() self.acquisition_seconds += perf_counter() - started - (self.model_seconds - previous) return point def _bayesian(seed, budget): def objective(genome): x, y, z = genome a = np.clip(.7 * x + .3 * y + .08 * np.sin(6. * z), 0., 1.) b = np.clip(.8 * z + .2 * x + .08 * np.sin(6. * y), 0., 1.) value = 1. - .65 * (y - (.2 + .5 * np.sin(3. * x)**2))**2 - .2 * (z - .55)**2 return (float(value),), (float(a), float(b)) for name in ("mcbo", "bop"): archive = Grid(shape=(7, 7), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,)) options = dict(seed=seed, initial_samples=8, candidate_pool=32, quality_floor=0.) if name == "mcbo": search = MCBOElites(archive, budget, 3, (0., 1.), inducing_points=24, posterior_samples=128, noise=.003, **options) else: search = _TimedBOP(archive, budget, 3, (0., 1.), restarts=1, **options) evaluator_seconds = 0. started = perf_counter() checkpoints, to_target = {}, None for _ in range(budget): point, = search.ask_batch() before = perf_counter() result = objective(point) evaluator_seconds += perf_counter() - before search.tell_batch([result]) qd_score = archive.qd_score(normalized=False) if to_target is None and qd_score >= 18: to_target = dict(evaluations=search.nb_evaluations, seconds=perf_counter() - started) if search.nb_evaluations in (32, 64, 128): checkpoints[str(search.nb_evaluations)] = qd_score total = perf_counter() - started timing = search.stats if name == "mcbo" else search yield dict(task="bayesian", method=name, seed=seed, evaluations=search.nb_evaluations, cells=len(archive), qd_score=archive.qd_score(normalized=False), checkpoints=checkpoints, to_target=to_target, model_seconds=timing.model_seconds, acquisition_seconds=timing.acquisition_seconds, evaluator_seconds=evaluator_seconds, seconds=total) ## @brief Run the comparisons and optionally save JSON Lines results. def main(): """Use explicit seeds and a budget in evaluator calls or environment steps.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("task", choices=("trajectory", "aurora", "control", "bayesian", "all")) parser.add_argument("--seeds", nargs="+", type=int, default=[7, 13, 23]) parser.add_argument("--budget", type=int) parser.add_argument("--batch-sizes", nargs="+", type=int, default=[4, 16]) parser.add_argument("--output", type=Path) args = parser.parse_args() if args.budget is not None and (args.task == "all" or args.budget < (12 if args.task == "control" else 24 if args.task == "aurora" else 1)): parser.error("Use a single task and enough budget for its initialization.") if any(size < 2 for size in args.batch_sizes): parser.error("Use batch sizes of at least two.") experiments = {"trajectory": (_trajectory, 384, (False,)), "aurora": (_trajectory, 384, (True,)), "control": (_control, 2304, (args.batch_sizes,)), "bayesian": (_bayesian, 128, ())} selected = ("aurora", "control", "bayesian") if args.task == "all" else (args.task,) lines = [] for task in selected: function, default, options = experiments[task] for seed in args.seeds: for row in function(seed, args.budget or default, *options): line = json.dumps(row, sort_keys=True, allow_nan=False) print(line) lines.append(line) if args.output: args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text("\n".join(lines) + "\n", encoding="utf-8") if __name__ == "__main__": main()