outsider86 commited on
Commit
14e702c
·
verified ·
1 Parent(s): 4f11a75

Package exact adaptive implementation: code/BSplineEncoder/src/spline_encoder/result.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/result.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Continuous-first result objects returned by SplineEncoder."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Mapping
7
+
8
+ import numpy as np
9
+ from numpy.typing import NDArray
10
+ from scipy.interpolate import BSpline
11
+
12
+
13
+ FloatArray = NDArray[np.float64]
14
+ IntArray = NDArray[np.int64]
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class SplineParameters:
19
+ """One observation-aligned local action spline.
20
+
21
+ ``control_points`` and ``knots`` always contain the continuous
22
+ representation. ``tokens`` is populated only when quantization was
23
+ explicitly requested. Knots are expressed in seconds; ``knot_steps``
24
+ exposes their action-timestep equivalent.
25
+ """
26
+
27
+ control_points: FloatArray
28
+ knots: FloatArray
29
+ degree: int
30
+ sample_period: float
31
+ executable_steps: int
32
+ tokenizer_id: str
33
+ observation_index: int | None = None
34
+ duration_steps: IntArray | None = None
35
+ tokens: IntArray | None = None
36
+ dequantized_control_points: FloatArray | None = None
37
+ metadata: Mapping[str, Any] = field(default_factory=dict)
38
+
39
+ def __post_init__(self) -> None:
40
+ controls = np.asarray(self.control_points, dtype=np.float64)
41
+ knots = np.asarray(self.knots, dtype=np.float64)
42
+ if controls.ndim != 2 or controls.shape[0] == 0 or controls.shape[1] == 0:
43
+ raise ValueError("control_points must have shape (num_basis, action_dim)")
44
+ if knots.ndim != 1 or len(knots) != len(controls) + self.degree + 1:
45
+ raise ValueError("knots must have num_basis + degree + 1 elements")
46
+ if np.any(np.diff(knots) < 0) or not np.all(np.isfinite(knots)):
47
+ raise ValueError("knots must be finite and nondecreasing")
48
+ if not np.all(np.isfinite(controls)):
49
+ raise ValueError("control_points must be finite")
50
+ if self.sample_period <= 0 or self.executable_steps < 1:
51
+ raise ValueError("sample_period and executable_steps must be positive")
52
+ if self.tokens is not None and np.asarray(self.tokens).shape != controls.shape:
53
+ raise ValueError("tokens must match control_points shape")
54
+ if (self.dequantized_control_points is not None and
55
+ np.asarray(self.dequantized_control_points).shape != controls.shape):
56
+ raise ValueError("dequantized_control_points must match controls")
57
+ object.__setattr__(self, "control_points", controls.copy())
58
+ object.__setattr__(self, "knots", knots.copy())
59
+ if self.duration_steps is not None:
60
+ durations = np.asarray(self.duration_steps)
61
+ if durations.ndim != 1 or not np.issubdtype(durations.dtype, np.integer):
62
+ raise ValueError("duration_steps must be a one-dimensional integer array")
63
+ if np.any(durations < 1):
64
+ raise ValueError("duration_steps must be positive")
65
+ object.__setattr__(self, "duration_steps", durations.astype(np.int64, copy=True))
66
+ if self.tokens is not None:
67
+ object.__setattr__(self, "tokens", np.asarray(self.tokens, dtype=np.int64).copy())
68
+ if self.dequantized_control_points is not None:
69
+ object.__setattr__(
70
+ self,
71
+ "dequantized_control_points",
72
+ np.asarray(self.dequantized_control_points, dtype=np.float64).copy(),
73
+ )
74
+
75
+ @property
76
+ def action_dim(self) -> int:
77
+ return int(self.control_points.shape[1])
78
+
79
+ @property
80
+ def num_basis(self) -> int:
81
+ return int(self.control_points.shape[0])
82
+
83
+ @property
84
+ def knot_steps(self) -> FloatArray:
85
+ return self.knots / self.sample_period
86
+
87
+ def scipy_spline(self, *, dequantized: bool = False) -> BSpline:
88
+ """Build a SciPy spline without extrapolation."""
89
+
90
+ controls = self.control_points
91
+ if dequantized:
92
+ if self.dequantized_control_points is None:
93
+ raise ValueError("this result has no quantized representation")
94
+ controls = self.dequantized_control_points
95
+ return BSpline(
96
+ self.knots,
97
+ controls,
98
+ self.degree,
99
+ extrapolate=False,
100
+ axis=0,
101
+ )
102
+
103
+ def interleaved_control_durations(self, *, dequantized: bool = False) -> FloatArray:
104
+ """Return adaptive rows as ``[control dimensions..., knot duration]``.
105
+
106
+ Duration row ``i`` is the integer timestep gap from distinct knot
107
+ ``i`` to ``i + 1``. This is the canonical
108
+ ``control_point_duration_interleaved_v1`` policy ordering. The lossless
109
+ ``control_points`` and full repeated ``knots`` remain separately
110
+ available on this object.
111
+ """
112
+ if self.duration_steps is None:
113
+ raise ValueError("fixed-knot spline has no adaptive durations to interleave")
114
+ if len(self.duration_steps) != self.num_basis:
115
+ raise ValueError("adaptive durations must match the number of control points")
116
+ controls = self.control_points
117
+ if dequantized:
118
+ if self.dequantized_control_points is None:
119
+ raise ValueError("this result has no quantized representation")
120
+ controls = self.dequantized_control_points
121
+ return np.concatenate(
122
+ (controls, self.duration_steps.astype(np.float64)[:, None]), axis=1
123
+ )
124
+
125
+ def decode(
126
+ self,
127
+ *,
128
+ samples: int | None = None,
129
+ dequantized: bool = False,
130
+ ) -> FloatArray:
131
+ """Sample the executable curve at endpoint-exclusive native times."""
132
+
133
+ count = self.executable_steps if samples is None else int(samples)
134
+ if count < 1:
135
+ raise ValueError("samples must be positive")
136
+ if self.metadata.get("inclusive_domain", False):
137
+ end = (self.executable_steps - 1) * self.sample_period
138
+ times = np.linspace(0.0, end, count, endpoint=True)
139
+ else:
140
+ end = self.executable_steps * self.sample_period
141
+ times = np.linspace(0.0, end, count, endpoint=False)
142
+ return np.asarray(self.scipy_spline(dequantized=dequantized)(times), dtype=np.float64)
143
+
144
+
145
+ @dataclass(frozen=True)
146
+ class SplineGeometry:
147
+ duration_steps: IntArray
148
+ distinct_steps: IntArray
149
+ knot_steps: IntArray
150
+ greville_steps: FloatArray
151
+ executable_spans: int
152
+ right_context_spans: int
153
+ executable_end_step: int
154
+ support_end_step: int
155
+
156
+
157
+ __all__ = ["SplineGeometry", "SplineParameters"]