outsider86 commited on
Commit
0577fe9
·
verified ·
1 Parent(s): 50716ca

Package exact adaptive implementation: code/BSplineEncoder/src/spline_encoder/adaptive.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/adaptive.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reference-compatible global adaptive B-spline fitting helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Iterable
7
+
8
+ import numpy as np
9
+ from scipy.interpolate import BSpline, generate_knots, make_lsq_spline
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class AdaptiveBSplineFit:
14
+ spline: BSpline
15
+ timestamps: np.ndarray
16
+ actions: np.ndarray
17
+ knots: np.ndarray
18
+ control_points: np.ndarray
19
+ degree: int
20
+ max_abs_error: float
21
+ weighted_squared_error: float
22
+ converged: bool
23
+ candidates_evaluated: int
24
+
25
+
26
+ def fit_adaptive_bspline(
27
+ actions,
28
+ *,
29
+ timestamps=None,
30
+ degree: int = 3,
31
+ max_error: float = 0.01,
32
+ smoothing: float = 1e-12,
33
+ weights=None,
34
+ max_control_points: int | None = None,
35
+ knot_insertion_excluded_dimensions=(),
36
+ ) -> AdaptiveBSplineFit:
37
+ values = np.asarray(actions, dtype=np.float64)
38
+ if values.ndim != 2 or values.shape[0] <= degree or values.shape[1] == 0:
39
+ raise ValueError("actions must have shape (steps > degree, action_dim)")
40
+ if not np.all(np.isfinite(values)):
41
+ raise ValueError("actions must be finite")
42
+ times = (np.arange(len(values), dtype=np.float64) if timestamps is None
43
+ else np.asarray(timestamps, dtype=np.float64))
44
+ if times.shape != (len(values),) or np.any(np.diff(times) <= 0):
45
+ raise ValueError("timestamps must be strictly increasing with one per action")
46
+ weight_array = None if weights is None else np.asarray(weights, dtype=np.float64)
47
+ if weight_array is not None and (
48
+ weight_array.shape != (len(values),) or np.any(weight_array <= 0)
49
+ ):
50
+ raise ValueError("weights must be positive with one value per action")
51
+ if degree < 1 or degree > 5 or max_error <= 0 or smoothing < 0:
52
+ raise ValueError("invalid FITPACK configuration")
53
+ if max_control_points is not None and max_control_points < degree + 1:
54
+ raise ValueError("max_control_points must be at least degree + 1")
55
+
56
+ excluded = tuple(int(index) for index in knot_insertion_excluded_dimensions)
57
+ if len(set(excluded)) != len(excluded):
58
+ raise ValueError("knot insertion excluded dimensions must be unique")
59
+ if any(index < 0 or index >= values.shape[1] for index in excluded):
60
+ raise ValueError("a knot insertion excluded dimension is out of range")
61
+ included = tuple(index for index in range(values.shape[1]) if index not in excluded)
62
+ if not included:
63
+ raise ValueError("at least one action dimension must drive adaptive knot insertion")
64
+ # SciPy's FITPACK QR path requires a C-contiguous 2-D ordinate array.
65
+ knot_values = np.ascontiguousarray(values[:, included], dtype=np.float64)
66
+
67
+ candidates: Iterable[np.ndarray] = generate_knots(
68
+ times,
69
+ knot_values,
70
+ w=weight_array,
71
+ k=degree,
72
+ s=smoothing,
73
+ nest=None if max_control_points is None else max_control_points + degree + 1,
74
+ )
75
+ selected = selected_knots = None
76
+ selected_max = selected_weighted = float("inf")
77
+ converged = False
78
+ evaluated = 0
79
+ for candidate in candidates:
80
+ knots = np.asarray(candidate, dtype=np.float64)
81
+ spline = make_lsq_spline(times, knot_values, knots, k=degree, w=weight_array)
82
+ residual = np.asarray(spline(times) - knot_values, dtype=np.float64)
83
+ candidate_max = float(np.max(np.abs(residual)))
84
+ candidate_weighted = float(np.sum(
85
+ residual**2 if weight_array is None
86
+ else (weight_array[:, None] * residual) ** 2
87
+ ))
88
+ selected, selected_knots = spline, knots
89
+ selected_max, selected_weighted = candidate_max, candidate_weighted
90
+ evaluated += 1
91
+ if candidate_max < max_error:
92
+ converged = True
93
+ break
94
+ if selected is None:
95
+ raise RuntimeError("FITPACK generated no candidate knot vector")
96
+ # Excluded channels do not participate in candidate generation or the
97
+ # stopping criterion. Fit all channels together exactly once after the
98
+ # final knot vector has been selected so column order is preserved.
99
+ if excluded:
100
+ selected = make_lsq_spline(
101
+ times, values, selected_knots, k=degree, w=weight_array
102
+ )
103
+ return AdaptiveBSplineFit(
104
+ spline=selected,
105
+ timestamps=times.copy(),
106
+ actions=values.copy(),
107
+ knots=selected_knots.copy(),
108
+ control_points=np.asarray(selected.c, dtype=np.float64).copy(),
109
+ degree=degree,
110
+ max_abs_error=selected_max,
111
+ weighted_squared_error=selected_weighted,
112
+ converged=converged,
113
+ candidates_evaluated=evaluated,
114
+ )
115
+
116
+
117
+ def encode_knot_durations(
118
+ distinct_knots,
119
+ *,
120
+ delta_t: float,
121
+ tolerance: float = 1e-8,
122
+ max_duration: int | None = None,
123
+ ) -> np.ndarray:
124
+ knots = np.asarray(distinct_knots, dtype=np.float64)
125
+ if knots.ndim != 1 or len(knots) < 2 or delta_t <= 0:
126
+ raise ValueError("invalid knots or delta_t")
127
+ if not np.isclose(knots[0], 0.0, rtol=0.0, atol=tolerance):
128
+ raise ValueError("first local knot must be zero")
129
+ gaps = np.diff(knots) / delta_t
130
+ rounded = np.rint(gaps)
131
+ if not np.allclose(gaps, rounded, rtol=0.0, atol=tolerance):
132
+ raise ValueError("knot gaps are not aligned to integer timesteps")
133
+ durations = rounded.astype(np.int64)
134
+ if np.any(durations < 1):
135
+ raise ValueError("knot durations must be positive")
136
+ if max_duration is not None and np.any(durations > max_duration):
137
+ raise ValueError("knot duration exceeds configured maximum")
138
+ return durations
139
+
140
+
141
+ __all__ = ["AdaptiveBSplineFit", "encode_knot_durations", "fit_adaptive_bspline"]