# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Initial-to-solution and across-solutions behavior characterization.
# @see https://doi.org/10.1145/2908812.2908929
"""Learn descriptor weights from task solutions and transfer them to other tasks."""
from dataclasses import dataclass
from math import isfinite
import numpy as np
from .modern import _positive_int
__all__ = ["BehaviorCharacterization", "spirit_descriptor"]
## @brief Estimate conditional action probabilities from a discrete state–action trace.
# @param states Integer sensory state IDs in [0, state_count), one per timestep.
# @param actions Integer action IDs in [0, action_count), one per timestep.
# @param state_count Number of possible sensory states.
# @param action_count Number of possible actions.
# @return State-major vector of probabilities, uniform for unobserved states.
[docs]
def spirit_descriptor(states, actions, *, state_count, action_count):
"""Build the paper's SPIRIT-o behavior descriptor from a discrete trajectory."""
state_count = _positive_int(state_count, "state_count")
action_count = _positive_int(action_count, "action_count")
states, actions = np.asarray(states), np.asarray(actions)
if states.ndim != 1 or states.shape != actions.shape:
raise ValueError("Supply one state and one action per step of a one-dimensional trace.")
counts = np.zeros((state_count, action_count))
if states.size:
if (states.dtype.kind not in "iu" or actions.dtype.kind not in "iu"
or np.any((states < 0) | (states >= state_count))
or np.any((actions < 0) | (actions >= action_count))):
raise ValueError("Use integer state and action IDs within the configured ranges.")
np.add.at(counts, (states, actions), 1.)
totals = counts.sum(axis=1, keepdims=True)
probabilities = np.full_like(counts, 1. / action_count)
np.divide(counts, totals, where=totals > 0, out=probabilities)
return probabilities.ravel()
## @brief Fixed descriptor scaling learned offline from successful training runs.
[docs]
@dataclass(frozen=True)
class BehaviorCharacterization:
"""Fit on training tasks, then apply the same transform to every search candidate."""
weights: tuple[float, ...]
bounds: tuple[tuple[float, float], ...] | None = None
## @brief Fit Initial-to-Solution (I2S) or Across-Solutions (XS) weights.
# @param initial One normalized descriptor per initial training observation.
# @param successful One normalized descriptor per successful training observation.
# @param method "i2s" centers on initial observations, "xs" on successful observations.
# @param exponent Nonnegative distance exponent. Zero assigns uniform weights.
# @param bounds Optional fixed feature bounds to normalize raw observations to unit scale.
# @return A fitted characterization usable across tasks with the same features.
@classmethod
def fit(cls, initial, successful, *, method="i2s", exponent=2., bounds=None):
initial = np.asarray(initial, dtype=float)
successful = np.asarray(successful, dtype=float)
if (initial.ndim != 2 or successful.ndim != 2 or not initial.size or not successful.size
or initial.shape[1] != successful.shape[1]
or not (np.isfinite(initial).all() and np.isfinite(successful).all())):
raise ValueError("Supply finite nonempty descriptor matrices with the same number of coordinates.")
if method not in ("i2s", "xs") or not isfinite(exponent) or exponent < 0.:
raise ValueError("Use method 'i2s' or 'xs' and a finite nonnegative exponent.")
if bounds is not None:
bounds = np.asarray(bounds, dtype=float)
if bounds.shape != (initial.shape[1], 2) or not np.isfinite(bounds).all():
raise ValueError("Supply one finite (lower, upper) pair per descriptor coordinate.")
with np.errstate(over="ignore"):
widths = bounds[:, 1] - bounds[:, 0]
if not np.isfinite(widths).all() or np.any(widths <= 0.):
raise ValueError("Normalization bounds must have finite positive widths.")
initial = _normalize(initial, bounds)
successful = _normalize(successful, bounds)
bounds = tuple(map(tuple, bounds.tolist()))
with np.errstate(over="ignore", invalid="ignore"):
center = (initial if method == "i2s" else successful).mean(axis=0)
weights = np.ones(initial.shape[1]) if exponent == 0 else (
np.abs(successful - center) ** exponent).mean(axis=0)
if not np.isfinite(weights).all():
raise ValueError("Descriptor weights must be finite. Normalize the input features.")
return cls(tuple(map(float, weights)), bounds)
## @brief Apply the fixed normalization and scaling to a descriptor or batch.
def transform(self, descriptors):
descriptors = np.asarray(descriptors, dtype=float)
if (descriptors.ndim not in (1, 2) or descriptors.shape[-1] != len(self.weights)
or not np.isfinite(descriptors).all()):
raise ValueError("Supply finite descriptors with the fitted number of coordinates.")
if self.bounds is not None:
descriptors = _normalize(descriptors, np.asarray(self.bounds))
with np.errstate(over="ignore", invalid="ignore"):
transformed = descriptors * self.weights
if not np.isfinite(transformed).all():
raise ValueError("Transformed descriptors must be finite.")
return transformed
def _normalize(values, bounds):
lower, upper = bounds.T
with np.errstate(over="ignore", invalid="ignore"):
normalized = (values - lower) / (upper - lower)
if not np.isfinite(normalized).all():
raise ValueError("Normalized descriptors must be finite.")
return normalized