Skip to main content

sparse_ir/
poly.rs

1//! Piecewise Legendre polynomial implementations for SparseIR
2//!
3//! This module provides high-performance piecewise Legendre polynomial
4//! functionality compatible with the C++ implementation.
5
6use crate::error::Error;
7
8/// A single piecewise Legendre polynomial
9#[derive(Debug, Clone)]
10pub struct PiecewiseLegendrePoly {
11    /// Polynomial order (degree of Legendre polynomials in each segment)
12    pub(crate) polyorder: usize,
13    /// Minimum x value of the domain
14    pub(crate) xmin: f64,
15    /// Maximum x value of the domain
16    pub(crate) xmax: f64,
17    /// Knot points defining the segments
18    pub(crate) knots: Vec<f64>,
19    /// Segment widths (for numerical stability)
20    pub(crate) delta_x: Vec<f64>,
21    /// Coefficient matrix: [degree][segment_index]
22    pub(crate) data: mdarray::DTensor<f64, 2>,
23    /// Symmetry parameter
24    pub(crate) symm: i32,
25    /// Index of this function in the sequence of singular functions it belongs
26    /// to (0-based, in order of non-increasing singular value)
27    ///
28    /// SVE results set it to the position of the function in the result, and
29    /// `PiecewiseLegendrePolyVector::from_3d_data` to the position in the
30    /// vector. `PiecewiseLegendreFT` takes the parity `(-1)^l` of the function
31    /// from it for the asymptotic expansion used at |n| >= n_asymp. For the
32    /// centrosymmetric kernels of this crate the even and odd singular
33    /// functions interlace, so that parity equals `symm`.
34    pub(crate) l: i32,
35    /// Segment midpoints
36    pub(crate) xm: Vec<f64>,
37    /// Inverse segment widths
38    pub(crate) inv_xs: Vec<f64>,
39    /// Normalization factors
40    pub(crate) norms: Vec<f64>,
41}
42
43/// `Ok` if there are `nsegments + 1` finite knots and every segment length is
44/// a positive normal double (so that `2 / length` is finite)
45fn check_knots(knots: &[f64], nsegments: usize) -> Result<(), Error> {
46    if knots.len() != nsegments + 1 {
47        return Err(Error::InvalidParameter {
48            name: "knots",
49            value: format!("{} knots", knots.len()),
50            reason: format!(
51                "must have {} entries, one more than the segments of data",
52                nsegments + 1
53            ),
54        });
55    }
56    if let Some((i, k)) = knots.iter().enumerate().find(|(_, k)| !k.is_finite()) {
57        return Err(Error::InvalidParameter {
58            name: "knots",
59            value: format!("{k:?} at index {i}"),
60            reason: "must be finite".to_string(),
61        });
62    }
63    for i in 1..knots.len() {
64        let length = knots[i] - knots[i - 1];
65        if !(length > 0.0 && length.is_normal()) {
66            return Err(Error::InvalidParameter {
67                name: "knots",
68                value: format!("{:?} after {:?} at index {i}", knots[i], knots[i - 1]),
69                reason: "must be strictly increasing, with each segment length a normal double"
70                    .to_string(),
71            });
72        }
73    }
74    Ok(())
75}
76
77/// `Ok` if `delta_x` has one entry per segment, each equal to the knot
78/// spacing `e = knots[i + 1] - knots[i]` within
79/// `max(1e-10 * |e|, 8 * f64::EPSILON * max(|knots[i]|, |knots[i + 1]|))`
80/// (NaN is rejected)
81///
82/// The first term is a relative tolerance on the segment length. The second
83/// covers the rounding of the knots, which grows with their magnitude: knots
84/// and widths scaled separately (as `FiniteTempBasis::from_sve_result` does,
85/// by β / 2) differ by a few units in the last place of the knots, which next
86/// to large knots can exceed 1e-10 times a narrow segment.
87fn check_delta_x(delta_x: &[f64], knots: &[f64]) -> Result<(), Error> {
88    let nsegments = knots.len() - 1;
89    if delta_x.len() != nsegments {
90        return Err(Error::InvalidParameter {
91            name: "delta_x",
92            value: format!("{} entries", delta_x.len()),
93            reason: format!("must have one entry per segment ({nsegments})"),
94        });
95    }
96    for (i, &d) in delta_x.iter().enumerate() {
97        let expected = knots[i + 1] - knots[i];
98        let rounding = 8.0 * f64::EPSILON * knots[i].abs().max(knots[i + 1].abs());
99        let tolerance = (1e-10 * expected.abs()).max(rounding);
100        if !((d - expected).abs() <= tolerance) {
101            return Err(Error::InvalidParameter {
102                name: "delta_x",
103                value: format!("{d:?} at index {i}"),
104                reason: format!(
105                    "must equal the knot spacing {expected:?} to a relative 1e-10, or to 8 machine epsilons times the magnitude of the knots"
106                ),
107            });
108        }
109    }
110    Ok(())
111}
112
113impl PiecewiseLegendrePoly {
114    /// Create a new PiecewiseLegendrePoly from data and knots
115    ///
116    /// `data` holds the Legendre coefficients, one column per segment; the
117    /// `nsegments + 1` knots bound the segments. `delta_x` (the segment
118    /// widths) is computed from the knots when `None`. `symm` is the parity of
119    /// the polynomial: 1 (even), -1 (odd) or 0 (no definite parity).
120    ///
121    /// # Errors
122    ///
123    /// * [`Error::EmptyInput`] if `data` has no row or no column
124    /// * [`Error::InvalidParameter`] if `knots` does not have one entry more
125    ///   than `data` has columns, a knot is not finite, or a segment length
126    ///   `knots[i] - knots[i - 1]` is not a positive normal double (this
127    ///   includes decreasing knots, NaN, lengths that overflow and subnormal
128    ///   lengths); or if `delta_x` does not have one entry per segment or
129    ///   differs from the knot spacing `e` by more than
130    ///   `max(1e-10 * |e|, 8 * f64::EPSILON * max(|knots[i]|, |knots[i + 1]|))`
131    /// * [`Error::InvalidParameter`] if `symm` is not -1, 0 or 1
132    pub fn new(
133        data: mdarray::DTensor<f64, 2>,
134        knots: Vec<f64>,
135        l: i32,
136        delta_x: Option<Vec<f64>>,
137        symm: i32,
138    ) -> Result<Self, Error> {
139        let polyorder = data.shape().0;
140        let nsegments = data.shape().1;
141        if polyorder == 0 || nsegments == 0 {
142            return Err(Error::EmptyInput { name: "data" });
143        }
144        check_knots(&knots, nsegments)?;
145
146        // Compute delta_x if not provided
147        let delta_x =
148            delta_x.unwrap_or_else(|| (1..knots.len()).map(|i| knots[i] - knots[i - 1]).collect());
149        check_delta_x(&delta_x, &knots)?;
150        if !matches!(symm, -1..=1) {
151            return Err(Error::InvalidParameter {
152                name: "symm",
153                value: symm.to_string(),
154                reason: "must be -1, 0 or 1".to_string(),
155            });
156        }
157
158        // Compute segment midpoints
159        let xm: Vec<f64> = (0..nsegments)
160            .map(|i| 0.5 * (knots[i] + knots[i + 1]))
161            .collect();
162
163        // Compute inverse segment widths
164        let inv_xs: Vec<f64> = delta_x.iter().map(|&dx| 2.0 / dx).collect();
165
166        // Compute normalization factors
167        let norms: Vec<f64> = inv_xs.iter().map(|&inv_x| inv_x.sqrt()).collect();
168
169        Ok(Self {
170            polyorder,
171            xmin: knots[0],
172            xmax: knots[knots.len() - 1],
173            knots,
174            delta_x,
175            data,
176            symm,
177            l,
178            xm,
179            inv_xs,
180            norms,
181        })
182    }
183
184    /// Create a new PiecewiseLegendrePoly with new data but same structure
185    ///
186    /// Crate-internal: `new_data` is not checked against the knots, so a
187    /// caller could break the invariants of the type.
188    pub(crate) fn with_data(&self, new_data: mdarray::DTensor<f64, 2>) -> Self {
189        Self {
190            data: new_data,
191            ..self.clone()
192        }
193    }
194
195    /// Get the symmetry parameter
196    pub fn symm(&self) -> i32 {
197        self.symm
198    }
199
200    /// The polynomial with every coefficient negated
201    ///
202    /// Knots, widths and normalizations are those of `self`, so this equals
203    /// `new` on the negated data without repeating its checks.
204    pub(crate) fn negated(&self) -> Self {
205        self.with_data(mdarray::DTensor::<f64, 2>::from_fn(
206            *self.data.shape(),
207            |idx| -self.data[idx],
208        ))
209    }
210
211    /// Rescale domain: create a new polynomial with the same data but different knots
212    ///
213    /// This is useful for transforming from one domain to another, e.g.,
214    /// from x ∈ [-1, 1] to τ ∈ [0, β].
215    ///
216    /// # Arguments
217    ///
218    /// * `new_knots` - New knot points
219    /// * `new_delta_x` - Optional new segment widths (computed from knots if None)
220    /// * `new_symm` - Optional new symmetry parameter (keeps old if None)
221    ///
222    /// # Returns
223    ///
224    /// New polynomial with rescaled domain
225    ///
226    /// # Errors
227    ///
228    /// The errors of [`new`](Self::new) for the new knots and widths
229    pub fn rescale_domain(
230        &self,
231        new_knots: Vec<f64>,
232        new_delta_x: Option<Vec<f64>>,
233        new_symm: Option<i32>,
234    ) -> Result<Self, Error> {
235        Self::new(
236            self.data.clone(),
237            new_knots,
238            self.l,
239            new_delta_x,
240            new_symm.unwrap_or(self.symm),
241        )
242    }
243
244    /// Scale all data values by a constant factor
245    ///
246    /// This is useful for normalizations, e.g., multiplying by √β for
247    /// Fourier transform preparations.
248    ///
249    /// # Arguments
250    ///
251    /// * `factor` - Scaling factor to multiply all data by
252    ///
253    /// # Returns
254    ///
255    /// New polynomial with scaled data
256    pub fn scale_data(&self, factor: f64) -> Self {
257        Self::with_data(
258            self,
259            mdarray::DTensor::<f64, 2>::from_fn(*self.data.shape(), |idx| self.data[idx] * factor),
260        )
261    }
262
263    /// `Ok` if `x` lies in [xmin, xmax] (NaN does not)
264    fn check_in_domain(&self, name: &'static str, x: f64) -> Result<(), Error> {
265        if x >= self.xmin && x <= self.xmax {
266            Ok(())
267        } else {
268            Err(Error::OutOfDomain {
269                name,
270                value: x,
271                domain: (self.xmin, self.xmax),
272            })
273        }
274    }
275
276    /// Evaluate the polynomial at a given point
277    ///
278    /// # Panics
279    ///
280    /// Panics if `x` is outside [xmin, xmax] or NaN; see [`Self::try_evaluate`].
281    pub fn evaluate(&self, x: f64) -> f64 {
282        self.try_evaluate(x).unwrap_or_else(|e| panic!("{e}"))
283    }
284
285    /// [`Self::evaluate`] returning an error instead of panicking
286    ///
287    /// # Errors
288    ///
289    /// [`Error::OutOfDomain`] if `x` is outside [xmin, xmax] or NaN
290    pub fn try_evaluate(&self, x: f64) -> Result<f64, Error> {
291        self.check_in_domain("x", x)?;
292        Ok(self.evaluate_in_domain(x))
293    }
294
295    /// [`Self::evaluate`] for an `x` already checked to lie in the domain
296    fn evaluate_in_domain(&self, x: f64) -> f64 {
297        let (i, x_tilde) = self.split_in_domain(x);
298        // Extract column i into a Vec
299        let coeffs: Vec<f64> = (0..self.data.shape().0)
300            .map(|row| self.data[[row, i]])
301            .collect();
302        let value = self.evaluate_legendre_polynomial(x_tilde, &coeffs);
303        value * self.norms[i]
304    }
305
306    /// Evaluate the polynomial at multiple points
307    ///
308    /// # Panics
309    ///
310    /// Panics if a point is outside [xmin, xmax] or NaN; see
311    /// [`Self::try_evaluate_many`].
312    pub fn evaluate_many(&self, xs: &[f64]) -> Vec<f64> {
313        self.try_evaluate_many(xs).unwrap_or_else(|e| panic!("{e}"))
314    }
315
316    /// [`Self::evaluate_many`] returning an error instead of panicking
317    ///
318    /// # Errors
319    ///
320    /// [`Error::OutOfDomain`] for the first point of `xs` that is outside
321    /// [xmin, xmax] or NaN; no point is evaluated then
322    pub fn try_evaluate_many(&self, xs: &[f64]) -> Result<Vec<f64>, Error> {
323        for &x in xs {
324            self.check_in_domain("xs", x)?;
325        }
326        Ok(xs.iter().map(|&x| self.evaluate_in_domain(x)).collect())
327    }
328
329    /// Split x into segment index and normalized x
330    ///
331    /// # Panics
332    ///
333    /// Panics if `x` is outside [xmin, xmax] or NaN; see [`Self::try_split`].
334    pub fn split(&self, x: f64) -> (usize, f64) {
335        self.try_split(x).unwrap_or_else(|e| panic!("{e}"))
336    }
337
338    /// [`Self::split`] returning an error instead of panicking
339    ///
340    /// # Errors
341    ///
342    /// [`Error::OutOfDomain`] if `x` is outside [xmin, xmax] or NaN
343    pub fn try_split(&self, x: f64) -> Result<(usize, f64), Error> {
344        self.check_in_domain("x", x)?;
345        Ok(self.split_in_domain(x))
346    }
347
348    /// [`Self::split`] for an `x` already checked to lie in the domain
349    fn split_in_domain(&self, x: f64) -> (usize, f64) {
350        // Find the segment containing x
351        for i in 0..self.knots.len() - 1 {
352            if x >= self.knots[i] && x <= self.knots[i + 1] {
353                // Transform x to [-1, 1] for Legendre polynomials
354                let x_tilde = 2.0 * (x - self.xm[i]) / self.delta_x[i];
355                return (i, x_tilde);
356            }
357        }
358
359        // Handle edge case: x exactly at the last knot
360        let last_idx = self.knots.len() - 2;
361        let x_tilde = 2.0 * (x - self.xm[last_idx]) / self.delta_x[last_idx];
362        (last_idx, x_tilde)
363    }
364
365    /// Evaluate Legendre polynomial using recurrence relation
366    pub fn evaluate_legendre_polynomial(&self, x: f64, coeffs: &[f64]) -> f64 {
367        if coeffs.is_empty() {
368            return 0.0;
369        }
370
371        let mut result = 0.0;
372        let mut p_prev = 1.0; // P_0(x) = 1
373        let mut p_curr = x; // P_1(x) = x
374
375        // Add first two terms
376        if !coeffs.is_empty() {
377            result += coeffs[0] * p_prev;
378        }
379        if coeffs.len() > 1 {
380            result += coeffs[1] * p_curr;
381        }
382
383        // Use recurrence relation: P_{n+1}(x) = ((2n+1)x*P_n(x) - n*P_{n-1}(x))/(n+1)
384        for n in 1..coeffs.len() - 1 {
385            let p_next =
386                ((2.0 * (n as f64) + 1.0) * x * p_curr - (n as f64) * p_prev) / ((n + 1) as f64);
387            result += coeffs[n + 1] * p_next;
388            p_prev = p_curr;
389            p_curr = p_next;
390        }
391
392        result
393    }
394
395    /// Compute derivative of the polynomial
396    ///
397    /// The result has `polyorder` equal to the number of its coefficient rows
398    /// (at least 1).
399    pub fn deriv(&self, n: usize) -> Self {
400        if n == 0 {
401            return self.clone();
402        }
403
404        // Compute derivative coefficients
405        let mut ddata = self.data.clone();
406        for _ in 0..n {
407            ddata = self.compute_derivative_coefficients(&ddata);
408        }
409
410        // Apply scaling factors (C++: ddata.col(i) *= std::pow(inv_xs[i], n))
411        let ddata_shape = *ddata.shape();
412        for i in 0..ddata_shape.1 {
413            let inv_x_power = self.inv_xs[i].powi(n as i32);
414            for j in 0..ddata_shape.0 {
415                ddata[[j, i]] *= inv_x_power;
416            }
417        }
418
419        // Update symmetry: C++: int new_symm = std::pow(-1, n) * symm;
420        let new_symm = if n % 2 == 0 { self.symm } else { -self.symm };
421
422        Self {
423            polyorder: ddata.shape().0,
424            data: ddata,
425            symm: new_symm,
426            ..self.clone()
427        }
428    }
429
430    /// Compute derivative coefficients using the same algorithm as C++ legder function
431    fn compute_derivative_coefficients(
432        &self,
433        coeffs: &mdarray::DTensor<f64, 2>,
434    ) -> mdarray::DTensor<f64, 2> {
435        let mut c = coeffs.clone();
436        let c_shape = *c.shape();
437        let mut n = c_shape.0;
438
439        // Single derivative step (equivalent to C++ legder with cnt=1)
440        if n <= 1 {
441            return mdarray::DTensor::<f64, 2>::from_elem([1, c.shape().1], 0.0);
442        }
443
444        n -= 1;
445        let mut der = mdarray::DTensor::<f64, 2>::from_elem([n, c.shape().1], 0.0);
446
447        // C++ implementation: for (int j = n; j >= 2; --j)
448        for j in (2..=n).rev() {
449            // C++: der.row(j - 1) = (2 * j - 1) * c.row(j);
450            for col in 0..c_shape.1 {
451                der[[j - 1, col]] = (2.0 * (j as f64) - 1.0) * c[[j, col]];
452            }
453            // C++: c.row(j - 2) += c.row(j);
454            for col in 0..c_shape.1 {
455                c[[j - 2, col]] += c[[j, col]];
456            }
457        }
458
459        // C++: if (n > 1) der.row(1) = 3 * c.row(2);
460        if n > 1 {
461            for col in 0..c_shape.1 {
462                der[[1, col]] = 3.0 * c[[2, col]];
463            }
464        }
465
466        // C++: der.row(0) = c.row(1);
467        for col in 0..c_shape.1 {
468            der[[0, col]] = c[[1, col]];
469        }
470
471        der
472    }
473
474    /// Compute derivatives at a point x
475    ///
476    /// Returns the values of the derivatives of order 0 to `polyorder - 1`.
477    ///
478    /// # Panics
479    ///
480    /// Panics if `x` is outside [xmin, xmax] or NaN; see [`Self::try_derivs`].
481    pub fn derivs(&self, x: f64) -> Vec<f64> {
482        self.try_derivs(x).unwrap_or_else(|e| panic!("{e}"))
483    }
484
485    /// [`Self::derivs`] returning an error instead of panicking
486    ///
487    /// # Errors
488    ///
489    /// [`Error::OutOfDomain`] if `x` is outside [xmin, xmax] or NaN
490    pub fn try_derivs(&self, x: f64) -> Result<Vec<f64>, Error> {
491        self.check_in_domain("x", x)?;
492        let mut results = Vec::new();
493
494        // Compute up to polyorder derivatives
495        // The derivatives have the knots of self, so x lies in their domain.
496        for n in 0..self.polyorder {
497            let deriv_poly = self.deriv(n);
498            results.push(deriv_poly.evaluate_in_domain(x));
499        }
500
501        Ok(results)
502    }
503
504    /// Compute overlap integral with a function
505    pub fn overlap<F>(&self, f: F) -> f64
506    where
507        F: Fn(f64) -> f64,
508    {
509        let mut integral = 0.0;
510
511        for i in 0..self.knots.len() - 1 {
512            let segment_integral =
513                self.gauss_legendre_quadrature(self.knots[i], self.knots[i + 1], |x| {
514                    self.evaluate(x) * f(x)
515                });
516            integral += segment_integral;
517        }
518
519        integral
520    }
521
522    /// Gauss-Legendre quadrature over [a, b]
523    fn gauss_legendre_quadrature<F>(&self, a: f64, b: f64, f: F) -> f64
524    where
525        F: Fn(f64) -> f64,
526    {
527        // 5-point Gauss-Legendre quadrature
528        const XG: [f64; 5] = [
529            -0.906179845938664,
530            -0.538469310105683,
531            0.0,
532            0.538469310105683,
533            0.906179845938664,
534        ];
535        const WG: [f64; 5] = [
536            0.236926885056189,
537            0.478628670499366,
538            0.568888888888889,
539            0.478628670499366,
540            0.236926885056189,
541        ];
542
543        let c1 = (b - a) / 2.0;
544        let c2 = (b + a) / 2.0;
545
546        let mut integral = 0.0;
547        for j in 0..5 {
548            let x = c1 * XG[j] + c2;
549            integral += WG[j] * f(x);
550        }
551
552        integral * c1
553    }
554
555    /// Find roots of the polynomial using C++ compatible algorithm
556    pub fn roots(&self) -> Vec<f64> {
557        let xmid = (self.xmax + self.xmin) / 2.0;
558
559        // Exploit symmetry: only search the right half, then mirror.
560        // This matches the Python 1.x / Julia v1 algorithm and guarantees
561        // exactly symmetric root positions.
562        let grid = if self.symm != 0 {
563            let nsegments = self.knots.len() - 1;
564            let mid_idx = nsegments / 2;
565            if (self.knots[mid_idx] - xmid).abs() < 1e-15 {
566                self.knots[mid_idx..].to_vec()
567            } else {
568                let mut g = vec![xmid];
569                g.extend(self.knots.iter().filter(|&&x| x > xmid));
570                g
571            }
572        } else {
573            self.knots.clone()
574        };
575
576        let refined_grid = self.refine_grid(&grid, 4);
577        let roots_half = self.find_all_roots(&refined_grid);
578
579        if self.symm == 1 {
580            // Even symmetry: roots on right half, mirror to left
581            let mut all_roots: Vec<f64> = roots_half
582                .iter()
583                .rev()
584                .map(|&r| (self.xmax + self.xmin) - r)
585                .collect();
586            all_roots.extend_from_slice(&roots_half);
587            all_roots
588        } else if self.symm == -1 {
589            // Odd symmetry: there must be a zero at xmid
590            let mut right = roots_half;
591            if !right.is_empty() {
592                // Remove the root at xmid if found (may be slightly off),
593                // or if f(xmid) and f'(xmid) have opposite signs (spurious zero)
594                let f_mid = self.evaluate(xmid);
595                let f_deriv_mid = self.deriv(1).evaluate(xmid);
596                if (right[0] - xmid).abs() < 1e-13 || f_mid * f_deriv_mid < 0.0 {
597                    right.remove(0);
598                }
599            }
600            let mut all_roots: Vec<f64> = right
601                .iter()
602                .rev()
603                .map(|&r| (self.xmax + self.xmin) - r)
604                .collect();
605            all_roots.push(xmid);
606            all_roots.extend_from_slice(&right);
607            all_roots
608        } else {
609            // No symmetry: search the full domain
610            let full_grid = self.refine_grid(&self.knots, 4);
611            self.find_all_roots(&full_grid)
612        }
613    }
614
615    /// Refine grid by factor alpha (C++ compatible)
616    fn refine_grid(&self, grid: &[f64], alpha: usize) -> Vec<f64> {
617        let mut refined = Vec::new();
618
619        for i in 0..grid.len() - 1 {
620            let start = grid[i];
621            let step = (grid[i + 1] - grid[i]) / (alpha as f64);
622            for j in 0..alpha {
623                refined.push(start + (j as f64) * step);
624            }
625        }
626        refined.push(grid[grid.len() - 1]);
627        refined
628    }
629
630    /// Find all roots using refined grid (C++ compatible)
631    fn find_all_roots(&self, xgrid: &[f64]) -> Vec<f64> {
632        if xgrid.is_empty() {
633            return Vec::new();
634        }
635
636        // Evaluate function at all grid points
637        let fx: Vec<f64> = xgrid.iter().map(|&x| self.evaluate(x)).collect();
638
639        // Find exact zeros (direct hits)
640        let mut x_hit = Vec::new();
641        for i in 0..fx.len() {
642            if fx[i] == 0.0 {
643                x_hit.push(xgrid[i]);
644            }
645        }
646
647        // Find sign changes
648        let mut sign_change = Vec::new();
649        for i in 0..fx.len() - 1 {
650            let has_sign_change = fx[i].signum() != fx[i + 1].signum();
651            let not_hit = fx[i] != 0.0 && fx[i + 1] != 0.0;
652            let sc = has_sign_change && not_hit;
653            sign_change.push(sc);
654        }
655
656        // If no sign changes, return only direct hits
657        if sign_change.iter().all(|&sc| !sc) {
658            x_hit.sort_by(|a, b| a.partial_cmp(b).unwrap());
659            return x_hit;
660        }
661
662        // Find intervals with sign changes
663        let mut a_intervals = Vec::new();
664        let mut b_intervals = Vec::new();
665        let mut fa_values = Vec::new();
666
667        for i in 0..sign_change.len() {
668            if sign_change[i] {
669                a_intervals.push(xgrid[i]);
670                b_intervals.push(xgrid[i + 1]);
671                fa_values.push(fx[i]);
672            }
673        }
674
675        // Calculate epsilon for convergence
676        let max_elm = xgrid.iter().map(|&x| x.abs()).fold(0.0, f64::max);
677        let epsilon_x = f64::EPSILON * max_elm;
678
679        // Use bisection for each interval with sign change
680        for i in 0..a_intervals.len() {
681            let root = self.bisect(a_intervals[i], b_intervals[i], fa_values[i], epsilon_x);
682            x_hit.push(root);
683        }
684
685        // Sort and return
686        x_hit.sort_by(|a, b| a.partial_cmp(b).unwrap());
687        x_hit
688    }
689
690    /// Bisection method to find root (C++ compatible)
691    fn bisect(&self, a: f64, b: f64, fa: f64, eps: f64) -> f64 {
692        let mut a = a;
693        let mut b = b;
694        let mut fa = fa;
695
696        loop {
697            let mid = (a + b) / 2.0;
698            if self.close_enough(a, mid, eps) {
699                return mid;
700            }
701
702            let fmid = self.evaluate(mid);
703            if fa.signum() != fmid.signum() {
704                b = mid;
705            } else {
706                a = mid;
707                fa = fmid;
708            }
709        }
710    }
711
712    /// Check if two values are close enough (C++ compatible)
713    fn close_enough(&self, a: f64, b: f64, eps: f64) -> bool {
714        (a - b).abs() <= eps
715    }
716
717    // Accessor methods to match C++ interface
718    pub fn get_xmin(&self) -> f64 {
719        self.xmin
720    }
721    pub fn get_xmax(&self) -> f64 {
722        self.xmax
723    }
724    pub fn get_l(&self) -> i32 {
725        self.l
726    }
727    pub fn get_domain(&self) -> (f64, f64) {
728        (self.xmin, self.xmax)
729    }
730    pub fn get_knots(&self) -> &[f64] {
731        &self.knots
732    }
733    pub fn get_delta_x(&self) -> &[f64] {
734        &self.delta_x
735    }
736    pub fn get_symm(&self) -> i32 {
737        self.symm
738    }
739    pub fn get_data(&self) -> &mdarray::DTensor<f64, 2> {
740        &self.data
741    }
742    pub fn get_norms(&self) -> &[f64] {
743        &self.norms
744    }
745    pub fn get_polyorder(&self) -> usize {
746        self.polyorder
747    }
748}
749
750/// Vector of piecewise Legendre polynomials
751#[derive(Debug, Clone)]
752pub struct PiecewiseLegendrePolyVector {
753    /// Individual polynomials
754    pub(crate) polyvec: Vec<PiecewiseLegendrePoly>,
755}
756
757impl PiecewiseLegendrePolyVector {
758    /// Constructor with a vector of PiecewiseLegendrePoly
759    ///
760    /// # Errors
761    ///
762    /// * [`Error::EmptyInput`] if `polyvec` is empty
763    /// * [`Error::InvalidParameter`] if a polynomial has other knots or
764    ///   another data shape than the first: the accessors of the vector
765    ///   (`get_knots`, `get_data`, ...) describe all of them by the first
766    pub fn new(polyvec: Vec<PiecewiseLegendrePoly>) -> Result<Self, Error> {
767        let Some(first) = polyvec.first() else {
768            return Err(Error::EmptyInput { name: "polyvec" });
769        };
770        if let Some(i) = polyvec
771            .iter()
772            .position(|p| p.knots != first.knots || p.data.shape() != first.data.shape())
773        {
774            return Err(Error::InvalidParameter {
775                name: "polyvec",
776                value: format!("polynomial {i}"),
777                reason: "must have the knots and the data shape of polynomial 0".to_string(),
778            });
779        }
780        Ok(Self { polyvec })
781    }
782
783    /// Constructor that skips the checks of [`Self::new`]
784    ///
785    /// For the SVE, which builds every polynomial of a vector from the same
786    /// knots and the same data shape and may legitimately build an empty
787    /// vector (a symmetrized half of an expansion with no singular value of
788    /// that parity).
789    pub(crate) fn from_polys_unchecked(polyvec: Vec<PiecewiseLegendrePoly>) -> Self {
790        Self { polyvec }
791    }
792
793    /// Get the polynomials
794    pub fn get_polys(&self) -> &[PiecewiseLegendrePoly] {
795        &self.polyvec
796    }
797
798    /// Constructor with a 3D array, knots, and symmetry vector
799    ///
800    /// `data3d` has the shape `(polyorder, nsegments, npolys)`; polynomial `i`
801    /// gets `l = i` and the symmetry `symm[i]` (0 if `symm` is `None`).
802    ///
803    /// # Errors
804    ///
805    /// * [`Error::EmptyInput`] if `data3d` has no polynomial
806    /// * [`Error::InvalidParameter`] if `symm` does not have one entry per
807    ///   polynomial
808    /// * The errors of [`PiecewiseLegendrePoly::new`] for the data and knots
809    pub fn from_3d_data(
810        data3d: mdarray::DTensor<f64, 3>,
811        knots: Vec<f64>,
812        symm: Option<Vec<i32>>,
813    ) -> Result<Self, Error> {
814        let npolys = data3d.shape().2;
815        if npolys == 0 {
816            return Err(Error::EmptyInput { name: "data3d" });
817        }
818        let mut polyvec = Vec::with_capacity(npolys);
819
820        if let Some(ref symm_vec) = symm {
821            if symm_vec.len() != npolys {
822                return Err(Error::InvalidParameter {
823                    name: "symm",
824                    value: format!("{} entries", symm_vec.len()),
825                    reason: format!("must have one entry per polynomial ({npolys})"),
826                });
827            }
828        }
829
830        // Compute delta_x from knots
831        let delta_x: Vec<f64> = (1..knots.len()).map(|i| knots[i] - knots[i - 1]).collect();
832
833        for i in 0..npolys {
834            // Extract 2D data for this polynomial
835            let data3d_shape = data3d.shape();
836            let mut data =
837                mdarray::DTensor::<f64, 2>::from_elem([data3d_shape.0, data3d_shape.1], 0.0);
838            for j in 0..data3d_shape.0 {
839                for k in 0..data3d_shape.1 {
840                    data[[j, k]] = data3d[[j, k, i]];
841                }
842            }
843
844            let poly = PiecewiseLegendrePoly::new(
845                data,
846                knots.clone(),
847                i as i32,
848                Some(delta_x.clone()),
849                symm.as_ref().map_or(0, |s| s[i]),
850            )?;
851
852            polyvec.push(poly);
853        }
854
855        Ok(Self { polyvec })
856    }
857
858    /// Get the size of the vector
859    pub fn size(&self) -> usize {
860        self.polyvec.len()
861    }
862
863    /// Rescale domain for all polynomials in the vector
864    ///
865    /// Creates a new PiecewiseLegendrePolyVector where each polynomial has
866    /// the same data but new knots and delta_x.
867    ///
868    /// # Arguments
869    ///
870    /// * `new_knots` - New knot points (same for all polynomials)
871    /// * `new_delta_x` - Optional new segment widths
872    /// * `new_symm` - Optional vector of new symmetry parameters (one per polynomial)
873    ///
874    /// # Returns
875    ///
876    /// New vector with rescaled domains
877    ///
878    /// # Errors
879    ///
880    /// * [`Error::InvalidParameter`] if `new_symm` does not have one entry per
881    ///   polynomial
882    /// * The errors of [`PiecewiseLegendrePoly::rescale_domain`]
883    pub fn rescale_domain(
884        &self,
885        new_knots: Vec<f64>,
886        new_delta_x: Option<Vec<f64>>,
887        new_symm: Option<Vec<i32>>,
888    ) -> Result<Self, Error> {
889        if let Some(symm) = &new_symm {
890            if symm.len() != self.polyvec.len() {
891                return Err(Error::InvalidParameter {
892                    name: "new_symm",
893                    value: format!("{} entries", symm.len()),
894                    reason: format!(
895                        "must have one entry per polynomial ({})",
896                        self.polyvec.len()
897                    ),
898                });
899            }
900        }
901        let polyvec = self
902            .polyvec
903            .iter()
904            .enumerate()
905            .map(|(i, poly)| {
906                let symm = new_symm.as_ref().map(|s| s[i]);
907                poly.rescale_domain(new_knots.clone(), new_delta_x.clone(), symm)
908            })
909            .collect::<Result<_, _>>()?;
910        Ok(Self { polyvec })
911    }
912
913    /// Scale all data values by a constant factor
914    ///
915    /// Multiplies the data of all polynomials by the same factor.
916    ///
917    /// # Arguments
918    ///
919    /// * `factor` - Scaling factor to multiply all data by
920    ///
921    /// # Returns
922    ///
923    /// New vector with scaled data
924    pub fn scale_data(&self, factor: f64) -> Self {
925        let polyvec = self
926            .polyvec
927            .iter()
928            .map(|poly| poly.scale_data(factor))
929            .collect();
930
931        Self { polyvec }
932    }
933
934    /// Get polynomial by index (immutable)
935    pub fn get(&self, index: usize) -> Option<&PiecewiseLegendrePoly> {
936        self.polyvec.get(index)
937    }
938
939    /// Get polynomial by index (mutable) - deprecated, use immutable design instead
940    #[deprecated(
941        note = "PiecewiseLegendrePolyVector is designed to be immutable. Use get() and create new instances for modifications."
942    )]
943    pub fn get_mut(&mut self, index: usize) -> Option<&mut PiecewiseLegendrePoly> {
944        self.polyvec.get_mut(index)
945    }
946
947    /// Extract a single polynomial as a vector
948    pub fn slice_single(&self, index: usize) -> Option<Self> {
949        self.polyvec.get(index).map(|poly| Self {
950            polyvec: vec![poly.clone()],
951        })
952    }
953
954    /// Extract multiple polynomials by indices, in the order of `indices`
955    ///
956    /// # Errors
957    ///
958    /// * [`Error::EmptyInput`] if `indices` is empty
959    /// * [`Error::InvalidParameter`] for the first index that is out of range
960    ///   or repeats an earlier one
961    pub fn slice_multi(&self, indices: &[usize]) -> Result<Self, Error> {
962        if indices.is_empty() {
963            return Err(Error::EmptyInput { name: "indices" });
964        }
965        let len = self.polyvec.len();
966        let mut seen = vec![false; len];
967        for &idx in indices {
968            if idx >= len {
969                return Err(Error::InvalidParameter {
970                    name: "indices",
971                    value: format!("{idx}"),
972                    reason: format!("must be less than the size {len}"),
973                });
974            }
975            if seen[idx] {
976                return Err(Error::InvalidParameter {
977                    name: "indices",
978                    value: format!("{idx}"),
979                    reason: "must not repeat".to_string(),
980                });
981            }
982            seen[idx] = true;
983        }
984
985        let new_polyvec: Vec<_> = indices
986            .iter()
987            .map(|&idx| self.polyvec[idx].clone())
988            .collect();
989
990        Ok(Self {
991            polyvec: new_polyvec,
992        })
993    }
994
995    /// Evaluate all polynomials at a single point
996    ///
997    /// # Panics
998    ///
999    /// Panics if `x` is outside the domain of a polynomial or NaN; see
1000    /// [`Self::try_evaluate_at`].
1001    pub fn evaluate_at(&self, x: f64) -> Vec<f64> {
1002        self.try_evaluate_at(x).unwrap_or_else(|e| panic!("{e}"))
1003    }
1004
1005    /// [`Self::evaluate_at`] returning an error instead of panicking
1006    ///
1007    /// # Errors
1008    ///
1009    /// [`Error::OutOfDomain`] if `x` is outside the domain of a polynomial
1010    /// or NaN
1011    pub fn try_evaluate_at(&self, x: f64) -> Result<Vec<f64>, Error> {
1012        self.polyvec
1013            .iter()
1014            .map(|poly| poly.try_evaluate(x))
1015            .collect()
1016    }
1017
1018    /// Evaluate all polynomials at multiple points
1019    ///
1020    /// The result has the shape `(size, xs.len())`.
1021    ///
1022    /// # Panics
1023    ///
1024    /// Panics if a point is outside the domain of a polynomial or NaN; see
1025    /// [`Self::try_evaluate_at_many`].
1026    pub fn evaluate_at_many(&self, xs: &[f64]) -> mdarray::DTensor<f64, 2> {
1027        self.try_evaluate_at_many(xs)
1028            .unwrap_or_else(|e| panic!("{e}"))
1029    }
1030
1031    /// [`Self::evaluate_at_many`] returning an error instead of panicking
1032    ///
1033    /// # Errors
1034    ///
1035    /// [`Error::OutOfDomain`] for the first point of `xs` that is outside
1036    /// the domain of a polynomial or NaN; every point is checked before any
1037    /// is evaluated
1038    pub fn try_evaluate_at_many(&self, xs: &[f64]) -> Result<mdarray::DTensor<f64, 2>, Error> {
1039        // `new` gives every polynomial the knots of the first, so checking the
1040        // points against the first checks them against all of them.
1041        if let Some(first) = self.polyvec.first() {
1042            for &x in xs {
1043                first.check_in_domain("xs", x)?;
1044            }
1045        }
1046        let n_funcs = self.polyvec.len();
1047        let n_points = xs.len();
1048        let mut results = mdarray::DTensor::<f64, 2>::from_elem([n_funcs, n_points], 0.0);
1049
1050        for (i, poly) in self.polyvec.iter().enumerate() {
1051            for (j, &x) in xs.iter().enumerate() {
1052                results[[i, j]] = poly.evaluate_in_domain(x);
1053            }
1054        }
1055
1056        Ok(results)
1057    }
1058
1059    // Accessor methods to match C++ interface
1060    pub fn xmin(&self) -> f64 {
1061        if self.polyvec.is_empty() {
1062            panic!("Cannot get xmin from empty PiecewiseLegendrePolyVector");
1063        }
1064        self.polyvec[0].xmin
1065    }
1066
1067    pub fn xmax(&self) -> f64 {
1068        if self.polyvec.is_empty() {
1069            panic!("Cannot get xmax from empty PiecewiseLegendrePolyVector");
1070        }
1071        self.polyvec[0].xmax
1072    }
1073
1074    pub fn get_knots(&self, tolerance: Option<f64>) -> Vec<f64> {
1075        if self.polyvec.is_empty() {
1076            panic!("Cannot get knots from empty PiecewiseLegendrePolyVector");
1077        }
1078        const DEFAULT_TOLERANCE: f64 = 1e-10;
1079        let tolerance = tolerance.unwrap_or(DEFAULT_TOLERANCE);
1080
1081        // Collect all knots from all polynomials
1082        let mut all_knots = Vec::new();
1083        for poly in &self.polyvec {
1084            for &knot in &poly.knots {
1085                all_knots.push(knot);
1086            }
1087        }
1088
1089        // Sort and remove duplicates
1090        {
1091            all_knots.sort_by(|a, b| a.partial_cmp(b).unwrap());
1092            all_knots.dedup_by(|a, b| (*a - *b).abs() < tolerance);
1093        }
1094        all_knots
1095    }
1096
1097    pub fn get_delta_x(&self) -> Vec<f64> {
1098        if self.polyvec.is_empty() {
1099            panic!("Cannot get delta_x from empty PiecewiseLegendrePolyVector");
1100        }
1101        self.polyvec[0].delta_x.clone()
1102    }
1103
1104    pub fn get_polyorder(&self) -> usize {
1105        if self.polyvec.is_empty() {
1106            panic!("Cannot get polyorder from empty PiecewiseLegendrePolyVector");
1107        }
1108        self.polyvec[0].polyorder
1109    }
1110
1111    pub fn get_norms(&self) -> &[f64] {
1112        if self.polyvec.is_empty() {
1113            panic!("Cannot get norms from empty PiecewiseLegendrePolyVector");
1114        }
1115        &self.polyvec[0].norms
1116    }
1117
1118    pub fn get_symm(&self) -> Vec<i32> {
1119        if self.polyvec.is_empty() {
1120            panic!("Cannot get symm from empty PiecewiseLegendrePolyVector");
1121        }
1122        self.polyvec.iter().map(|poly| poly.symm).collect()
1123    }
1124
1125    /// Get data as 3D tensor: [segment][degree][polynomial]
1126    pub fn get_data(&self) -> mdarray::DTensor<f64, 3> {
1127        if self.polyvec.is_empty() {
1128            panic!("Cannot get data from empty PiecewiseLegendrePolyVector");
1129        }
1130
1131        let nsegments = self.polyvec[0].data.shape().1;
1132        let polyorder = self.polyvec[0].polyorder;
1133        let npolys = self.polyvec.len();
1134
1135        let mut data = mdarray::DTensor::<f64, 3>::from_elem([nsegments, polyorder, npolys], 0.0);
1136
1137        for (poly_idx, poly) in self.polyvec.iter().enumerate() {
1138            for segment in 0..nsegments {
1139                for degree in 0..polyorder {
1140                    data[[segment, degree, poly_idx]] = poly.data[[degree, segment]];
1141                }
1142            }
1143        }
1144
1145        data
1146    }
1147
1148    /// Find roots of all polynomials
1149    pub fn roots(&self, tolerance: Option<f64>) -> Vec<f64> {
1150        if self.polyvec.is_empty() {
1151            panic!("Cannot get roots from empty PiecewiseLegendrePolyVector");
1152        }
1153        const DEFAULT_TOLERANCE: f64 = 1e-10;
1154        let tolerance = tolerance.unwrap_or(DEFAULT_TOLERANCE);
1155        let mut all_roots = Vec::new();
1156
1157        for poly in &self.polyvec {
1158            let poly_roots = poly.roots();
1159            for root in poly_roots {
1160                all_roots.push(root);
1161            }
1162        }
1163
1164        // Sort in descending order and remove duplicates (like C++ implementation)
1165        {
1166            all_roots.sort_by(|a, b| b.partial_cmp(a).unwrap());
1167            all_roots.dedup_by(|a, b| (*a - *b).abs() < tolerance);
1168        }
1169        all_roots
1170    }
1171
1172    /// Get reference to last polynomial
1173    ///
1174    /// C++ equivalent: u.polyvec.back()
1175    pub fn last(&self) -> &PiecewiseLegendrePoly {
1176        self.polyvec
1177            .last()
1178            .expect("Cannot get last from empty PiecewiseLegendrePolyVector")
1179    }
1180
1181    /// Get the number of roots
1182    pub fn nroots(&self, tolerance: Option<f64>) -> usize {
1183        if self.polyvec.is_empty() {
1184            panic!("Cannot get nroots from empty PiecewiseLegendrePolyVector");
1185        }
1186        self.roots(tolerance).len()
1187    }
1188}
1189
1190impl std::ops::Index<usize> for PiecewiseLegendrePolyVector {
1191    type Output = PiecewiseLegendrePoly;
1192
1193    fn index(&self, index: usize) -> &Self::Output {
1194        &self.polyvec[index]
1195    }
1196}
1197
1198/// Get default sampling points in [-1, 1]
1199///
1200/// C++ implementation: libsparseir/include/sparseir/basis.hpp:287-310
1201///
1202/// For orthogonal polynomials (the high-T limit of IR), we know that the
1203/// ideal sampling points for a basis of size L are the roots of the L-th
1204/// polynomial. We empirically find that these stay good sampling points
1205/// for our kernels (probably because the kernels are totally positive).
1206///
1207/// If we do not have enough polynomials in the basis, we approximate the
1208/// roots of the L'th polynomial by the extrema of the last basis function,
1209/// which is sensible due to the strong interleaving property of these
1210/// functions' roots.
1211///
1212/// `name` names `u` in the errors (`"u"` or `"v"`).
1213///
1214/// # Errors
1215///
1216/// * [`Error::InvalidParameter`] named `name` if `u` is not on [-1, 1]
1217///   (1e-10), i.e. not the unscaled functions of an SVE
1218/// * [`Error::NotSupported`] if the extrema are needed and the last function
1219///   has none (e.g. an SVE truncated to 2 functions, whose u_1 is monotonic)
1220pub(crate) fn default_sampling_points(
1221    u: &PiecewiseLegendrePolyVector,
1222    name: &'static str,
1223    l: usize,
1224) -> Result<Vec<f64>, Error> {
1225    // C++: if (u.xmin() != -1.0 || u.xmax() != 1.0)
1226    //          throw std::runtime_error("Expecting unscaled functions here.");
1227    if (u.xmin() - (-1.0)).abs() > 1e-10 || (u.xmax() - 1.0).abs() > 1e-10 {
1228        return Err(Error::InvalidParameter {
1229            name,
1230            value: format!("functions on [{:?}, {:?}]", u.xmin(), u.xmax()),
1231            reason: "must be the unscaled functions of an SVE, on [-1, 1]".to_string(),
1232        });
1233    }
1234
1235    let x0 = if l < u.polyvec.len() {
1236        // C++: return u.polyvec[L].roots();
1237        u[l].roots()
1238    } else {
1239        // C++: PiecewiseLegendrePoly poly = u.polyvec.back();
1240        //      Eigen::VectorXd maxima = poly.deriv().roots();
1241        let poly = u.last();
1242        let poly_deriv = poly.deriv(1);
1243        let maxima = poly_deriv.roots();
1244
1245        // C++ reads maxima[0] without a check; SparseIR.jl's first(maxima)
1246        // fails the same way.
1247        let (Some(&first), Some(&last)) = (maxima.first(), maxima.last()) else {
1248            return Err(Error::NotSupported {
1249                what: format!(
1250                    "default sampling points for {l} basis functions: the last singular \
1251                     function (l = {}) has no extrema to stand in for the roots of the \
1252                     missing function l = {l} (an SVE truncated to too few functions)",
1253                    poly.l
1254                ),
1255            });
1256        };
1257
1258        // C++: double left = (maxima[0] + poly.xmin) / 2.0;
1259        let left = (first + poly.xmin) / 2.0;
1260
1261        // C++: double right = (maxima[maxima.size() - 1] + poly.xmax) / 2.0;
1262        let right = (last + poly.xmax) / 2.0;
1263
1264        // C++: Eigen::VectorXd x0(maxima.size() + 2);
1265        //      x0[0] = left;
1266        //      x0.segment(1, maxima.size()) = maxima;
1267        //      x0[x0.size() - 1] = right;
1268        let mut x0_vec = Vec::with_capacity(maxima.len() + 2);
1269        x0_vec.push(left);
1270        x0_vec.extend_from_slice(&maxima);
1271        x0_vec.push(right);
1272        x0_vec
1273    };
1274
1275    // C++: if (x0.size() != L) { warning }
1276    if x0.len() != l {
1277        debug_warn!(
1278            "Expecting to get {} sampling points for corresponding basis function, \
1279             instead got {}. This may happen if not enough precision is left in the polynomial.",
1280            l,
1281            x0.len()
1282        );
1283    }
1284
1285    Ok(x0)
1286}
1287
1288// IndexMut implementation removed - PiecewiseLegendrePolyVector is designed to be immutable
1289// If modification is needed, create a new instance instead
1290
1291// Note: FnOnce implementation removed due to experimental nature
1292// Use evaluate_at() and evaluate_at_many() methods directly
1293
1294#[cfg(test)]
1295#[path = "poly_tests.rs"]
1296mod poly_tests;