# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare trajectory-derived and hand-written descriptors for steering. """Compare AutoQD, a frozen projection, and fixed descriptors at equal budgets.""" from argparse import ArgumentParser import json from time import perf_counter import numpy as np from qdpy.algorithms import CMAMAE, autoqd_search from qdpy.containers import Grid from qdpy.phenotype import Features, Fitness, Individual HORIZON = 20 ROLLOUTS = 2 DOMAIN = ((-1.2, 1.2),) * 2 def make_archive(): """Use the same shape for all searches and for held-out comparison.""" return Grid(shape=(8, 8), features_domain=DOMAIN, fitness_domain=((0., 1.),), fitness_weights=(1.,)) ## @brief Evaluate a steering policy with two constant and two time-varying controls. def evaluate(genome, seed): """Return mean quality and flattened state-action trajectories.""" genome = np.asarray(genome) controls = np.clip(genome[:2] + np.sin(np.linspace(0, 2 * np.pi, HORIZON))[:, None] * genome[2:], -1, 1) starts = np.random.default_rng(seed).uniform(-0.04, 0.04, size=(ROLLOUTS, 2)) displacement = controls / HORIZON traveled = np.vstack((np.zeros(2), np.cumsum(displacement, axis=0)[:-1])) trajectories = tuple(np.column_stack((start + traveled, controls)) for start in starts) error = np.square(controls - [0.45, -0.25]).mean() steer_cost = np.square(np.diff(controls, axis=0)).mean() return 1 - 0.2 * float(error) - 0.05 * float(steer_cost), trajectories def endpoint(trajectories): """Report final positions on the shared evaluation grid.""" return np.mean([trial[0, :2] + trial[:, 2:].mean(axis=0) for trial in trajectories], axis=0) def _record(method, archive, seed, attempts, rollouts, trajectory_steps, seconds, **metadata): held_out = make_archive() for elite in archive: fitness, trajectories = evaluate(elite, 100_000 + seed) held_out.add(Individual(elite, fitness=Fitness((fitness,), weights=(1.,)), features=Features(endpoint(trajectories)))) return dict(method=method, seed=seed, attempts=attempts, rollouts=rollouts, trajectory_steps=trajectory_steps, seconds=seconds, search_cells=archive.filled_bins, held_out_steps=len(archive) * ROLLOUTS * HORIZON, held_out_coverage=held_out.filled_bins / 64, held_out_qd_score=held_out.qd_score(normalized=False), **metadata) def comparison(budget, seed): """Run the three variants and remeasure their elites in one reporting geometry.""" settings = dict(budget=budget, x0=(0.,) * 4, sigma0=0.5, threshold_min=0., batch_size=16, ind_domain=(-1., 1.)) for method, interval in (("autoqd", 4), ("frozen-projection", None)): start = perf_counter() result = autoqd_search(evaluate, make_archive(), trajectory_width=4, gamma=0.91, bandwidth=0.5, update_interval=interval, seed=seed, **settings) yield _record(method, result.archive, seed, result.attempts, result.rollouts, result.trajectory_steps, perf_counter() - start, rebuilds=result.rebuilds, skipped_rebuilds=result.skipped_rebuilds, boundary_evaluations=result.boundary_evaluations, failures=result.failures) start = perf_counter() _, evaluation_seed, emitter_seed = np.random.SeedSequence(seed).spawn(3) rng = np.random.default_rng(evaluation_seed) cma_seed = int(np.random.default_rng(emitter_seed).integers(2**32)) archive = make_archive() search = CMAMAE(archive, seed=cma_seed, optimisation_task="maximisation", **settings) for offset in range(0, budget, search.batch_size): batch = search.ask_batch(min(search.batch_size, budget - offset)) feedback = [] for candidate in batch: fitness, trajectories = evaluate(candidate, int(rng.integers(2**32))) feedback.append(((fitness,), endpoint(trajectories))) search.tell_batch(feedback) attempts = search.nb_evaluations yield _record("fixed-descriptors", archive, seed, attempts, attempts * ROLLOUTS, attempts * ROLLOUTS * HORIZON, perf_counter() - start) if __name__ == "__main__": parser = ArgumentParser(description=__doc__) parser.add_argument("--budget", type=int, default=512) parser.add_argument("--seeds", nargs="+", type=int, default=[11, 29, 47]) options = parser.parse_args() for seed in options.seeds: for row in comparison(options.budget, seed): print(json.dumps(row, sort_keys=True, allow_nan=False))