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
5"""Return to reached cells before exploring from them again."""
6
7from collections import Counter
8from collections.abc import Hashable
9from copy import deepcopy
10from dataclasses import dataclass
11from math import isclose, isfinite
12
13import numpy as np
14
15from .modern import _positive_int
16
17__all__ = ["GoExplore", "GoExploreCell", "GoExploreStats"]
18
19
20
21@dataclass(frozen=True)
23 """Report a cell key, replay seed and path, cumulative return, and end flag."""
24
25 key: Hashable
26 reset_seed: int
27 actions: tuple
28 return_: float
29 ended: bool
30
31
32
33@dataclass(frozen=True)
35 """Cumulative search costs and number of distinct reached cells."""
36
37 exploration_steps: int
38 replay_steps: int
39 occupied_cells: int
40
41 @property
42 def env_steps(self):
43 """Return the total number of calls to the environment's step method."""
44 return self.exploration_steps + self.replay_steps
45
46
47@dataclass(frozen=True)
48class _Path:
49 parent: "_Path | None"
50 action: object
51 length: int
52
53
54def _actions(path):
55 actions = []
56 while path is not None:
57 actions.append(path.action)
58 path = path.parent
59 return tuple(reversed(actions))
60
61
62@dataclass(frozen=True)
63class _State:
64 key: Hashable
65 path: _Path | None
66 return_: float
67 ended: bool
68 snapshot: object = None
69
70 @property
71 def length(self):
72 return self.path.length if self.path is not None else 0
73
74
75def _better(candidate, retained):
76 return (retained is None
77 or (candidate.return_, -candidate.length) > (retained.return_, -retained.length))
78
79
80
82 """Run the exploration phase of Go-Explore with a Gymnasium-style environment.
83
84 :param env_factory: Factory for a single environment with seeded reset,
85 five-value step, and close methods.
86 :param cell: Callable mapping observation and info to a stable hashable key.
87 :param sample_action: Callable given observation, info, and a seeded NumPy
88 generator. Return a legal exploration action compatible with deepcopy.
89 :param exploration_steps: Maximum new actions per selected cell.
90 :param max_trajectory_steps: Optional cap on the length of any saved path.
91 :param snapshot: Optional callable taking the environment and returning
92 its complete restorable state, including RNG and wrapper state.
93 :param restore: Paired callable receiving a fresh copy of that snapshot
94 and the environment as ``restore(env, snapshot)``. Return the restored
95 observation and info. Without the pair, reset and replay each path.
96 :param seed: Seed for cell selection, actions, and a fixed reset seed.
97 """
98
99 def __init__(self, env_factory, *, cell, sample_action, exploration_steps=20,
100 max_trajectory_steps=None, snapshot=None, restore=None, seed=0):
101 if not all(map(callable, (env_factory, cell, sample_action))):
102 raise TypeError("env_factory, cell, and sample_action must be callable.")
103 if (snapshot is not None or restore is not None) and not (callable(snapshot) and callable(restore)):
104 raise TypeError("Provide paired snapshot and restore callbacks.")
105 self._factory, self._cell, self._action = env_factory, cell, sample_action
106 self._snapshot, self._restore = snapshot, restore
107 self._branch_length = _positive_int(exploration_steps, "exploration_steps")
108 self._horizon = (None if max_trajectory_steps is None
109 else _positive_int(max_trajectory_steps, "max_trajectory_steps"))
110 self._rng = np.random.default_rng(seed)
111 self._reset_seed = int(self._rng.integers(2**32))
112 self._records, self._starts = {}, {}
113 self._visited, self._selected = Counter(), Counter()
114 self._root = None
115 self._replayed = self._explored = 0
116
117 @property
118 def stats(self):
119 """Return the current step totals and archive coverage as a cell count."""
120 return GoExploreStats(self._explored, self._replayed, len(self._records))
121
122 def _record(self, state):
123 return GoExploreCell(deepcopy(state.key), self._reset_seed, deepcopy(_actions(state.path)),
124 state.return_, state.ended)
125
126 @property
127 def cells(self):
128 """Return independent snapshots of the highest-return paths to each cell."""
129 return tuple(self._record(state) for state in self._records.values())
130
131 @property
132 def best(self):
133 """Return the highest-return path, with shorter paths winning ties."""
134 state = max(self._records.values(), key=lambda row: (row.return_, -row.length), default=None)
135 return self._record(state) if state is not None else None
136
137 def _choose(self, remaining):
138 candidates = [start for start in self._starts.values()
139 if self._restore is not None or start.length < remaining]
140 if not candidates:
141 return self._root
142 scores = np.array([1 + 1 / np.sqrt(1 + self._visited[row.key])
143 + 1 / np.sqrt(1 + self._selected[row.key]) for row in candidates])
144 return candidates[self._rng.choice(len(candidates), p=scores / scores.sum())]
145
146 def _step(self, env, action, *, replay):
147 if replay:
148 self._replayed += 1
149 else:
150 self._explored += 1
151 observation, reward, terminated, truncated, info = env.step(deepcopy(action))
152 reward = float(reward)
153 if not isfinite(reward):
154 raise ValueError("Go-Explore requires finite rewards.")
155 ended = bool(terminated or truncated)
156 if ended and "final_observation" in info:
157 observation, info = info["final_observation"], info.get("final_info", info)
158 return observation, reward, ended, info
159
160 def _capture(self, env, key, path, return_, ended):
161 self._visited[key] += 1
162 state = _State(key, path, return_, ended)
163 report = _better(state, self._records.get(key))
164 start = not ended and _better(state, self._starts.get(key))
165 if start:
166 snapshot = deepcopy(self._snapshot(env)) if self._snapshot is not None else None
167 state = _State(key, path, return_, ended, snapshot)
168 self._starts[key] = state
169 if report:
170 self._records[key] = state
171 return state
172
173 def _return(self, env, state, observation, info):
174 if self._restore is not None:
175 observation, info = self._restore(env, deepcopy(state.snapshot))
176 else:
177 return_ = 0.
178 for action in _actions(state.path):
179 observation, reward, ended, info = self._step(env, action, replay=True)
180 return_ += reward
181 if ended:
182 raise RuntimeError("Go-Explore replay ended before reaching the saved state.")
183 if not isclose(return_, state.return_, rel_tol=1e-12, abs_tol=1e-12):
184 raise RuntimeError("Go-Explore replay produced a different trajectory return.")
185 if self._cell(observation, info) != state.key:
186 raise RuntimeError("Go-Explore did not return to the saved cell.")
187 return observation, info
188
189
190 def explore(self, max_env_steps):
191 """Advance the archive by exactly this many calls to env.step on success."""
192 remaining = _positive_int(max_env_steps, "max_env_steps")
193 target = self._replayed + self._explored + remaining
194 env = self._factory()
195 try:
196 while remaining:
197 observation, info = env.reset(seed=self._reset_seed)
198 if self._root is None:
199 self._root = self._capture(env, self._cell(observation, info), None, 0., False)
200 state = self._choose(remaining)
201 observation, info = self._return(env, state, observation, info)
202 self._selected[state.key] += 1
203
204 count = min(self._branch_length, remaining - (state.length if self._restore is None else 0))
205 if self._horizon is not None:
206 count = min(count, self._horizon - state.length)
207 path, return_ = state.path, state.return_
208 for offset in range(count):
209 action = deepcopy(self._action(observation, info, self._rng))
210 observation, reward, ended, info = self._step(env, action, replay=False)
211 path = _Path(path, action, state.length + offset + 1)
212 return_ += reward
213 if not isfinite(return_):
214 raise ValueError("Go-Explore requires finite trajectory returns.")
215 ended = ended or path.length == self._horizon
216 self._capture(env, self._cell(observation, info), path, return_, ended)
217 if ended:
218 break
219 remaining = target - self._replayed - self._explored
220 finally:
221 env.close()
222 return self.stats
A trajectory from a seeded reset to a reached cell.
Definition go_explore.py:22
Account for exploration calls and replay calls separately.
Definition go_explore.py:34
Explore reachable states by returning to an archive of visited cells.
Definition go_explore.py:81
_capture(self, env, key, path, return_, ended)
_return(self, env, state, observation, info)
_step(self, env, action, *, replay)
explore(self, max_env_steps)
Spend an additional budget, including the cost of all replay actions.