QDpy
Loading...
Searching...
No Matches
go_explore.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5import argparse
6import json
7from time import perf_counter
8
9import numpy as np
10
11from qdpy.algorithms import GoExplore
12
13
15 """Advance by finding the right sequence of three possible actions."""
16
17 def __init__(self, code):
18 self.code = code
19 self.calls = 0
20 self.first_solution = None
21
22 def reset(self, *, seed):
23 self.depth = self.elapsed = 0
24 return self.depth, {}
25
26 def step(self, action):
27 self.calls += 1
28 self.elapsed += 1
29 self.depth = self.depth + 1 if action == self.code[self.depth] else 0
30 solved = self.depth == len(self.code)
31 if solved and self.first_solution is None:
32 self.first_solution = self.calls
33 return self.depth, float(solved), solved, self.elapsed >= 36, {}
34
35 def close(self):
36 pass
37
38
39def restore(env, state):
40 """Restore progress and the simulator's time limit."""
41 env.depth, env.elapsed = state
42 return env.depth, {}
43
44
45def benchmark(seed, budget):
46 """Charge replay and exploration against the same hard simulator budget."""
47 task_seed, exploration_seed = np.random.SeedSequence(seed).spawn(2)
48 code = np.random.default_rng(task_seed).integers(3, size=12)
49 exploration_seed = int(exploration_seed.generate_state(1)[0])
50
51 def sample(_, info, rng):
52 return int(rng.integers(3))
53
54 for mode in ("replay", "snapshots", "random-restarts"):
55 start = perf_counter()
56 env = SequencePuzzle(code)
57 if mode == "random-restarts":
58 env.reset(seed=exploration_seed)
59 rng = np.random.default_rng(exploration_seed)
60 visited, best = {0}, 0.
61 for _ in range(budget):
62 depth, reward, terminated, truncated, _ = env.step(sample(None, None, rng))
63 visited.add(depth)
64 best = max(best, reward)
65 if terminated or truncated:
66 env.reset(seed=exploration_seed)
67 env.close()
68 steps, replay, cells = budget, 0, len(visited)
69 else:
70 adapter = dict(snapshot=lambda env: (env.depth, env.elapsed), restore=restore) if mode == "snapshots" else {}
71 search = GoExplore(lambda: env, cell=lambda depth, _: depth,
72 sample_action=sample, exploration_steps=6, seed=exploration_seed, **adapter)
73 stats = search.explore(budget)
74 steps, replay, cells, best = stats.env_steps, stats.replay_steps, stats.occupied_cells, search.best.return_
75 yield dict(method=mode, seed=seed, steps=steps, replay_steps=replay, cells=cells, best=best,
76 first_solution=env.first_solution, seconds=perf_counter() - start)
77
78
79if __name__ == "__main__":
80 parser = argparse.ArgumentParser(description=__doc__)
81 parser.add_argument("--budget", type=int, default=1600)
82 parser.add_argument("--seeds", nargs="+", type=int, default=[11, 22, 33])
83 args = parser.parse_args()
84 for seed in args.seeds:
85 for result in benchmark(seed, args.budget):
86 print(json.dumps(result, sort_keys=True))