77 """Reset-free Trial-and-Error following Chatzilygeroudis et al.
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.
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.
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)
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])
120 self.
horizon = _positive_int(horizon,
"horizon")
121 self.
simulations = _positive_int(simulations,
"simulations")
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)
129 self.
_rng = np.random.default_rng(seed)
134 """Return the current count of live actions, observations, and simulated paths."""
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.")
145 """Add a measured displacement from an executed skill to the rolling model dataset."""
146 slot = self.
skills.index(skill)
148 if not np.isfinite(residual).all():
149 raise ValueError(
"The state transition produced a nonfinite model residual.")
150 self.
_history.append((slot, residual))
154 def _predictions(self):
157 slots, residuals = zip(*self.
_history)
160 deviations = deviations[:,
None]
if deviations.ndim == 1
else deviations
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()
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)))
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))
186 edge.outcomes.append(outcome)
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)
194 edge.value += (value - edge.value) / edge.visits
198 def plan(self, state, goal, *, traversable=None):
199 """Return an RTESkill or None if the state is already within goal_tolerance.
201 traversable, if supplied, tests the whole predicted transition as
202 (before, after). A blocked result receives the collision cost and ends
205 if traversable
is not None and not callable(traversable):
206 raise TypeError(
"traversable must be callable.")
208 distance = float(np.linalg.norm(state - goal))
212 root =
_Outcome(state, distance,
False, 0.)
214 self.
_visit(root, self.
horizon, goal, means, deviations, traversable)
216 selected = max(root.edges, key=
lambda slot: (root.edges[slot].visits, root.edges[slot].value))
217 return self.
skills[selected]
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)
232 successor = tuple(map(float, self.
_state(execute(state, skill.genome))))
234 self.
observe(state, skill, successor)
235 states.append(successor)
238 return RTEPath(tuple(states), tuple(skills), bool(np.linalg.norm(np.subtract(state, goal)) <= self.
goal_tolerance))