Skip to main content

sparse_ir_basis/
gauss.rs

1//! Gauss quadrature rules for numerical integration
2//!
3//! This module provides quadrature rules for approximating integrals by weighted sums.
4//!
5//! The integral of f(x) * omega(x) is approximated by a weighted sum:
6//!
7//! sum(f(xi) * wi for (xi, wi) in zip(x, w))
8//!
9//! where we generally have superexponential convergence for smooth f(x)
10//! with the number of quadrature points.
11
12use crate::error::Error;
13use crate::matrix::Mat;
14use crate::numeric::CustomNumeric;
15use std::fmt::Debug;
16
17/// `Ok` if there is one weight per point
18fn check_weights<T>(x: &[T], w: &[T]) -> Result<(), Error> {
19    if x.len() == w.len() {
20        Ok(())
21    } else {
22        Err(Error::InvalidParameter {
23            name: "w",
24            value: format!("{} weights", w.len()),
25            reason: format!("must have one weight per point ({})", x.len()),
26        })
27    }
28}
29
30/// Quadrature rule for numerical integration.
31///
32/// Represents an approximation of an integral by a weighted sum over discrete points.
33/// The rule contains quadrature points `x`, weights `w`, and auxiliary arrays
34/// `x_forward` and `x_backward` for efficient computation.
35#[derive(Debug, Clone)]
36pub struct Rule<T> {
37    /// Quadrature points, in non-decreasing order
38    pub(crate) x: Vec<T>,
39    /// Quadrature weights
40    pub(crate) w: Vec<T>,
41    /// Distance from left endpoint: x - a
42    pub(crate) x_forward: Vec<T>,
43    /// Distance from right endpoint: b - x
44    pub(crate) x_backward: Vec<T>,
45    /// Left endpoint of integration interval
46    pub(crate) a: T,
47    /// Right endpoint of integration interval
48    pub(crate) b: T,
49}
50
51impl<T: Copy> Rule<T> {
52    /// Quadrature points, in non-decreasing order
53    pub fn x(&self) -> &[T] {
54        &self.x
55    }
56
57    /// Quadrature weights, one per point
58    pub fn w(&self) -> &[T] {
59        &self.w
60    }
61
62    /// Distance of each point from the left endpoint: `x - a`
63    pub fn x_forward(&self) -> &[T] {
64        &self.x_forward
65    }
66
67    /// Distance of each point from the right endpoint: `b - x`
68    pub fn x_backward(&self) -> &[T] {
69        &self.x_backward
70    }
71
72    /// Left endpoint of the integration interval
73    pub fn a(&self) -> T {
74        self.a
75    }
76
77    /// Right endpoint of the integration interval
78    pub fn b(&self) -> T {
79        self.b
80    }
81}
82
83impl<T> Rule<T>
84where
85    T: CustomNumeric,
86{
87    /// Create a new quadrature rule from points and weights.
88    ///
89    /// # Arguments
90    /// * `x` - Quadrature points
91    /// * `w` - Quadrature weights
92    /// * `a` - Left endpoint (default: -1.0)
93    /// * `b` - Right endpoint (default: 1.0)
94    ///
95    /// The points are not checked for order or for lying in `[a, b]`;
96    /// [`Self::validate`] does that.
97    ///
98    /// # Errors
99    /// [`Error::InvalidParameter`] if x and w have different lengths.
100    pub fn new(x: Vec<T>, w: Vec<T>, a: T, b: T) -> Result<Self, Error> {
101        check_weights(&x, &w)?;
102
103        let x_forward: Vec<T> = x.iter().map(|&xi| xi - a).collect();
104        let x_backward: Vec<T> = x.iter().map(|&xi| b - xi).collect();
105
106        Ok(Self {
107            x,
108            w,
109            x_forward,
110            x_backward,
111            a,
112            b,
113        })
114    }
115
116    /// Create a new quadrature rule from vectors.
117    ///
118    /// # Errors
119    /// The errors of [`Self::new`].
120    pub fn from_vectors(x: Vec<T>, w: Vec<T>, a: T, b: T) -> Result<Self, Error> {
121        Self::new(x, w, a, b)
122    }
123
124    /// Create a default rule with empty arrays.
125    pub fn empty() -> Self {
126        Self {
127            x: vec![],
128            w: vec![],
129            x_forward: vec![],
130            x_backward: vec![],
131            a: <T as CustomNumeric>::from_f64_unchecked(-1.0),
132            b: <T as CustomNumeric>::from_f64_unchecked(1.0),
133        }
134    }
135
136    /// Reseat the rule to a new interval [a, b].
137    ///
138    /// Scales and translates the quadrature points and weights to the new interval.
139    pub fn reseat(&self, a: T, b: T) -> Self {
140        let scaling = (b - a) / (self.b - self.a);
141        let midpoint_old = (self.b + self.a) * <T as CustomNumeric>::from_f64_unchecked(0.5);
142        let midpoint_new = (b + a) * <T as CustomNumeric>::from_f64_unchecked(0.5);
143
144        // Transform x: scaling * (xi - midpoint_old) + midpoint_new
145        let new_x: Vec<T> = self
146            .x
147            .iter()
148            .map(|&xi| scaling * (xi - midpoint_old) + midpoint_new)
149            .collect();
150        let new_w: Vec<T> = self.w.iter().map(|&wi| wi * scaling).collect();
151        let new_x_forward: Vec<T> = self.x_forward.iter().map(|&xi| xi * scaling).collect();
152        let new_x_backward: Vec<T> = self.x_backward.iter().map(|&xi| xi * scaling).collect();
153
154        Self {
155            x: new_x,
156            w: new_w,
157            x_forward: new_x_forward,
158            x_backward: new_x_backward,
159            a,
160            b,
161        }
162    }
163
164    /// Scale the weights by a factor.
165    pub fn scale(&self, factor: T) -> Self {
166        Self {
167            x: self.x.clone(),
168            w: self.w.iter().map(|&wi| wi * factor).collect(),
169            x_forward: self.x_forward.clone(),
170            x_backward: self.x_backward.clone(),
171            a: self.a,
172            b: self.b,
173        }
174    }
175
176    /// Create a piecewise rule over multiple segments.
177    ///
178    /// # Arguments
179    /// * `edges` - Segment boundaries: at least 2, finite and strictly
180    ///   increasing, with finite segment lengths and a finite sum of the ends
181    ///   of each segment (the midpoint of the segment is computed from it)
182    ///
183    /// # Errors
184    /// [`Error::InvalidParameter`] if `edges` does not meet these conditions
185    pub fn piecewise(&self, edges: &[T]) -> Result<Self, Error> {
186        if edges.len() < 2 {
187            return Err(Error::InvalidParameter {
188                name: "edges",
189                value: format!("{} edges", edges.len()),
190                reason: "must have at least 2 entries".to_string(),
191            });
192        }
193        if let Some((i, e)) = edges
194            .iter()
195            .enumerate()
196            .find(|(_, e)| !e.to_f64().is_finite())
197        {
198            return Err(Error::InvalidParameter {
199                name: "edges",
200                value: format!("{:?} at index {i}", e.to_f64()),
201                reason: "must be finite".to_string(),
202            });
203        }
204        for i in 1..edges.len() {
205            let length = (edges[i] - edges[i - 1]).to_f64();
206            if !(length > 0.0 && length.is_finite()) {
207                return Err(Error::InvalidParameter {
208                    name: "edges",
209                    value: format!(
210                        "{:?} after {:?} at index {i}",
211                        edges[i].to_f64(),
212                        edges[i - 1].to_f64()
213                    ),
214                    reason: "must be strictly increasing, with finite segment lengths".to_string(),
215                });
216            }
217            // `reseat` computes the midpoint as (a + b) * 0.5
218            if !(edges[i] + edges[i - 1]).to_f64().is_finite() {
219                return Err(Error::InvalidParameter {
220                    name: "edges",
221                    value: format!(
222                        "{:?} after {:?} at index {i}",
223                        edges[i].to_f64(),
224                        edges[i - 1].to_f64()
225                    ),
226                    reason: "must have a finite sum of the ends of each segment".to_string(),
227                });
228            }
229        }
230
231        let mut rules = Vec::new();
232        for i in 0..edges.len() - 1 {
233            let rule = self.reseat(edges[i], edges[i + 1]);
234            rules.push(rule);
235        }
236
237        Ok(Self::join(&rules))
238    }
239
240    /// Join multiple rules into a single rule.
241    ///
242    /// # Arguments
243    /// * `rules` - Vector of rules to join (must be contiguous and sorted)
244    ///
245    /// # Panics
246    /// Panics if rules are empty, not contiguous, or not sorted.
247    pub fn join(rules: &[Self]) -> Self {
248        if rules.is_empty() {
249            return Self::empty();
250        }
251
252        let a = rules[0].a;
253        let b = rules[rules.len() - 1].b;
254
255        // Check that rules are contiguous
256        for i in 1..rules.len() {
257            if (rules[i].a - rules[i - 1].b).abs_as_same_type() > T::epsilon() {
258                panic!("rules must be contiguous");
259            }
260        }
261
262        // Concatenate all arrays
263        let mut x_vec = Vec::new();
264        let mut w_vec = Vec::new();
265        let mut x_forward_vec = Vec::new();
266        let mut x_backward_vec = Vec::new();
267
268        for rule in rules {
269            // Adjust x_forward and x_backward for global coordinates
270            let x_forward_adj: Vec<T> =
271                rule.x_forward.iter().map(|&xi| xi + (rule.a - a)).collect();
272            let x_backward_adj: Vec<T> = rule
273                .x_backward
274                .iter()
275                .map(|&xi| xi + (b - rule.b))
276                .collect();
277
278            x_vec.extend(rule.x.iter().cloned());
279            w_vec.extend(rule.w.iter().cloned());
280            x_forward_vec.extend(x_forward_adj.iter().cloned());
281            x_backward_vec.extend(x_backward_adj.iter().cloned());
282        }
283
284        // Sort by x values to maintain order
285        let mut indices: Vec<usize> = (0..x_vec.len()).collect();
286        indices.sort_by(|&a, &b| x_vec[a].partial_cmp(&x_vec[b]).unwrap());
287
288        let sorted_x: Vec<T> = indices.iter().map(|&i| x_vec[i]).collect();
289        let sorted_w: Vec<T> = indices.iter().map(|&i| w_vec[i]).collect();
290
291        // Recalculate x_forward and x_backward after sorting
292        let sorted_x_forward: Vec<T> = sorted_x.iter().map(|&xi| xi - a).collect();
293        let sorted_x_backward: Vec<T> = sorted_x.iter().map(|&xi| b - xi).collect();
294
295        Self {
296            x: sorted_x,
297            w: sorted_w,
298            x_forward: sorted_x_forward,
299            x_backward: sorted_x_backward,
300            a,
301            b,
302        }
303    }
304
305    /// Convert the rule to a different numeric type.
306    pub fn convert<U>(&self) -> Rule<U>
307    where
308        U: CustomNumeric + Copy + Debug + std::fmt::Display,
309    {
310        let x: Vec<U> = self
311            .x
312            .iter()
313            .map(|&xi| <U as CustomNumeric>::from_f64_unchecked(xi.to_f64()))
314            .collect();
315        let w: Vec<U> = self
316            .w
317            .iter()
318            .map(|&wi| <U as CustomNumeric>::from_f64_unchecked(wi.to_f64()))
319            .collect();
320        let x_forward: Vec<U> = self
321            .x_forward
322            .iter()
323            .map(|&xi| <U as CustomNumeric>::from_f64_unchecked(xi.to_f64()))
324            .collect();
325        let x_backward: Vec<U> = self
326            .x_backward
327            .iter()
328            .map(|&xi| <U as CustomNumeric>::from_f64_unchecked(xi.to_f64()))
329            .collect();
330        let a = <U as CustomNumeric>::from_f64_unchecked(self.a.to_f64());
331        let b = <U as CustomNumeric>::from_f64_unchecked(self.b.to_f64());
332
333        Rule {
334            x,
335            w,
336            x_forward,
337            x_backward,
338            a,
339            b,
340        }
341    }
342
343    /// Validate the rule for consistency.
344    ///
345    /// # Returns
346    /// `true` if the rule is valid, `false` otherwise.
347    pub fn validate(&self) -> bool {
348        // Check interval validity
349        if self.a >= self.b {
350            return false;
351        }
352
353        // Check array lengths
354        if self.x.len() != self.w.len() {
355            return false;
356        }
357
358        if self.x.len() != self.x_forward.len() || self.x.len() != self.x_backward.len() {
359            return false;
360        }
361
362        // Check that all points are within [a, b]
363        for &xi in self.x.iter() {
364            if xi < self.a || xi > self.b {
365                return false;
366            }
367        }
368
369        // Check that points are sorted
370        for i in 1..self.x.len() {
371            if self.x[i] <= self.x[i - 1] {
372                return false;
373            }
374        }
375
376        // Check x_forward and x_backward consistency
377        for i in 0..self.x.len() {
378            let expected_forward = self.x[i] - self.a;
379            let expected_backward = self.b - self.x[i];
380
381            if (self.x_forward[i] - expected_forward).abs_as_same_type() > T::epsilon() {
382                return false;
383            }
384            if (self.x_backward[i] - expected_backward).abs_as_same_type() > T::epsilon() {
385                return false;
386            }
387        }
388
389        true
390    }
391}
392
393/// CustomNumeric-based implementation for f64 and Df64 support
394impl<T> Rule<T>
395where
396    T: CustomNumeric,
397{
398    /// Create a new quadrature rule from points and weights (CustomNumeric version).
399    ///
400    /// # Errors
401    /// [`Error::InvalidParameter`] if x and w have different lengths.
402    pub fn new_custom(x: Vec<T>, w: Vec<T>, a: T, b: T) -> Result<Self, Error> {
403        check_weights(&x, &w)?;
404
405        let x_forward: Vec<T> = x.iter().map(|&xi| xi - a).collect();
406        let x_backward: Vec<T> = x.iter().map(|&xi| b - xi).collect();
407
408        Ok(Self {
409            x,
410            w,
411            x_forward,
412            x_backward,
413            a,
414            b,
415        })
416    }
417
418    /// Create a new quadrature rule from vectors (CustomNumeric version).
419    ///
420    /// # Errors
421    /// The errors of [`Self::new_custom`].
422    pub fn from_vectors_custom(x: Vec<T>, w: Vec<T>, a: T, b: T) -> Result<Self, Error> {
423        Self::new_custom(x, w, a, b)
424    }
425
426    /// Reseat the rule to a new interval [a, b] (CustomNumeric version).
427    pub fn reseat_custom(&self, a: T, b: T) -> Self {
428        let scaling = (b - a) / (self.b - self.a);
429        let midpoint_old = (self.b + self.a) * <T as CustomNumeric>::from_f64_unchecked(0.5);
430        let midpoint_new = (b + a) * <T as CustomNumeric>::from_f64_unchecked(0.5);
431
432        // Transform x: scaling * (xi - midpoint_old) + midpoint_new
433        let new_x: Vec<T> = self
434            .x
435            .iter()
436            .map(|&xi| scaling * (xi - midpoint_old) + midpoint_new)
437            .collect();
438        let new_w: Vec<T> = self.w.iter().map(|&wi| wi * scaling).collect();
439        let new_x_forward: Vec<T> = self.x_forward.iter().map(|&xi| xi * scaling).collect();
440        let new_x_backward: Vec<T> = self.x_backward.iter().map(|&xi| xi * scaling).collect();
441
442        Self {
443            x: new_x,
444            w: new_w,
445            x_forward: new_x_forward,
446            x_backward: new_x_backward,
447            a,
448            b,
449        }
450    }
451
452    /// Scale the weights by a factor (CustomNumeric version).
453    pub fn scale_custom(&self, factor: T) -> Self {
454        Self {
455            x: self.x.clone(),
456            w: self.w.iter().map(|&wi| wi * factor).collect(),
457            x_forward: self.x_forward.clone(),
458            x_backward: self.x_backward.clone(),
459            a: self.a,
460            b: self.b,
461        }
462    }
463
464    /// Validate the rule for consistency (CustomNumeric version).
465    pub fn validate_custom(&self) -> bool {
466        // Check interval validity
467        if self.a >= self.b {
468            return false;
469        }
470
471        // Check array lengths
472        if self.x.len() != self.w.len() {
473            return false;
474        }
475
476        if self.x.len() != self.x_forward.len() || self.x.len() != self.x_backward.len() {
477            return false;
478        }
479
480        // Check that all points are within [a, b]
481        for &xi in self.x.iter() {
482            if xi < self.a || xi > self.b {
483                return false;
484            }
485        }
486
487        // Check that points are sorted
488        for i in 1..self.x.len() {
489            if self.x[i] <= self.x[i - 1] {
490                return false;
491            }
492        }
493
494        // Check x_forward and x_backward consistency
495        for i in 0..self.x.len() {
496            let expected_forward = self.x[i] - self.a;
497            let expected_backward = self.b - self.x[i];
498
499            if (self.x_forward[i] - expected_forward).abs_as_same_type() > T::epsilon() {
500                return false;
501            }
502            if (self.x_backward[i] - expected_backward).abs_as_same_type() > T::epsilon() {
503                return false;
504            }
505        }
506
507        true
508    }
509}
510
511/// Df64-specific implementation without ScalarOperand requirement
512impl Rule<crate::Df64> {
513    /// Create a new quadrature rule from points and weights (Df64 version).
514    ///
515    /// # Errors
516    /// [`Error::InvalidParameter`] if x and w have different lengths.
517    pub fn new_twofloat(
518        x: Vec<crate::Df64>,
519        w: Vec<crate::Df64>,
520        a: crate::Df64,
521        b: crate::Df64,
522    ) -> Result<Self, Error> {
523        check_weights(&x, &w)?;
524
525        let x_forward: Vec<crate::Df64> = x.iter().map(|&xi| xi - a).collect();
526        let x_backward: Vec<crate::Df64> = x.iter().map(|&xi| b - xi).collect();
527
528        Ok(Self {
529            x,
530            w,
531            x_forward,
532            x_backward,
533            a,
534            b,
535        })
536    }
537
538    /// Create a new quadrature rule from vectors (Df64 version).
539    ///
540    /// # Errors
541    /// The errors of [`Self::new_twofloat`].
542    pub fn from_vectors_twofloat(
543        x: Vec<crate::Df64>,
544        w: Vec<crate::Df64>,
545        a: crate::Df64,
546        b: crate::Df64,
547    ) -> Result<Self, Error> {
548        Self::new_twofloat(x, w, a, b)
549    }
550
551    /// Reseat the rule to a new interval [a, b] (Df64 version).
552    pub fn reseat_twofloat(&self, a: crate::Df64, b: crate::Df64) -> Self {
553        let scaling = (b - a) / (self.b - self.a);
554        let midpoint_old =
555            (self.b + self.a) * <crate::Df64 as CustomNumeric>::from_f64_unchecked(0.5);
556        let midpoint_new = (b + a) * <crate::Df64 as CustomNumeric>::from_f64_unchecked(0.5);
557
558        // Transform x: scaling * (xi - midpoint_old) + midpoint_new
559        let new_x: Vec<crate::Df64> = self
560            .x
561            .iter()
562            .map(|&xi| scaling * (xi - midpoint_old) + midpoint_new)
563            .collect();
564        let new_w: Vec<crate::Df64> = self.w.iter().map(|&wi| wi * scaling).collect();
565        let new_x_forward: Vec<crate::Df64> =
566            self.x_forward.iter().map(|&xi| xi * scaling).collect();
567        let new_x_backward: Vec<crate::Df64> =
568            self.x_backward.iter().map(|&xi| xi * scaling).collect();
569
570        Self {
571            x: new_x,
572            w: new_w,
573            x_forward: new_x_forward,
574            x_backward: new_x_backward,
575            a,
576            b,
577        }
578    }
579
580    /// Scale the weights by a factor (Df64 version).
581    pub fn scale_twofloat(&self, factor: crate::Df64) -> Self {
582        Self {
583            x: self.x.clone(),
584            w: self.w.iter().map(|&wi| wi * factor).collect(),
585            x_forward: self.x_forward.clone(),
586            x_backward: self.x_backward.clone(),
587            a: self.a,
588            b: self.b,
589        }
590    }
591
592    /// Validate the rule for consistency (Df64 version).
593    pub fn validate_twofloat(&self) -> bool {
594        // Check interval validity
595        if self.a >= self.b {
596            return false;
597        }
598
599        // Check array lengths
600        if self.x.len() != self.w.len() {
601            return false;
602        }
603
604        if self.x.len() != self.x_forward.len() || self.x.len() != self.x_backward.len() {
605            return false;
606        }
607
608        // Check that all points are within [a, b]
609        for &xi in self.x.iter() {
610            if xi < self.a || xi > self.b {
611                return false;
612            }
613        }
614
615        // Check that points are sorted
616        for i in 1..self.x.len() {
617            if self.x[i] <= self.x[i - 1] {
618                return false;
619            }
620        }
621
622        // Check x_forward and x_backward consistency
623        for i in 0..self.x.len() {
624            let expected_forward = self.x[i] - self.a;
625            let expected_backward = self.b - self.x[i];
626
627            if (self.x_forward[i] - expected_forward).abs() > crate::Df64::epsilon() {
628                return false;
629            }
630            if (self.x_backward[i] - expected_backward).abs() > crate::Df64::epsilon() {
631                return false;
632            }
633        }
634
635        true
636    }
637}
638
639/// Compute Gauss-Legendre quadrature nodes and weights using Newton's method.
640///
641/// This is a simplified implementation of the Gauss-Legendre quadrature rule.
642/// For production use, a more sophisticated algorithm would be preferred.
643fn gauss_legendre_nodes_weights<T>(n: usize) -> (Vec<T>, Vec<T>)
644where
645    T: CustomNumeric + Copy + Debug + std::fmt::Display + 'static,
646{
647    if n == 0 {
648        return (Vec::new(), Vec::new());
649    }
650
651    if n == 1 {
652        return (
653            vec![<T as CustomNumeric>::from_f64_unchecked(0.0)],
654            vec![<T as CustomNumeric>::from_f64_unchecked(2.0)],
655        );
656    }
657
658    let mut x = Vec::with_capacity(n);
659    let mut w = Vec::with_capacity(n);
660
661    // Use Newton's method to find roots of Legendre polynomial
662    let m = n.div_ceil(2);
663
664    // Use high-precision constants via CustomNumeric trait
665    let pi = T::pi();
666
667    for i in 0..m {
668        // Convert integers directly to avoid f64 intermediate
669        let i_val = <T as CustomNumeric>::from_f64_unchecked(i as f64);
670        let n_val = <T as CustomNumeric>::from_f64_unchecked(n as f64);
671        let three_quarters = <T as CustomNumeric>::from_f64_unchecked(0.75);
672        let half = <T as CustomNumeric>::from_f64_unchecked(0.5);
673
674        // Initial guess using Chebyshev nodes
675        let mut z = (pi * (i_val + three_quarters) / (n_val + half)).cos();
676
677        // Newton's method to refine the root
678        for _ in 0..10 {
679            let (p0, p1) = legendre_polynomial_and_derivative(n, z);
680            if p0.abs_as_same_type() < T::epsilon() {
681                break;
682            }
683            z = z - p0 / p1;
684        }
685
686        // Compute weight using high-precision constants
687        let two = <T as CustomNumeric>::from_f64_unchecked(2.0);
688        let one = <T as CustomNumeric>::from_f64_unchecked(1.0);
689        let (_, p1) = legendre_polynomial_and_derivative(n, z);
690        let weight = two / ((one - z * z) * p1 * p1);
691
692        x.push(-z);
693        w.push(weight);
694
695        if i != n - 1 - i {
696            x.push(z);
697            w.push(weight);
698        }
699    }
700
701    // Sort by x values
702    let mut indices: Vec<usize> = (0..n).collect();
703    indices.sort_by(|&a, &b| x[a].partial_cmp(&x[b]).unwrap());
704
705    let sorted_x: Vec<T> = indices.iter().map(|&i| x[i]).collect();
706    let sorted_w: Vec<T> = indices.iter().map(|&i| w[i]).collect();
707
708    (sorted_x, sorted_w)
709}
710
711/// Compute Legendre polynomial P_n(x) and its derivative using recurrence relation.
712fn legendre_polynomial_and_derivative<T>(n: usize, x: T) -> (T, T)
713where
714    T: CustomNumeric + Copy + Debug + std::fmt::Display + 'static,
715{
716    if n == 0 {
717        return (
718            <T as CustomNumeric>::from_f64_unchecked(1.0),
719            <T as CustomNumeric>::from_f64_unchecked(0.0),
720        );
721    }
722
723    if n == 1 {
724        return (x, <T as CustomNumeric>::from_f64_unchecked(1.0));
725    }
726
727    let mut p0 = <T as CustomNumeric>::from_f64_unchecked(1.0);
728    let mut p1 = x;
729    let mut dp0 = <T as CustomNumeric>::from_f64_unchecked(0.0);
730    let mut dp1 = <T as CustomNumeric>::from_f64_unchecked(1.0);
731
732    for k in 2..=n {
733        let k_f = <T as CustomNumeric>::from_f64_unchecked(k as f64);
734        let k1_f = <T as CustomNumeric>::from_f64_unchecked((k - 1) as f64);
735        let _k2_f = <T as CustomNumeric>::from_f64_unchecked((k - 2) as f64);
736
737        let p2 = ((<T as CustomNumeric>::from_f64_unchecked(2.0) * k1_f
738            + <T as CustomNumeric>::from_f64_unchecked(1.0))
739            * x
740            * p1
741            - k1_f * p0)
742            / k_f;
743        let dp2 = ((<T as CustomNumeric>::from_f64_unchecked(2.0) * k1_f
744            + <T as CustomNumeric>::from_f64_unchecked(1.0))
745            * (p1 + x * dp1)
746            - k1_f * dp0)
747            / k_f;
748
749        p0 = p1;
750        p1 = p2;
751        dp0 = dp1;
752        dp1 = dp2;
753    }
754
755    (p1, dp1)
756}
757
758/// Create a Gauss-Legendre quadrature rule with n points on [-1, 1].
759///
760/// # Arguments
761/// * `n` - Number of quadrature points
762///
763/// # Returns
764/// A Gauss-Legendre quadrature rule
765pub fn legendre<T>(n: usize) -> Rule<T>
766where
767    T: CustomNumeric + Copy + Debug + std::fmt::Display + 'static,
768{
769    if n == 0 {
770        return Rule::empty();
771    }
772
773    let (x, w) = gauss_legendre_nodes_weights(n);
774
775    Rule::from_vectors(
776        x,
777        w,
778        <T as CustomNumeric>::from_f64_unchecked(-1.0),
779        <T as CustomNumeric>::from_f64_unchecked(1.0),
780    )
781    .expect("the Gauss-Legendre nodes and weights have the same length")
782}
783
784/// Compute Gauss-Legendre quadrature nodes and weights using CustomNumeric
785fn gauss_legendre_nodes_weights_custom<T>(n: usize) -> (Vec<T>, Vec<T>)
786where
787    T: CustomNumeric,
788{
789    if n == 0 {
790        return (Vec::new(), Vec::new());
791    }
792
793    if n == 1 {
794        return (
795            vec![<T as CustomNumeric>::from_f64_unchecked(0.0)],
796            vec![<T as CustomNumeric>::from_f64_unchecked(2.0)],
797        );
798    }
799
800    let mut x = Vec::with_capacity(n);
801    let mut w = Vec::with_capacity(n);
802
803    // Use Newton's method to find roots of Legendre polynomial
804    let m = n.div_ceil(2);
805    let pi = <T as CustomNumeric>::from_f64_unchecked(std::f64::consts::PI);
806
807    for i in 0..m {
808        // Initial guess using Chebyshev nodes
809        // Note: Df64's cos() has only f64-level precision (~15-16 digits), not the full
810        // theoretical 30-digit precision. This limits Df64 interpolation accuracy to ~1e-16,
811        // not the 1e-30 that might be theoretically possible with perfect double-double arithmetic.
812        let mut z = (pi * <T as CustomNumeric>::from_f64_unchecked(i as f64 + 0.75)
813            / <T as CustomNumeric>::from_f64_unchecked(n as f64 + 0.5))
814        .cos();
815
816        // Newton's method to refine the root
817        for _ in 0..10 {
818            let (p0, p1) = legendre_polynomial_and_derivative_custom(n, z);
819            if p0.abs_as_same_type() < T::epsilon() {
820                break;
821            }
822            z = z - p0 / p1;
823        }
824
825        // Compute weight
826        let (_, p1) = legendre_polynomial_and_derivative_custom(n, z);
827        let weight = <T as CustomNumeric>::from_f64_unchecked(2.0)
828            / ((<T as CustomNumeric>::from_f64_unchecked(1.0) - z * z) * p1 * p1);
829
830        x.push(-z);
831        w.push(weight);
832
833        if i != n - 1 - i {
834            x.push(z);
835            w.push(weight);
836        }
837    }
838
839    // Sort by x values
840    let mut indices: Vec<usize> = (0..n).collect();
841    indices.sort_by(|&a, &b| x[a].partial_cmp(&x[b]).unwrap());
842
843    let sorted_x: Vec<T> = indices.iter().map(|&i| x[i]).collect();
844    let sorted_w: Vec<T> = indices.iter().map(|&i| w[i]).collect();
845
846    (sorted_x, sorted_w)
847}
848
849/// Compute Legendre polynomial P_n(x) and its derivative using CustomNumeric
850fn legendre_polynomial_and_derivative_custom<T>(n: usize, x: T) -> (T, T)
851where
852    T: CustomNumeric,
853{
854    if n == 0 {
855        return (
856            <T as CustomNumeric>::from_f64_unchecked(1.0),
857            <T as CustomNumeric>::from_f64_unchecked(0.0),
858        );
859    }
860
861    if n == 1 {
862        return (x, <T as CustomNumeric>::from_f64_unchecked(1.0));
863    }
864
865    let mut p0 = <T as CustomNumeric>::from_f64_unchecked(1.0);
866    let mut p1 = x;
867    let mut dp0 = <T as CustomNumeric>::from_f64_unchecked(0.0);
868    let mut dp1 = <T as CustomNumeric>::from_f64_unchecked(1.0);
869
870    for k in 2..=n {
871        let k_f = <T as CustomNumeric>::from_f64_unchecked(k as f64);
872        let k1_f = <T as CustomNumeric>::from_f64_unchecked((k - 1) as f64);
873        let _k2_f = <T as CustomNumeric>::from_f64_unchecked((k - 2) as f64);
874
875        let two = <T as CustomNumeric>::from_f64_unchecked(2.0);
876        let one = <T as CustomNumeric>::from_f64_unchecked(1.0);
877
878        let p2 = ((two * k1_f + one) * x * p1 - k1_f * p0) / k_f;
879        let dp2 = ((two * k1_f + one) * (p1 + x * dp1) - k1_f * dp0) / k_f;
880
881        p0 = p1;
882        p1 = p2;
883        dp0 = dp1;
884        dp1 = dp2;
885    }
886
887    (p1, dp1)
888}
889
890/// Create a Gauss-Legendre quadrature rule with n points on [-1, 1] (CustomNumeric version).
891pub fn legendre_custom<T>(n: usize) -> Rule<T>
892where
893    T: CustomNumeric,
894{
895    if n == 0 {
896        return Rule::new_custom(
897            vec![],
898            vec![],
899            <T as CustomNumeric>::from_f64_unchecked(-1.0),
900            <T as CustomNumeric>::from_f64_unchecked(1.0),
901        )
902        .expect("the Gauss-Legendre nodes and weights have the same length");
903    }
904
905    let (x, w) = gauss_legendre_nodes_weights_custom(n);
906
907    Rule::from_vectors_custom(
908        x,
909        w,
910        <T as CustomNumeric>::from_f64_unchecked(-1.0),
911        <T as CustomNumeric>::from_f64_unchecked(1.0),
912    )
913    .expect("the Gauss-Legendre nodes and weights have the same length")
914}
915
916/// Create a Gauss-Legendre quadrature rule with n points on [-1, 1] (Df64 version).
917pub fn legendre_twofloat(n: usize) -> Rule<crate::Df64> {
918    if n == 0 {
919        return Rule::new_twofloat(
920            vec![],
921            vec![],
922            <crate::Df64 as CustomNumeric>::from_f64_unchecked(-1.0),
923            <crate::Df64 as CustomNumeric>::from_f64_unchecked(1.0),
924        )
925        .expect("the Gauss-Legendre nodes and weights have the same length");
926    }
927
928    let mut x: Vec<crate::Df64> = vec![crate::Df64::ZERO; n];
929    let mut w: Vec<crate::Df64> = vec![crate::Df64::ZERO; n];
930    xprec::gauss::gauss_legendre(&mut x, &mut w);
931
932    Rule::from_vectors_twofloat(
933        x,
934        w,
935        <crate::Df64 as CustomNumeric>::from_f64_unchecked(-1.0),
936        <crate::Df64 as CustomNumeric>::from_f64_unchecked(1.0),
937    )
938    .expect("the Gauss-Legendre nodes and weights have the same length")
939}
940
941/// Create Legendre Vandermonde matrix for polynomial interpolation
942///
943/// # Arguments
944/// * `x` - Points where polynomials are evaluated
945/// * `degree` - Maximum degree of Legendre polynomials
946///
947/// # Returns
948/// Matrix V where V[i,j] = P_j(x_i), with P_j being the j-th Legendre polynomial
949pub fn legendre_vandermonde<T: CustomNumeric>(x: &[T], degree: usize) -> Mat<T> {
950    let n = x.len();
951    let mut v = Mat::<T>::from_elem([n, degree + 1], T::zero());
952
953    // First column is all ones (P_0(x) = 1)
954    for i in 0..n {
955        v[[i, 0]] = T::from_f64_unchecked(1.0);
956    }
957
958    // Second column is x (P_1(x) = x)
959    if degree > 0 {
960        for i in 0..n {
961            v[[i, 1]] = x[i];
962        }
963    }
964
965    // Recurrence relation: P_n(x) = ((2n-1)x*P_{n-1}(x) - (n-1)*P_{n-2}(x)) / n
966    for j in 2..=degree {
967        for i in 0..n {
968            let n_f64 = j as f64;
969            let term1 = T::from_f64_unchecked(2.0 * n_f64 - 1.0) * x[i] * v[[i, j - 1]];
970            let term2 = T::from_f64_unchecked(n_f64 - 1.0) * v[[i, j - 2]];
971            v[[i, j]] = (term1 - term2) / T::from_f64_unchecked(n_f64);
972        }
973    }
974
975    v
976}
977
978/// Generic Legendre Gauss quadrature rule for CustomNumeric types
979pub fn legendre_generic<T: CustomNumeric + 'static>(n: usize) -> Rule<T> {
980    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f64>() {
981        // For f64, use the existing legendre function
982        let rule_f64 = legendre::<f64>(n);
983        Rule::new(
984            rule_f64
985                .x
986                .iter()
987                .map(|&x| T::from_f64_unchecked(x))
988                .collect(),
989            rule_f64
990                .w
991                .iter()
992                .map(|&w| T::from_f64_unchecked(w))
993                .collect(),
994            T::from_f64_unchecked(rule_f64.a),
995            T::from_f64_unchecked(rule_f64.b),
996        )
997        .expect("the Gauss-Legendre nodes and weights have the same length")
998    } else {
999        // For Df64, use legendre_twofloat
1000        let rule_tf = legendre_twofloat(n);
1001        Rule::new(
1002            rule_tf.x.iter().map(|&x| T::convert_from(x)).collect(),
1003            rule_tf.w.iter().map(|&w| T::convert_from(w)).collect(),
1004            T::from_f64_unchecked(rule_tf.a.into()),
1005            T::from_f64_unchecked(rule_tf.b.into()),
1006        )
1007        .expect("the Gauss-Legendre nodes and weights have the same length")
1008    }
1009}
1010
1011#[cfg(test)]
1012#[path = "gauss_tests.rs"]
1013mod tests;