6"""Deterministic, finite-action QD-guided subgoal Monte Carlo tree search."""
8from dataclasses
import dataclass, field
9from math
import isfinite, log1p, sqrt
10from operator
import index
14from .modern
import _positive_int
16__all__ = [
"MCTSPlan",
"MCTSResult",
"qd_subgoal_mcts",
"primitive_mcts"]
20@dataclass(frozen=True)
22 """Hold the actual successor, reward sequence, and terminal flag."""
26 rewards: tuple[float, ...]
31 """Return the undiscounted sum of rewards."""
36@dataclass(frozen=True)
38 """Return the best observed path and the published subgoals at the root."""
41 root_subgoals: tuple[MCTSPlan, ...]
45 published_subgoals: int
48def _return(rewards, discount):
50 for reward
in reversed(rewards):
51 value = reward + discount * value
55def _backup(node, value):
60def _ucb(node, children, exploration, value):
61 scale = log1p(node.visits)
62 return max(children, key=
lambda edge: value(edge) + exploration * sqrt(scale / edge.node.visits))
71 children: list = field(default_factory=list)
72 untried: list |
None =
None
73 exhausted: bool =
False
74 descriptor: np.ndarray |
None =
None
90 children: list |
None =
None
91 local: _Primitive |
None =
None
92 candidates: list = field(default_factory=list)
93 exhausted: bool =
False
102def _normalized(values):
103 span = values.max() - values.min()
104 return (values - values.min()) / span
if span
else np.zeros_like(values)
108def _select_subgoals(candidates, descriptors, count, neighbors, reward_weight, discount):
109 rewards = np.asarray([_return(plan.rewards, discount)
for plan
in candidates])
110 first = int(np.argmax(rewards))
112 remaining = [i
for i
in range(len(candidates))
if i != first]
113 while remaining
and len(chosen) < count:
114 distance = np.hypot.reduce(descriptors[remaining,
None, :] - descriptors[
None, chosen, :], axis=2)
115 if not np.isfinite(distance).all():
116 raise ValueError(
"Descriptor distances must be finite.")
117 closest = np.argsort(distance, axis=1, kind=
"stable")[:, :neighbors]
118 novelty = np.take_along_axis(distance, closest, axis=1).mean(axis=1)
119 better = (rewards[remaining,
None] > rewards[np.asarray(chosen)[closest]]).mean(axis=1)
120 scores = (1. - reward_weight) * _normalized(novelty) + reward_weight * _normalized(better)
121 chosen.append(remaining.pop(int(np.argmax(scores))))
122 return [candidates[i]
for i
in chosen]
126 """Own one planning call and charge every transition at the simulator boundary."""
128 def __init__(self, actions, simulate, budget, horizon, discount, exploration, seed):
129 if not callable(actions)
or not callable(simulate):
130 raise TypeError(
"actions and simulate must be callable.")
132 self.
budget = index(budget)
133 self.
horizon = _positive_int(horizon,
"horizon")
134 if self.
budget < 0
or not 0. < discount <= 1.
or not 0. <= exploration < np.inf:
135 raise ValueError(
"Require nonnegative budget and exploration, and a discount in (0, 1].")
137 self.
rng = np.random.default_rng(seed)
141 def _step(self, state, action, low_level):
144 successor, reward, terminal = self.
simulate(state, action)
145 reward = float(reward)
146 if not isfinite(reward):
147 raise ValueError(
"The simulator must return a finite reward.")
148 return successor, reward, bool(terminal)
151 """Extend and traverse a primitive tree while spending only uncached transitions."""
153 actions, rewards, returns = [], [], []
155 reached_boundary =
False
158 return edge.reward
if distance
is None else distance(edge.node) - distance(node)
160 for _
in range(limit):
162 reached_boundary =
True
164 if node.untried
is None:
165 node.untried = list(self.
actions(node.state))
169 slot = int(self.
rng.integers(len(node.untried)))
170 action = node.untried.pop(slot)
171 successor, reward, terminal = self.
_step(node.state, action, distance
is not None)
173 node.children.append(edge)
175 available = [edge
for edge
in node.children
if not edge.node.exhausted]
177 reached_boundary =
True
179 edge = _ucb(node, available, self.
exploration,
lambda child:
180 immediate(child) + self.
discount * child.node.total / child.node.visits)
182 actions.append(edge.action)
183 rewards.append(edge.reward)
184 returns.append(immediate(edge))
188 reached_boundary |= node.terminated
or len(actions) == limit
190 node.exhausted =
True
193 for parent, reward
in zip(reversed(nodes[:-1]), reversed(returns), strict=
True):
194 value = reward + self.
discount * value
195 _backup(parent, value)
196 parent.exhausted =
not parent.untried
and all(edge.node.exhausted
for edge
in parent.children)
197 return MCTSPlan(tuple(actions), node.state, tuple(rewards), node.terminated), reached_boundary
199 def _rollout(self, start, terminal, limit):
200 actions, rewards = [], []
203 for _
in range(limit):
206 choices = tuple(self.
actions(state))
210 action = choices[int(self.
rng.integers(len(choices)))]
211 state, reward, terminal = self.
_step(state, action,
False)
212 actions.append(action)
213 rewards.append(reward)
214 plan =
MCTSPlan(tuple(actions), state, tuple(rewards), terminal)
215 return plan, terminal
or dead_end
or len(actions) == limit
217 def _report(self, start, terminated, root_subgoals=()):
221 def _consider(self, plan, complete):
223 score = _return(plan.rewards, self.
discount)
224 key = complete, score, plan.terminated, -len(plan.actions)
230 def __init__(self, actions, simulate, budget, horizon, discount, exploration, seed,
231 describe, macro_steps, probes, subgoals, neighbors, reward_weight):
232 super().__init__(actions, simulate, budget, horizon, discount, exploration, seed)
233 if not callable(describe)
or not 0. <= reward_weight <= 1.:
234 raise ValueError(
"Require a callable descriptor and a reward_weight in [0, 1].")
236 self.
macro_steps = _positive_int(macro_steps,
"macro_steps")
237 self.
probes = _positive_int(probes,
"probes")
238 self.
subgoals = _positive_int(subgoals,
"subgoals")
239 self.
neighbors = _positive_int(neighbors,
"neighbors")
243 def _features(self, state):
244 point = np.array(self.
describe(state), dtype=float, copy=
True)
245 if point.ndim != 1
or not len(point)
or not np.isfinite(point).all()
or (
246 self.
shape is not None and self.
shape != point.shape):
247 raise ValueError(
"Describe each state with a fixed nonempty finite vector.")
248 self.
shape = point.shape
251 def _distance(self, node, origin):
252 if node.descriptor
is None:
253 node.descriptor = self.
_features(node.state)
254 value = float(np.hypot.reduce(node.descriptor - origin))
255 if not isfinite(value):
256 raise ValueError(
"Descriptor distances must be finite.")
259 def _discover(self, node, left):
260 if node.local
is None:
261 node.local =
_Primitive(node.state, node.terminated)
262 node.local.descriptor = self.
_features(node.state)
263 origin = node.local.descriptor
265 lambda point: self.
_distance(point, origin))
266 if trial.actions
and complete:
267 node.candidates.append(trial)
268 if len(node.candidates) >= self.
probes or node.local.exhausted:
270 descriptors = np.asarray([self.
_features(plan.final_state)
for plan
in node.candidates])
271 selected = _select_subgoals(node.candidates, descriptors, self.
subgoals, self.
neighbors,
275 exhausted=plan.terminated
or len(plan.actions) == left))
282 node.candidates.clear()
285 def plan(self, start, terminated):
286 root =
_Subgoal(start, terminated, exhausted=terminated)
287 while self.
calls < self.
budget and not root.exhausted:
289 actions, rewards, path = [], [], []
291 path.append((node, len(actions)))
292 if node.children
is None:
294 actions.extend(probe.actions)
295 rewards.extend(probe.rewards)
296 tail, complete = self.
_rollout(probe.final_state, probe.terminated, self.
horizon - len(actions))
297 actions.extend(tail.actions)
298 rewards.extend(tail.rewards)
299 self.
_consider(
MCTSPlan(tuple(actions), tail.final_state, tuple(rewards), tail.terminated), complete)
301 edges = [edge
for edge
in node.children
if not edge.node.exhausted]
304 edge = next((edge
for edge
in edges
if edge.node.visits == 0),
None)
306 edge = _ucb(node, edges, self.
exploration,
lambda child:
307 _return(child.plan.rewards, self.
discount) + self.
discount ** len(child.plan.actions)
308 * child.node.total / child.node.visits)
309 actions.extend(edge.plan.actions)
310 rewards.extend(edge.plan.rewards)
313 for ancestor, start_index
in reversed(path):
314 _backup(ancestor, _return(rewards[start_index:], self.
discount))
315 ancestor.exhausted = ancestor.children
is not None and all(
316 edge.node.exhausted
for edge
in ancestor.children)
317 return self.
_report(start, terminated, tuple(edge.plan
for edge
in root.children
or ()))
321def primitive_mcts(start, *, actions, simulate, budget, horizon, discount=.99, exploration=1.4,
322 start_terminated=False, seed=0):
323 """Run the primitive-action control with cached deterministic transitions.
325 See :func:`qd_subgoal_mcts` for the simulator contract. The same
326 horizon, reward discount, and simulator-call cap apply. Tree
327 traversals pick an untried action uniformly or use UCB over
328 existing children. Search ends early if the finite tree is exhausted.
330 search =
_Search(actions, simulate, budget, horizon, discount, exploration, seed)
331 root =
_Primitive(start, bool(start_terminated), exhausted=bool(start_terminated))
332 while search.calls < search.budget
and not root.exhausted:
333 trial, complete = search._visit_path(root, search.horizon)
334 search._consider(trial, complete)
335 search.simulations += 1
336 return search._report(start, bool(start_terminated))
340def qd_subgoal_mcts(start, *, actions, simulate, describe, budget, horizon, macro_steps=3,
341 probes=8, subgoals=3, neighbors=3, reward_weight=.5, discount=.99,
342 exploration=1.4, start_terminated=False, seed=0):
343 """Interleave local trajectory discovery with a high-level subgoal tree.
345 Each visit to an unexpanded macro node samples one path in its
346 low-level tree. Local UCB uses discounted distance gains from that
347 node. Once enough paths are available, keep a small set using
348 novelty and local reward comparisons. High-level UCB backs up task
349 rewards and uses the sampled endpoints for continuation rollouts.
350 Return the best complete primitive path under discounted reward,
351 or a measured prefix if the budget allowed only partial paths.
353 :param start: Initial simulator snapshot.
354 :param actions: Callable yielding available actions for a snapshot.
355 :param simulate: Pure deterministic callback (state, action) returning
356 (successor, finite reward, terminated). Treat snapshots as immutable.
357 :param describe: Callable returning a fixed nonempty numeric state descriptor.
358 :param budget: Maximum total calls to simulate, including low-level search.
359 :param horizon: Maximum primitive steps in any searched path.
360 :param macro_steps: Target primitive length of a subgoal trajectory.
361 Terminal and dead-end paths can be shorter.
362 :param probes: Complete low-level samples before publishing subgoals,
363 or fewer if the local tree is exhausted.
364 :param subgoals: Maximum number of macro-actions published per node.
365 :param neighbors: Nearest selected endpoints used in the local comparison.
366 :param reward_weight: Weight of local competition relative to novelty.
367 :param discount: Per-primitive-step reward and distance discount.
368 :param exploration: UCB exploration coefficient in both trees.
369 :param start_terminated: Whether the initial snapshot is already terminal.
370 :param seed: Private action-selection and rollout seed.
372 search =
_SubgoalSearch(actions, simulate, budget, horizon, discount, exploration, seed,
373 describe, macro_steps, probes, subgoals, neighbors, reward_weight)
374 return search.plan(start, bool(start_terminated))
A measured simulator path, with its primitive actions and rewards.
A plan and its simulator transition costs, including the low-level search.
_step(self, state, action, low_level)
_consider(self, plan, complete)
_report(self, start, terminated, root_subgoals=())
_rollout(self, start, terminal, limit)
_visit_path(self, root, limit, distance=None)
_distance(self, node, origin)
_discover(self, node, left)