QDpy
Loading...
Searching...
No Matches
behavior_transfer.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Learn descriptor weights from task solutions and transfer them to other tasks."""
7
8from dataclasses import dataclass
9from math import isfinite
10
11import numpy as np
12
13from .modern import _positive_int
14
15__all__ = ["BehaviorCharacterization", "spirit_descriptor"]
16
17
18
24def spirit_descriptor(states, actions, *, state_count, action_count):
25 """Build the paper's SPIRIT-o behavior descriptor from a discrete trajectory."""
26 state_count = _positive_int(state_count, "state_count")
27 action_count = _positive_int(action_count, "action_count")
28 states, actions = np.asarray(states), np.asarray(actions)
29 if states.ndim != 1 or states.shape != actions.shape:
30 raise ValueError("Supply one state and one action per step of a one-dimensional trace.")
31 counts = np.zeros((state_count, action_count))
32 if states.size:
33 if (states.dtype.kind not in "iu" or actions.dtype.kind not in "iu"
34 or np.any((states < 0) | (states >= state_count))
35 or np.any((actions < 0) | (actions >= action_count))):
36 raise ValueError("Use integer state and action IDs within the configured ranges.")
37 np.add.at(counts, (states, actions), 1.)
38 totals = counts.sum(axis=1, keepdims=True)
39 probabilities = np.full_like(counts, 1. / action_count)
40 np.divide(counts, totals, where=totals > 0, out=probabilities)
41 return probabilities.ravel()
42
43
44
45@dataclass(frozen=True)
47 """Fit on training tasks, then apply the same transform to every search candidate."""
48
49 weights: tuple[float, ...]
50 bounds: tuple[tuple[float, float], ...] | None = None
51
52
59 @classmethod
60 def fit(cls, initial, successful, *, method="i2s", exponent=2., bounds=None):
61 initial = np.asarray(initial, dtype=float)
62 successful = np.asarray(successful, dtype=float)
63 if (initial.ndim != 2 or successful.ndim != 2 or not initial.size or not successful.size
64 or initial.shape[1] != successful.shape[1]
65 or not (np.isfinite(initial).all() and np.isfinite(successful).all())):
66 raise ValueError("Supply finite nonempty descriptor matrices with the same number of coordinates.")
67 if method not in ("i2s", "xs") or not isfinite(exponent) or exponent < 0.:
68 raise ValueError("Use method 'i2s' or 'xs' and a finite nonnegative exponent.")
69 if bounds is not None:
70 bounds = np.asarray(bounds, dtype=float)
71 if bounds.shape != (initial.shape[1], 2) or not np.isfinite(bounds).all():
72 raise ValueError("Supply one finite (lower, upper) pair per descriptor coordinate.")
73 with np.errstate(over="ignore"):
74 widths = bounds[:, 1] - bounds[:, 0]
75 if not np.isfinite(widths).all() or np.any(widths <= 0.):
76 raise ValueError("Normalization bounds must have finite positive widths.")
77 initial = _normalize(initial, bounds)
78 successful = _normalize(successful, bounds)
79 bounds = tuple(map(tuple, bounds.tolist()))
80 with np.errstate(over="ignore", invalid="ignore"):
81 center = (initial if method == "i2s" else successful).mean(axis=0)
82 weights = np.ones(initial.shape[1]) if exponent == 0 else (
83 np.abs(successful - center) ** exponent).mean(axis=0)
84 if not np.isfinite(weights).all():
85 raise ValueError("Descriptor weights must be finite. Normalize the input features.")
86 return cls(tuple(map(float, weights)), bounds)
87
88
89 def transform(self, descriptors):
90 descriptors = np.asarray(descriptors, dtype=float)
91 if (descriptors.ndim not in (1, 2) or descriptors.shape[-1] != len(self.weights)
92 or not np.isfinite(descriptors).all()):
93 raise ValueError("Supply finite descriptors with the fitted number of coordinates.")
94 if self.bounds is not None:
95 descriptors = _normalize(descriptors, np.asarray(self.bounds))
96 with np.errstate(over="ignore", invalid="ignore"):
97 transformed = descriptors * self.weights
98 if not np.isfinite(transformed).all():
99 raise ValueError("Transformed descriptors must be finite.")
100 return transformed
101
102
103def _normalize(values, bounds):
104 lower, upper = bounds.T
105 with np.errstate(over="ignore", invalid="ignore"):
106 normalized = (values - lower) / (upper - lower)
107 if not np.isfinite(normalized).all():
108 raise ValueError("Normalized descriptors must be finite.")
109 return normalized
Fixed descriptor scaling learned offline from successful training runs.
transform(self, descriptors)
Apply the fixed normalization and scaling to a descriptor or batch.
fit(cls, initial, successful, *, method="i2s", exponent=2., bounds=None)
Fit Initial-to-Solution (I2S) or Across-Solutions (XS) weights.