5"""Run deterministic CPU pilots for structured sequences, noisy outcomes, and continuing control."""
9from itertools
import product
10from pathlib
import Path
15 DistributionMAPElites,
16 EmpiricalDistribution,
22 wasserstein_descriptor_distance,
28_TILE_STEPS = {
"a": 0,
"b": 1,
"c": 2,
"k": 1,
"d": 1}
29_CORPUS = (
"ababkbbcdbab",
"bababccbkddb",
"abbabkbcbbda",
"bccbkdbababa",
30 "abbdbbabkcbb",
"bbkbcbbdbcba",
"babcbabkabdb",
"babccbbkadba")
34_CENTERS = (-1., 0., 1.)
35_WIDTHS = (.05, .45, .95)
40 """Check climb height and access to locked doors, then score tile variety."""
41 keys, previous, doors = 0, 0, 0
43 elevation = _TILE_STEPS[tile]
44 if abs(elevation - previous) > 1
or (tile ==
"d" and keys == 0):
52 quality = len(set(zip(level, level[1:]))) / (len(level) - 1)
53 return quality, (min(3, doors), min(4, level.count(
"c")))
57 def __init__(self, archive, space, budget, seed, *, sampling):
59 self.
rng = np.random.default_rng(seed)
60 super().__init__(archive, budget, dimension=space.length, batch_size=1,
61 optimisation_task=
"maximisation")
65 individual[:] = self.
space.sample(self.
rng)
67 first, second = self.
rng.integers(len(self.
container), size=2)
68 cut = self.
rng.integers(1, self.
space.length)
70 if self.
rng.random() < .2:
71 individual[self.
rng.integers(self.
space.length)] = tuple(_TILE_STEPS)[self.
rng.integers(len(_TILE_STEPS))]
75def compare_levels(budget, seed):
76 """Compare valid levels and niche quality at equal proposal cost."""
78 for method
in (
"gram-elites",
"standard-map-elites",
"ngram-sampling"):
79 grid =
Grid(shape=(4, 5), features_domain=((0, 4), (0, 5)), fitness_domain=((0., 1.),))
80 if method ==
"gram-elites":
81 search =
GramElites(grid, budget, space, mutation_probability=.2, seed=seed)
83 search =
_TileBaseline(grid, space, budget, seed, sampling=method ==
"ngram-sampling")
84 supported, playable = 0, 0
85 for _
in range(budget):
86 individual = search.ask()
87 supported += space.supports(individual)
88 result = play_level(individual)
89 playable += result
is not None
90 quality, descriptors = result
or (0., (0, 0))
91 search.tell(individual, (quality,), descriptors, tell_container=result
is not None)
92 yield dict(task=
"levels", method=method, seed=seed, proposals=search.nb_evaluations,
93 supported=supported, playable=playable, cells=len(grid),
94 qd_score=sum(elite.fitness.values[0]
for elite
in grid))
98 return (int(rng.integers(3)), int(rng.integers(3)), int(rng.integers(9)))
101def _mutate(genome, rng):
103 index = rng.integers(len(child))
104 child[index] = (child[index] + int(rng.choice([-1, 1]))) % (3, 3, 9)[index]
108def stochastic_outcome(genome, seed):
109 """Generate an outcome whose expectation and spread vary independently."""
110 mean, spread, quality = genome
111 rng = np.random.default_rng(seed)
112 outcome = _CENTERS[mean] + _WIDTHS[spread] * rng.choice((-1., 1.)) + rng.normal(0., .025)
113 return quality / 8., float(outcome)
116def _distribution_grid():
118 for mean, spread
in product(_CENTERS, _WIDTHS))
119 return MedoidArchive(anchors, wasserstein_descriptor_distance)
122def compare_outcomes(budget, seed):
123 """Reassign both methods to the same distribution niches on held-out seeds."""
124 distribution = _distribution_grid()
126 rollouts=_ROLLOUTS, seed=seed)
127 search.optimise(stochastic_outcome, budget=budget)
128 audit = search.audit(stochastic_outcome, rollouts=_AUDIT)
129 yield dict(task=
"outcomes", method=
"distribution", seed=seed, proposals=search.nb_evaluations,
130 rollouts=search.nb_rollouts, audit_rollouts=search.nb_audit_rollouts,
131 search_cells=len(distribution), stable=sum(row.stable
for row
in audit),
132 **_audit_summary((row.audit_niche, row.fitness)
for row
in audit))
135 mean_grid =
MedoidArchive(np.linspace(-1., 1., 9),
lambda a, b: abs(a - b))
136 variation, training, holdout = np.random.SeedSequence(seed).spawn(3)
137 rng = np.random.default_rng(training)
140 def evaluate(genome):
142 results = [stochastic_outcome(genome, rng.bit_generator.random_raw())
for _
in range(_ROLLOUTS)]
143 called += len(results)
144 return tuple(np.mean(results, axis=0))
146 baseline =
MedoidMAPElites(mean_grid, propose=_propose, mutate=_mutate, seed=variation)
147 baseline.optimise(evaluate, budget=budget)
148 audit_panel = holdout.generate_state(_AUDIT, dtype=np.uint64)
150 for cell, elite
in mean_grid.cells.items():
151 scores, outcomes = zip(*(stochastic_outcome(elite.genome, int(s))
for s
in audit_panel))
152 stable += mean_grid.index(float(np.mean(outcomes))) == cell
154 rows.append((index, float(np.mean(scores))))
155 yield dict(task=
"outcomes", method=
"mean", seed=seed, proposals=baseline.nb_evaluations,
156 rollouts=called, audit_rollouts=len(rows) * _AUDIT,
157 search_cells=len(mean_grid), stable=stable, **_audit_summary(rows))
160def _audit_summary(rows):
162 for niche, score
in rows:
163 best[niche] = max(score, best.get(niche, -np.inf))
164 return dict(audit_cells=len(best), audit_qd_score=sum(best.values()))
167def safety_margin(observation):
168 """Return positive margin inside the circular navigation region."""
169 return .77 - float(np.linalg.norm(observation))
172def fallback_action(observation):
173 """Steer toward the center of the training region."""
174 return np.clip(-3. * observation, -1., 1.).astype(np.float32)
177def navigation_reward(observation, action, successor):
178 """Reward progress while charging for control effort."""
179 return .5 + float(np.linalg.norm(successor - observation)) - .12 * float(action @ action)
182def displacement(episode):
183 """Describe a skill by the measured displacement of its complete trajectory."""
184 return episode.observations[-1] - episode.observations[0]
188 return Grid(shape=(7, 7), features_domain=((-1., 1.),) * 2, fitness_domain=((0., 4.),))
191def _navigation_factory(trace):
192 import gymnasium
as gym
194 class Navigation(gym.Env):
196 self.observation_space = gym.spaces.Box(-1.5, 1.5, (2,), dtype=np.float32)
197 self.action_space = gym.spaces.Box(-1., 1., (2,), dtype=np.float32)
199 def reset(self, *, seed=None, options=None):
200 super().reset(seed=seed)
202 self.state = self.np_random.uniform(-.035, .035, 2).astype(np.float32)
203 return self.state.copy(), {}
205 def step(self, action):
206 assert self.action_space.contains(action)
208 drift = np.array((.055 + .06 * y, -.035 - .04 * x), dtype=np.float32)
209 successor = np.clip(self.state + .16 * action + drift, -1.5, 1.5)
210 reward = navigation_reward(self.state, action, successor)
212 trace[
"unsafe_steps"] += safety_margin(successor) < 0.
213 self.state = successor
214 return successor.copy(), reward,
False,
False, {}
219def _fixed_navigation(factory, archive, budget, seed):
220 """Select from nine hand-written actions with nominal safety and novelty scores."""
221 library = [np.asarray(move, dtype=np.float32)
for move
in product((-.8, 0., .8), repeat=2)]
225 observation, _ = env.reset(seed=seed)
226 for _
in range(budget // _HORIZON):
227 start = observation.copy()
229 for action
in library:
230 path = [start + .16 * i * action
for i
in range(1, _HORIZON + 1)]
231 margin = min(map(safety_margin, path))
233 features = tuple(path[-1] - start)
234 priority.append((
not archive.solutions[archive.index_grid(features)], margin, action))
235 candidate = (max(priority, key=
lambda row: row[:2])[-1]
236 if priority
and safety_margin(start) >= 0.
else None)
238 valid = candidate
is not None
239 for _
in range(_HORIZON):
243 action = fallback_action(observation)
245 observation, reward, *_ = env.step(action)
246 valid &= safety_margin(observation) >= 0.
250 features=
Features(observation - start))
257def compare_navigation(budget, seed):
258 """Measure real and model steps, cumulative archive score, and safety outcomes."""
261 from qdpy.rl import DynamicsAwareQD, PolicyConfig, ResetFreeQD
263 if budget <= 32
or budget % _HORIZON:
264 raise ValueError(
"Navigation uses more than 32 steps and a multiple of four.")
265 torch.set_num_threads(1)
266 for method
in (
"reset-free",
"fixed-repertoire",
"episodic-da-qd"):
267 trace = dict(resets=0, steps=0, unsafe_steps=0)
268 factory, archive = _navigation_factory(trace), _nav_grid()
269 kwargs = dict(descriptor=displacement, model_reward=navigation_reward, initial_policies=4,
270 policy=PolicyConfig(()), model_policy=PolicyConfig((16,)), min_model_steps=32,
271 model_updates=6, model_learning_rate=.01, ensemble_size=2, model_batch_size=24,
272 imagined_candidates=16, iso_sigma=.30, seed=seed)
273 model_steps, recovery_steps = 0, 0
274 if method ==
"reset-free":
275 rng = np.random.default_rng(seed)
277 def warmup(observation):
278 if safety_margin(observation) < .31:
279 return fallback_action(observation)
280 return rng.uniform(-1., 1., 2).astype(np.float32)
282 with ResetFreeQD(factory, archive, safety_margin=safety_margin, fallback_action=fallback_action,
283 safety_buffer=.10, warmup_action=warmup, skill_steps=_HORIZON, **kwargs)
as search:
284 stats = search.train(budget)
285 model_steps, recovery_steps = stats.imagined_steps, stats.recovery_steps
286 elif method ==
"fixed-repertoire":
287 recovery_steps = _fixed_navigation(factory, archive, budget, seed)
289 search = DynamicsAwareQD(factory, archive, max_episode_steps=_HORIZON, max_transfers=1, **kwargs)
290 stats = search.train(budget)
291 model_steps = stats.imagined_steps
292 yield dict(task=
"navigation", method=method, seed=seed, step_budget=budget, **trace,
293 external_resets=trace[
"resets"] - 1, model_steps=model_steps, recovery_steps=recovery_steps,
294 cells=len(archive), qd_score=sum(elite.fitness.values[0]
for elite
in archive))
298 """Run base pilots by default, or select the optional RL pilot."""
299 parser = argparse.ArgumentParser(description=__doc__)
300 parser.add_argument(
"--task", choices=(
"base",
"levels",
"outcomes",
"navigation",
"all"), default=
"base")
301 parser.add_argument(
"--seeds", type=int, default=3)
302 parser.add_argument(
"--budget", type=int, default=160)
303 parser.add_argument(
"--output", type=Path)
304 args = parser.parse_args()
305 if args.seeds < 1
or args.budget < 1:
306 parser.error(
"seeds and budget must be positive")
307 tasks = {
"levels": compare_levels,
"outcomes": compare_outcomes,
"navigation": compare_navigation}
308 chosen = (
"levels",
"outcomes")
if args.task ==
"base" else tuple(tasks)
if args.task ==
"all" else (args.task,)
309 rows = [row
for task
in chosen
for seed
in range(args.seeds)
for row
in tasks[task](args.budget, seed)]
310 contents =
"".join(json.dumps(row, sort_keys=
True, allow_nan=
False) +
"\n" for row
in rows)
311 if args.output
is None:
312 print(contents, end=
"")
314 args.output.write_text(contents, encoding=
"utf-8")
317if __name__ ==
"__main__":
Measure stochastic outcomes repeatedly and illuminate fixed distributional niches.
Represent an empirical probability measure with equal mass per observation.
Illuminate supported token sequences in a native Grid or CVTGrid.
Learn allowed token transitions and keep variation within their support.
Assign descriptors to the nearest fixed medoid and keep the best candidate there.
Draw parents from occupied medoid niches and mutate with caller-defined operators.
:param obj: Slice indicating on which objectives the domination is tested.
_internal_ask(self, individual)