5"""Shared synchronous environment interaction for PPO, TD3, and neural QD."""
7from contextlib
import contextmanager
8from copy
import deepcopy
9from dataclasses
import dataclass
10from math
import isfinite
12from gymnasium.vector
import VectorEnv
15from .policy
import _action_layout, _flatten_observation, _integer, _observation_shape
19@dataclass(frozen=True)
21 """One episode with its initial observation and the actual final observation.
23 Observations have shape ``(steps + 1, *observation_shape)``. Actions
24 and rewards have one entry per environment step. The two info mappings
25 are independent copies of the reset and last step info. Use values
26 that support ``copy.deepcopy`` in these mappings. A budget-cut
27 episode is never reported as a completed evaluation.
30 observations: np.ndarray
32 rewards: tuple[float, ...]
40 """Return the number of environment steps in the episode."""
45 """Return the undiscounted sum of rewards."""
50@dataclass(frozen=True)
52 """Report search interactions as separate training and archive evaluation costs.
54 :param training_steps: Environment steps collected for standalone training or PPO variation.
55 :param evaluation_steps: Steps used to score candidates for the live archive.
56 :param optimizer_steps: Total optimizer steps across all networks.
57 :param candidate_attempts: Candidates started, including partial evaluations.
58 :param evaluated_policies: Candidates with all requested episodes complete.
59 :param archive_updates: Insertions and replacements reported by QDpy.
60 :param out_of_domain: Completed candidates outside the archive bounds.
61 :param ppo_offspring: Candidates whose actors underwent PPO improvement.
64 training_steps: int = 0
65 evaluation_steps: int = 0
66 optimizer_steps: int = 0
67 candidate_attempts: int = 0
68 evaluated_policies: int = 0
69 archive_updates: int = 0
70 out_of_domain: int = 0
71 ppo_offspring: int = 0
75 """Return the total number of calls to the search environment's step."""
80 """Charge each step at the call site, before advancing the simulator."""
82 def __init__(self, limit, counts):
83 self.
remaining = _integer(limit,
"max_env_steps")
86 def take(self, phase):
88 raise RuntimeError(
"The environment step budget is exhausted.")
94def _open_environment(factory):
97 if isinstance(env, VectorEnv):
98 raise ValueError(
"Use a factory for a single Gymnasium environment.")
105 return int(rng.integers(0, 2**32, dtype=np.uint64))
108def _check_spaces(env, policy):
109 if (_observation_shape(env.observation_space) != policy._obs_shape
110 or _action_layout(env.action_space) != policy._actions):
111 raise ValueError(
"The environment factory changed its observation or action space.")
115 """Keep the true successor observation until the caller explicitly resets."""
117 def __init__(self, env, policy, max_episode_steps, seeds):
120 shape = _observation_shape(env.observation_space)
121 self.
_observe =
lambda observation: _flatten_observation(observation, shape)
124 self.
horizon = max_episode_steps
128 def reset(self, *, seed=None):
129 observation, info = self.
env.reset(seed=_seed(self.
seeds)
if seed
is None else seed)
135 def step(self, action, budget, phase):
137 observation, reward, terminated, truncated, info = self.
env.step(action)
138 reward = float(reward)
139 if not isfinite(reward):
140 raise ValueError(
"The environment returned a nonfinite reward.")
141 terminated = bool(terminated)
142 truncated = bool(truncated)
143 if (terminated
or truncated)
and "final_observation" in info:
144 observation = info[
"final_observation"]
145 info = info.get(
"final_info", info)
149 self.
ended = terminated
or truncated
150 return reward, terminated, truncated, info
153def _evaluate_episode(cursor, actor, budget, on_transition=None, state_descriptor=None, *,
154 phase="evaluation_steps", transition_info=None):
155 """Score one deterministic policy, returning None for a budget-cut prefix."""
156 if not budget.remaining:
158 current_info = cursor.reset()
159 initial_info = deepcopy(current_info)
160 observations = [cursor.observation]
161 actions, rewards = [], []
162 while budget.remaining:
164 if state_descriptor
is not None:
165 state_data = (state_descriptor(cursor.observation.reshape(actor._obs_shape), current_info),)
166 action = actor._greedy(cursor.observation)
167 actions.append(action.copy()
if isinstance(action, np.ndarray)
else action)
168 reward, terminated, truncated, info = cursor.step(action, budget, phase)
169 if on_transition
is not None:
170 on_transition(observations[-1], actions[-1], reward, cursor.observation, terminated, *state_data)
171 if transition_info
is not None:
172 transition_info(observations[-1].reshape(actor._obs_shape), actions[-1], reward,
173 cursor.observation.reshape(actor._obs_shape), terminated, truncated, info)
175 rewards.append(reward)
176 observations.append(cursor.observation)
178 return Episode(np.stack(observations).reshape(len(observations), *actor._obs_shape),
179 tuple(actions), tuple(rewards), initial_info, deepcopy(dict(info)), terminated, truncated)
Measurements from a completed evaluation episode.
Cumulative search costs and evaluated-candidate counts.