Skip to main content

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