5"""Explore a continuous line with two rewarding targets and fixed-step episodes."""
9from time
import perf_counter
11import gymnasium
as gym
16from qdpy.rl import DOMiNO, DiverseQualitySpecies, PPOConfig, PolicyConfig, TD3Config
21 """Use one signed action to move along a line and measure the center of each trajectory."""
23 observation_space = gym.spaces.Box(-1., 1., shape=(2,), dtype=np.float32)
24 action_space = gym.spaces.Box(-1., 1., shape=(1,), dtype=np.float32)
27 def reset(self, *, seed=None, options=None):
28 super().reset(seed=seed)
29 self.
position = float(self.np_random.uniform(-.08, .08))
30 self.
target = float(self.np_random.uniform(.62, .78))
37 def step(self, action):
38 self.
position = float(np.clip(self.
position + .21 * float(action[0]), -1., 1.))
39 reward = max(0., 1. - 1.45 * abs(abs(self.
position) - self.
target))
45 return Grid(shape=(9,), features_domain=((-1., 1.),),
46 fitness_domain=((0., float(TwoPeaks.horizon)),), fitness_weights=(1.,))
50def trial(seed, budget):
51 """Report coverage of achieved bins and rewarding directions using an independent reset panel."""
52 horizon = TwoPeaks.horizon
54 for method
in (
"dqs",
"dqs_no_bonus",
"domino"):
55 start = perf_counter()
56 discriminator_updates = offspring = 0
58 if method ==
"domino":
59 trainer =
DOMiNO(TwoPeaks, feature=
lambda observation, action, info: (observation[0],),
60 feature_dimension=1, num_skills=4, policy=config,
61 reward_floor=.55, config=
PPOConfig(rollout_steps=24, epochs=3,
62 batch_size=12, learning_rate=2e-3),
63 max_episode_steps=horizon, seed=seed)
64 stats = trainer.train(budget)
65 audit = trainer.evaluate(episodes_per_skill=5, seed=80_000 + seed)
66 panel = [(row.occupancy, row.return_mean)
for row
in audit.skills]
67 audit_steps = audit.steps
70 td3=
TD3Config(replay_capacity=4096, critic_hidden_sizes=(32, 32),
71 batch_size=32, learning_starts=96,
72 actor_learning_rate=2e-3),
73 update_frequency=3, gradient_steps=16, max_episode_steps=horizon,
74 diversity_scale=.25
if method ==
"dqs" else 0., seed=seed)
75 stats = trainer.train(budget)
77 audit = trainer.evaluate(episodes=5, seed=80_000 + seed,
78 descriptor=
lambda episode: (float(episode.observations[:-1, 0].mean()),),
79 archive=geometry, best_per_species=
True)
80 panel = [(row.descriptor, row.return_)
for row
in audit.policies]
81 audit_steps = audit.env_steps
82 discriminator_updates, offspring = stats.discriminator_updates, stats.pg_offspring
84 best_by_cell, directions = {}, set()
85 for behavior, score
in panel:
86 cell = geometry.index_grid(behavior)
87 best_by_cell[cell] = max(best_by_cell.get(cell, 0.), score)
88 if score / horizon >= .55
and abs(behavior[0]) >= .2:
89 directions.add(int(np.sign(behavior[0])))
90 yield dict(method=method, seed=seed, env_steps=stats.env_steps, audit_steps=audit_steps,
91 occupied=len(best_by_cell), score=sum(best_by_cell.values()), high_return_directions=len(directions),
92 mean_return=float(np.mean([score
for _, score
in panel])), updates=stats.optimizer_steps,
93 discriminator_updates=discriminator_updates, refined=offspring,
94 elapsed_s=perf_counter() - start)
98 """Run seeded CPU comparisons and print JSON records."""
99 parser = argparse.ArgumentParser(description=__doc__)
100 parser.add_argument(
"--seeds", type=int, nargs=
"+", default=[7])
101 parser.add_argument(
"--steps", type=int, default=1440)
102 args = parser.parse_args()
103 if args.steps < 4 * 3 * TwoPeaks.horizon:
104 parser.error(
"--steps must be at least one full DQS generation (144 steps)")
105 torch.set_num_threads(1)
106 for seed
in args.seeds:
107 for record
in trial(seed, args.steps):
108 print(json.dumps(record))
111if __name__ ==
"__main__":
Continuous controls can move toward either of two rewarding positions.
Train a shared actor for distinct policies subject to a task reward floor.
Evolve multiple high-performing species without requiring a descriptor grid.
Architecture of the actor and, for PPO, the separate value network.
Sampling and minibatch settings for the clipped PPO update.
Settings for the shared TD3 actor, critics, and replay buffer.