outsider86 commited on
Commit
8bc84c4
·
verified ·
1 Parent(s): 71b4038

Package exact adaptive implementation: code/BSplineEncoder/src/spline_encoder/encoder.py

Browse files
models/piper-pick-white-block-25hz-qwenpi-v3-adaptive-left-exclude-gripper-native-controls13-gb32-50k-20260905/code/BSplineEncoder/src/spline_encoder/encoder.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Framework-independent continuous and optionally quantized spline encoders."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Iterable
6
+
7
+ import numpy as np
8
+ from scipy.interpolate import BSpline, make_lsq_spline
9
+
10
+ from .adaptive import encode_knot_durations, fit_adaptive_bspline
11
+ from .config import (
12
+ AdaptiveBSplineConfig,
13
+ Config,
14
+ UniformBSplineConfig,
15
+ UniformLeftBSplineConfig,
16
+ )
17
+ from .quantization import ControlQuantizer
18
+ from .result import SplineGeometry, SplineParameters
19
+ from .subdivision import extract_left_clamped_prefix
20
+
21
+
22
+ def _validate_actions(actions: Any, length: int | None, dim: int) -> np.ndarray:
23
+ values = np.asarray(actions, dtype=np.float64)
24
+ if values.ndim != 2 or values.shape[1] != dim:
25
+ raise ValueError(f"actions must have shape (steps, {dim}), got {values.shape}")
26
+ if length is not None and len(values) != length:
27
+ raise ValueError(f"actions must have shape ({length}, {dim}), got {values.shape}")
28
+ if not np.all(np.isfinite(values)):
29
+ raise ValueError("actions must contain only finite values")
30
+ return values
31
+
32
+
33
+ def _design(x: np.ndarray, knots: np.ndarray, degree: int) -> np.ndarray:
34
+ x = np.asarray(x, dtype=np.float64)
35
+ n = len(knots) - degree - 1
36
+ values = np.zeros((len(x), n + degree))
37
+ for index in range(n + degree):
38
+ values[:, index] = ((x >= knots[index]) & (x < knots[index + 1])).astype(float)
39
+ values[x == knots[-1], n - 1] = 1.0
40
+ for order in range(1, degree + 1):
41
+ next_values = np.zeros((len(x), n + degree - order))
42
+ for index in range(n + degree - order):
43
+ left = knots[index + order] - knots[index]
44
+ right = knots[index + order + 1] - knots[index + 1]
45
+ if left > 0:
46
+ next_values[:, index] += (
47
+ (x - knots[index]) / left * values[:, index]
48
+ )
49
+ if right > 0:
50
+ next_values[:, index] += (
51
+ (knots[index + order + 1] - x) / right * values[:, index + 1]
52
+ )
53
+ values = next_values
54
+ return values[:, :n]
55
+
56
+
57
+ def _inclusive_basis(num_basis: int, degree: int, count: int):
58
+ internal = np.linspace(0.0, count - 1, num_basis - degree + 1)
59
+ knots = np.r_[np.zeros(degree), internal, np.full(degree, count - 1)]
60
+ basis = _design(np.linspace(0, count - 1, count), knots, degree)
61
+ return basis, knots
62
+
63
+
64
+ def _fixed_span_bases(num_basis: int, degree: int, count: int, span_steps: int):
65
+ end = (num_basis - degree) * span_steps
66
+ breaks = np.arange(num_basis - degree + 1, dtype=np.float64) * span_steps
67
+ knots = np.r_[np.zeros(degree), breaks, np.full(degree, end)]
68
+ return (
69
+ _design(np.arange(count, dtype=np.float64), knots, degree),
70
+ _design(np.arange(count + 1, dtype=np.float64), knots, degree),
71
+ knots,
72
+ )
73
+
74
+
75
+ class BaseSplineEncoder:
76
+ """Shared public surface for all spline geometries."""
77
+
78
+ config: Config
79
+
80
+ def __init__(self) -> None:
81
+ self.quantizer = ControlQuantizer(self.config.vocab_size)
82
+
83
+ @property
84
+ def tokenizer_id(self) -> str:
85
+ return self.config.fingerprint
86
+
87
+ @property
88
+ def calibrated(self) -> bool:
89
+ return self.quantizer.calibrated
90
+
91
+ def calibration_state(self) -> dict[str, list]:
92
+ return self.quantizer.state_dict()
93
+
94
+ def load_calibration(self, state: dict[str, Any]) -> None:
95
+ self.quantizer.set_bounds(state["low"], state["high"])
96
+
97
+ def _quantized_fields(self, controls: np.ndarray, quantize: bool):
98
+ if not quantize:
99
+ return None, None
100
+ tokens = self.quantizer.encode(controls)
101
+ return tokens, self.quantizer.decode(tokens)
102
+
103
+ def encode(self, actions: Any, *, quantize: bool = False) -> SplineParameters:
104
+ """Alias for :meth:`encode_chunk`."""
105
+
106
+ return self.encode_chunk(actions, quantize=quantize)
107
+
108
+
109
+ class UniformBSplineEncoder(BaseSplineEncoder):
110
+ """Double-clamped uniform action-chunk encoder."""
111
+
112
+ def __init__(self, config: UniformBSplineConfig, calibration: dict | None = None):
113
+ self.config = config
114
+ if config.span_length_steps is None:
115
+ self.basis, self.knots = _inclusive_basis(
116
+ config.num_basis, config.degree, config.chunk_size
117
+ )
118
+ self._fit_basis = self.basis
119
+ else:
120
+ self.basis, self._fit_basis, self.knots = _fixed_span_bases(
121
+ config.num_basis, config.degree, config.chunk_size,
122
+ config.span_length_steps,
123
+ )
124
+ self._solver = (
125
+ np.linalg.inv(
126
+ self._fit_basis.T @ self._fit_basis
127
+ + config.regularization * np.eye(config.num_basis)
128
+ )
129
+ @ self._fit_basis.T
130
+ )
131
+ super().__init__()
132
+ if calibration is not None:
133
+ self.load_calibration(calibration)
134
+
135
+ def fit_control_points(self, actions: Any) -> np.ndarray:
136
+ values = _validate_actions(actions, self.config.chunk_size, self.config.action_dim)
137
+ if self.config.span_length_steps is not None and self.config.end_padding:
138
+ values = np.concatenate((values, values[-1:]), axis=0)
139
+ elif len(values) != self._fit_basis.shape[0]:
140
+ raise ValueError("fixed-span fitting requires end_padding=True")
141
+ return self._solver @ values
142
+
143
+ def calibrate(self, chunks: Iterable[Any]) -> None:
144
+ low = high = None
145
+ count = 0
146
+ for chunk in chunks:
147
+ controls = self.fit_control_points(chunk)
148
+ low = controls.copy() if low is None else np.minimum(low, controls)
149
+ high = controls.copy() if high is None else np.maximum(high, controls)
150
+ count += 1
151
+ if count == 0:
152
+ raise ValueError("cannot calibrate from an empty chunk iterable")
153
+ self.quantizer.set_bounds(low, high)
154
+
155
+ def encode_chunk(self, actions: Any, *, quantize: bool = False) -> SplineParameters:
156
+ controls = self.fit_control_points(actions)
157
+ tokens, dequantized = self._quantized_fields(controls, quantize)
158
+ return SplineParameters(
159
+ control_points=controls,
160
+ knots=self.knots * self.config.delta_t,
161
+ degree=self.config.degree,
162
+ sample_period=self.config.delta_t,
163
+ executable_steps=self.config.chunk_size,
164
+ tokenizer_id=self.tokenizer_id,
165
+ tokens=tokens,
166
+ dequantized_control_points=dequantized,
167
+ metadata={
168
+ "mode": self.config.mode,
169
+ "boundary_condition": "double_clamped",
170
+ "inclusive_domain": self.config.span_length_steps is None,
171
+ },
172
+ )
173
+
174
+ def decode_control_points(self, tokens: Any) -> np.ndarray:
175
+ values = np.asarray(tokens)
176
+ expected = (self.config.num_basis, self.config.action_dim)
177
+ if values.shape != expected:
178
+ raise ValueError(f"tokens must have shape {expected}")
179
+ return self.quantizer.decode(values)
180
+
181
+ def decode(self, tokens: Any) -> np.ndarray:
182
+ return self.basis @ self.decode_control_points(tokens)
183
+
184
+ def load_calibration(self, state: dict[str, Any]) -> None:
185
+ super().load_calibration(state)
186
+ expected = (self.config.num_basis, self.config.action_dim)
187
+ if self.quantizer.low.shape != expected:
188
+ raise ValueError(f"uniform calibration must have shape {expected}")
189
+
190
+
191
+ class UniformLeftBSplineEncoder(UniformBSplineEncoder):
192
+ """Fixed-knot left-clamped encoder with right fitting context."""
193
+
194
+ def __init__(self, config: UniformLeftBSplineConfig, calibration: dict | None = None):
195
+ self.config = config
196
+ span = int(config.span_length_steps)
197
+ support_end = config.fitting_num_spans * span
198
+ breaks = np.arange(config.fitting_num_spans + 1, dtype=np.float64) * span
199
+ self.full_knots = np.concatenate((
200
+ np.zeros(config.degree),
201
+ breaks,
202
+ np.full(config.degree, support_end),
203
+ ))
204
+ self._fit_basis = _design(
205
+ np.arange(config.fitting_chunk_size + 1, dtype=np.float64),
206
+ self.full_knots,
207
+ config.degree,
208
+ )
209
+ self.full_basis = _design(
210
+ np.arange(config.fitting_chunk_size, dtype=np.float64),
211
+ self.full_knots,
212
+ config.degree,
213
+ )
214
+ self.knots = self.full_knots[: config.num_basis + config.degree + 1].copy()
215
+ self.basis = _design(
216
+ np.arange(config.chunk_size, dtype=np.float64), self.knots, config.degree
217
+ )
218
+ regularized = (
219
+ self._fit_basis.T @ self._fit_basis
220
+ + config.regularization * np.eye(config.fitting_num_basis)
221
+ )
222
+ self._solver = np.linalg.solve(regularized, self._fit_basis.T)
223
+ self._retained_control_indices = np.arange(config.num_basis, dtype=np.int64)
224
+ BaseSplineEncoder.__init__(self)
225
+ if calibration is not None:
226
+ self.load_calibration(calibration)
227
+
228
+ @property
229
+ def retained_control_indices(self) -> np.ndarray:
230
+ return self._retained_control_indices.copy()
231
+
232
+ def fit_full_control_points(self, actions: Any) -> np.ndarray:
233
+ values = _validate_actions(
234
+ actions, self.config.fitting_chunk_size, self.config.action_dim
235
+ )
236
+ if not self.config.end_padding:
237
+ raise ValueError("uniform_left endpoint-exclusive fitting needs end_padding=True")
238
+ return self._solver @ np.concatenate((values, values[-1:]), axis=0)
239
+
240
+ def fit_control_points(self, actions: Any) -> np.ndarray:
241
+ return self.fit_full_control_points(actions)[self._retained_control_indices]
242
+
243
+ def geometry(self) -> SplineGeometry:
244
+ durations = np.full(
245
+ self.config.num_basis, int(self.config.span_length_steps), dtype=np.int64
246
+ )
247
+ distinct = np.r_[0, np.cumsum(durations)].astype(np.int64)
248
+ knots = np.rint(self.knots).astype(np.int64)
249
+ greville = np.asarray([
250
+ knots[index + 1 : index + self.config.degree + 1].mean()
251
+ for index in range(self.config.num_basis)
252
+ ])
253
+ return SplineGeometry(
254
+ duration_steps=durations,
255
+ distinct_steps=distinct,
256
+ knot_steps=knots,
257
+ greville_steps=greville,
258
+ executable_spans=self.config.executable_spans,
259
+ right_context_spans=self.config.right_context_spans,
260
+ executable_end_step=self.config.chunk_size,
261
+ support_end_step=self.config.support_end_step,
262
+ )
263
+
264
+ def encode_chunk(self, actions: Any, *, quantize: bool = False) -> SplineParameters:
265
+ controls = self.fit_control_points(actions)
266
+ tokens, dequantized = self._quantized_fields(controls, quantize)
267
+ geometry = self.geometry()
268
+ return SplineParameters(
269
+ control_points=controls,
270
+ knots=self.knots * self.config.delta_t,
271
+ degree=self.config.degree,
272
+ sample_period=self.config.delta_t,
273
+ executable_steps=self.config.chunk_size,
274
+ tokenizer_id=self.tokenizer_id,
275
+ duration_steps=geometry.duration_steps,
276
+ tokens=tokens,
277
+ dequantized_control_points=dequantized,
278
+ metadata={"mode": self.config.mode,
279
+ "boundary_condition": "left_clamped_right_open"},
280
+ )
281
+
282
+ def decode_spline(self, tokens: Any) -> BSpline:
283
+ return BSpline(
284
+ self.knots * self.config.delta_t,
285
+ self.decode_control_points(tokens),
286
+ self.config.degree,
287
+ extrapolate=False,
288
+ axis=0,
289
+ )
290
+
291
+ def decode(self, tokens: Any) -> np.ndarray:
292
+ times = np.arange(self.config.chunk_size) * self.config.delta_t
293
+ return np.asarray(self.decode_spline(tokens)(times), dtype=np.float64)
294
+
295
+
296
+ class AdaptiveBSplineEncoder(BaseSplineEncoder):
297
+ """Adaptive episode encoder with exact observation-aligned subdivision."""
298
+
299
+ def __init__(self, config: AdaptiveBSplineConfig, calibration: dict | None = None):
300
+ self.config = config
301
+ super().__init__()
302
+ if calibration is not None:
303
+ self.load_calibration(calibration)
304
+
305
+ def max_episode_control_points(self, num_steps: int) -> int | None:
306
+ if not self.config.limit_global_knot_density:
307
+ return None
308
+ if num_steps <= self.config.degree:
309
+ raise ValueError("episode is too short for the configured degree")
310
+ spans = int(np.floor(
311
+ (num_steps - 1) / self.config.average_span_steps
312
+ + self.config.alignment_tolerance
313
+ ))
314
+ return max(self.config.num_basis, spans + self.config.degree)
315
+
316
+ def _refit_with_repeated_tail(self, spline, actions, timestamps):
317
+ if not self.config.end_padding:
318
+ return spline
319
+ degree = int(spline.k)
320
+ knots = np.asarray(spline.t, dtype=np.float64)
321
+ end = float(knots[-degree - 1])
322
+ padding_steps = self.config.tail_padding_spans * self.config.average_span_steps
323
+ final = end + padding_steps * self.config.delta_t
324
+ extended_times = np.concatenate((
325
+ timestamps,
326
+ end + np.arange(1, padding_steps + 1) * self.config.delta_t,
327
+ ))
328
+ extended_actions = np.concatenate((
329
+ actions,
330
+ np.repeat(actions[-1:], padding_steps, axis=0),
331
+ ))
332
+ extended_knots = np.concatenate((
333
+ knots[: -(degree + 1)],
334
+ end + np.arange(self.config.tail_padding_spans)
335
+ * self.config.average_span_steps * self.config.delta_t,
336
+ np.repeat(final, degree + 1),
337
+ ))
338
+ subdivisions = degree + 1
339
+ dense_count = (len(actions) - 1 + padding_steps) * subdivisions + 1
340
+ dense_times = np.linspace(float(timestamps[0]), final, dense_count)
341
+ dense_actions = np.empty((dense_count, actions.shape[1]), dtype=np.float64)
342
+ original = dense_times <= end
343
+ dense_actions[original] = spline(dense_times[original])
344
+ dense_actions[~original] = actions[-1]
345
+ dense_actions[np.arange(len(actions)) * subdivisions] = actions
346
+ extended = make_lsq_spline(
347
+ dense_times, dense_actions, extended_knots, k=degree, axis=0
348
+ )
349
+ residual = np.asarray(extended(extended_times) - extended_actions)
350
+ if not np.all(np.isfinite(extended.c)) or not np.all(np.isfinite(residual)):
351
+ raise RuntimeError("adaptive repeated-action tail refit is non-finite")
352
+ return extended
353
+
354
+ def episode_control_points(self, actions: Any):
355
+ values = _validate_actions(actions, None, self.config.action_dim)
356
+ if len(values) <= self.config.degree:
357
+ return []
358
+ timestamps = np.arange(len(values), dtype=np.float64) * self.config.delta_t
359
+ fit = fit_adaptive_bspline(
360
+ values,
361
+ timestamps=timestamps,
362
+ degree=self.config.degree,
363
+ max_error=self.config.fit_tolerance,
364
+ smoothing=self.config.smoothing,
365
+ max_control_points=self.max_episode_control_points(len(values)),
366
+ knot_insertion_excluded_dimensions=(
367
+ self.config.knot_insertion_excluded_dimensions
368
+ ),
369
+ )
370
+ spline = self._refit_with_repeated_tail(fit.spline, values, timestamps)
371
+ breaks = np.unique(spline.t)
372
+ records = []
373
+ for observation, timestamp in enumerate(timestamps):
374
+ left = np.searchsorted(breaks, timestamp, side="right") - 1
375
+ if left < 0 or left + self.config.num_basis >= len(breaks):
376
+ continue
377
+ prefix = extract_left_clamped_prefix(
378
+ spline, float(timestamp), num_knot_spans=self.config.num_basis
379
+ )
380
+ durations = encode_knot_durations(
381
+ prefix.distinct_knots,
382
+ delta_t=self.config.delta_t,
383
+ tolerance=self.config.alignment_tolerance,
384
+ max_duration=self.config.max_duration,
385
+ )
386
+ if len(prefix.control_points) != self.config.num_basis:
387
+ raise RuntimeError("adaptive prefix shape mismatch")
388
+ records.append((observation, prefix.control_points.copy(), durations))
389
+ return records
390
+
391
+ def calibrate(self, episodes: Iterable[Any]) -> None:
392
+ low = high = None
393
+ count = 0
394
+ for episode in episodes:
395
+ for _, controls, _ in self.episode_control_points(episode):
396
+ local_low, local_high = controls.min(axis=0), controls.max(axis=0)
397
+ low = local_low.copy() if low is None else np.minimum(low, local_low)
398
+ high = local_high.copy() if high is None else np.maximum(high, local_high)
399
+ count += 1
400
+ if count == 0:
401
+ raise ValueError("no valid adaptive records to calibrate")
402
+ self.quantizer.set_bounds(low, high)
403
+
404
+ def geometry(self, duration_steps: Any) -> SplineGeometry:
405
+ durations = np.asarray(duration_steps)
406
+ if durations.shape != (self.config.num_basis,) or not np.issubdtype(
407
+ durations.dtype, np.integer
408
+ ) or np.any(durations < 1):
409
+ raise ValueError("duration_steps must be positive integers matching num_basis")
410
+ durations = durations.astype(np.int64, copy=False)
411
+ distinct = np.r_[0, np.cumsum(durations)].astype(np.int64)
412
+ knots = np.r_[np.zeros(self.config.degree + 1, dtype=np.int64), distinct[1:]]
413
+ greville = np.asarray([
414
+ knots[index + 1 : index + self.config.degree + 1].mean()
415
+ for index in range(self.config.num_basis)
416
+ ])
417
+ executable_spans = self.config.num_basis - self.config.degree
418
+ return SplineGeometry(
419
+ duration_steps=durations.copy(),
420
+ distinct_steps=distinct,
421
+ knot_steps=knots,
422
+ greville_steps=greville,
423
+ executable_spans=executable_spans,
424
+ right_context_spans=self.config.degree,
425
+ executable_end_step=int(distinct[executable_spans]),
426
+ support_end_step=int(distinct[-1]),
427
+ )
428
+
429
+ def _make_result(self, observation: int, controls: np.ndarray,
430
+ durations: np.ndarray, quantize: bool) -> SplineParameters:
431
+ geometry = self.geometry(durations)
432
+ tokens, dequantized = self._quantized_fields(controls, quantize)
433
+ return SplineParameters(
434
+ control_points=controls,
435
+ knots=geometry.knot_steps.astype(np.float64) * self.config.delta_t,
436
+ degree=self.config.degree,
437
+ sample_period=self.config.delta_t,
438
+ executable_steps=geometry.executable_end_step,
439
+ tokenizer_id=self.tokenizer_id,
440
+ observation_index=observation,
441
+ duration_steps=durations,
442
+ tokens=tokens,
443
+ dequantized_control_points=dequantized,
444
+ metadata={"mode": self.config.mode,
445
+ "boundary_condition": "left_clamped_right_open",
446
+ "policy_layout": "control_point_duration_interleaved_v1",
447
+ "knot_insertion_excluded_dimensions": list(
448
+ self.config.knot_insertion_excluded_dimensions
449
+ )},
450
+ )
451
+
452
+ def encode_episode(self, actions: Any, *, quantize: bool = False):
453
+ return [
454
+ self._make_result(observation, controls, durations, quantize)
455
+ for observation, controls, durations in self.episode_control_points(actions)
456
+ ]
457
+
458
+ def encode_chunk(self, actions: Any, *, quantize: bool = False) -> SplineParameters:
459
+ values = _validate_actions(
460
+ actions, self.config.input_chunk_size, self.config.action_dim
461
+ )
462
+ records = self.encode_episode(values, quantize=quantize)
463
+ if not records or records[0].observation_index != 0:
464
+ raise RuntimeError("adaptive chunk did not produce an observation-zero prefix")
465
+ return records[0]
466
+
467
+ def decode_control_points(self, tokens: Any) -> np.ndarray:
468
+ values = np.asarray(tokens)
469
+ expected = (self.config.num_basis, self.config.action_dim)
470
+ if values.shape != expected:
471
+ raise ValueError(f"tokens must have shape {expected}")
472
+ return self.quantizer.decode(values)
473
+
474
+ def decode_spline(self, tokens: Any, duration_steps: Any) -> BSpline:
475
+ geometry = self.geometry(duration_steps)
476
+ return BSpline(
477
+ geometry.knot_steps.astype(np.float64) * self.config.delta_t,
478
+ self.decode_control_points(tokens),
479
+ self.config.degree,
480
+ extrapolate=False,
481
+ axis=0,
482
+ )
483
+
484
+ def decode(self, tokens: Any, duration_steps: Any,
485
+ samples: int | None = None) -> np.ndarray:
486
+ geometry = self.geometry(duration_steps)
487
+ count = geometry.executable_end_step if samples is None else int(samples)
488
+ if count < 1:
489
+ raise ValueError("samples must be positive")
490
+ steps = np.linspace(0.0, geometry.executable_end_step, count, endpoint=False)
491
+ return np.asarray(
492
+ self.decode_spline(tokens, duration_steps)(steps * self.config.delta_t),
493
+ dtype=np.float64,
494
+ )
495
+
496
+ def load_calibration(self, state: dict[str, Any]) -> None:
497
+ super().load_calibration(state)
498
+ if self.quantizer.low.shape != (self.config.action_dim,):
499
+ raise ValueError("adaptive calibration must be per action dimension")
500
+
501
+
502
+ UniformDoubleBSplineEncoder = UniformBSplineEncoder
503
+ AdaptiveLeftBSplineEncoder = AdaptiveBSplineEncoder
504
+
505
+
506
+ def create_encoder(config: Config, calibration: dict | None = None) -> BaseSplineEncoder:
507
+ if isinstance(config, UniformLeftBSplineConfig):
508
+ return UniformLeftBSplineEncoder(config, calibration)
509
+ if isinstance(config, UniformBSplineConfig):
510
+ return UniformBSplineEncoder(config, calibration)
511
+ if isinstance(config, AdaptiveBSplineConfig):
512
+ return AdaptiveBSplineEncoder(config, calibration)
513
+ raise TypeError(f"unsupported configuration: {type(config).__name__}")
514
+
515
+
516
+ def encode_action_chunk(
517
+ actions: Any,
518
+ config: Config,
519
+ *,
520
+ quantize: bool = False,
521
+ calibration: dict | None = None,
522
+ ) -> SplineParameters:
523
+ """One-call action-chunk encoding convenience API."""
524
+
525
+ return create_encoder(config, calibration).encode_chunk(actions, quantize=quantize)
526
+
527
+
528
+ __all__ = [
529
+ "AdaptiveBSplineEncoder", "AdaptiveLeftBSplineEncoder", "BaseSplineEncoder",
530
+ "UniformBSplineEncoder", "UniformDoubleBSplineEncoder",
531
+ "UniformLeftBSplineEncoder", "create_encoder", "encode_action_chunk",
532
+ ]