QDpy
Loading...
Searching...
No Matches
rte.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Chain measured skills by planning from the current observed state."""
6
7from collections import deque
8from dataclasses import dataclass, field
9from math import ceil, log, sqrt
10from operator import index
11
12import numpy as np
13from sklearn.gaussian_process import GaussianProcessRegressor
14from sklearn.gaussian_process.kernels import Matern
15
16from .mboa import _repertoire
17from .modern import _positive_int
18
19__all__ = ["RTESkill", "RTEStats", "RTEPath", "ResetFreeTrialAndError"]
20
21
22
23@dataclass(frozen=True)
25 """A numeric genome and a finite displacement in the planner's state coordinates."""
26
27 genome: tuple[float, ...]
28 displacement: tuple[float, ...]
29
30 def __post_init__(self):
31 for name in ("genome", "displacement"):
32 value = np.asarray(getattr(self, name), dtype=float)
33 if value.ndim != 1 or not len(value) or not np.isfinite(value).all():
34 raise ValueError(f"{name} must be a nonempty finite vector.")
35 object.__setattr__(self, name, tuple(map(float, value)))
36
37
38
39@dataclass(frozen=True)
41 """Cumulative counts over any number of replanning calls."""
42
43 real_attempts: int
44 observations: int
45 planning_rollouts: int
46
47
48
49@dataclass(frozen=True)
50class RTEPath:
51 """A path has one more state than skill and includes the caller's initial state."""
52
53 states: tuple[tuple[float, ...], ...]
54 skills: tuple[RTESkill, ...]
55 goal_reached: bool
56
57
58@dataclass
60 state: np.ndarray
61 goal_distance: float
62 terminal: bool
63 reward: float
64 visits: int = 0
65 edges: dict = field(default_factory=dict)
66
67
68@dataclass
69class _Edge:
70 visits: int = 0
71 value: float = 0.
72 outcomes: list = field(default_factory=list)
73
74
75
77 """Reset-free Trial-and-Error following Chatzilygeroudis et al.
78
79 The first implementation assumes additive, stationary displacements
80 in fixed numeric state coordinates. A residual GP updates the
81 nominal skill effects from live outcomes. MCTS uses UCB and
82 progressive widening for skills and their possible successor states.
83 The caller supplies the environment and handles execution.
84
85 :param repertoire: Nonempty sequence of RTESkill records, live numeric
86 repertoire, or its portable grid export. For a grid, each descriptor
87 must be the skill's nominal displacement in state coordinates.
88 :param horizon: Number of skill applications planned per simulated path.
89 :param simulations: Monte Carlo rollouts per planning call.
90 :param goal_tolerance: Distance at which the goal is reached.
91 :param prior_std: Standard deviation of the nominal transition error.
92 :param observation_noise: Positive observation standard deviation for the GP.
93 :param length_scale: GP kernel scale in normalized skill coordinates.
94 :param model_capacity: Number of recent live outcomes retained by the GP.
95 :param exploration: UCB exploration coefficient for simulated actions.
96 :param discount: Discount on future distance improvements.
97 :param collision_penalty: Positive cost of a forbidden simulated transition.
98 :param seed: Random seed for planning.
99 """
100
101 def __init__(self, repertoire, *, horizon=4, simulations=128, goal_tolerance=.15,
102 prior_std=.12, observation_noise=.02, length_scale=.4, model_capacity=128,
103 exploration=.7, discount=.95, collision_penalty=6., seed=0):
104 if isinstance(repertoire, (tuple, list)) and all(isinstance(skill, RTESkill) for skill in repertoire):
105 self.skills = tuple(repertoire)
106 else:
107 candidates, _, _ = _repertoire(repertoire)
108 self.skills = tuple(RTESkill(row.genome, row.descriptor) for row in candidates)
109 if not self.skills or len({len(skill.displacement) for skill in self.skills}) != 1:
110 raise ValueError("Provide a nonempty repertoire with the same displacement width per skill.")
111 limits = np.finfo(float)
112 std_low, std_high = sqrt(limits.tiny), sqrt(limits.max)
113 if not (0 <= goal_tolerance < np.inf and std_low <= prior_std <= std_high
114 and std_low <= observation_noise <= std_high
115 and 0 < length_scale < np.inf and 0 <= exploration < np.inf
116 and 0 <= discount <= 1 and 0 < collision_penalty < np.inf):
117 raise ValueError("Use finite planning settings with positive uncertainties, scale, and collision cost.")
118 self._moves = np.asarray([skill.displacement for skill in self.skills])
119 self._descriptors = self._moves / (np.max(np.abs(self._moves)) or 1.)
120 self.horizon = _positive_int(horizon, "horizon")
121 self.simulations = _positive_int(simulations, "simulations")
122 self.goal_tolerance = goal_tolerance
123 self._prior_std, self._exploration, self._discount = prior_std, exploration, discount
124 self._collision_penalty = collision_penalty
125 self._history = deque(maxlen=_positive_int(model_capacity, "model_capacity"))
126 self._model = GaussianProcessRegressor(kernel=prior_std ** 2 * Matern(length_scale, nu=2.5),
127 alpha=observation_noise ** 2, optimizer=None)
128 self._posterior = None
129 self._rng = np.random.default_rng(seed)
130 self._trials = self._observations = self._rollouts = 0
131
132 @property
133 def stats(self):
134 """Return the current count of live actions, observations, and simulated paths."""
135 return RTEStats(self._trials, self._observations, self._rollouts)
136
137 def _state(self, state):
138 value = np.asarray(state, dtype=float)
139 if value.shape != (self._moves.shape[1],) or not np.isfinite(value).all():
140 raise ValueError("State and goal vectors must match the nominal displacements.")
141 return value
142
143
144 def observe(self, state, skill, successor):
145 """Add a measured displacement from an executed skill to the rolling model dataset."""
146 slot = self.skills.index(skill)
147 residual = self._state(successor) - self._state(state) - self._moves[slot]
148 if not np.isfinite(residual).all():
149 raise ValueError("The state transition produced a nonfinite model residual.")
150 self._history.append((slot, residual))
151 self._observations += 1
152 self._posterior = None
153
154 def _predictions(self):
155 if self._posterior is None:
156 if self._history:
157 slots, residuals = zip(*self._history)
158 self._model.fit(self._descriptors[list(slots)], np.asarray(residuals))
159 correction, deviations = self._model.predict(self._descriptors, return_std=True)
160 deviations = deviations[:, None] if deviations.ndim == 1 else deviations
161 self._posterior = self._moves + correction.reshape(self._moves.shape), deviations
162 else:
163 self._posterior = self._moves, np.full_like(self._moves, self._prior_std)
164 return self._posterior
165
166 def _select(self, node, goal, means):
167 width = min(len(self.skills), ceil(sqrt(node.visits + 1)))
168 if len(node.edges) < width:
169 candidates = [slot for slot in range(len(self.skills)) if slot not in node.edges]
170 distances = np.linalg.norm(node.state + means[candidates] - goal, axis=1)
171 slot = candidates[int(np.argmin(distances))]
172 node.edges[slot] = _Edge()
173 return slot
174 return max(node.edges, key=lambda slot: node.edges[slot].value + self._exploration *
175 sqrt(log(node.visits + 1) / max(1, node.edges[slot].visits)))
176
177 def _visit(self, node, depth, goal, means, deviations, traversable):
178 slot = self._select(node, goal, means)
179 edge = node.edges[slot]
180 if len(edge.outcomes) < ceil(sqrt(edge.visits + 1)):
181 successor = node.state + means[slot] + deviations[slot] * self._rng.standard_normal(goal.shape)
182 distance = float(np.linalg.norm(successor - goal))
183 blocked = traversable is not None and not traversable(tuple(node.state), tuple(successor))
184 reward = -self._collision_penalty if blocked else node.goal_distance - distance
185 outcome = _Outcome(successor, distance, blocked or distance <= self.goal_tolerance, reward)
186 edge.outcomes.append(outcome)
187 else:
188 outcome = edge.outcomes[int(self._rng.integers(len(edge.outcomes)))]
189 value = outcome.reward
190 if depth > 1 and not outcome.terminal:
191 value += self._discount * self._visit(outcome, depth - 1, goal, means, deviations, traversable)
192 node.visits += 1
193 edge.visits += 1
194 edge.value += (value - edge.value) / edge.visits
195 return value
196
197
198 def plan(self, state, goal, *, traversable=None):
199 """Return an RTESkill or None if the state is already within goal_tolerance.
200
201 traversable, if supplied, tests the whole predicted transition as
202 (before, after). A blocked result receives the collision cost and ends
203 that simulated path.
204 """
205 if traversable is not None and not callable(traversable):
206 raise TypeError("traversable must be callable.")
207 state, goal = self._state(state), self._state(goal)
208 distance = float(np.linalg.norm(state - goal))
209 if distance <= self.goal_tolerance:
210 return None
211 means, deviations = self._predictions()
212 root = _Outcome(state, distance, False, 0.)
213 for _ in range(self.simulations):
214 self._visit(root, self.horizon, goal, means, deviations, traversable)
215 self._rollouts += 1
216 selected = max(root.edges, key=lambda slot: (root.edges[slot].visits, root.edges[slot].value))
217 return self.skills[selected]
218
219
220 def run(self, state, goal, execute, *, max_trials, traversable=None, adapt=True):
221 """Return an RTEPath by calling execute(current_state, genome) at most max_trials times."""
222 limit = index(max_trials)
223 if limit < 0 or not callable(execute):
224 raise ValueError("Use nonnegative max_trials and a callable execute.")
225 state, goal = tuple(map(float, self._state(state))), self._state(goal)
226 states, skills = [state], []
227 for _ in range(limit):
228 skill = self.plan(state, goal, traversable=traversable)
229 if skill is None:
230 break
231 self._trials += 1
232 successor = tuple(map(float, self._state(execute(state, skill.genome))))
233 if adapt:
234 self.observe(state, skill, successor)
235 states.append(successor)
236 skills.append(skill)
237 state = successor
238 return RTEPath(tuple(states), tuple(skills), bool(np.linalg.norm(np.subtract(state, goal)) <= self.goal_tolerance))
Record the sequence of observed states and executed skills.
Definition rte.py:50
An archive action with a nominal state displacement.
Definition rte.py:24
Separate live skill trials from model observations and Monte Carlo rollouts.
Definition rte.py:40
Plan with a repertoire and update its transition model from live observations.
Definition rte.py:76
observe(self, state, skill, successor)
Update the residual model with one actual state transition.
Definition rte.py:144
_select(self, node, goal, means)
Definition rte.py:166
_visit(self, node, depth, goal, means, deviations, traversable)
Definition rte.py:177
plan(self, state, goal, *, traversable=None)
Plan the next skill from the current state without making a real transition.
Definition rte.py:198
run(self, state, goal, execute, *, max_trials, traversable=None, adapt=True)
Execute and replan from observed successors, with a hard live trial limit.
Definition rte.py:220