# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare neural MAP-Elites and PPO in a custom MultiDiscrete environment. """Train and export three categorical policies on a small navigation task.""" import argparse from dataclasses import asdict import json from pathlib import Path import gymnasium as gym import numpy as np import torch from qdpy.containers import Grid from qdpy.rl import CategoricalPolicy, NeuralMAPElites, PPO, PPOAssistedMAPElites, PPOConfig, PolicyConfig ## @brief A bounded navigation task with six independent categorical controls. class Navigation(gym.Env): """Use two directions to move. Each of the four switches has a small cost.""" observation_space = gym.spaces.Box(low=0, high=1, shape=(3,), dtype=np.float32) action_space = gym.spaces.MultiDiscrete([3, 3, 2, 2, 2, 2]) horizon = 8 def _observation(self): return np.array([*self.position, 1. - self.turn / self.horizon], dtype=np.float32) def reset(self, *, seed=None, options=None): super().reset(seed=seed) self.turn = 0 self.position = self.np_random.uniform(0.4, 0.6, size=2) return self._observation(), {} def step(self, action): if not self.action_space.contains(action): raise ValueError("Invalid categorical action.") direction = np.asarray(action[:2]) - 1 self.position = np.clip(self.position + direction * 0.10, 0, 1) self.turn += 1 distance = np.linalg.norm(self.position - (0.8, 0.7)) reward = 1. - distance / np.sqrt(2) - 0.005 * float(sum(action[2:])) return self._observation(), float(reward), self.turn == self.horizon, False, {} def descriptor(episode): """Use the final position as the two-dimensional archive descriptor.""" return episode.observations[-1, :2] def make_archive(): return Grid(shape=(8, 8), max_items_per_bin=1, fitness_domain=((0., 8.),), features_domain=((0., 1.), (0., 1.)), fitness_weights=(1.,)) ## @brief Evaluate a saved actor in an application-owned environment. def replay(path, seed): """Run one held-out episode with deterministic actions.""" policy = CategoricalPolicy.load(path) env = Navigation() try: observation, _ = env.reset(seed=seed) total = 0.0 for step in range(1, env.horizon + 1): action = policy.act(observation, deterministic=True) observation, reward, terminated, truncated, _ = env.step(action) total += reward if terminated or truncated: break return {"steps": step, "return": total, "descriptor": observation[:2].tolist()} finally: env.close() def main(steps, seed, output_dir): torch.set_num_threads(1) output_dir.mkdir(parents=True, exist_ok=True) architecture = PolicyConfig(hidden_sizes=(32, 32)) ppo = PPOConfig(rollout_steps=32, epochs=2, batch_size=16, learning_rate=0.003) common = dict(policy=architecture, max_episode_steps=Navigation.horizon, seed=seed) searches = { "ppo": PPO(Navigation, config=ppo, **common), "neural_map_elites": NeuralMAPElites(Navigation, make_archive(), descriptor=descriptor, initial_policies=4, **common), "ppo_assisted_map_elites": PPOAssistedMAPElites( Navigation, make_archive(), descriptor=descriptor, initial_policies=4, ppo=ppo, ppo_probability=0.5, **common, ), } for method, search in searches.items(): stats = search.train(steps) actor = search.policy if method == "ppo" else search.best_policy() path = output_dir / f"{method}.npz" actor.save(path) report = {"method": method, "seed": seed, "env_steps": stats.env_steps, **asdict(stats), "policy": path.name, "heldout": replay(path, seed + 10000)} if method != "ppo": report.update(occupied_cells=search.archive.filled_bins, qd_score=search.archive.qd_score(normalized=False), best_fitness=search.archive.best_fitness.values[0]) print(json.dumps(report), flush=True) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--steps", type=int, default=512, help="Environment-step budget for each method.") parser.add_argument("--seed", type=int, default=42) parser.add_argument("--output-dir", type=Path, default=Path("results.discrete-qd-rl")) arguments = parser.parse_args() if arguments.steps < Navigation.horizon: parser.error(f"--steps must be at least {Navigation.horizon} for an archived elite") main(arguments.steps, arguments.seed, arguments.output_dir)