# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Construct and deploy hierarchical behavioural repertoires.
"""Compose measured skills and adapt the choice of secondary behaviours online."""
from collections import deque
from dataclasses import dataclass
from math import isfinite, sqrt
from operator import index
import numpy as np
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern
from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from .modern import _positive_int
from .rte import RTESkill, ResetFreeTrialAndError
__all__ = ["HTESkill", "HierarchicalRepertoire", "HTEStats", "HTEPath", "HierarchicalTrialAndError"]
## @brief An evaluated composition and its immediate and primitive instructions.
[docs]
@dataclass(frozen=True)
class HTESkill:
"""Store a program, nominal displacement, and secondary descriptor."""
program: tuple[int, ...]
primitive_indices: tuple[int, ...]
displacement: tuple[float, ...]
secondary: tuple[float, ...]
fitness: float
primary_cell: tuple[int, ...]
## @brief Build higher-level repertoire layers over fixed primitive skills.
[docs]
class HierarchicalRepertoire:
"""Grow a hierarchy from finite low-level RTESkill records.
Each new layer evolves sequences of indices into the layer below.
Candidates are executed during construction by a caller-supplied
simulator or scorer. Its returned displacement and secondary
descriptors identify the cell used for scalar fitness competition.
"""
def __init__(self, primitives):
self._primitives = tuple(primitives)
if not self._primitives or any(not isinstance(skill, RTESkill) for skill in self._primitives):
raise ValueError("Supply at least one RTESkill primitive.")
self._width = len(self._primitives[0].displacement)
if any(len(skill.displacement) != self._width for skill in self._primitives):
raise ValueError("Primitive displacements must have the same width.")
self._layers = ()
self._attempts = 0
@property
def primitives(self):
"""Return the immutable primitive layer."""
return self._primitives
@property
def layers(self):
"""Return all constructed layers, from lowest to highest."""
return self._layers
@property
def evaluations(self):
"""Count calls to layer evaluators, including failed calls."""
return self._attempts
## @brief Illuminate one layer of sequences made out of the previous layer.
[docs]
def add_layer(self, evaluate, *, shape, features_domain, sequence_length, budget, seed=None):
"""Return a new layer of evaluated HTESkill records.
Evaluate receives the expanded tuple of primitive RTESkills and
returns (fitness, displacement, secondary). The first descriptor
axes in the native Grid are the displacement coordinates. Use at
least one secondary descriptor axis to retain alternatives.
"""
count = _positive_int(budget, "budget")
length = _positive_int(sequence_length, "sequence_length")
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
domains = tuple(features_domain)
if len(domains) < self._width:
raise ValueError("The grid needs one descriptor axis per displacement coordinate.")
archive = Grid(shape=shape, features_domain=domains, fitness_domain=((-np.inf, np.inf),))
previous = (tuple(skill.primitive_indices for skill in self._layers[-1]) if self._layers
else tuple((i,) for i in range(len(self.primitives))))
rng = np.random.default_rng(seed)
for _ in range(count):
if len(archive) and rng.random() >= .2:
program = list(archive[int(rng.integers(len(archive)))])
program[int(rng.integers(length))] = int(rng.integers(len(previous)))
else:
program = list(map(int, rng.integers(len(previous), size=length)))
expanded = tuple(i for slot in program for i in previous[slot])
self._attempts += 1
quality, displacement, secondary = evaluate(tuple(self.primitives[i] for i in expanded))
quality = float(quality)
displacement, secondary = tuple(map(float, displacement)), tuple(map(float, secondary))
features = displacement + secondary
if (len(displacement) != self._width or len(features) != len(domains)
or not isfinite(quality) or not all(map(isfinite, features))):
raise ValueError("Return finite fitness and exactly the configured descriptor widths.")
if archive.in_bounds(features, archive.features_domain):
archive.add(Individual(program, fitness=Fitness((quality,), weights=(1.,)),
features=Features(features)))
if not len(archive):
raise ValueError("No evaluated program landed inside the layer's descriptor domain.")
layer = tuple(HTESkill(tuple(elite), tuple(i for slot in elite for i in previous[slot]),
tuple(elite.features[:self._width]), tuple(elite.features[self._width:]),
elite.fitness.values[0], tuple(archive.index_grid(elite)[:self._width]))
for elite in archive)
self._layers = (*self._layers, layer)
return layer
## @brief Track attempted macro actions and actual calls to primitive execution.
[docs]
@dataclass(frozen=True)
class HTEStats:
"""Cumulative costs for online deployment."""
macro_trials: int
primitive_steps: int
observations: int
planning_rollouts: int
## @brief Store observed macro endpoints and the programs executed between them.
[docs]
@dataclass(frozen=True)
class HTEPath:
"""One more state than skill, beginning at the given initial state."""
states: tuple[tuple[float, ...], ...]
skills: tuple[HTESkill, ...]
goal_reached: bool
## @brief Plan primary displacements and adapt secondary compositions.
[docs]
class HierarchicalTrialAndError:
"""Deploy a built hierarchy using RTE and a secondary error model.
Each occupied primary cell supplies one nominal displacement from
its highest-quality composition. The primary planner uses online
residual GPs and MCTS. A second GP predicts error relative to that
nominal displacement from primary and secondary descriptors. Its
lower confidence bound chooses a measured composition in the cell.
"""
def __init__(self, repertoire, *, secondary_exploration=1., secondary_prior=.5,
secondary_noise=.03, model_capacity=128, seed=0, **planning):
if not isinstance(repertoire, HierarchicalRepertoire) or not repertoire.layers:
raise ValueError("Build at least one repertoire layer first.")
limits = np.finfo(float)
low, high = sqrt(limits.tiny), sqrt(limits.max)
if not (0 <= secondary_exploration < np.inf
and low <= secondary_prior <= high and low <= secondary_noise <= high):
raise ValueError("Invalid secondary exploration or model uncertainties.")
self._primitives = repertoire.primitives
self._variants = repertoire.layers[-1]
groups = {}
for i, skill in enumerate(self._variants):
groups.setdefault(skill.primary_cell, []).append(i)
self._targets = {}
costs, points = [0.] * len(self._variants), [None] * len(self._variants)
for slots in groups.values():
slots.sort(key=lambda i: self._variants[i].fitness, reverse=True)
target = RTESkill((len(self._targets),), self._variants[slots[0]].displacement)
self._targets[target] = slots
for i in slots:
variant = self._variants[i]
costs[i] = np.linalg.norm(np.subtract(variant.displacement, target.displacement))
points[i] = target.displacement + variant.secondary
self._costs, self._points = np.asarray(costs), np.asarray(points)
span = np.ptp(self._points, axis=0)
self._points = (self._points - self._points.min(axis=0)) / np.where(span > 0, span, 1.)
self._secondary_exploration = secondary_exploration
self._prior = secondary_prior
self._model = GaussianProcessRegressor(kernel=secondary_prior ** 2 * Matern(.4, nu=2.5),
alpha=secondary_noise ** 2, optimizer=None)
self._history = deque(maxlen=_positive_int(model_capacity, "model_capacity"))
self._planner = ResetFreeTrialAndError(tuple(self._targets), model_capacity=model_capacity, seed=seed,
**planning)
self._macro_trials = self._primitive_steps = 0
@property
def stats(self):
"""Return costs for construction-independent online deployment."""
primary = self._planner.stats
return HTEStats(self._macro_trials, self._primitive_steps, primary.observations, primary.planning_rollouts)
def _variant(self, target, adapt):
slots = self._targets[target]
mean = self._costs[slots]
if adapt and self._history:
indices, residuals = zip(*self._history)
self._model.fit(self._points[list(indices)], residuals)
change, std = self._model.predict(self._points[slots], return_std=True)
mean = mean + change - self._secondary_exploration * std
return slots[int(np.argmin(mean))]
## @brief Execute an upper-layer plan using one callback per primitive.
[docs]
def run(self, state, goal, execute, *, max_trials, traversable=None, adapt=True):
"""Return an HTEPath on a budget of macro trials.
Execute receives (state, primitive_genome) and returns the new
state. Traversable tests predicted primary transitions in the
planner. The caller may enforce its own rules during execution.
"""
remaining = index(max_trials)
if remaining < 0 or not callable(execute):
raise ValueError("Use nonnegative max_trials and a callable execute.")
state, goal = tuple(self._planner._state(state)), self._planner._state(goal)
states, skills = [state], []
for _ in range(remaining):
target = self._planner.plan(state, goal, traversable=traversable)
if target is None:
break
slot = self._variant(target, adapt)
skill = self._variants[slot]
successor = state
self._macro_trials += 1
for primitive in skill.primitive_indices:
self._primitive_steps += 1
successor = tuple(self._planner._state(execute(successor, self._primitives[primitive].genome)))
if adapt:
error = np.linalg.norm(np.subtract(successor, state) - target.displacement)
if not isfinite(error):
raise ValueError("The macro action produced a nonfinite displacement error.")
self._planner.observe(state, target, successor)
self._history.append((slot, error - self._costs[slot]))
state = successor
states.append(state)
skills.append(skill)
reached = bool(np.linalg.norm(np.subtract(state, goal)) <= self._planner.goal_tolerance)
return HTEPath(tuple(states), tuple(skills), reached)