#!/usr/bin/env python3 # SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Matched CPU comparisons for sparse rewards, tree policies, and determinant ES. """Run one or all of the sparse-reward, tree-policy, and population comparisons.""" import argparse import json from pathlib import Path import numpy as np from qdpy.algorithms import DvDES, SERENE, TraceElites, behavior_logdet from qdpy.containers import Grid, TraceArchive def _navigation(genome): route, endpoint = np.asarray(genome).reshape(2, 2) gates = np.array([[.23, .28], [.73, .71]]) goals = np.array([[.14, .82], [.86, .18]]) route_error, goal_error = np.linalg.norm(route - gates, axis=1), np.linalg.norm(endpoint - goals, axis=1) quality = np.where((route_error < .23) & (goal_error < .16), 1. - route_error - 2 * goal_error, 0.) return float(quality.max()), tuple(map(float, endpoint)) def _sparse(seed, budget): settings = dict(shape=(16, 16), features_domain=((0., 1.), (0., 1.)), fitness_domain=((0., 1.),), fitness_weights=(1.,)) for method in ("serene", "endpoint-map-elites"): first, calls = None, 0 def evaluate(genome, _seed=None): nonlocal first, calls calls += 1 reward, endpoint = _navigation(genome) if reward > 0 and first is None: first = calls return reward, endpoint if method == "serene": archive = Grid(**settings) search = SERENE(archive, 4, exploration_sigma=.18, emitter_sigma=.04, seed=seed) stats = search.run(evaluate, budget) rows = [(ind.fitness.values[0], ind.features.values) for ind in archive] phases = dict(exploration=stats.exploration_evaluations, bootstrap=stats.bootstrap_evaluations, emitter=stats.emitter_evaluations, novelty_records=len(search.novelty_archive)) assert stats.evaluations == calls and stats.first_reward_evaluation == first else: archive = TraceArchive(Grid(**settings)) search = TraceElites(archive, 4, iso_sigma=.18, line_sigma=0., initial_samples=24, seed=seed) def single_point(genome): reward, endpoint = evaluate(genome) return reward, [endpoint] search.run(single_point, budget) rows = [(elite.fitness, elite.trace[0]) for elite in archive] phases = {} assert calls == budget regions = [max((value for value, endpoint in rows if (endpoint[0] < .5) == left), default=0.) for left in (True, False)] yield dict(task="sparse", method=method, seed=seed, evaluations=calls, first_reward=first, rewarding_cells=sum(value > 0 for value, _ in rows), rewarding_regions=sum(x > 0 for x in regions), best_reward=max(regions), region_rewards=regions, **phases) def _balance_factory(): import gymnasium as gym class LineBalance(gym.Env): """Keep a particle near the origin with two available impulses.""" observation_space = gym.spaces.Box(-np.inf, np.inf, (2,), dtype=np.float32) action_space = gym.spaces.Discrete(2) def reset(self, *, seed=None, options=None): super().reset(seed=seed) self.x, self.v = self.np_random.uniform([-.8, -.18], [.8, .18]) return np.array([self.x, self.v], dtype=np.float32), {} def step(self, action): self.v = .62 * self.v + .12 * (2 * action - 1) self.x += self.v return np.array([self.x, self.v], dtype=np.float32), max(0., 1. - abs(self.x)), False, False, {} return LineBalance() def _trees(seed, budget, policy_dir): from qdpy.rl import DecisionTreeMAPElites, DecisionTreePolicy for selection in ("archive", "quality"): method = "tree-map-elites" if selection == "archive" else "reward-only-trees" search = DecisionTreeMAPElites([(-1., 1.), (-.35, .35)], max_depth=4, entropy_bins=8, train_episodes=8, evaluation_episodes=4, max_episode_steps=16, selection=selection, seed=seed) stats = search.run(_balance_factory, budget) policy = search.best_policy if policy_dir: policy_dir.mkdir(parents=True, exist_ok=True) path = policy_dir / f"{method}-{seed}.json" policy.save(path) policy = DecisionTreePolicy.load(path) audit = search.evaluate(_balance_factory, policy, episodes=24, seed=seed + 10_000) best = search.archive.best.fitness.values[0] yield dict(task="trees", method=method, seed=seed, training_steps=stats.training_steps, evaluation_steps=stats.evaluation_steps, evaluated_policies=stats.evaluated_policies, audit_steps=audit.steps, occupied_cells=len(search.archive), best_return=best, qd_score=float(np.nansum(search.archive.quality_array)), best_depth=policy.depth, audit_return=audit.mean_return, audit_entropy=audit.action_entropy) _MODES = np.array([[-.6, -.6], [-.6, .6], [.6, -.6], [.6, .6]]) _PROBES = np.array([-.75, 0., .75]) def _control(genome, rng): point = np.asarray(genome).reshape(2, 2) context = rng.uniform(-.85, .85) action = np.tanh(point[0] + context * point[1]) reward = np.exp(-np.min(np.sum((action - _MODES)**2, axis=1)) / .24) return float(reward) def _population(seed, budget): initial = np.random.default_rng(seed).normal(.15, .12, size=(4, 4)) def evaluate(genome, rollout_seed): point = np.asarray(genome).reshape(2, 2) actions = np.tanh(point[0] + _PROBES[:, None] * point[1]).ravel() return _control(genome, np.random.default_rng(rollout_seed)), actions for method, weight in (("dvd-es", None), ("dvd-es-fixed", .5), ("independent-es", 0.)): search = DvDES(initial, pairs=4, sigma=.14, learning_rate=.07, diversity_weight=weight, bandwidth=.7, ind_domain=(-2., 2.), seed=seed) stats = search.run(evaluate, budget) diagnostics = [] for member in search.population: outcomes = [_control(member.genome, np.random.default_rng([seed, 20_000, i])) for i in range(64)] mean_action = np.mean(np.asarray(member.embedding).reshape(-1, 2), axis=0) distances = np.linalg.norm(_MODES - mean_action, axis=1) diagnostics.append((float(np.mean(outcomes)), int(np.argmin(distances)), float(distances.min()))) quality = [row[0] for row in diagnostics] yield dict(task="dvd", method=method, seed=seed, evaluations=stats.evaluations, rounds=stats.updates, mixed_rounds=stats.mixed_updates, audit_evaluations=64 * len(quality), audit_mean=float(np.mean(quality)), audit_best=max(quality), strong_modes=len({mode for reward, mode, distance in diagnostics if reward >= .7 and distance < .35}), logdet=behavior_logdet([member.embedding for member in search.population], bandwidth=.7)) ## @brief Execute fixed-budget comparisons and print one JSON row per method and seed. def main(): """Use a headless synthetic workload and optionally persist results and trees.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("task", choices=("sparse", "trees", "dvd", "all")) parser.add_argument("--budget", type=int, help="Evaluator calls for sparse and dvd, or environment steps for trees.") parser.add_argument("--seeds", nargs="+", type=int, default=[7, 13, 23]) parser.add_argument("--output", type=Path) parser.add_argument("--policy-dir", type=Path) args = parser.parse_args() if args.budget is not None and (args.task == "all" or args.budget < {"sparse": 1, "trees": 192, "dvd": 4}[args.task]): parser.error("For a custom budget select a single task and allow at least 1, 192, or 4 calls respectively.") tasks = {"sparse": (_sparse, 768, ()), "trees": (_trees, 12_288, (args.policy_dir,)), "dvd": (_population, 1_156, ())} selected = tasks if args.task == "all" else (args.task,) lines = [] for task in selected: run, default, options = tasks[task] for seed in args.seeds: for row in run(seed, args.budget or default, *options): line = json.dumps(row, sort_keys=True, allow_nan=False) lines.append(line) print(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()