# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Reset-free repertoire planning with online transition adaptation.
"""Chain measured skills by planning from the current observed state."""
from collections import deque
from dataclasses import dataclass, field
from math import ceil, log, sqrt
from operator import index
import numpy as np
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern
from .mboa import _repertoire
from .modern import _positive_int
__all__ = ["RTESkill", "RTEStats", "RTEPath", "ResetFreeTrialAndError"]
## @brief An archive action with a nominal state displacement.
[docs]
@dataclass(frozen=True)
class RTESkill:
"""A numeric genome and a finite displacement in the planner's state coordinates."""
genome: tuple[float, ...]
displacement: tuple[float, ...]
def __post_init__(self):
for name in ("genome", "displacement"):
value = np.asarray(getattr(self, name), dtype=float)
if value.ndim != 1 or not len(value) or not np.isfinite(value).all():
raise ValueError(f"{name} must be a nonempty finite vector.")
object.__setattr__(self, name, tuple(map(float, value)))
## @brief Separate live skill trials from model observations and Monte Carlo rollouts.
[docs]
@dataclass(frozen=True)
class RTEStats:
"""Cumulative counts over any number of replanning calls."""
real_attempts: int
observations: int
planning_rollouts: int
## @brief Record the sequence of observed states and executed skills.
[docs]
@dataclass(frozen=True)
class RTEPath:
"""A path has one more state than skill and includes the caller's initial state."""
states: tuple[tuple[float, ...], ...]
skills: tuple[RTESkill, ...]
goal_reached: bool
@dataclass
class _Outcome:
state: np.ndarray
goal_distance: float
terminal: bool
reward: float
visits: int = 0
edges: dict = field(default_factory=dict)
@dataclass
class _Edge:
visits: int = 0
value: float = 0.
outcomes: list = field(default_factory=list)
## @brief Plan with a repertoire and update its transition model from live observations.
[docs]
class ResetFreeTrialAndError:
"""Reset-free Trial-and-Error following Chatzilygeroudis et al.
The first implementation assumes additive, stationary displacements
in fixed numeric state coordinates. A residual GP updates the
nominal skill effects from live outcomes. MCTS uses UCB and
progressive widening for skills and their possible successor states.
The caller supplies the environment and handles execution.
:param repertoire: Nonempty sequence of RTESkill records, live numeric
repertoire, or its portable grid export. For a grid, each descriptor
must be the skill's nominal displacement in state coordinates.
:param horizon: Number of skill applications planned per simulated path.
:param simulations: Monte Carlo rollouts per planning call.
:param goal_tolerance: Distance at which the goal is reached.
:param prior_std: Standard deviation of the nominal transition error.
:param observation_noise: Positive observation standard deviation for the GP.
:param length_scale: GP kernel scale in normalized skill coordinates.
:param model_capacity: Number of recent live outcomes retained by the GP.
:param exploration: UCB exploration coefficient for simulated actions.
:param discount: Discount on future distance improvements.
:param collision_penalty: Positive cost of a forbidden simulated transition.
:param seed: Random seed for planning.
"""
def __init__(self, repertoire, *, horizon=4, simulations=128, goal_tolerance=.15,
prior_std=.12, observation_noise=.02, length_scale=.4, model_capacity=128,
exploration=.7, discount=.95, collision_penalty=6., seed=0):
if isinstance(repertoire, (tuple, list)) and all(isinstance(skill, RTESkill) for skill in repertoire):
self.skills = tuple(repertoire)
else:
candidates, _, _ = _repertoire(repertoire)
self.skills = tuple(RTESkill(row.genome, row.descriptor) for row in candidates)
if not self.skills or len({len(skill.displacement) for skill in self.skills}) != 1:
raise ValueError("Provide a nonempty repertoire with the same displacement width per skill.")
limits = np.finfo(float)
std_low, std_high = sqrt(limits.tiny), sqrt(limits.max)
if not (0 <= goal_tolerance < np.inf and std_low <= prior_std <= std_high
and std_low <= observation_noise <= std_high
and 0 < length_scale < np.inf and 0 <= exploration < np.inf
and 0 <= discount <= 1 and 0 < collision_penalty < np.inf):
raise ValueError("Use finite planning settings with positive uncertainties, scale, and collision cost.")
self._moves = np.asarray([skill.displacement for skill in self.skills])
self._descriptors = self._moves / (np.max(np.abs(self._moves)) or 1.)
self.horizon = _positive_int(horizon, "horizon")
self.simulations = _positive_int(simulations, "simulations")
self.goal_tolerance = goal_tolerance
self._prior_std, self._exploration, self._discount = prior_std, exploration, discount
self._collision_penalty = collision_penalty
self._history = deque(maxlen=_positive_int(model_capacity, "model_capacity"))
self._model = GaussianProcessRegressor(kernel=prior_std ** 2 * Matern(length_scale, nu=2.5),
alpha=observation_noise ** 2, optimizer=None)
self._posterior = None
self._rng = np.random.default_rng(seed)
self._trials = self._observations = self._rollouts = 0
@property
def stats(self):
"""Return the current count of live actions, observations, and simulated paths."""
return RTEStats(self._trials, self._observations, self._rollouts)
def _state(self, state):
value = np.asarray(state, dtype=float)
if value.shape != (self._moves.shape[1],) or not np.isfinite(value).all():
raise ValueError("State and goal vectors must match the nominal displacements.")
return value
## @brief Update the residual model with one actual state transition.
[docs]
def observe(self, state, skill, successor):
"""Add a measured displacement from an executed skill to the rolling model dataset."""
slot = self.skills.index(skill)
residual = self._state(successor) - self._state(state) - self._moves[slot]
if not np.isfinite(residual).all():
raise ValueError("The state transition produced a nonfinite model residual.")
self._history.append((slot, residual))
self._observations += 1
self._posterior = None
def _predictions(self):
if self._posterior is None:
if self._history:
slots, residuals = zip(*self._history)
self._model.fit(self._descriptors[list(slots)], np.asarray(residuals))
correction, deviations = self._model.predict(self._descriptors, return_std=True)
deviations = deviations[:, None] if deviations.ndim == 1 else deviations
self._posterior = self._moves + correction.reshape(self._moves.shape), deviations
else:
self._posterior = self._moves, np.full_like(self._moves, self._prior_std)
return self._posterior
def _select(self, node, goal, means):
width = min(len(self.skills), ceil(sqrt(node.visits + 1)))
if len(node.edges) < width:
candidates = [slot for slot in range(len(self.skills)) if slot not in node.edges]
distances = np.linalg.norm(node.state + means[candidates] - goal, axis=1)
slot = candidates[int(np.argmin(distances))]
node.edges[slot] = _Edge()
return slot
return max(node.edges, key=lambda slot: node.edges[slot].value + self._exploration *
sqrt(log(node.visits + 1) / max(1, node.edges[slot].visits)))
def _visit(self, node, depth, goal, means, deviations, traversable):
slot = self._select(node, goal, means)
edge = node.edges[slot]
if len(edge.outcomes) < ceil(sqrt(edge.visits + 1)):
successor = node.state + means[slot] + deviations[slot] * self._rng.standard_normal(goal.shape)
distance = float(np.linalg.norm(successor - goal))
blocked = traversable is not None and not traversable(tuple(node.state), tuple(successor))
reward = -self._collision_penalty if blocked else node.goal_distance - distance
outcome = _Outcome(successor, distance, blocked or distance <= self.goal_tolerance, reward)
edge.outcomes.append(outcome)
else:
outcome = edge.outcomes[int(self._rng.integers(len(edge.outcomes)))]
value = outcome.reward
if depth > 1 and not outcome.terminal:
value += self._discount * self._visit(outcome, depth - 1, goal, means, deviations, traversable)
node.visits += 1
edge.visits += 1
edge.value += (value - edge.value) / edge.visits
return value
## @brief Plan the next skill from the current state without making a real transition.
[docs]
def plan(self, state, goal, *, traversable=None):
"""Return an RTESkill or None if the state is already within goal_tolerance.
traversable, if supplied, tests the whole predicted transition as
(before, after). A blocked result receives the collision cost and ends
that simulated path.
"""
if traversable is not None and not callable(traversable):
raise TypeError("traversable must be callable.")
state, goal = self._state(state), self._state(goal)
distance = float(np.linalg.norm(state - goal))
if distance <= self.goal_tolerance:
return None
means, deviations = self._predictions()
root = _Outcome(state, distance, False, 0.)
for _ in range(self.simulations):
self._visit(root, self.horizon, goal, means, deviations, traversable)
self._rollouts += 1
selected = max(root.edges, key=lambda slot: (root.edges[slot].visits, root.edges[slot].value))
return self.skills[selected]
## @brief Execute and replan from observed successors, with a hard live trial limit.
[docs]
def run(self, state, goal, execute, *, max_trials, traversable=None, adapt=True):
"""Return an RTEPath by calling execute(current_state, genome) at most max_trials times."""
limit = index(max_trials)
if limit < 0 or not callable(execute):
raise ValueError("Use nonnegative max_trials and a callable execute.")
state, goal = tuple(map(float, self._state(state))), self._state(goal)
states, skills = [state], []
for _ in range(limit):
skill = self.plan(state, goal, traversable=traversable)
if skill is None:
break
self._trials += 1
successor = tuple(map(float, self._state(execute(state, skill.genome))))
if adapt:
self.observe(state, skill, successor)
states.append(successor)
skills.append(skill)
state = successor
return RTEPath(tuple(states), tuple(skills), bool(np.linalg.norm(np.subtract(state, goal)) <= self.goal_tolerance))