QDpy
Loading...
Searching...
No Matches
aprol.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Adaptive Prior Selection for Repertoire-Based Online Learning."""
7
8from dataclasses import dataclass
9
10import numpy as np
11from scipy.special import logsumexp
12from sklearn.gaussian_process import GaussianProcessRegressor
13from sklearn.gaussian_process.kernels import RBF
14
15from .rte import RTESkill
16
17__all__ = ["APROL", "APROLChoice"]
18
19
20
21@dataclass(frozen=True)
23 """Identify the chosen nominal repertoire and its executable policy genome."""
24
25 repertoire: str
26 genome: tuple[float, ...]
27 displacement: tuple[float, ...]
28 deviation: tuple[float, ...]
29
30
31
32class APROL:
33 """Adapt several candidate skill repertoires under unknown dynamics.
34
35 Supply the desired displacement from the current state to the local
36 subgoal. Execute the selected skill and report its measured displacement.
37 Compatibility is based on nominal transition error. Gaussian process
38 residual corrections use every observed genome present in that prior.
39
40 :param repertoires: Ordered mapping from names to nonempty RTESkill sequences.
41 :param length_scale: GP length scale in nominal displacement coordinates.
42 :param prior_std: Standard deviation of unobserved transition residuals.
43 :param observation_std: Positive Gaussian observation noise.
44 :param compatibility_std: Scale of nominal-versus-observed transition errors.
45 :param goal_std: Positive tolerance used in the goal likelihood.
46 :param exploration: Nonnegative UCB coefficient for trying underused priors.
47 """
48
49 def __init__(self, repertoires, *, length_scale=.3, prior_std=.25, observation_std=.03,
50 compatibility_std=.25, goal_std=.15, exploration=.2):
51 if (not repertoires or any(not isinstance(name, str) or not name for name in repertoires)
52 or any(not 0. < value < np.inf for value in (
53 length_scale, prior_std, observation_std, compatibility_std, goal_std))
54 or not 0 <= exploration < np.inf):
55 raise ValueError("Use named repertoires, positive finite scales, and nonnegative finite exploration.")
56 self._skills = {name: tuple(skills) for name, skills in repertoires.items()}
57 if any(not skills or not all(isinstance(skill, RTESkill) for skill in skills)
58 for skills in self._skills.values()):
59 raise ValueError("Each repertoire must contain at least one RTESkill.")
60 self._dimension = len(next(iter(self._skills.values()))[0].displacement)
61 self._nominal = {name: np.asarray([skill.displacement for skill in skills])
62 for name, skills in self._skills.items()}
63 self._lookup = {name: {skill.genome: row for row, skill in enumerate(skills)}
64 for name, skills in self._skills.items()}
65 if any(len(self._lookup[name]) != len(skills) or self._nominal[name].shape[1] != self._dimension
66 for name, skills in self._skills.items()):
67 raise ValueError("Use unique genomes within each prior and a common displacement dimension.")
68 if max(prior_std, observation_std) > np.sqrt(np.finfo(float).max) or prior_std ** 2 == 0.:
69 raise ValueError("The prior and observation variances must be representable.")
70 self._kernel = prior_std ** 2 * RBF(length_scale)
71 self._noise = max(observation_std ** 2, prior_std ** 2 * 1e-12)
72 self._prior_std = prior_std
73 self._compatibility_std, self._goal_std = compatibility_std, goal_std
74 self._exploration = exploration
75 self._data = {name: [] for name in self._skills}
76 self._counts = dict.fromkeys(self._skills, 0)
77 self._models = {}
78 self._pending = None
79
80 @property
81 def trials(self):
82 """Return total reported live actions across all priors."""
83 return sum(self._counts.values())
84
85 @property
87 """Return a copy of the live selections charged to each prior."""
88 return self._counts.copy()
89
90 def _vector(self, values):
91 vector = np.array(values, dtype=float, copy=True)
92 if vector.shape != (self._dimension,) or not np.isfinite(vector).all():
93 raise ValueError("Supply a finite displacement of the configured dimension.")
94 return vector
95
96 def _log_priors(self):
97 scores = []
98 for name in self._skills:
99 data, count = self._data[name], self._counts[name]
100 log_match = logsumexp([entry[2] for entry in data]) - np.log(len(data)) if data else 0.
101 bonus = self._exploration * np.sqrt(np.log(self.trials + 2.) / max(1, count))
102 scores.append(np.logaddexp(log_match, np.log(bonus) if bonus else -np.inf))
103 relative = np.asarray(scores) - max(scores)
104 return relative - logsumexp(relative)
105
106
108 """Report weights before multiplying by the likelihood of reaching a subgoal."""
109 return dict(zip(self._skills, map(float, np.exp(self._log_priors()))))
110
111 def _posterior(self, name):
112 nominal = self._nominal[name]
113 observations = self._data[name]
114 if not observations:
115 return nominal, np.full(nominal.shape, self._prior_std)
116 if name not in self._models:
117 rows, residuals, _ = zip(*observations)
118 self._models[name] = GaussianProcessRegressor(
119 kernel=self._kernel, alpha=self._noise, optimizer=None
120 ).fit(nominal[list(rows)], np.stack(residuals))
121 residual, deviation = self._models[name].predict(nominal, return_std=True)
122 return nominal + residual.reshape(nominal.shape), deviation.reshape(nominal.shape)
123
124
125 def ask(self, desired_displacement):
126 """Return a skill for the local subgoal. Complete it with tell()."""
127 if self._pending is not None:
128 raise RuntimeError("Report the pending skill before asking for another.")
129 target = self._vector(desired_displacement)
130 best = None
131 for name, prior in zip(self._skills, self._log_priors()):
132 mean, std = self._posterior(name)
133 if not np.isfinite(mean).all() or not np.isfinite(std).all():
134 raise ValueError("The residual GP must predict finite means and uncertainties.")
135 scale = np.hypot(std, self._goal_std)
136 with np.errstate(over="ignore"):
137 log_score = prior - (.5 * ((target - mean) / scale) ** 2 + np.log(scale)).sum(axis=1)
138 row = int(np.argmax(log_score))
139 if best is None or log_score[row] > best[0]:
140 best = (log_score[row], name, row, mean, std)
141 _, name, row, mean, std = best
142 self._pending = APROLChoice(name, self._skills[name][row].genome,
143 tuple(map(float, mean[row])), tuple(map(float, std[row])))
144 return self._pending
145
146
147 def tell(self, achieved_displacement):
148 """Use a shared observation in each repertoire where the executed genome occurs."""
149 if self._pending is None:
150 raise RuntimeError("Call ask() before recording a skill outcome.")
151 observed = self._vector(achieved_displacement)
152 choice = self._pending
153 updates = {}
154 for name, lookup in self._lookup.items():
155 if choice.genome in lookup:
156 row = lookup[choice.genome]
157 residual = observed - self._nominal[name][row]
158 if not np.isfinite(residual).all():
159 raise ValueError("The residual must be finite.")
160 with np.errstate(over="ignore"):
161 likelihood = -min(float(((residual / self._compatibility_std) ** 2).sum() / 2), 1e300)
162 updates[name] = (row, residual, likelihood)
163 for name, entry in updates.items():
164 self._data[name].append(entry)
165 self._models.pop(name, None)
166 self._counts[choice.repertoire] += 1
167 self._pending = None
Skill and posterior transition prediction for one local deployment decision.
Definition aprol.py:22
Combine a compatibility bandit with one residual GP per transition prior.
Definition aprol.py:32
_vector(self, values)
Definition aprol.py:90
ask(self, desired_displacement)
Choose one policy by prior weight and predicted probability density at the goal.
Definition aprol.py:125
repertoire_probabilities(self)
Return the normalized compatibility and exploration weights of the priors.
Definition aprol.py:107
tell(self, achieved_displacement)
Record one actual observed displacement and invalidate affected residual models.
Definition aprol.py:147