QDpy
Loading...
Searching...
No Matches
path_signature.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Path signatures for piecewise linear, multichannel trajectories."""
7
8import numpy as np
9from sklearn.cluster import KMeans
10from threadpoolctl import threadpool_limits
11
12from qdpy.base import registry
13from qdpy.containers import CVTGrid
14from .modern import _positive_int
15from .occupancy_me import _TrajectoryMAPElites
16
17__all__ = ["PathSignature", "PathSignatureMAPElites"]
18
19
20
22 """Compute level one and optionally level two of a piecewise linear signature.
23
24 Level one stores the sum of increments. Level two stores all ordered
25 pairs of coordinates in row-major order (first differential before
26 second). The descriptor omits the constant level zero. Signatures are
27 translation invariant. Adding a time channel can distinguish paths
28 that retrace their steps and helps when timing matters.
29
30 :param observation_size: Number of channels in each observation.
31 :param order: Signature truncation level, either 1 or 2.
32 :param scale: Positive scale per observation coordinate, shared across rollouts.
33 :param time_channel: Append normalized time for equally spaced samples.
34 """
35
36 def __init__(self, observation_size, *, order=2, scale=None, time_channel=False):
37 self.observation_size = _positive_int(observation_size, "observation_size")
38 self.order = _positive_int(order, "order")
39 if self.order > 2:
40 raise ValueError("PathSignature supports order 1 or 2.")
41 if not isinstance(time_channel, (bool, np.bool_)):
42 raise TypeError("time_channel must be a bool.")
43 self.time_channel = bool(time_channel)
44 self._width = self.observation_size + self.time_channel
45 self._scale = np.ones(self.observation_size) if scale is None else np.array(scale, dtype=float, copy=True)
46 if (self._scale.shape != (self.observation_size,) or not np.isfinite(self._scale).all()
47 or (self._scale <= 0).any()):
48 raise ValueError("Use one positive finite scale per observation channel.")
49
50 @property
51 def descriptor_size(self):
52 """Return the signature width, including the optional time channel."""
53 return self._width if self.order == 1 else self._width + self._width**2
54
55
59 def encode(self, trajectory, *, times=None):
60 """Use exact first and second iterated integrals for linear segments."""
61 points = np.asarray(trajectory, dtype=float)
62 if (points.ndim != 2 or points.shape[1] != self.observation_size
63 or not len(points) or not np.isfinite(points).all()):
64 raise ValueError("Supply a nonempty finite path with the declared observation width.")
65 if times is not None and not self.time_channel:
66 raise ValueError("Explicit times require time_channel=True.")
67 with np.errstate(over="ignore", invalid="ignore", divide="ignore"):
68 increments = np.diff(points, axis=0)
69 overflowed = np.isinf(increments)
70 increments /= self._scale
71 if overflowed.any():
72 rows, cols = np.nonzero(overflowed)
73 increments[rows, cols] = (points[rows + 1, cols] / self._scale[cols]
74 - points[rows, cols] / self._scale[cols])
75 if self.time_channel:
76 if times is None:
77 time_increments = np.full(len(points) - 1, 1 / max(1, len(points) - 1))
78 else:
79 timestamps = np.asarray(times, dtype=float)
80 if (timestamps.shape != (len(points),) or not np.isfinite(timestamps).all()
81 or (timestamps[1:] <= timestamps[:-1]).any()):
82 raise ValueError("Supply one finite, strictly increasing timestamp per observation.")
83 # Half scaling avoids overflowing for finite endpoints at opposite extremes.
84 if len(timestamps) > 1 and not np.isfinite(timestamps[-1] - timestamps[0]):
85 timestamps = timestamps * .5
86 time_increments = np.diff(timestamps)
87 if len(time_increments):
88 time_increments /= timestamps[-1] - timestamps[0]
89 increments = np.column_stack((increments, time_increments))
90 level_one = increments.sum(axis=0)
91 result = level_one
92 if self.order == 2:
93 prefixes = np.zeros_like(increments)
94 prefixes[1:] = np.cumsum(increments[:-1], axis=0)
95 level_two = prefixes.T @ increments + .5 * (increments.T @ increments)
96 result = np.concatenate((level_one, level_two.ravel()))
97 if not np.isfinite(result).all():
98 raise ValueError("The path signature overflowed. Rescale the input channels.")
99 return result
100
101
108 def make_archive(self, trajectories, cells, *, fitness_domain=(-np.inf, np.inf), fitness_weight=1., seed=0):
109 """Use reference paths for centroids and allow finite extrapolations at search time."""
110 cells = _positive_int(cells, "cells")
111 if not np.isfinite(fitness_weight) or fitness_weight == 0:
112 raise ValueError("Use a finite nonzero fitness weight.")
113 descriptors = np.asarray([self.encode(path) for path in trajectories])
114 if len(descriptors) < cells or len(np.unique(descriptors, axis=0)) < cells:
115 raise ValueError("Provide at least one distinct reference signature per cell.")
116 rng = np.random.default_rng(seed)
117 with threadpool_limits(limits=1):
118 model = KMeans(cells, n_init=1, random_state=int(rng.integers(2**32)))
119 centers = model.fit(descriptors).cluster_centers_
120 # CVT uses precomputed centroids. Its domain can admit new outlying paths.
121 return CVTGrid(shape=cells, centroids=centers, features_domain=((-np.inf, np.inf),) * self.descriptor_size,
122 fitness_domain=(tuple(fitness_domain),), fitness_weights=(fitness_weight,))
123
124
125
126@registry.register
128 """Evaluate bounded real genomes using a fixed encoder and CVT archive.
129
130 Use optimise() with (scalar fitness, trajectory) or use native ask/tell
131 with encoded descriptors. Packed evaluators return rows in proposal
132 order. Trajectory lengths are stored as scores["signature_steps"].
133
134 :param container: Best-only CVTGrid with matching signature dimension.
135 :param budget: Maximum attempted evaluations.
136 :param dimension: Real genome length.
137 :param signature: PathSignature used for every evaluation.
138 :param initial_samples: Uniform proposals before archive variation.
139 :param seed: Private proposal seed.
140 :param kwargs: Native IsoLineMAPElites options.
141 """
142
143 _steps_score = "signature_steps"
144
145 def __init__(self, container, budget, dimension, *, signature, initial_samples=16, seed=0, **kwargs):
146 if not isinstance(signature, PathSignature):
147 raise TypeError("Supply a PathSignature.")
148 if (type(container) is not CVTGrid or len(container.features_domain) != signature.descriptor_size
149 or len(container.fitness_domain or ()) != 1 or container.discard_random_on_bin_overload
150 or container.fitness_score_names or container.features_score_names):
151 raise ValueError("Use a native best-only CVTGrid with direct fitness and matching descriptors.")
152 self.signature = signature
153 super().__init__(container, budget, dimension, initial_samples=initial_samples, seed=seed, **kwargs)
154
155 @property
156 def _trajectory_encoder(self):
157 return self.signature
Illuminate a CVT repertoire with path signatures and Iso+LineDD variation.
Encode displacements and ordered channel interactions.
make_archive(self, trajectories, cells, *, fitness_domain=(-np.inf, np.inf), fitness_weight=1., seed=0)
Fit reproducible CVT centroids using reference trajectories.
encode(self, trajectory, *, times=None)
Encode a path with equally spaced observations or explicit sample times.