82 """Run the exploration phase of Go-Explore with a Gymnasium-style environment.
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.
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.")
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)
119 """Return the current step totals and archive coverage as a cell count."""
122 def _record(self, state):
124 state.return_, state.ended)
128 """Return independent snapshots of the highest-return paths to each cell."""
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
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]
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())]
146 def _step(self, env, action, *, replay):
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
160 def _capture(self, env, key, path, return_, ended):
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))
167 state =
_State(key, path, return_, ended, snapshot)
173 def _return(self, env, state, observation, info):
175 observation, info = self.
_restore(env, deepcopy(state.snapshot))
178 for action
in _actions(state.path):
179 observation, reward, ended, info = self.
_step(env, action, replay=
True)
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
191 """Advance the archive by exactly this many calls to env.step on success."""
192 remaining = _positive_int(max_env_steps,
"max_env_steps")
197 observation, info = env.reset(seed=self.
_reset_seed)
198 if self.
_root is None:
200 state = self.
_choose(remaining)
201 observation, info = self.
_return(env, state, observation, info)
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)
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)