89 """Evolve split structures and fit fresh action values for each structure.
91 Train on seeded epsilon-greedy episodes, then place the greedy policy
92 by tree depth and action entropy measured on fixed scoring episodes.
93 Use evaluate for a separate audit on new resets. The reward-only
94 control retains the same reporting grid and mutates its best policy
95 across all cells. The default selects a uniform occupied cell.
97 :param observation_bounds: Finite (low, high) threshold interval per flattened coordinate.
98 :param max_depth: Maximum split depth, up to 12.
99 :param entropy_bins: Grid resolution on the normalized action entropy axis.
100 :param train_episodes: Q-learning episodes per proposed tree.
101 :param evaluation_episodes: Fixed greedy scoring episodes per tree.
102 :param max_episode_steps: Hard limit on steps per training or scoring episode.
103 :param epsilon: Exploration probability for the leaf learner.
104 :param learning_rate: Tabular Q-learning step size.
105 :param gamma: Future reward discount. Truncation permits bootstrapping.
106 :param restart_probability: Probability of generating a fresh structure from scratch.
107 :param selection: "archive" for MAP-Elites or "quality" for the reward-only control.
108 :param seed: Private seed for structure, tabular training, and scoring streams.
111 def __init__(self, observation_bounds, *, max_depth=4, entropy_bins=8, train_episodes=8,
112 evaluation_episodes=3, max_episode_steps=200, epsilon=.2, learning_rate=.2,
113 gamma=.95, restart_probability=.1, selection="archive", seed=0):
114 self.
_bounds = np.asarray(observation_bounds, dtype=float).copy()
116 or not np.isfinite(self.
_bounds).all()
119 raise ValueError(
"Supply one finite increasing threshold interval per observation coordinate.")
120 self.
_max_depth = _integer(max_depth,
"max_depth", minimum=0)
122 raise ValueError(f
"max_depth must be at most {_MAX_DEPTH}.")
123 if not (0 <= epsilon <= 1
and 0 < learning_rate <= 1
and 0 <= gamma <= 1
124 and 0 <= restart_probability <= 1):
125 raise ValueError(
"Use probabilities and gamma in [0, 1] and a learning rate in (0, 1].")
126 if selection
not in (
"archive",
"quality"):
127 raise ValueError(
"Choose archive or quality parent selection.")
130 self.
_horizon = _integer(max_episode_steps,
"max_episode_steps")
134 max_items_per_bin=1, fitness_domain=((-np.inf, np.inf),),
135 features_domain=((-0.5, self.
_max_depth + .5), (0., 1.)), fitness_weights=(1.,))
136 variation, learning, scoring = np.random.SeedSequence(seed).spawn(3)
137 self.
_rng, self.
_learning = np.random.default_rng(variation), np.random.default_rng(learning)
140 self.
_steps = dict(training_steps=0, evaluation_steps=0)
145 """Return cumulative search costs."""
150 """Return the highest-scoring policy currently in the grid."""
152 raise RuntimeError(
"Run the search until at least one policy has been evaluated.")
158 """Read the fitted tree from the individual's genome."""
160 raise RuntimeError(
"Run the search before restoring a policy from its grid.")
163 def _layout_for(self, env):
164 shape = _observation_shape(env.observation_space)
165 if (prod(shape) != len(self.
_bounds)
or not isinstance(env.action_space, spaces.Discrete)):
166 raise ValueError(
"Use a numeric Box matching observation_bounds and a Discrete action space.")
167 return shape, int(env.action_space.n), int(env.action_space.start)
169 def _random_tree(self, depth):
170 if depth == 0
or self.
_rng.random() < .3:
172 feature = int(self.
_rng.integers(len(self.
_bounds)))
173 threshold = float(self.
_rng.uniform(*self.
_bounds[feature]))
180 structure = _structure(parent[0])
181 paths = tuple(_paths(structure))
182 path = paths[self.
_rng.integers(len(paths))]
185 def _fit(self, env, structure, budget):
186 resets, behavior = (np.random.default_rng(seed)
for seed
in self.
_learning.integers(2**32, size=2))
189 indexed = _leaves(structure, indices)
190 leaves = next(indices)
191 _, actions, start = self.
_layout
192 values = np.zeros((leaves, actions))
195 leaf = _leaf(indexed, cursor.observation)
196 while not cursor.ended:
197 if behavior.random() < self.
_epsilon:
198 action = behavior.integers(actions)
200 action = behavior.choice(np.flatnonzero(values[leaf] == values[leaf].max()))
201 reward, terminated, _, _ = cursor.step(start + int(action), budget,
"training_steps")
202 successor = _leaf(indexed, cursor.observation)
203 target = reward
if terminated
else reward + self.
_gamma * values[successor].max()
204 values[leaf, action] += self.
_rate * (target - values[leaf, action])
205 if not np.isfinite(values[leaf, action]):
206 raise ValueError(
"Leaf Q-learning produced a nonfinite value.")
210 def _score(self, env, policy, episodes, rng, budget):
212 counts = [0] * policy._action_count
214 for _
in range(episodes):
217 while not cursor.ended:
218 index = _leaf(policy._tree, cursor.observation)
220 reward, _, _, _ = cursor.step(policy._action_start + index, budget,
"evaluation_steps")
221 episode_rewards.append(reward)
222 rewards.append(fsum(episode_rewards))
226 proportions = [count / steps
for count
in counts
if count]
227 entropy = min(1., max(0., -fsum(p * log(p)
for p
in proportions) / log(len(counts))))
228 return TreeEvaluation(fsum(value / episodes
for value
in rewards), entropy, tuple(counts), steps)
234 def run(self, env_factory, max_env_steps):
235 """Reserve the worst-case cost per candidate and charge actual steps."""
238 with _open_environment(env_factory)
as env:
241 raise ValueError(
"The environment factory changed its observation or action layout.")
243 while budget.remaining >= reservation:
246 np.random.default_rng(self.
_scoring), budget)
247 descriptor = (policy.depth, measurement.action_entropy)
248 cell = self.
archive.index_grid(descriptor)
250 previous = self.
archive.nb_added
252 weights=(1.,)), features=
Features(descriptor)))
253 self._updates += self.
archive.nb_added - previous
262 def evaluate(self, env_factory, policy, *, episodes, seed):
263 """Evaluate without changing search state or the repertoire."""
264 episodes = _integer(episodes,
"episodes")
266 with _open_environment(env_factory)
as env:
267 if self.
_layout_for(env) != (policy._shape, policy._action_count, policy._action_start):
268 raise ValueError(
"The policy and environment action or observation layouts differ.")
269 return self.
_score(env, policy, episodes, np.random.default_rng(seed), budget)