#!/usr/bin/env python3 # SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief CPU comparisons for layered archives, alternate decoders, and learned exploration. """Run six reproducible demonstrations with independent measurement budgets.""" import argparse import json import numpy as np from qdpy.algorithms import age_layered_map_elites, minimize_surprise_map_elites, multi_decoder_map_elites from qdpy.benchmarks import generate_local_optima_benchmarks from qdpy.containers import Grid from qdpy.phenotype import Features, Fitness, Individual def _grid(shape, features=None, direction=1.): return Grid(shape=shape, features_domain=((0., 1.),) * len(shape) if features is None else features, fitness_domain=((-np.inf, np.inf),), fitness_weights=(direction,)) def _update(grid, genome, fitness, descriptor): grid.add(Individual(genome, fitness=Fitness((fitness,), weights=grid.fitness_weights), features=Features(descriptor))) def layers(seed): def sample(rng): return rng.random(3) def mutate(parent, rng): return np.clip(parent + rng.normal(0., .13, 3), 0., 1.) def evaluate(genome): x, y, z = genome return max(0., 1. - (z - np.cos(3 * x + 2 * y) ** 2) ** 2), ((x,), (y,)) budgets = 192 search = age_layered_map_elites((_grid((8,)), _grid((8,))), evaluate, sample=sample, mutate=mutate, max_ages=(22,), budget=budgets, immigrant_interval=6, seed=seed) control = _grid((4, 4)) rng = np.random.default_rng(seed) for i in range(budgets): child = sample(rng) if i % 6 == 0 or not control else mutate(control[int(rng.integers(len(control)))], rng) quality, features = evaluate(child) _update(control, child, quality, (features[0][0], features[1][0])) for method, archives, promotions in (("age-layered", search.archives, sum(search.promotions)), ("joint-grid", (control,), 0)): audit = _grid((8, 8)) for grid in archives: for row in grid: _update(audit, row, row.fitness.values[0], tuple(row[:2])) yield dict(method=method, evaluations=budgets, capacity=16, promotions=promotions, audit_cells=len(audit), audit_score=float(sum(row.fitness.values[0] for row in audit))) def decoders(seed): rng = np.random.default_rng(982) positions = rng.random((10, 2)) demands = (2, 2, 3, 3, 2, 1, 3, 2, 2, 2) capacity = 6 depot = np.array((.5, .5)) def decode(tour, first_fit): routes, loads = [], [] for visit in tour: slots = range(len(routes)) if first_fit else range(max(0, len(routes) - 1), len(routes)) slot = next((i for i in slots if loads[i] + demands[visit] <= capacity), len(routes)) if slot == len(routes): routes.append([]) loads.append(0) routes[slot].append(visit) loads[slot] += demands[visit] return routes def evaluate(routes): distances = [] for route in routes: points = np.vstack((depot, positions[route], depot)) distances.append(float(np.linalg.norm(np.diff(points, axis=0), axis=1).sum())) return sum(distances), (float(len(routes)), max(distances)) def swap(parent, rng): child = list(parent) i, j = map(int, rng.choice(len(child), 2, replace=False)) child[i], child[j] = child[j], child[i] return child def reverse(parent, rng): i, j = sorted(map(int, rng.choice(len(parent), 2, replace=False))) return (*parent[:i], *reversed(parent[i:j+1]), *parent[j+1:]) both = (lambda genome: decode(genome, False), lambda genome: decode(genome, True)) for name, rule, choices in (("single-decoder", "round_robin", both[:1]), ("multi-round-robin", "round_robin", both), ("multi-bandit", "ucb1", both)): grid = _grid((6, 12), ((3., 9.), (0., 6.)), -1.) result = multi_decoder_map_elites(grid, evaluate, sample=lambda rng: rng.permutation(len(demands)), emitters=(swap, reverse), decoders=choices, budget=200, seed=seed) yield dict(method=name, calls=result.objective_calls, proposals=result.proposals, cells=len(grid), best_distance=grid.best.fitness.values[0], emitter_calls=result.emitter_calls) def predict(seed): def rollout(genome, world): target, feedback, gain, drift = genome rng = np.random.default_rng(world) state = rng.random(4) predicted, measured = [], [] for _ in range(12): action = np.clip(.65 * (target - state) + .4 * feedback * (state.mean() - state), -.5, .5) predicted.append(np.clip(state + gain * action + .2 * (drift - .5), 0., 1.)) state = np.clip(state + .55 * action + rng.normal(0., .02, size=4), 0., 1.) measured.append(state.copy()) return predicted, measured def describe(sensors): return (float(np.mean(sensors[-1])),) for name, mutate in (("actor-predictor", lambda row, rng: np.clip(row + rng.normal(0., .12, 4), 0., 1.)), ("random-pairs", lambda row, rng: rng.random(4))): grid = _grid((12,)) result = minimize_surprise_map_elites(grid, rollout, describe=describe, sample=lambda rng: rng.random(4), mutate=mutate, budget=144, repeats=3, seed=seed) errors = [np.abs(np.asarray(predicted) - measured).mean() for row in grid for case in (8191, 4099, 6151) for predicted, measured in [rollout(tuple(row), case)]] yield dict(method=name, rollouts=result.rollout_calls, steps=result.sensor_steps, cells=len(grid), audit_rollouts=len(errors), heldout_error=float(np.mean(errors))) def _policy_fixture(seed): import gymnasium as gym import torch from qdpy.rl import PolicyConfig, TD3Config torch.set_num_threads(1) class Track(gym.Env): observation_space = gym.spaces.Box(-3., 3., (2,), 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 = float(self.np_random.uniform(-.12, .12)) self.v, self.t = 0., 0 return np.array([self.x, self.v], np.float32), {} def step(self, action): self.t += 1 self.v = .6 * self.v + .16 * float(action[0]) self.x += self.v quality = 1. - abs(self.x - .34) return np.array([self.x, self.v], np.float32), quality, self.t == 6, False, {} config = dict(seed=seed, initial_policies=8, batch_size=5, max_episode_steps=6, critic_steps=2, pg_steps=1, policy=PolicyConfig((8,)), td3=TD3Config(learning_starts=24, batch_size=16, replay_capacity=512, critic_hidden_sizes=(12,))) return Track, config def _audit_policy(search, environment): result = _grid((14,), ((-1.6, 1.6),)) for elite in search.archive: actor = search.policy_for(elite) returns, locations = [], [] with environment() as env: for seed in (417, 641, 991): observation, _ = env.reset(seed=seed) quality = 0. for _ in range(6): observation, reward, _, _, _ = env.step(actor.act(observation)) quality += reward returns.append(quality) locations.append(float(observation[0])) _update(result, elite, float(np.mean(returns)), (float(np.mean(locations)),)) return dict(audit_steps=18 * len(search.archive), audit_cells=len(result), best_return=result.best.fitness.values[0], audit_score=float(sum(row.fitness.values[0] for row in result))) def pga(seed): from qdpy.rl import PGAAURORA, PGAMAPElites env, config = _policy_fixture(seed) common = dict(capacity=24, training_period=8, encoder_epochs=3, size_gain=.04) candidates = (("pga-aurora", PGAAURORA(env, **common, **config)), ("genetic-aurora", PGAAURORA(env, gradient=False, **common, **config)), ("pga-known", PGAMAPElites(env, _grid((14,), ((-1.6, 1.6),)), descriptor=lambda episode: (float(episode.observations[-1, 0]),), **config))) for name, search in candidates: stats = search.train(360) yield dict(method=name, steps=stats.env_steps, gradient=stats.pg_offspring, refits=getattr(stats, "encoder_refits", 0), **_audit_policy(search, env)) def adaptive(seed): from qdpy.rl import AdaHOME env, config = _policy_fixture(seed) modes = (("ada-home", True, .1, .25), ("fixed-with-replay", False, .1, .25), ("base-pga", False, 0., 0.)) for name, use_bandit, crossover, replay in modes: search = AdaHOME(env, _grid((14,), ((-1.6, 1.6),)), descriptor=lambda episode: (float(episode.observations[-1, 0]),), adaptive=use_bandit, swap_probability=crossover, elite_capacity=128, elite_fraction=replay, **config) stats = search.train(360) yield dict(method=name, steps=stats.env_steps, operator_trials=stats.operator_trials, elite_replay=stats.elite_replay_size, **_audit_policy(search, env)) def landscapes(seed): for use_novelty in (True, False): result = generate_local_optima_benchmarks(peaks=14, budget=100, population_size=10, offspring=10, samples=48, novelty=use_novelty, seed=seed) signatures = {(int(net.descriptors[0]), int(net.descriptors[2]), min(4, int(5 * net.descriptors[-1]))) for net in result.networks} yield dict(method="network-novelty" if use_novelty else "random", evaluations=result.evaluations, basin_probes=result.basin_probes, signatures=len(signatures), max_optima=max(net.descriptors[0] for net in result.networks)) def main(): cases = dict(layers=layers, decoders=decoders, predict=predict, pga=pga, adaptive=adaptive, landscapes=landscapes) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("case", choices=cases) parser.add_argument("--seeds", nargs="+", type=int, default=[11]) arguments = parser.parse_args() for seed in arguments.seeds: for result in cases[arguments.case](seed): print(json.dumps(dict(case=arguments.case, seed=seed, **result), sort_keys=True), flush=True) if __name__ == "__main__": main()