# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Online subgoal discovery and tree search with a hard simulation budget.
# @see https://ieee-cog.org/2021/assets/papers/paper_283.pdf
"""Deterministic, finite-action QD-guided subgoal Monte Carlo tree search."""
from dataclasses import dataclass, field
from math import isfinite, log1p, sqrt
from operator import index
import numpy as np
from .modern import _positive_int
__all__ = ["MCTSPlan", "MCTSResult", "qd_subgoal_mcts", "primitive_mcts"]
## @brief A measured simulator path, with its primitive actions and rewards.
[docs]
@dataclass(frozen=True)
class MCTSPlan:
"""Hold the actual successor, reward sequence, and terminal flag."""
actions: tuple
final_state: object
rewards: tuple[float, ...]
terminated: bool
@property
def return_(self):
"""Return the undiscounted sum of rewards."""
return sum(self.rewards)
## @brief A plan and its simulator transition costs, including the low-level search.
[docs]
@dataclass(frozen=True)
class MCTSResult:
"""Return the best observed path and the published subgoals at the root."""
plan: MCTSPlan
root_subgoals: tuple[MCTSPlan, ...]
simulator_calls: int
low_level_calls: int
simulations: int
published_subgoals: int
def _return(rewards, discount):
value = 0.
for reward in reversed(rewards):
value = reward + discount * value
return value
def _backup(node, value):
node.visits += 1
node.total += value
def _ucb(node, children, exploration, value):
scale = log1p(node.visits)
return max(children, key=lambda edge: value(edge) + exploration * sqrt(scale / edge.node.visits))
@dataclass
class _Primitive:
state: object
terminated: bool
visits: int = 0
total: float = 0.
children: list = field(default_factory=list)
untried: list | None = None
exhausted: bool = False
descriptor: np.ndarray | None = None
@dataclass
class _Action:
action: object
reward: float
node: _Primitive
@dataclass
class _Subgoal:
state: object
terminated: bool
visits: int = 0
total: float = 0.
children: list | None = None
local: _Primitive | None = None
candidates: list = field(default_factory=list)
exhausted: bool = False
@dataclass
class _MacroAction:
plan: MCTSPlan
node: _Subgoal
def _normalized(values):
span = values.max() - values.min()
return (values - values.min()) / span if span else np.zeros_like(values)
## @brief Greedily retain high-return, locally different macro endpoints.
def _select_subgoals(candidates, descriptors, count, neighbors, reward_weight, discount):
rewards = np.asarray([_return(plan.rewards, discount) for plan in candidates])
first = int(np.argmax(rewards))
chosen = [first]
remaining = [i for i in range(len(candidates)) if i != first]
while remaining and len(chosen) < count:
distance = np.hypot.reduce(descriptors[remaining, None, :] - descriptors[None, chosen, :], axis=2)
if not np.isfinite(distance).all():
raise ValueError("Descriptor distances must be finite.")
closest = np.argsort(distance, axis=1, kind="stable")[:, :neighbors]
novelty = np.take_along_axis(distance, closest, axis=1).mean(axis=1)
better = (rewards[remaining, None] > rewards[np.asarray(chosen)[closest]]).mean(axis=1)
scores = (1. - reward_weight) * _normalized(novelty) + reward_weight * _normalized(better)
chosen.append(remaining.pop(int(np.argmax(scores))))
return [candidates[i] for i in chosen]
class _Search:
"""Own one planning call and charge every transition at the simulator boundary."""
def __init__(self, actions, simulate, budget, horizon, discount, exploration, seed):
if not callable(actions) or not callable(simulate):
raise TypeError("actions and simulate must be callable.")
self.actions, self.simulate = actions, simulate
self.budget = index(budget)
self.horizon = _positive_int(horizon, "horizon")
if self.budget < 0 or not 0. < discount <= 1. or not 0. <= exploration < np.inf:
raise ValueError("Require nonnegative budget and exploration, and a discount in (0, 1].")
self.discount, self.exploration = discount, exploration
self.rng = np.random.default_rng(seed)
self.calls = self.low_calls = self.simulations = self.published = 0
self.best = self._best_key = None
def _step(self, state, action, low_level):
self.calls += 1
self.low_calls += low_level
successor, reward, terminal = self.simulate(state, action)
reward = float(reward)
if not isfinite(reward):
raise ValueError("The simulator must return a finite reward.")
return successor, reward, bool(terminal)
def _visit_path(self, root, limit, distance=None):
"""Extend and traverse a primitive tree while spending only uncached transitions."""
nodes = [root]
actions, rewards, returns = [], [], []
node = root
reached_boundary = False
def immediate(edge):
return edge.reward if distance is None else distance(edge.node) - distance(node)
for _ in range(limit):
if node.terminated:
reached_boundary = True
break
if node.untried is None:
node.untried = list(self.actions(node.state))
if node.untried:
if self.calls == self.budget:
break
slot = int(self.rng.integers(len(node.untried)))
action = node.untried.pop(slot)
successor, reward, terminal = self._step(node.state, action, distance is not None)
edge = _Action(action, reward, _Primitive(successor, terminal))
node.children.append(edge)
else:
available = [edge for edge in node.children if not edge.node.exhausted]
if not available:
reached_boundary = True
break
edge = _ucb(node, available, self.exploration, lambda child:
immediate(child) + self.discount * child.node.total / child.node.visits)
actions.append(edge.action)
rewards.append(edge.reward)
returns.append(immediate(edge))
node = edge.node
nodes.append(node)
reached_boundary |= node.terminated or len(actions) == limit
if reached_boundary:
node.exhausted = True
_backup(node, 0.)
value = 0.
for parent, reward in zip(reversed(nodes[:-1]), reversed(returns), strict=True):
value = reward + self.discount * value
_backup(parent, value)
parent.exhausted = not parent.untried and all(edge.node.exhausted for edge in parent.children)
return MCTSPlan(tuple(actions), node.state, tuple(rewards), node.terminated), reached_boundary
def _rollout(self, start, terminal, limit):
actions, rewards = [], []
state = start
dead_end = False
for _ in range(limit):
if terminal or self.calls == self.budget:
break
choices = tuple(self.actions(state))
if not choices:
dead_end = True
break
action = choices[int(self.rng.integers(len(choices)))]
state, reward, terminal = self._step(state, action, False)
actions.append(action)
rewards.append(reward)
plan = MCTSPlan(tuple(actions), state, tuple(rewards), terminal)
return plan, terminal or dead_end or len(actions) == limit
def _report(self, start, terminated, root_subgoals=()):
plan = self.best or MCTSPlan((), start, (), terminated)
return MCTSResult(plan, root_subgoals, self.calls, self.low_calls, self.simulations, self.published)
def _consider(self, plan, complete):
if plan.actions:
score = _return(plan.rewards, self.discount)
key = complete, score, plan.terminated, -len(plan.actions)
if self.best is None or key > self._best_key:
self.best, self._best_key = plan, key
class _SubgoalSearch(_Search):
def __init__(self, actions, simulate, budget, horizon, discount, exploration, seed,
describe, macro_steps, probes, subgoals, neighbors, reward_weight):
super().__init__(actions, simulate, budget, horizon, discount, exploration, seed)
if not callable(describe) or not 0. <= reward_weight <= 1.:
raise ValueError("Require a callable descriptor and a reward_weight in [0, 1].")
self.describe = describe
self.macro_steps = _positive_int(macro_steps, "macro_steps")
self.probes = _positive_int(probes, "probes")
self.subgoals = _positive_int(subgoals, "subgoals")
self.neighbors = _positive_int(neighbors, "neighbors")
self.reward_weight = reward_weight
self.shape = None
def _features(self, state):
point = np.array(self.describe(state), dtype=float, copy=True)
if point.ndim != 1 or not len(point) or not np.isfinite(point).all() or (
self.shape is not None and self.shape != point.shape):
raise ValueError("Describe each state with a fixed nonempty finite vector.")
self.shape = point.shape
return point
def _distance(self, node, origin):
if node.descriptor is None:
node.descriptor = self._features(node.state)
value = float(np.hypot.reduce(node.descriptor - origin))
if not isfinite(value):
raise ValueError("Descriptor distances must be finite.")
return value
def _discover(self, node, left):
if node.local is None:
node.local = _Primitive(node.state, node.terminated)
node.local.descriptor = self._features(node.state)
origin = node.local.descriptor
trial, complete = self._visit_path(node.local, min(left, self.macro_steps),
lambda point: self._distance(point, origin))
if trial.actions and complete:
node.candidates.append(trial)
if len(node.candidates) >= self.probes or node.local.exhausted:
if node.candidates:
descriptors = np.asarray([self._features(plan.final_state) for plan in node.candidates])
selected = _select_subgoals(node.candidates, descriptors, self.subgoals, self.neighbors,
self.reward_weight, self.discount)
node.children = [
_MacroAction(plan, _Subgoal(plan.final_state, plan.terminated,
exhausted=plan.terminated or len(plan.actions) == left))
for plan in selected
]
self.published += len(selected)
else:
node.children = []
node.local = None
node.candidates.clear()
return trial
def plan(self, start, terminated):
root = _Subgoal(start, terminated, exhausted=terminated)
while self.calls < self.budget and not root.exhausted:
node = root
actions, rewards, path = [], [], []
while True:
path.append((node, len(actions)))
if node.children is None:
probe = self._discover(node, self.horizon - len(actions))
actions.extend(probe.actions)
rewards.extend(probe.rewards)
tail, complete = self._rollout(probe.final_state, probe.terminated, self.horizon - len(actions))
actions.extend(tail.actions)
rewards.extend(tail.rewards)
self._consider(MCTSPlan(tuple(actions), tail.final_state, tuple(rewards), tail.terminated), complete)
break
edges = [edge for edge in node.children if not edge.node.exhausted]
if not edges:
break
edge = next((edge for edge in edges if edge.node.visits == 0), None)
if edge is None:
edge = _ucb(node, edges, self.exploration, lambda child:
_return(child.plan.rewards, self.discount) + self.discount ** len(child.plan.actions)
* child.node.total / child.node.visits)
actions.extend(edge.plan.actions)
rewards.extend(edge.plan.rewards)
node = edge.node
self.simulations += 1
for ancestor, start_index in reversed(path):
_backup(ancestor, _return(rewards[start_index:], self.discount))
ancestor.exhausted = ancestor.children is not None and all(
edge.node.exhausted for edge in ancestor.children)
return self._report(start, terminated, tuple(edge.plan for edge in root.children or ()))
## @brief Search a simulator with a single tree of primitive actions.
[docs]
def primitive_mcts(start, *, actions, simulate, budget, horizon, discount=.99, exploration=1.4,
start_terminated=False, seed=0):
"""Run the primitive-action control with cached deterministic transitions.
See :func:`qd_subgoal_mcts` for the simulator contract. The same
horizon, reward discount, and simulator-call cap apply. Tree
traversals pick an untried action uniformly or use UCB over
existing children. Search ends early if the finite tree is exhausted.
"""
search = _Search(actions, simulate, budget, horizon, discount, exploration, seed)
root = _Primitive(start, bool(start_terminated), exhausted=bool(start_terminated))
while search.calls < search.budget and not root.exhausted:
trial, complete = search._visit_path(root, search.horizon)
search._consider(trial, complete)
search.simulations += 1
return search._report(start, bool(start_terminated))
## @brief Discover macro-actions locally and choose among them with a second MCTS tree.
[docs]
def qd_subgoal_mcts(start, *, actions, simulate, describe, budget, horizon, macro_steps=3,
probes=8, subgoals=3, neighbors=3, reward_weight=.5, discount=.99,
exploration=1.4, start_terminated=False, seed=0):
"""Interleave local trajectory discovery with a high-level subgoal tree.
Each visit to an unexpanded macro node samples one path in its
low-level tree. Local UCB uses discounted distance gains from that
node. Once enough paths are available, keep a small set using
novelty and local reward comparisons. High-level UCB backs up task
rewards and uses the sampled endpoints for continuation rollouts.
Return the best complete primitive path under discounted reward,
or a measured prefix if the budget allowed only partial paths.
:param start: Initial simulator snapshot.
:param actions: Callable yielding available actions for a snapshot.
:param simulate: Pure deterministic callback (state, action) returning
(successor, finite reward, terminated). Treat snapshots as immutable.
:param describe: Callable returning a fixed nonempty numeric state descriptor.
:param budget: Maximum total calls to simulate, including low-level search.
:param horizon: Maximum primitive steps in any searched path.
:param macro_steps: Target primitive length of a subgoal trajectory.
Terminal and dead-end paths can be shorter.
:param probes: Complete low-level samples before publishing subgoals,
or fewer if the local tree is exhausted.
:param subgoals: Maximum number of macro-actions published per node.
:param neighbors: Nearest selected endpoints used in the local comparison.
:param reward_weight: Weight of local competition relative to novelty.
:param discount: Per-primitive-step reward and distance discount.
:param exploration: UCB exploration coefficient in both trees.
:param start_terminated: Whether the initial snapshot is already terminal.
:param seed: Private action-selection and rollout seed.
"""
search = _SubgoalSearch(actions, simulate, budget, horizon, discount, exploration, seed,
describe, macro_steps, probes, subgoals, neighbors, reward_weight)
return search.plan(start, bool(start_terminated))