1use crate::error::Error;
13use crate::matrix::Mat;
14use crate::numeric::CustomNumeric;
15use std::fmt::Debug;
16
17fn 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#[derive(Debug, Clone)]
36pub struct Rule<T> {
37 pub(crate) x: Vec<T>,
39 pub(crate) w: Vec<T>,
41 pub(crate) x_forward: Vec<T>,
43 pub(crate) x_backward: Vec<T>,
45 pub(crate) a: T,
47 pub(crate) b: T,
49}
50
51impl<T: Copy> Rule<T> {
52 pub fn x(&self) -> &[T] {
54 &self.x
55 }
56
57 pub fn w(&self) -> &[T] {
59 &self.w
60 }
61
62 pub fn x_forward(&self) -> &[T] {
64 &self.x_forward
65 }
66
67 pub fn x_backward(&self) -> &[T] {
69 &self.x_backward
70 }
71
72 pub fn a(&self) -> T {
74 self.a
75 }
76
77 pub fn b(&self) -> T {
79 self.b
80 }
81}
82
83impl<T> Rule<T>
84where
85 T: CustomNumeric,
86{
87 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn validate(&self) -> bool {
348 if self.a >= self.b {
350 return false;
351 }
352
353 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 for &xi in self.x.iter() {
364 if xi < self.a || xi > self.b {
365 return false;
366 }
367 }
368
369 for i in 1..self.x.len() {
371 if self.x[i] <= self.x[i - 1] {
372 return false;
373 }
374 }
375
376 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
393impl<T> Rule<T>
395where
396 T: CustomNumeric,
397{
398 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 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 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 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 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 pub fn validate_custom(&self) -> bool {
466 if self.a >= self.b {
468 return false;
469 }
470
471 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 for &xi in self.x.iter() {
482 if xi < self.a || xi > self.b {
483 return false;
484 }
485 }
486
487 for i in 1..self.x.len() {
489 if self.x[i] <= self.x[i - 1] {
490 return false;
491 }
492 }
493
494 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
511impl Rule<crate::Df64> {
513 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 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 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 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 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 pub fn validate_twofloat(&self) -> bool {
594 if self.a >= self.b {
596 return false;
597 }
598
599 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 for &xi in self.x.iter() {
610 if xi < self.a || xi > self.b {
611 return false;
612 }
613 }
614
615 for i in 1..self.x.len() {
617 if self.x[i] <= self.x[i - 1] {
618 return false;
619 }
620 }
621
622 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
639fn 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 let m = n.div_ceil(2);
663
664 let pi = T::pi();
666
667 for i in 0..m {
668 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 let mut z = (pi * (i_val + three_quarters) / (n_val + half)).cos();
676
677 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 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 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
711fn 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
758pub 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
784fn 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 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 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 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 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 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
849fn 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
890pub 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
916pub 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
941pub 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 for i in 0..n {
955 v[[i, 0]] = T::from_f64_unchecked(1.0);
956 }
957
958 if degree > 0 {
960 for i in 0..n {
961 v[[i, 1]] = x[i];
962 }
963 }
964
965 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
978pub fn legendre_generic<T: CustomNumeric + 'static>(n: usize) -> Rule<T> {
980 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f64>() {
981 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 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;