QDpy
Loading...
Searching...
No Matches
tree_map_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Decision-tree MAP-Elites for discrete Gymnasium environments."""
7
8from dataclasses import dataclass
9from itertools import count
10from math import fsum, log, prod
11
12from gymnasium import spaces
13import numpy as np
14
15from qdpy.algorithms.tree_policy import DecisionTreePolicy, _MAX_DEPTH, _leaf
16from qdpy.containers import Grid
17from qdpy.phenotype import Features, Fitness, _CellIndividual
18from .policy import _integer, _observation_shape
19from .rollout import _Cursor, _open_environment, _StepBudget
20
21__all__ = ["DecisionTreePolicy", "DecisionTreeMAPElites", "TreeEvaluation", "TreeSearchStats"]
22
23
24@dataclass(frozen=True)
26 """Action counts are ordered by zero-based policy action index."""
27
28 mean_return: float
29 action_entropy: float
30 action_counts: tuple[int, ...]
31 steps: int
32
33
34
35@dataclass(frozen=True)
37 """Report cumulative environment interaction and admission counts."""
38
39 training_steps: int
40 evaluation_steps: int
41 evaluated_policies: int
42 archive_updates: int
43
44 @property
45 def env_steps(self):
46 """Return total environment steps, excluding independent audits."""
47 return self.training_steps + self.evaluation_steps
48
49
50def _leaves(node, index):
51 if node is None:
52 return next(index)
53 feature, threshold, left, right = node
54 return feature, threshold, _leaves(left, index), _leaves(right, index)
55
56
57def _map_leaves(node, actions):
58 if isinstance(node, tuple):
59 feature, threshold, left, right = node
60 return feature, threshold, _map_leaves(left, actions), _map_leaves(right, actions)
61 return int(actions[node])
62
63
64def _structure(node):
65 if isinstance(node, tuple):
66 feature, threshold, left, right = node
67 return feature, threshold, _structure(left), _structure(right)
68 return None
69
70
71def _paths(node, path=()):
72 yield path
73 if node is not None:
74 yield from _paths(node[2], (*path, 2))
75 yield from _paths(node[3], (*path, 3))
76
77
78def _replace(node, path, subtree):
79 if not path:
80 return subtree
81 branch = path[0]
82 children = list(node)
83 children[branch] = _replace(children[branch], path[1:], subtree)
84 return tuple(children)
85
86
87
89 """Evolve split structures and fit fresh action values for each structure.
90
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.
96
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.
109 """
110
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()
115 if (self._bounds.ndim != 2 or self._bounds.shape[1] != 2 or not len(self._bounds)
116 or not np.isfinite(self._bounds).all()
117 or not np.isfinite(self._bounds[:, 1] - self._bounds[:, 0]).all()
118 or np.any(self._bounds[:, 0] >= self._bounds[:, 1])):
119 raise ValueError("Supply one finite increasing threshold interval per observation coordinate.")
120 self._max_depth = _integer(max_depth, "max_depth", minimum=0)
121 if self._max_depth > _MAX_DEPTH:
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.")
128 self._training_episodes = _integer(train_episodes, "train_episodes")
129 self._evaluation_episodes = _integer(evaluation_episodes, "evaluation_episodes")
130 self._horizon = _integer(max_episode_steps, "max_episode_steps")
131 self._epsilon, self._rate, self._gamma = epsilon, learning_rate, gamma
132 self._restart, self._selection = restart_probability, selection
133 self.archive = Grid(shape=(self._max_depth + 1, _integer(entropy_bins, "entropy_bins")),
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)
138 self._scoring = scoring
139 self._layout = None
140 self._steps = dict(training_steps=0, evaluation_steps=0)
141 self._evaluated = self._updates = 0
142
143 @property
144 def stats(self):
145 """Return cumulative search costs."""
146 return TreeSearchStats(**self._steps, evaluated_policies=self._evaluated, archive_updates=self._updates)
147
148 @property
149 def best_policy(self):
150 """Return the highest-scoring policy currently in the grid."""
151 if not self.archive:
152 raise RuntimeError("Run the search until at least one policy has been evaluated.")
153 return self.policy_for(self.archive.best)
154
155
157 def policy_for(self, individual):
158 """Read the fitted tree from the individual's genome."""
159 if self._layout is None:
160 raise RuntimeError("Run the search before restoring a policy from its grid.")
161 return DecisionTreePolicy(individual[0], *self._layout)
162
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)
168
169 def _random_tree(self, depth):
170 if depth == 0 or self._rng.random() < .3:
171 return None
172 feature = int(self._rng.integers(len(self._bounds)))
173 threshold = float(self._rng.uniform(*self._bounds[feature]))
174 return feature, threshold, self._random_tree(depth - 1), self._random_tree(depth - 1)
175
176 def _propose(self):
177 if not self.archive or self._rng.random() < self._restart:
178 return self._random_tree(self._max_depth)
179 parent = self.archive.best if self._selection == "quality" else self.archive[self._rng.integers(len(self.archive))]
180 structure = _structure(parent[0])
181 paths = tuple(_paths(structure))
182 path = paths[self._rng.integers(len(paths))]
183 return _replace(structure, path, self._random_tree(self._max_depth - len(path)))
184
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))
187 cursor = _Cursor(env, None, self._horizon, resets)
188 indices = count()
189 indexed = _leaves(structure, indices)
190 leaves = next(indices)
191 _, actions, start = self._layout
192 values = np.zeros((leaves, actions))
193 for _ in range(self._training_episodes):
194 cursor.reset()
195 leaf = _leaf(indexed, cursor.observation)
196 while not cursor.ended:
197 if behavior.random() < self._epsilon:
198 action = behavior.integers(actions)
199 else:
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.")
207 leaf = successor
208 return DecisionTreePolicy(_map_leaves(indexed, np.argmax(values, axis=1)), *self._layout)
209
210 def _score(self, env, policy, episodes, rng, budget):
211 cursor = _Cursor(env, None, self._horizon, rng)
212 counts = [0] * policy._action_count
213 rewards = []
214 for _ in range(episodes):
215 cursor.reset()
216 episode_rewards = []
217 while not cursor.ended:
218 index = _leaf(policy._tree, cursor.observation)
219 counts[index] += 1
220 reward, _, _, _ = cursor.step(policy._action_start + index, budget, "evaluation_steps")
221 episode_rewards.append(reward)
222 rewards.append(fsum(episode_rewards))
223 steps = sum(counts)
224 entropy = 0.
225 if len(counts) > 1:
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)
229
230
234 def run(self, env_factory, max_env_steps):
235 """Reserve the worst-case cost per candidate and charge actual steps."""
236 budget = _StepBudget(max_env_steps, self._steps)
237 reservation = (self._training_episodes + self._evaluation_episodes) * self._horizon
238 with _open_environment(env_factory) as env:
239 layout = self._layout_for(env)
240 if self._layout is not None and self._layout != layout:
241 raise ValueError("The environment factory changed its observation or action layout.")
242 self._layout = layout
243 while budget.remaining >= reservation:
244 policy = self._fit(env, self._propose(), budget)
245 measurement = self._score(env, policy, self._evaluation_episodes,
246 np.random.default_rng(self._scoring), budget)
247 descriptor = (policy.depth, measurement.action_entropy)
248 cell = self.archive.index_grid(descriptor)
249 self._evaluated += 1
250 previous = self.archive.nb_added
251 self.archive.add(_CellIndividual((policy._tree,), cell, fitness=Fitness((measurement.mean_return,),
252 weights=(1.,)), features=Features(descriptor)))
253 self._updates += self.archive.nb_added - previous
254 return self.stats
255
256
262 def evaluate(self, env_factory, policy, *, episodes, seed):
263 """Evaluate without changing search state or the repertoire."""
264 episodes = _integer(episodes, "episodes")
265 budget = _StepBudget(episodes * self._horizon, {"evaluation_steps": 0})
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)
A deterministic decision tree with portable JSON inference.
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405
Optimize decision-tree structure and learn actions at the leaves.
evaluate(self, env_factory, policy, *, episodes, seed)
Audit one fitted policy on an independent reset stream.
_score(self, env, policy, episodes, rng, budget)
run(self, env_factory, max_env_steps)
Train and score as many complete trees as fit the budget.
policy_for(self, individual)
Restore a policy from one repertoire individual.
Report greedy returns and action entropy over completed episodes.
Keep training calls, archive calls, and completed trees distinguishable.