sidereon_core/sp3/interp.rs
1//! SP3 arbitrary-epoch position/clock interpolation.
2//!
3//! Two channels with different recipes, each validated against its correct
4//! external reference (the two-bars doctrine: capability vs the deployed
5//! reference, not a bit-exact port of a convenient primitive):
6//!
7//! # Position channel: sliding-window Lagrange/Neville (RTKLIB recipe)
8//!
9//! The satellite position is interpolated with a sliding-window high-degree
10//! Lagrange (Neville) polynomial matching RTKLIB `preceph.c` pephpos/interppol:
11//! the contiguous run of nodes bracketing the query, the RTKLIB window of up to
12//! 11 nodes (degree 10) centred on the query, an `OMEGA_E_DOT` per-node
13//! earth-rotation correction into the query-epoch frame, then Neville evaluation
14//! per axis. This is the IGS-standard orbit interpolation. It replaced a global
15//! not-a-knot cubic spline, which is only degree 3 over the whole day and erred
16//! ~200 m at the day boundary and across coverage gaps (a query deep inside a
17//! coverage gap is now rejected, never interpolated across). Validated against
18//! the RTKLIB reference (`interp_tests`) and end-to-end against ZIM2 PPP truth.
19//!
20//! # Clock channel: not-a-knot cubic spline (gnssanalysis recipe)
21//!
22//! The clock is locally smooth, so it keeps the not-a-knot cubic spline matching
23//! `scipy.interpolate.CubicSpline(x, y)` with gnssanalysis defaults
24//! (`bc_type="not-a-knot"`, `extrapolate=true`), evaluated at the query, with
25//! clock-event (`E`) arc splitting. BLAS-free (the not-a-knot solve dispatches
26//! to LAPACK `dgtsv`), a legitimate 0-ULP target against scipy.
27//!
28//! # Node substrate (load-bearing for 0-ULP)
29//!
30//! Nodes are **integer seconds since J2000** (2000-01-01 12:00:00 in the file's
31//! own time scale), exactly as gnssanalysis builds them in `datetime2j2000`
32//! (`gn_datetime.py:286-288`): epochs floored to whole seconds, differenced
33//! against the J2000 origin, kept as `i64`, then promoted to `f64` on entry to
34//! the spline. This module reconstructs the same `i64`-seconds axis from the
35//! parser's [`Instant`] epochs (NOT fractional JD, NOT nanoseconds), so the
36//! spline coefficients are bit-identical.
37//!
38//! J2000 = JD 2451545.0. Seconds-since-J2000 for a split JD `(whole, frac)` is
39//! computed in a cancellation-safe way and floored to whole seconds.
40//!
41//! # Units
42//!
43//! The spline is fit in the SP3-native units the reference carries -
44//! **kilometers** for position, **microseconds** for clock - and the evaluated
45//! result is converted to the public API boundary (**meters**, **seconds**) by a
46//! **single final multiply** (`* 1000.0`, `* 1e-6`). The conversion happens
47//! AFTER evaluation, never before the fit; this operation order is pinned.
48//!
49//! # Clock interpolation near gaps / discontinuities
50//!
51//! gnssanalysis defines none, so the policy is authored in the canonical recipe
52//! and matched here:
53//!
54//! - Clock uses the **same** `CubicSpline` construction over the nodes that have
55//! a clock estimate (the bad-clock sentinel yields no clock node).
56//! - Position and clock node sets are independent.
57//! - Position is never split (orbits are continuous through clock resets).
58//! - Clock interpolation does **not** cross a clock-event (`E`) epoch: the arc
59//! is split at each `E`-flagged epoch and the clock spline is fit on the
60//! contiguous sub-arc containing the query epoch.
61
62use crate::astro::time::model::{Instant, InstantRepr};
63
64use crate::astro::time::civil::j2000_seconds_from_split;
65use crate::constants::{KM_TO_M, OMEGA_E_DOT_RAD_S, US_TO_S};
66use crate::frame::ItrfPositionM;
67use crate::id::GnssSatelliteId;
68use crate::sp3::{Sp3, Sp3State};
69use crate::validate;
70use crate::{Error, Result};
71
72impl Sp3 {
73 /// The product's parsed epochs as seconds since J2000, in the file's own time
74 /// scale, ascending.
75 ///
76 /// This is the exact query axis [`Sp3::position_at_j2000_seconds`] interpolates
77 /// against (each epoch converted by the same [`instant_to_j2000_seconds`] used
78 /// for the spline nodes, NOT floored), so a caller can read the grid here, form
79 /// query times on it, and feed them straight back without a Julian-date
80 /// round-trip. An epoch whose representation cannot be mapped to J2000 seconds
81 /// is skipped (SP3 epochs are always Julian-date, so on real data this returns
82 /// one value per epoch).
83 pub fn epochs_j2000_seconds(&self) -> Vec<f64> {
84 self.epochs
85 .iter()
86 .filter_map(instant_to_j2000_seconds)
87 .collect()
88 }
89
90 /// Interpolate the state of `sat` at an arbitrary `epoch`.
91 ///
92 /// Reproduces the pinned `scipy.interpolate.CubicSpline` recipe (see module
93 /// docs) bit-for-bit: a per-axis not-a-knot cubic spline over the
94 /// J2000-integer-second node axis, evaluated at `epoch`, with the unit
95 /// conversion as a single final multiply.
96 ///
97 /// - `position` is always returned (interpolated from all position nodes of
98 /// `sat`), in meters, ITRF/IGS ECEF.
99 /// - `clock_s` is `Some` when `sat` has at least two clock nodes in the
100 /// clock sub-arc containing `epoch` (after clock-event splitting); `None`
101 /// otherwise.
102 /// - `velocity` / `clock_rate_s_s` are `None` (this API interpolates the
103 /// position/clock product; velocity products are a separate concern).
104 /// - `flags` are defaulted (an interpolated state is synthetic, not a record).
105 ///
106 /// Errors:
107 /// - [`Error::UnknownSatellite`] if `sat` has no position nodes.
108 /// - [`Error::EpochOutOfRange`] if fewer than two position nodes exist (a
109 /// spline needs at least two points) or the epoch is not representable.
110 /// - [`Error::InvalidInput`] if `epoch` is tagged with a different time
111 /// scale than the SP3 product.
112 pub fn position(&self, sat: GnssSatelliteId, epoch: Instant) -> Result<Sp3State> {
113 if epoch.scale != self.header.time_scale {
114 return Err(Error::InvalidInput(format!(
115 "SP3 query time scale {} does not match product time scale {}",
116 epoch.scale.abbrev(),
117 self.header.time_scale.abbrev()
118 )));
119 }
120 let query = instant_to_j2000_seconds(&epoch).ok_or(Error::EpochOutOfRange)?;
121 self.position_at_j2000_seconds(sat, query)
122 }
123
124 /// Interpolate the state of `sat` at an arbitrary J2000-second epoch
125 /// supplied directly as an `f64`.
126 ///
127 /// Identical to [`Sp3::position`] except the query is the seconds-since-J2000
128 /// value as already computed by the caller, rather than derived from an
129 /// [`Instant`]. The transmit-time iteration of the SPP residual carries the
130 /// epoch as a J2000-second `f64` (`t_tx = t_rx - rho/c`) and must feed that
131 /// exact value to the spline, with no Julian-date round-trip in the loop, so
132 /// the interpolated position/clock match the reference recipe bit-for-bit.
133 ///
134 /// Errors:
135 /// - [`Error::InvalidInput`] if `query` is NaN or infinite.
136 pub fn position_at_j2000_seconds(&self, sat: GnssSatelliteId, query: f64) -> Result<Sp3State> {
137 // Gather this satellite's position nodes (x = J2000 seconds, y = km),
138 // in ascending epoch order, skipping epochs where the satellite has no
139 // record. Track clock nodes and clock-event epochs alongside.
140 let mut pos_x: Vec<f64> = Vec::new();
141 let mut pos_kx: Vec<f64> = Vec::new();
142 let mut pos_ky: Vec<f64> = Vec::new();
143 let mut pos_kz: Vec<f64> = Vec::new();
144 // Clock nodes: (x_seconds, clock_us, is_clock_event_epoch).
145 let mut clk_nodes: Vec<(f64, f64, bool)> = Vec::new();
146
147 for (idx, ep) in self.epochs.iter().enumerate() {
148 // Node axis: floored to whole seconds to match gnssanalysis
149 // datetime2j2000 (the query, below, is NOT floored).
150 let xi = match instant_to_j2000_seconds(ep) {
151 Some(v) => v.floor(),
152 None => continue,
153 };
154 // Use the parser's NATIVE km/us node values (exact ASCII->f64, as
155 // gnssanalysis read_sp3 carries them). Reconstructing km from the
156 // public meters (km->m->km) drifts up to 1 ULP and breaks parity;
157 // the *1000 / *1e-6 happens once, AFTER eval. interp_raw is
158 // populated only from real position records, so a velocity-only
159 // (fabricated) state never enters the spline.
160 let Some(raw) = self.interp_raw[idx].get(&sat) else {
161 continue;
162 };
163 pos_x.push(xi);
164 pos_kx.push(raw.km[0]);
165 pos_ky.push(raw.km[1]);
166 pos_kz.push(raw.km[2]);
167
168 if let Some(clk_us) = raw.clock_us {
169 clk_nodes.push((xi, clk_us, raw.clock_event));
170 }
171 }
172
173 interpolate_precise_state(sat, &pos_x, &pos_kx, &pos_ky, &pos_kz, &clk_nodes, query)
174 }
175}
176
177/// Interpolate a satellite state from already-gathered native-unit nodes.
178///
179/// This is the shared interpolation substrate. Both the SP3-parsed source
180/// ([`Sp3::position_at_j2000_seconds`]) and the sample-backed source
181/// ([`crate::sp3::PreciseEphemerisSamples`]) gather the same node vectors
182/// (ascending floored J2000 seconds `x`; native km `kx/ky/kz`; native
183/// `(x, clock_us, clock_event)` clock nodes) and drive this one function, so a
184/// source built from samples produces byte-identical states to the SP3 source
185/// those samples serialize to.
186///
187/// Inputs are the file-native units the reference recipes consume (km for
188/// position, microseconds for clock); the single final unit multiply to meters /
189/// seconds happens inside the position/clock evaluators, exactly as the SP3 path
190/// requires for 0-ULP parity.
191pub(super) fn interpolate_precise_state(
192 sat: GnssSatelliteId,
193 pos_x: &[f64],
194 pos_kx: &[f64],
195 pos_ky: &[f64],
196 pos_kz: &[f64],
197 clk_nodes: &[(f64, f64, bool)],
198 query: f64,
199) -> Result<Sp3State> {
200 let query = validate::finite(query, "query_j2000_s").map_err(map_query_input)?;
201
202 if pos_x.is_empty() {
203 return Err(Error::UnknownSatellite(sat));
204 }
205 if pos_x.len() < 2 {
206 // A cubic spline needs >= 2 points; a single node cannot define one.
207 return Err(Error::EpochOutOfRange);
208 }
209 validate_strictly_increasing_nodes(pos_x)?;
210
211 // Refuse grossly out-of-coverage queries instead of silently returning a
212 // diverging extrapolation. The underlying cubic spline mirrors scipy
213 // CubicSpline(extrapolate=True): a query well past the node span runs off
214 // to nonsense (megametres and worse). We allow up to one node spacing of
215 // edge extrapolation (the end cubic is still physically reasonable that
216 // close to the data) and reject anything beyond. In-coverage interpolation
217 // is bit-for-bit unchanged, so 0-ULP parity is preserved. Nodes are in
218 // ascending epoch order.
219 // Reject a query that lands deep inside an interior coverage gap rather
220 // than interpolating across it. Nominal spacing is the smallest
221 // consecutive node gap; a bracketing interval far larger than that is a
222 // gap. One nominal spacing of interpolation past either edge node is
223 // allowed (the near-gap edge stays usable); beyond that the query is in
224 // the gap and is refused.
225 let nominal = nominal_positive_spacing(pos_x).ok_or(Error::EpochOutOfRange)?;
226 let first = pos_x[0];
227 let last = pos_x[pos_x.len() - 1];
228 if query < first - nominal || query > last + nominal {
229 return Err(Error::EpochOutOfRange);
230 }
231
232 let gap_thresh = 1.5 * nominal;
233 let mut bi = 0usize;
234 while bi + 1 < pos_x.len() && pos_x[bi + 1] <= query {
235 bi += 1;
236 }
237 if bi + 1 < pos_x.len() {
238 let (lo, hi) = (pos_x[bi], pos_x[bi + 1]);
239 if hi - lo > gap_thresh && query > lo + nominal && query < hi - nominal {
240 return Err(Error::EpochOutOfRange);
241 }
242 }
243
244 let (x_m, y_m, z_m) = interpolate_position_neville(pos_x, pos_kx, pos_ky, pos_kz, query);
245
246 let clock_s = interpolate_clock(clk_nodes, query);
247
248 Ok(Sp3State {
249 position: ItrfPositionM::new(x_m, y_m, z_m).expect("valid ITRF position"),
250 clock_s,
251 velocity: None,
252 clock_rate_s_s: None,
253 flags: crate::sp3::Sp3Flags::default(),
254 })
255}
256
257fn map_query_input(error: validate::FieldError) -> Error {
258 Error::InvalidInput(format!("{} {}", error.field(), error.reason()))
259}
260
261fn nominal_positive_spacing(x: &[f64]) -> Option<f64> {
262 let nominal = x
263 .windows(2)
264 .map(|w| w[1] - w[0])
265 .filter(|&d| d > 0.0)
266 .fold(f64::INFINITY, f64::min);
267 if nominal.is_finite() {
268 Some(nominal)
269 } else {
270 None
271 }
272}
273
274fn validate_strictly_increasing_nodes(x: &[f64]) -> Result<()> {
275 for window in x.windows(2) {
276 if window[1] <= window[0] {
277 return Err(Error::InvalidInput(
278 "SP3 interpolation epochs must be strictly increasing".to_string(),
279 ));
280 }
281 }
282 Ok(())
283}
284
285/// Interpolate the clock channel with the clock-event-split policy.
286///
287/// Splits the clock node arc at each clock-event (`E`) epoch and fits the
288/// not-a-knot spline on the contiguous sub-arc containing `query`. Returns
289/// `None` if that sub-arc has fewer than two nodes.
290fn interpolate_clock(clk_nodes: &[(f64, f64, bool)], query: f64) -> Option<f64> {
291 if clk_nodes.len() < 2 {
292 return None;
293 }
294
295 // Partition into contiguous sub-arcs split at clock-event epochs. A
296 // clock-event epoch marks a discontinuity *at* that epoch, so it ends the
297 // sub-arc before it and starts a new one (the flagged node belongs to the
298 // new sub-arc, since the reset takes effect there).
299 let mut sub_start = 0usize;
300 let mut chosen: Option<(usize, usize)> = None; // [start, end) into clk_nodes
301 for i in 0..clk_nodes.len() {
302 let is_break = clk_nodes[i].2 && i > sub_start;
303 if is_break {
304 // Sub-arc [sub_start, i) ends here.
305 if range_contains_query(clk_nodes, sub_start, i, query) {
306 chosen = Some((sub_start, i));
307 }
308 sub_start = i;
309 }
310 }
311 // Trailing sub-arc [sub_start, len).
312 if chosen.is_none() && range_contains_query(clk_nodes, sub_start, clk_nodes.len(), query) {
313 chosen = Some((sub_start, clk_nodes.len()));
314 }
315 // If the query is outside every sub-arc span (extrapolation), use the
316 // sub-arc nearest the query so the default extrapolate=True behavior holds
317 // within the contiguous piece on that side.
318 let (start, end) = match chosen {
319 Some(r) => r,
320 None => nearest_subarc(clk_nodes, query)?,
321 };
322
323 if end - start < 2 {
324 return None;
325 }
326 let x: Vec<f64> = clk_nodes[start..end].iter().map(|n| n.0).collect();
327 let y: Vec<f64> = clk_nodes[start..end].iter().map(|n| n.1).collect();
328 Some(eval_cubic_spline(&x, &y, query) * US_TO_S)
329}
330
331/// Whether `query` lies within the closed node-span of sub-arc `[start, end)`.
332fn range_contains_query(nodes: &[(f64, f64, bool)], start: usize, end: usize, query: f64) -> bool {
333 if end <= start {
334 return false;
335 }
336 let lo = nodes[start].0;
337 let hi = nodes[end - 1].0;
338 query >= lo && query <= hi
339}
340
341/// Find the sub-arc (split at clock-event epochs) whose node-span is nearest to
342/// `query` for extrapolation. Returns `[start, end)` or `None` if empty.
343#[allow(clippy::needless_range_loop)]
344fn nearest_subarc(nodes: &[(f64, f64, bool)], query: f64) -> Option<(usize, usize)> {
345 if nodes.is_empty() {
346 return None;
347 }
348 // Rebuild sub-arc boundaries (same rule as interpolate_clock).
349 let mut bounds: Vec<(usize, usize)> = Vec::new();
350 let mut sub_start = 0usize;
351 for i in 0..nodes.len() {
352 if nodes[i].2 && i > sub_start {
353 bounds.push((sub_start, i));
354 sub_start = i;
355 }
356 }
357 bounds.push((sub_start, nodes.len()));
358
359 // Pick the sub-arc minimizing distance from query to its [lo, hi] span.
360 bounds
361 .into_iter()
362 .filter(|&(s, e)| e - s >= 2)
363 .min_by(|&(s1, e1), &(s2, e2)| {
364 let d1 = span_distance(nodes, s1, e1, query);
365 let d2 = span_distance(nodes, s2, e2, query);
366 d1.partial_cmp(&d2).unwrap_or(core::cmp::Ordering::Equal)
367 })
368}
369
370fn span_distance(nodes: &[(f64, f64, bool)], start: usize, end: usize, query: f64) -> f64 {
371 let lo = nodes[start].0;
372 let hi = nodes[end - 1].0;
373 if query < lo {
374 lo - query
375 } else if query > hi {
376 query - hi
377 } else {
378 0.0
379 }
380}
381
382/// Convert a parser [`Instant`] to seconds since J2000, as `f64`, **exact**
383/// (not floored).
384///
385/// The split-JD difference is taken whole-part first to avoid cancellation.
386/// This returns the precise instant; flooring belongs to the *node axis* only:
387///
388/// - **Node epochs** are floored to whole seconds at the call site to mirror
389/// gnssanalysis `datetime2j2000` (`datetime64[s]` truncation), so the spline's
390/// x-axis is bit-identical to the reference. SP3 epochs are integer-second in
391/// practice, so this floor is a no-op on real data but kept for faithfulness.
392/// - The **query** is evaluated at this exact value, never floored: flooring a
393/// sub-second query epoch would discard up to ~1 s, a kilometre-scale position
394/// error at orbital speed (this was a real bug - the node and query
395/// conversions must NOT share the flooring).
396pub(super) fn instant_to_j2000_seconds(instant: &Instant) -> Option<f64> {
397 match instant.repr {
398 InstantRepr::JulianDate(split) => {
399 // (jd - J2000_JD) days -> seconds, whole/fraction kept separate to
400 // avoid cancellation (canonical split-to-J2000-seconds reduction).
401 Some(j2000_seconds_from_split(split.jd_whole, split.fraction))
402 }
403 InstantRepr::Nanos(ns) => {
404 // Integer ns since the scale epoch - but the parser stores SP3
405 // epochs as JulianDate, so this path is not exercised by SP3.
406 // J2000 is JD 2451545.0; without a fixed ns-origin convention here
407 // we cannot map ns->J2000-seconds unambiguously, so decline.
408 let _ = ns;
409 None
410 }
411 }
412}
413
414/// Number of nodes in the sliding interpolation window (RTKLIB `NMAX`=10 ->
415/// degree-10 polynomial, 11 nodes).
416const NEVILLE_POINTS: usize = 11;
417
418/// Sliding-window Lagrange (Neville) satellite-POSITION interpolation, matching
419/// RTKLIB `preceph.c` pephpos/interppol. Replaces the global not-a-knot cubic
420/// spline, which is degree-3 over the whole day and errs ~200 m at the day
421/// boundary and across coverage gaps; SP3 15-minute orbit nodes need local
422/// ~degree-10 interpolation for sub-cm accuracy. Validated against the external
423/// RTKLIB reference and the ZIM2 PPP truth (two-bars doctrine: this channel is a
424/// capability gated on the deployed reference, not a bit-exact port of a scipy
425/// primitive). The CLOCK channel keeps its cubic spline (locally smooth, matched
426/// to the 30 s clock product at the cm level).
427///
428/// Recipe: restrict to the contiguous run of nodes bracketing `query` (never
429/// interpolate across a coverage gap), take the RTKLIB window of up to
430/// `NEVILLE_POINTS` nodes centred on the query (shifted inward at run edges),
431/// rotate each node's ECEF position about +z by `OMEGA_E_DOT * (t_node - query)`
432/// into the query-epoch earth-fixed frame, then Neville-interpolate each axis at
433/// the query. Inputs are ascending J2000 seconds (`x`) and km (`kx/ky/kz`).
434fn interpolate_position_neville(
435 x: &[f64],
436 kx: &[f64],
437 ky: &[f64],
438 kz: &[f64],
439 query: f64,
440) -> (f64, f64, f64) {
441 let n = x.len();
442
443 // Nominal node spacing = smallest positive consecutive gap (robust to one
444 // large coverage gap); the gap threshold marks a non-contiguous jump.
445 let nominal = nominal_positive_spacing(x).unwrap_or(1.0);
446 let gap_thresh = 1.5 * nominal;
447
448 // Last node at or before the query (clamped into range).
449 let mut pivot = 0usize;
450 while pivot + 1 < n && x[pivot + 1] <= query {
451 pivot += 1;
452 }
453 // The gap policy admits one nominal spacing of extrapolation from either
454 // arc. Near the next arc, anchor the window there instead of extrapolating
455 // the previous arc across the whole gap.
456 if pivot + 1 < n && (x[pivot + 1] - x[pivot]) > gap_thresh && query >= x[pivot + 1] - nominal {
457 pivot += 1;
458 }
459
460 // Contiguous run [run_lo, run_hi) around the pivot: extend while the
461 // neighbour gap stays within the threshold (do not cross a coverage gap).
462 let mut run_lo = pivot;
463 while run_lo > 0 && (x[run_lo] - x[run_lo - 1]) <= gap_thresh {
464 run_lo -= 1;
465 }
466 let mut run_hi = pivot + 1;
467 while run_hi < n && (x[run_hi] - x[run_hi - 1]) <= gap_thresh {
468 run_hi += 1;
469 }
470 let run_len = run_hi - run_lo;
471
472 // RTKLIB window: centre on the pivot, width = min(NEVILLE_POINTS, run_len),
473 // clamped to the run.
474 let win = NEVILLE_POINTS.min(run_len);
475 let half = (NEVILLE_POINTS / 2) as isize;
476 let mut start = pivot as isize - half;
477 if start < run_lo as isize {
478 start = run_lo as isize;
479 }
480 if start + win as isize > run_hi as isize {
481 start = run_hi as isize - win as isize;
482 }
483 let start = start as usize;
484
485 // Windowed nodes on the (t = node - query) abscissa, earth-rotation-corrected
486 // into the query-epoch frame; query is t = 0.
487 let mut t = [0.0f64; NEVILLE_POINTS];
488 let mut px = [0.0f64; NEVILLE_POINTS];
489 let mut py = [0.0f64; NEVILLE_POINTS];
490 let mut pz = [0.0f64; NEVILLE_POINTS];
491 for j in 0..win {
492 let k = start + j;
493 let tj = x[k] - query;
494 let (s, c) = (OMEGA_E_DOT_RAD_S * tj).sin_cos();
495 t[j] = tj;
496 px[j] = c * kx[k] - s * ky[k];
497 py[j] = s * kx[k] + c * ky[k];
498 pz[j] = kz[k];
499 }
500
501 let x_km = neville(&t[..win], &px[..win]);
502 let y_km = neville(&t[..win], &py[..win]);
503 let z_km = neville(&t[..win], &pz[..win]);
504 (x_km * KM_TO_M, y_km * KM_TO_M, z_km * KM_TO_M)
505}
506
507/// Neville's algorithm evaluated at 0, reproducing RTKLIB `rtkcmn.c` interppol
508/// (the abscissa `x` carries node-minus-query offsets, so the query is 0).
509fn neville(x: &[f64], y: &[f64]) -> f64 {
510 let n = y.len();
511 let mut c: [f64; NEVILLE_POINTS] = [0.0; NEVILLE_POINTS];
512 c[..n].copy_from_slice(&y[..n]);
513 for j in 1..n {
514 for i in 0..(n - j) {
515 c[i] = (x[i + j] * c[i] - x[i] * c[i + 1]) / (x[i + j] - x[i]);
516 }
517 }
518 c[0]
519}
520
521/// Evaluate a not-a-knot cubic spline at `query`, reproducing
522/// `scipy.interpolate.CubicSpline(x, y)(query)` bit-for-bit.
523///
524/// `x` must be strictly increasing with `x.len() == y.len() >= 2`.
525fn eval_cubic_spline(x: &[f64], y: &[f64], query: f64) -> f64 {
526 let n = x.len();
527 debug_assert_eq!(n, y.len());
528 debug_assert!(n >= 2);
529
530 let dydx = solve_not_a_knot_slopes(x, y);
531 let (c0, c1, c2, c3) = hermite_segment_coeffs(x, y, &dydx);
532 evaluate_ppoly(x, &c0, &c1, &c2, &c3, query)
533}
534
535/// Solve the not-a-knot tridiagonal system for the derivative values `s[i]` at
536/// each node, exactly as `scipy.interpolate.CubicSpline.__init__` assembles it
537/// (`_cubic.py`, scipy 1.17.1) and `scipy.linalg.solve_banded((1,1), ...)`
538/// solves it via LAPACK `dgtsv`.
539///
540/// Banded layout mirrors scipy's `A` of shape `(3, n)`:
541/// - `A[1, :]` diagonal `d`
542/// - `A[0, 1:]` upper diagonal `du` (i.e. `du[j]` couples row `j` to `j+1`)
543/// - `A[2, :-1]` lower diagonal `dl` (i.e. `dl[j]` couples row `j+1` to `j`)
544fn solve_not_a_knot_slopes(x: &[f64], y: &[f64]) -> Vec<f64> {
545 let n = x.len();
546
547 // dx[i] = x[i+1]-x[i]; slope[i] = (y[i+1]-y[i])/dx[i]. (scipy: np.diff / dxr)
548 let mut dx = vec![0.0; n - 1];
549 let mut slope = vec![0.0; n - 1];
550 for i in 0..n - 1 {
551 dx[i] = x[i + 1] - x[i];
552 slope[i] = (y[i + 1] - y[i]) / dx[i];
553 }
554
555 // Special case n == 2: not-a-knot is replaced by clamped to the secant
556 // slope on both ends (scipy `_cubic.py`: bc -> (1, slope[0])), giving the
557 // straight-line Hermite - both derivatives equal slope[0].
558 if n == 2 {
559 return vec![slope[0], slope[0]];
560 }
561
562 // Special case n == 3 with not-a-knot on both ends: scipy builds a 3x3 dense
563 // system (a parabola through the points) and solves with LAPACK `gesv`.
564 if n == 3 {
565 return solve_n3_parabola(&dx, &slope, y);
566 }
567
568 // General n >= 4: tridiagonal banded system.
569 // Diagonal/off-diagonals as scipy fills them.
570 // Interior rows i=1..n-2:
571 // d[i] = 2*(dx[i-1]+dx[i])
572 // du[i] (A[0, i+1]) = dx[i-1]
573 // dl[i-1](A[2, i-1]) = dx[i]
574 // b[i] = 3*(dx[i]*slope[i-1] + dx[i-1]*slope[i])
575 let mut d = vec![0.0; n];
576 // upper diagonal du[j] for j in 0..n-1 couples row j -> j+1 (A[0, j+1]).
577 let mut du = vec![0.0; n - 1];
578 // lower diagonal dl[j] for j in 0..n-1 couples row j+1 -> j (A[2, j]).
579 let mut dl = vec![0.0; n - 1];
580 let mut b = vec![0.0; n];
581
582 for i in 1..n - 1 {
583 d[i] = 2.0 * (dx[i - 1] + dx[i]); // A[1, i]
584 du[i] = dx[i - 1]; // A[0, i+1] -> our du index i (couples i->i+1)
585 dl[i - 1] = dx[i]; // A[2, i-1] -> our dl index i-1 (couples i->i-1)
586 b[i] = 3.0 * (dx[i] * slope[i - 1] + dx[i - 1] * slope[i]);
587 }
588
589 // not-a-knot start (scipy):
590 // A[1,0]=dx[1]; A[0,1]=x[2]-x[0]; d=x[2]-x[0];
591 // b[0]=((dx[0]+2*d)*dx[1]*slope[0] + dx[0]^2*slope[1]) / d
592 {
593 let dd = x[2] - x[0];
594 d[0] = dx[1]; // A[1,0]
595 du[0] = dd; // A[0,1] couples row 0->1
596 b[0] = ((dx[0] + 2.0 * dd) * dx[1] * slope[0] + dx[0] * dx[0] * slope[1]) / dd;
597 }
598 // not-a-knot end (scipy):
599 // A[1,-1]=dx[-2]; A[-1,-2]=x[-1]-x[-3]; d=x[-1]-x[-3];
600 // b[-1]=(dx[-1]^2*slope[-2] + (2*d+dx[-1])*dx[-2]*slope[-1]) / d
601 {
602 let dd = x[n - 1] - x[n - 3];
603 d[n - 1] = dx[n - 2]; // A[1,-1]
604 dl[n - 2] = dd; // A[-1,-2] couples row n-1 -> n-2
605 b[n - 1] = (dx[n - 2] * dx[n - 2] * slope[n - 3]
606 + (2.0 * dd + dx[n - 2]) * dx[n - 3] * slope[n - 2])
607 / dd;
608 }
609
610 dgtsv(dl, d, du, b)
611}
612
613/// n == 3 not-a-knot special case: scipy solves a dense 3x3 `A s = b` via
614/// LAPACK `gesv` (partial-pivot LU). Reproduced with the same partial-pivoting
615/// Gaussian elimination operation order.
616fn solve_n3_parabola(dx: &[f64], slope: &[f64], _y: &[f64]) -> Vec<f64> {
617 // A (scipy `_cubic.py` n==3 branch):
618 // A[0,0]=1 A[0,1]=1
619 // A[1,0]=dx[1] A[1,1]=2*(dx[0]+dx[1]) A[1,2]=dx[0]
620 // A[2,1]=1 A[2,2]=1
621 // b:
622 // b[0]=2*slope[0]
623 // b[1]=3*(dx[0]*slope[1] + dx[1]*slope[0])
624 // b[2]=2*slope[1]
625 let mut a = [
626 [1.0, 1.0, 0.0],
627 [dx[1], 2.0 * (dx[0] + dx[1]), dx[0]],
628 [0.0, 1.0, 1.0],
629 ];
630 let mut b = [
631 2.0 * slope[0],
632 3.0 * (dx[0] * slope[1] + dx[1] * slope[0]),
633 2.0 * slope[1],
634 ];
635 gesv3(&mut a, &mut b);
636 b.to_vec()
637}
638
639/// LAPACK `dgtsv`-equivalent tridiagonal solve (scipy `solve_banded((1,1),...)`
640/// dispatch). Partial pivoting, scalar arithmetic, NRHS=1.
641///
642/// `dl[i]` = sub-diagonal coupling row `i+1`->`i`; `d[i]` = diagonal; `du[i]` =
643/// super-diagonal coupling row `i`->`i+1`. Reproduces the Reference-LAPACK
644/// `dgtsv.f` operation order, **with one pinned-environment subtlety**: the
645/// certified parity target's LAPACK is **Apple Accelerate** (macOS arm64; scipy
646/// 1.17.1, `detection method: extraframeworks`), whose `dgtsv` contracts each
647/// `acc - fact*x` update into a **fused multiply-add**. So every `y - a*x`
648/// elimination/back-substitution update here uses [`f64::mul_add`]
649/// (`(-a).mul_add(x, y)`), NOT a separate multiply then subtract - the
650/// per-function FMA-contraction discipline the parity contract requires.
651/// Verified 0-ULP against `scipy.linalg.lapack.dgtsv` on this target; on a
652/// non-FMA LAPACK build the last bits differ (the portable-mode reality, where
653/// 0 ULP is not promised across platforms).
654fn dgtsv(mut dl: Vec<f64>, mut d: Vec<f64>, mut du: Vec<f64>, mut b: Vec<f64>) -> Vec<f64> {
655 let n = d.len();
656
657 if n == 1 {
658 b[0] /= d[0];
659 return b;
660 }
661
662 // Forward elimination, rows i = 0 .. n-3 (Fortran 1..N-2). On a pivot, the
663 // fill-in second super-diagonal is stored back into `dl[i]` (NOT a separate
664 // du2 array) - exactly as Reference-LAPACK dgtsv.f does; the back
665 // substitution reads it as the B(I+2) coefficient.
666 for i in 0..n.saturating_sub(2) {
667 if d[i].abs() >= dl[i].abs() {
668 // No pivot.
669 let fact = dl[i] / d[i];
670 d[i + 1] = (-fact).mul_add(du[i], d[i + 1]);
671 b[i + 1] = (-fact).mul_add(b[i], b[i + 1]);
672 dl[i] = 0.0;
673 } else {
674 // Pivot (swap rows i and i+1). Note `dl[i] = du[i+1]` happens
675 // BEFORE `du[i+1] = -fact*dl[i]`, so the latter uses the new dl[i]
676 // (= old du[i+1]).
677 let fact = d[i] / dl[i];
678 d[i] = dl[i];
679 let temp = d[i + 1];
680 d[i + 1] = (-fact).mul_add(temp, du[i]);
681 dl[i] = du[i + 1];
682 du[i + 1] = -fact * dl[i];
683 du[i] = temp;
684 let tb = b[i];
685 b[i] = b[i + 1];
686 b[i + 1] = (-fact).mul_add(b[i + 1], tb);
687 }
688 }
689
690 // Row i = n-2 (Fortran I = N-1) - no du2 fill-in.
691 if n > 1 {
692 let i = n - 2;
693 if d[i].abs() >= dl[i].abs() {
694 let fact = dl[i] / d[i];
695 d[i + 1] = (-fact).mul_add(du[i], d[i + 1]);
696 b[i + 1] = (-fact).mul_add(b[i], b[i + 1]);
697 } else {
698 let fact = d[i] / dl[i];
699 d[i] = dl[i];
700 let temp = d[i + 1];
701 d[i + 1] = (-fact).mul_add(temp, du[i]);
702 du[i] = temp;
703 let tb = b[i];
704 b[i] = b[i + 1];
705 b[i + 1] = (-fact).mul_add(b[i + 1], tb);
706 }
707 }
708
709 // Back substitution (dgtsv), FMA-contracted as above.
710 b[n - 1] /= d[n - 1];
711 if n > 1 {
712 b[n - 2] = (-du[n - 2]).mul_add(b[n - 1], b[n - 2]) / d[n - 2];
713 }
714 for i in (0..n.saturating_sub(2)).rev() {
715 // (b[i] - du[i]*b[i+1] - dl[i]*b[i+2]) / d[i], each subtraction fused.
716 let t = (-du[i]).mul_add(b[i + 1], b[i]);
717 b[i] = (-dl[i]).mul_add(b[i + 2], t) / d[i];
718 }
719
720 b
721}
722
723/// 3x3 dense solve with partial-pivot LU, matching LAPACK `gesv` (`dgesv`) for
724/// the n==3 not-a-knot parabola case. As with [`dgtsv`], the certified parity
725/// target is Apple Accelerate, whose `dgesv` contracts the `acc - factor*x`
726/// elimination and substitution updates into fused multiply-adds; this routine
727/// uses [`f64::mul_add`] to match it bit-for-bit.
728#[allow(clippy::needless_range_loop)]
729fn gesv3(a: &mut [[f64; 3]; 3], b: &mut [f64; 3]) {
730 let mut perm = [0usize, 1, 2];
731 // LU with partial pivoting (column-major in LAPACK; we keep row-major but
732 // pivot by largest |a[col]| in the column, matching the same pivot choice).
733 for k in 0..3 {
734 // Find pivot row in column k at or below k.
735 let mut piv = k;
736 let mut best = a[k][k].abs();
737 for r in (k + 1)..3 {
738 let v = a[r][k].abs();
739 if v > best {
740 best = v;
741 piv = r;
742 }
743 }
744 if piv != k {
745 a.swap(k, piv);
746 perm.swap(k, piv);
747 }
748 for r in (k + 1)..3 {
749 let factor = a[r][k] / a[k][k];
750 a[r][k] = factor;
751 for c in (k + 1)..3 {
752 a[r][c] = (-factor).mul_add(a[k][c], a[r][c]);
753 }
754 }
755 }
756 // Apply row permutation to b.
757 let pb = [b[perm[0]], b[perm[1]], b[perm[2]]];
758 // Forward solve Ly = Pb (unit lower).
759 let mut yv = [0.0; 3];
760 for r in 0..3 {
761 let mut s = pb[r];
762 for c in 0..r {
763 s = (-a[r][c]).mul_add(yv[c], s);
764 }
765 yv[r] = s;
766 }
767 // Back solve Ux = y.
768 for r in (0..3).rev() {
769 let mut s = yv[r];
770 for c in (r + 1)..3 {
771 s = (-a[r][c]).mul_add(b[c], s);
772 }
773 b[r] = s / a[r][r];
774 }
775}
776
777/// Build the per-segment PPoly coefficients exactly as
778/// `scipy.interpolate.CubicHermiteSpline.__init__` (scipy 1.17.1):
779///
780/// ```text
781/// dxr = x[i+1]-x[i]
782/// slope = (y[i+1]-y[i])/dxr
783/// t = (dydx[i] + dydx[i+1] - 2*slope)/dxr
784/// c0 = t/dxr
785/// c1 = (slope - dydx[i])/dxr - t
786/// c2 = dydx[i]
787/// c3 = y[i]
788/// ```
789///
790/// for segment `i` between `x[i]` and `x[i+1]`, with local variable
791/// `s = xval - x[i]`.
792fn hermite_segment_coeffs(
793 x: &[f64],
794 y: &[f64],
795 dydx: &[f64],
796) -> (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) {
797 let n = x.len();
798 let mut c0 = vec![0.0; n - 1];
799 let mut c1 = vec![0.0; n - 1];
800 let mut c2 = vec![0.0; n - 1];
801 let mut c3 = vec![0.0; n - 1];
802 for i in 0..n - 1 {
803 let dxr = x[i + 1] - x[i];
804 let slope = (y[i + 1] - y[i]) / dxr;
805 let t = (dydx[i] + dydx[i + 1] - 2.0 * slope) / dxr;
806 c0[i] = t / dxr;
807 c1[i] = (slope - dydx[i]) / dxr - t;
808 c2[i] = dydx[i];
809 c3[i] = y[i];
810 }
811 (c0, c1, c2, c3)
812}
813
814/// Evaluate the PPoly at `query`, reproducing scipy `_ppoly.evaluate` /
815/// `find_interval_ascending` (extrapolate=True) and `evaluate_poly1` (dx=0).
816///
817/// Interval selection: the largest `i` with `x[i] <= query`, clamped to
818/// `[0, n-2]`; `query == x[n-1]` maps to interval `n-2` (right-closed); out of
819/// bounds extrapolates from interval 0 (below) or `n-2` (above).
820///
821/// Evaluation order (`evaluate_poly1`, dx=0): with `s = query - x[i]` and
822/// `z` accumulating powers via repeated `z *= s`,
823/// `res = c3 + c2*s + c1*s^2 + c0*s^3` summed low-power-first.
824fn evaluate_ppoly(x: &[f64], c0: &[f64], c1: &[f64], c2: &[f64], c3: &[f64], query: f64) -> f64 {
825 let n = x.len();
826 let last = n - 2; // last interval index
827
828 // find_interval_ascending with extrapolate=True.
829 let interval = if query.is_nan() {
830 // scipy returns -1 -> NaN out; propagate NaN.
831 return f64::NAN;
832 } else if query < x[0] {
833 0
834 } else if query > x[n - 1] {
835 last
836 } else {
837 // x[0] <= query <= x[n-1]: binary search for i with x[i] <= query < x[i+1];
838 // query == x[n-1] -> n-2.
839 if query == x[n - 1] {
840 last
841 } else {
842 let mut lo = 0usize;
843 let mut hi = n - 1;
844 while hi - lo > 1 {
845 let mid = (lo + hi) / 2;
846 if x[mid] <= query {
847 lo = mid;
848 } else {
849 hi = mid;
850 }
851 }
852 lo
853 }
854 };
855
856 // evaluate_poly1 (dx=0): res = sum_{kp} c[K-kp-1] * z, z = s^kp built by *=.
857 let s = query - x[interval];
858 let mut res = 0.0;
859 let mut z = 1.0;
860 // kp = 0 -> coefficient c3 (lowest power), kp=1 -> c2, kp=2 -> c1, kp=3 -> c0.
861 res += c3[interval] * z;
862 z *= s;
863 res += c2[interval] * z;
864 z *= s;
865 res += c1[interval] * z;
866 z *= s;
867 res += c0[interval] * z;
868 res
869}
870
871/// Test-only re-export of the core spline evaluator so the parity test can
872/// drive it directly against the scipy golden fixture.
873#[cfg(all(test, sidereon_repo_tests))]
874pub(super) fn eval_cubic_spline_for_test(x: &[f64], y: &[f64], query: f64) -> f64 {
875 eval_cubic_spline(x, y, query)
876}
877
878#[cfg(all(test, sidereon_repo_tests))]
879mod interp_tests;