QDpy
Loading...
Searching...
No Matches
hte.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Compose measured skills and adapt the choice of secondary behaviours online."""
6
7from collections import deque
8from dataclasses import dataclass
9from math import isfinite, 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 qdpy.containers import Grid
17from qdpy.phenotype import Features, Fitness, Individual
18
19from .modern import _positive_int
20from .rte import RTESkill, ResetFreeTrialAndError
21
22__all__ = ["HTESkill", "HierarchicalRepertoire", "HTEStats", "HTEPath", "HierarchicalTrialAndError"]
23
24
25
26@dataclass(frozen=True)
28 """Store a program, nominal displacement, and secondary descriptor."""
29
30 program: tuple[int, ...]
31 primitive_indices: tuple[int, ...]
32 displacement: tuple[float, ...]
33 secondary: tuple[float, ...]
34 fitness: float
35 primary_cell: tuple[int, ...]
36
37
38
40 """Grow a hierarchy from finite low-level RTESkill records.
41
42 Each new layer evolves sequences of indices into the layer below.
43 Candidates are executed during construction by a caller-supplied
44 simulator or scorer. Its returned displacement and secondary
45 descriptors identify the cell used for scalar fitness competition.
46 """
47
48 def __init__(self, primitives):
49 self._primitives = tuple(primitives)
50 if not self._primitives or any(not isinstance(skill, RTESkill) for skill in self._primitives):
51 raise ValueError("Supply at least one RTESkill primitive.")
52 self._width = len(self._primitives[0].displacement)
53 if any(len(skill.displacement) != self._width for skill in self._primitives):
54 raise ValueError("Primitive displacements must have the same width.")
55 self._layers = ()
56 self._attempts = 0
57
58 @property
59 def primitives(self):
60 """Return the immutable primitive layer."""
61 return self._primitives
62
63 @property
64 def layers(self):
65 """Return all constructed layers, from lowest to highest."""
66 return self._layers
67
68 @property
69 def evaluations(self):
70 """Count calls to layer evaluators, including failed calls."""
71 return self._attempts
72
73
74 def add_layer(self, evaluate, *, shape, features_domain, sequence_length, budget, seed=None):
75 """Return a new layer of evaluated HTESkill records.
76
77 Evaluate receives the expanded tuple of primitive RTESkills and
78 returns (fitness, displacement, secondary). The first descriptor
79 axes in the native Grid are the displacement coordinates. Use at
80 least one secondary descriptor axis to retain alternatives.
81 """
82 count = _positive_int(budget, "budget")
83 length = _positive_int(sequence_length, "sequence_length")
84 if not callable(evaluate):
85 raise TypeError("evaluate must be callable.")
86 domains = tuple(features_domain)
87 if len(domains) < self._width:
88 raise ValueError("The grid needs one descriptor axis per displacement coordinate.")
89 archive = Grid(shape=shape, features_domain=domains, fitness_domain=((-np.inf, np.inf),))
90 previous = (tuple(skill.primitive_indices for skill in self._layers[-1]) if self._layers
91 else tuple((i,) for i in range(len(self.primitives))))
92 rng = np.random.default_rng(seed)
93 for _ in range(count):
94 if len(archive) and rng.random() >= .2:
95 program = list(archive[int(rng.integers(len(archive)))])
96 program[int(rng.integers(length))] = int(rng.integers(len(previous)))
97 else:
98 program = list(map(int, rng.integers(len(previous), size=length)))
99 expanded = tuple(i for slot in program for i in previous[slot])
100 self._attempts += 1
101 quality, displacement, secondary = evaluate(tuple(self.primitives[i] for i in expanded))
102 quality = float(quality)
103 displacement, secondary = tuple(map(float, displacement)), tuple(map(float, secondary))
104 features = displacement + secondary
105 if (len(displacement) != self._width or len(features) != len(domains)
106 or not isfinite(quality) or not all(map(isfinite, features))):
107 raise ValueError("Return finite fitness and exactly the configured descriptor widths.")
108 if archive.in_bounds(features, archive.features_domain):
109 archive.add(Individual(program, fitness=Fitness((quality,), weights=(1.,)),
110 features=Features(features)))
111 if not len(archive):
112 raise ValueError("No evaluated program landed inside the layer's descriptor domain.")
113 layer = tuple(HTESkill(tuple(elite), tuple(i for slot in elite for i in previous[slot]),
114 tuple(elite.features[:self._width]), tuple(elite.features[self._width:]),
115 elite.fitness.values[0], tuple(archive.index_grid(elite)[:self._width]))
116 for elite in archive)
117 self._layers = (*self._layers, layer)
118 return layer
119
120
121
122@dataclass(frozen=True)
124 """Cumulative costs for online deployment."""
125
126 macro_trials: int
127 primitive_steps: int
128 observations: int
129 planning_rollouts: int
130
131
132
133@dataclass(frozen=True)
135 """One more state than skill, beginning at the given initial state."""
136
137 states: tuple[tuple[float, ...], ...]
138 skills: tuple[HTESkill, ...]
139 goal_reached: bool
140
141
142
144 """Deploy a built hierarchy using RTE and a secondary error model.
145
146 Each occupied primary cell supplies one nominal displacement from
147 its highest-quality composition. The primary planner uses online
148 residual GPs and MCTS. A second GP predicts error relative to that
149 nominal displacement from primary and secondary descriptors. Its
150 lower confidence bound chooses a measured composition in the cell.
151 """
152
153 def __init__(self, repertoire, *, secondary_exploration=1., secondary_prior=.5,
154 secondary_noise=.03, model_capacity=128, seed=0, **planning):
155 if not isinstance(repertoire, HierarchicalRepertoire) or not repertoire.layers:
156 raise ValueError("Build at least one repertoire layer first.")
157 limits = np.finfo(float)
158 low, high = sqrt(limits.tiny), sqrt(limits.max)
159 if not (0 <= secondary_exploration < np.inf
160 and low <= secondary_prior <= high and low <= secondary_noise <= high):
161 raise ValueError("Invalid secondary exploration or model uncertainties.")
162 self._primitives = repertoire.primitives
163 self._variants = repertoire.layers[-1]
164 groups = {}
165 for i, skill in enumerate(self._variants):
166 groups.setdefault(skill.primary_cell, []).append(i)
167 self._targets = {}
168 costs, points = [0.] * len(self._variants), [None] * len(self._variants)
169 for slots in groups.values():
170 slots.sort(key=lambda i: self._variants[i].fitness, reverse=True)
171 target = RTESkill((len(self._targets),), self._variants[slots[0]].displacement)
172 self._targets[target] = slots
173 for i in slots:
174 variant = self._variants[i]
175 costs[i] = np.linalg.norm(np.subtract(variant.displacement, target.displacement))
176 points[i] = target.displacement + variant.secondary
177 self._costs, self._points = np.asarray(costs), np.asarray(points)
178 span = np.ptp(self._points, axis=0)
179 self._points = (self._points - self._points.min(axis=0)) / np.where(span > 0, span, 1.)
180 self._secondary_exploration = secondary_exploration
181 self._prior = secondary_prior
182 self._model = GaussianProcessRegressor(kernel=secondary_prior ** 2 * Matern(.4, nu=2.5),
183 alpha=secondary_noise ** 2, optimizer=None)
184 self._history = deque(maxlen=_positive_int(model_capacity, "model_capacity"))
185 self._planner = ResetFreeTrialAndError(tuple(self._targets), model_capacity=model_capacity, seed=seed,
186 **planning)
187 self._macro_trials = self._primitive_steps = 0
188
189 @property
190 def stats(self):
191 """Return costs for construction-independent online deployment."""
192 primary = self._planner.stats
193 return HTEStats(self._macro_trials, self._primitive_steps, primary.observations, primary.planning_rollouts)
194
195 def _variant(self, target, adapt):
196 slots = self._targets[target]
197 mean = self._costs[slots]
198 if adapt and self._history:
199 indices, residuals = zip(*self._history)
200 self._model.fit(self._points[list(indices)], residuals)
201 change, std = self._model.predict(self._points[slots], return_std=True)
202 mean = mean + change - self._secondary_exploration * std
203 return slots[int(np.argmin(mean))]
204
205
206 def run(self, state, goal, execute, *, max_trials, traversable=None, adapt=True):
207 """Return an HTEPath on a budget of macro trials.
208
209 Execute receives (state, primitive_genome) and returns the new
210 state. Traversable tests predicted primary transitions in the
211 planner. The caller may enforce its own rules during execution.
212 """
213 remaining = index(max_trials)
214 if remaining < 0 or not callable(execute):
215 raise ValueError("Use nonnegative max_trials and a callable execute.")
216 state, goal = tuple(self._planner._state(state)), self._planner._state(goal)
217 states, skills = [state], []
218 for _ in range(remaining):
219 target = self._planner.plan(state, goal, traversable=traversable)
220 if target is None:
221 break
222 slot = self._variant(target, adapt)
223 skill = self._variants[slot]
224 successor = state
225 self._macro_trials += 1
226 for primitive in skill.primitive_indices:
227 self._primitive_steps += 1
228 successor = tuple(self._planner._state(execute(successor, self._primitives[primitive].genome)))
229 if adapt:
230 error = np.linalg.norm(np.subtract(successor, state) - target.displacement)
231 if not isfinite(error):
232 raise ValueError("The macro action produced a nonfinite displacement error.")
233 self._planner.observe(state, target, successor)
234 self._history.append((slot, error - self._costs[slot]))
235 state = successor
236 states.append(state)
237 skills.append(skill)
238 reached = bool(np.linalg.norm(np.subtract(state, goal)) <= self._planner.goal_tolerance)
239 return HTEPath(tuple(states), tuple(skills), reached)
Store observed macro endpoints and the programs executed between them.
Definition hte.py:134
An evaluated composition and its immediate and primitive instructions.
Definition hte.py:27
Track attempted macro actions and actual calls to primitive execution.
Definition hte.py:123
Build higher-level repertoire layers over fixed primitive skills.
Definition hte.py:39
add_layer(self, evaluate, *, shape, features_domain, sequence_length, budget, seed=None)
Illuminate one layer of sequences made out of the previous layer.
Definition hte.py:74
Plan primary displacements and adapt secondary compositions.
Definition hte.py:143
run(self, state, goal, execute, *, max_trials, traversable=None, adapt=True)
Execute an upper-layer plan using one callback per primitive.
Definition hte.py:206
An archive action with a nominal state displacement.
Definition rte.py:24
Plan with a repertoire and update its transition model from live observations.
Definition rte.py:76
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405