33 """Adapt several candidate skill repertoires under unknown dynamics.
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.
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.
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.")
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()}
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)
82 """Return total reported live actions across all priors."""
83 return sum(self.
_counts.values())
87 """Return a copy of the live selections charged to each prior."""
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.")
96 def _log_priors(self):
100 log_match = logsumexp([entry[2]
for entry
in data]) - np.log(len(data))
if data
else 0.
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)
108 """Report weights before multiplying by the likelihood of reaching a subgoal."""
111 def _posterior(self, name):
113 observations = self.
_data[name]
115 return nominal, np.full(nominal.shape, self.
_prior_std)
117 rows, residuals, _ = zip(*observations)
118 self.
_models[name] = GaussianProcessRegressor(
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)
125 def ask(self, desired_displacement):
126 """Return a skill for the local subgoal. Complete it with tell()."""
128 raise RuntimeError(
"Report the pending skill before asking for another.")
129 target = self.
_vector(desired_displacement)
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.")
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
143 tuple(map(float, mean[row])), tuple(map(float, std[row])))
147 def tell(self, achieved_displacement):
148 """Use a shared observation in each repertoire where the executed genome occurs."""
150 raise RuntimeError(
"Call ask() before recording a skill outcome.")
151 observed = self.
_vector(achieved_displacement)
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)
166 self.
_counts[choice.repertoire] += 1