# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Archive-based Go-Explore with deterministic replay or state restoration.
"""Return to reached cells before exploring from them again."""
from collections import Counter
from collections.abc import Hashable
from copy import deepcopy
from dataclasses import dataclass
from math import isclose, isfinite
import numpy as np
from .modern import _positive_int
__all__ = ["GoExplore", "GoExploreCell", "GoExploreStats"]
## @brief A trajectory from a seeded reset to a reached cell.
[docs]
@dataclass(frozen=True)
class GoExploreCell:
"""Report a cell key, replay seed and path, cumulative return, and end flag."""
key: Hashable
reset_seed: int
actions: tuple
return_: float
ended: bool
## @brief Account for exploration calls and replay calls separately.
[docs]
@dataclass(frozen=True)
class GoExploreStats:
"""Cumulative search costs and number of distinct reached cells."""
exploration_steps: int
replay_steps: int
occupied_cells: int
@property
def env_steps(self):
"""Return the total number of calls to the environment's step method."""
return self.exploration_steps + self.replay_steps
@dataclass(frozen=True)
class _Path:
parent: "_Path | None"
action: object
length: int
def _actions(path):
actions = []
while path is not None:
actions.append(path.action)
path = path.parent
return tuple(reversed(actions))
@dataclass(frozen=True)
class _State:
key: Hashable
path: _Path | None
return_: float
ended: bool
snapshot: object = None
@property
def length(self):
return self.path.length if self.path is not None else 0
def _better(candidate, retained):
return (retained is None
or (candidate.return_, -candidate.length) > (retained.return_, -retained.length))
## @brief Explore reachable states by returning to an archive of visited cells.
[docs]
class GoExplore:
"""Run the exploration phase of Go-Explore with a Gymnasium-style environment.
:param env_factory: Factory for a single environment with seeded reset,
five-value step, and close methods.
:param cell: Callable mapping observation and info to a stable hashable key.
:param sample_action: Callable given observation, info, and a seeded NumPy
generator. Return a legal exploration action compatible with deepcopy.
:param exploration_steps: Maximum new actions per selected cell.
:param max_trajectory_steps: Optional cap on the length of any saved path.
:param snapshot: Optional callable taking the environment and returning
its complete restorable state, including RNG and wrapper state.
:param restore: Paired callable receiving a fresh copy of that snapshot
and the environment as ``restore(env, snapshot)``. Return the restored
observation and info. Without the pair, reset and replay each path.
:param seed: Seed for cell selection, actions, and a fixed reset seed.
"""
def __init__(self, env_factory, *, cell, sample_action, exploration_steps=20,
max_trajectory_steps=None, snapshot=None, restore=None, seed=0):
if not all(map(callable, (env_factory, cell, sample_action))):
raise TypeError("env_factory, cell, and sample_action must be callable.")
if (snapshot is not None or restore is not None) and not (callable(snapshot) and callable(restore)):
raise TypeError("Provide paired snapshot and restore callbacks.")
self._factory, self._cell, self._action = env_factory, cell, sample_action
self._snapshot, self._restore = snapshot, restore
self._branch_length = _positive_int(exploration_steps, "exploration_steps")
self._horizon = (None if max_trajectory_steps is None
else _positive_int(max_trajectory_steps, "max_trajectory_steps"))
self._rng = np.random.default_rng(seed)
self._reset_seed = int(self._rng.integers(2**32))
self._records, self._starts = {}, {}
self._visited, self._selected = Counter(), Counter()
self._root = None
self._replayed = self._explored = 0
@property
def stats(self):
"""Return the current step totals and archive coverage as a cell count."""
return GoExploreStats(self._explored, self._replayed, len(self._records))
def _record(self, state):
return GoExploreCell(deepcopy(state.key), self._reset_seed, deepcopy(_actions(state.path)),
state.return_, state.ended)
@property
def cells(self):
"""Return independent snapshots of the highest-return paths to each cell."""
return tuple(self._record(state) for state in self._records.values())
@property
def best(self):
"""Return the highest-return path, with shorter paths winning ties."""
state = max(self._records.values(), key=lambda row: (row.return_, -row.length), default=None)
return self._record(state) if state is not None else None
def _choose(self, remaining):
candidates = [start for start in self._starts.values()
if self._restore is not None or start.length < remaining]
if not candidates:
return self._root
scores = np.array([1 + 1 / np.sqrt(1 + self._visited[row.key])
+ 1 / np.sqrt(1 + self._selected[row.key]) for row in candidates])
return candidates[self._rng.choice(len(candidates), p=scores / scores.sum())]
def _step(self, env, action, *, replay):
if replay:
self._replayed += 1
else:
self._explored += 1
observation, reward, terminated, truncated, info = env.step(deepcopy(action))
reward = float(reward)
if not isfinite(reward):
raise ValueError("Go-Explore requires finite rewards.")
ended = bool(terminated or truncated)
if ended and "final_observation" in info:
observation, info = info["final_observation"], info.get("final_info", info)
return observation, reward, ended, info
def _capture(self, env, key, path, return_, ended):
self._visited[key] += 1
state = _State(key, path, return_, ended)
report = _better(state, self._records.get(key))
start = not ended and _better(state, self._starts.get(key))
if start:
snapshot = deepcopy(self._snapshot(env)) if self._snapshot is not None else None
state = _State(key, path, return_, ended, snapshot)
self._starts[key] = state
if report:
self._records[key] = state
return state
def _return(self, env, state, observation, info):
if self._restore is not None:
observation, info = self._restore(env, deepcopy(state.snapshot))
else:
return_ = 0.
for action in _actions(state.path):
observation, reward, ended, info = self._step(env, action, replay=True)
return_ += reward
if ended:
raise RuntimeError("Go-Explore replay ended before reaching the saved state.")
if not isclose(return_, state.return_, rel_tol=1e-12, abs_tol=1e-12):
raise RuntimeError("Go-Explore replay produced a different trajectory return.")
if self._cell(observation, info) != state.key:
raise RuntimeError("Go-Explore did not return to the saved cell.")
return observation, info
## @brief Spend an additional budget, including the cost of all replay actions.
[docs]
def explore(self, max_env_steps):
"""Advance the archive by exactly this many calls to env.step on success."""
remaining = _positive_int(max_env_steps, "max_env_steps")
target = self._replayed + self._explored + remaining
env = self._factory()
try:
while remaining:
observation, info = env.reset(seed=self._reset_seed)
if self._root is None:
self._root = self._capture(env, self._cell(observation, info), None, 0., False)
state = self._choose(remaining)
observation, info = self._return(env, state, observation, info)
self._selected[state.key] += 1
count = min(self._branch_length, remaining - (state.length if self._restore is None else 0))
if self._horizon is not None:
count = min(count, self._horizon - state.length)
path, return_ = state.path, state.return_
for offset in range(count):
action = deepcopy(self._action(observation, info, self._rng))
observation, reward, ended, info = self._step(env, action, replay=False)
path = _Path(path, action, state.length + offset + 1)
return_ += reward
if not isfinite(return_):
raise ValueError("Go-Explore requires finite trajectory returns.")
ended = ended or path.length == self._horizon
self._capture(env, self._cell(observation, info), path, return_, ended)
if ended:
break
remaining = target - self._replayed - self._explored
finally:
env.close()
return self.stats