1use crate::error::Error;
7
8#[derive(Debug, Clone)]
10pub struct PiecewiseLegendrePoly {
11 pub(crate) polyorder: usize,
13 pub(crate) xmin: f64,
15 pub(crate) xmax: f64,
17 pub(crate) knots: Vec<f64>,
19 pub(crate) delta_x: Vec<f64>,
21 pub(crate) data: mdarray::DTensor<f64, 2>,
23 pub(crate) symm: i32,
25 pub(crate) l: i32,
35 pub(crate) xm: Vec<f64>,
37 pub(crate) inv_xs: Vec<f64>,
39 pub(crate) norms: Vec<f64>,
41}
42
43fn 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
77fn 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 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 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 let xm: Vec<f64> = (0..nsegments)
160 .map(|i| 0.5 * (knots[i] + knots[i + 1]))
161 .collect();
162
163 let inv_xs: Vec<f64> = delta_x.iter().map(|&dx| 2.0 / dx).collect();
165
166 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 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 pub fn symm(&self) -> i32 {
197 self.symm
198 }
199
200 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 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 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 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 pub fn evaluate(&self, x: f64) -> f64 {
282 self.try_evaluate(x).unwrap_or_else(|e| panic!("{e}"))
283 }
284
285 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 fn evaluate_in_domain(&self, x: f64) -> f64 {
297 let (i, x_tilde) = self.split_in_domain(x);
298 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 pub fn evaluate_many(&self, xs: &[f64]) -> Vec<f64> {
313 self.try_evaluate_many(xs).unwrap_or_else(|e| panic!("{e}"))
314 }
315
316 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 pub fn split(&self, x: f64) -> (usize, f64) {
335 self.try_split(x).unwrap_or_else(|e| panic!("{e}"))
336 }
337
338 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 fn split_in_domain(&self, x: f64) -> (usize, f64) {
350 for i in 0..self.knots.len() - 1 {
352 if x >= self.knots[i] && x <= self.knots[i + 1] {
353 let x_tilde = 2.0 * (x - self.xm[i]) / self.delta_x[i];
355 return (i, x_tilde);
356 }
357 }
358
359 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 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; let mut p_curr = x; 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 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 pub fn deriv(&self, n: usize) -> Self {
400 if n == 0 {
401 return self.clone();
402 }
403
404 let mut ddata = self.data.clone();
406 for _ in 0..n {
407 ddata = self.compute_derivative_coefficients(&ddata);
408 }
409
410 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 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 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 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 for j in (2..=n).rev() {
449 for col in 0..c_shape.1 {
451 der[[j - 1, col]] = (2.0 * (j as f64) - 1.0) * c[[j, col]];
452 }
453 for col in 0..c_shape.1 {
455 c[[j - 2, col]] += c[[j, col]];
456 }
457 }
458
459 if n > 1 {
461 for col in 0..c_shape.1 {
462 der[[1, col]] = 3.0 * c[[2, col]];
463 }
464 }
465
466 for col in 0..c_shape.1 {
468 der[[0, col]] = c[[1, col]];
469 }
470
471 der
472 }
473
474 pub fn derivs(&self, x: f64) -> Vec<f64> {
482 self.try_derivs(x).unwrap_or_else(|e| panic!("{e}"))
483 }
484
485 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 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 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 fn gauss_legendre_quadrature<F>(&self, a: f64, b: f64, f: F) -> f64
524 where
525 F: Fn(f64) -> f64,
526 {
527 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 pub fn roots(&self) -> Vec<f64> {
557 let xmid = (self.xmax + self.xmin) / 2.0;
558
559 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 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 let mut right = roots_half;
591 if !right.is_empty() {
592 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 let full_grid = self.refine_grid(&self.knots, 4);
611 self.find_all_roots(&full_grid)
612 }
613 }
614
615 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 fn find_all_roots(&self, xgrid: &[f64]) -> Vec<f64> {
632 if xgrid.is_empty() {
633 return Vec::new();
634 }
635
636 let fx: Vec<f64> = xgrid.iter().map(|&x| self.evaluate(x)).collect();
638
639 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 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 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 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 let max_elm = xgrid.iter().map(|&x| x.abs()).fold(0.0, f64::max);
677 let epsilon_x = f64::EPSILON * max_elm;
678
679 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 x_hit.sort_by(|a, b| a.partial_cmp(b).unwrap());
687 x_hit
688 }
689
690 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 fn close_enough(&self, a: f64, b: f64, eps: f64) -> bool {
714 (a - b).abs() <= eps
715 }
716
717 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#[derive(Debug, Clone)]
752pub struct PiecewiseLegendrePolyVector {
753 pub(crate) polyvec: Vec<PiecewiseLegendrePoly>,
755}
756
757impl PiecewiseLegendrePolyVector {
758 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 pub(crate) fn from_polys_unchecked(polyvec: Vec<PiecewiseLegendrePoly>) -> Self {
790 Self { polyvec }
791 }
792
793 pub fn get_polys(&self) -> &[PiecewiseLegendrePoly] {
795 &self.polyvec
796 }
797
798 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 let delta_x: Vec<f64> = (1..knots.len()).map(|i| knots[i] - knots[i - 1]).collect();
832
833 for i in 0..npolys {
834 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 pub fn size(&self) -> usize {
860 self.polyvec.len()
861 }
862
863 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 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 pub fn get(&self, index: usize) -> Option<&PiecewiseLegendrePoly> {
936 self.polyvec.get(index)
937 }
938
939 #[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 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 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 pub fn evaluate_at(&self, x: f64) -> Vec<f64> {
1002 self.try_evaluate_at(x).unwrap_or_else(|e| panic!("{e}"))
1003 }
1004
1005 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 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 pub fn try_evaluate_at_many(&self, xs: &[f64]) -> Result<mdarray::DTensor<f64, 2>, Error> {
1039 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 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 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 {
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 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 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 {
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 pub fn last(&self) -> &PiecewiseLegendrePoly {
1176 self.polyvec
1177 .last()
1178 .expect("Cannot get last from empty PiecewiseLegendrePolyVector")
1179 }
1180
1181 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
1198pub(crate) fn default_sampling_points(
1221 u: &PiecewiseLegendrePolyVector,
1222 name: &'static str,
1223 l: usize,
1224) -> Result<Vec<f64>, Error> {
1225 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 u[l].roots()
1238 } else {
1239 let poly = u.last();
1242 let poly_deriv = poly.deriv(1);
1243 let maxima = poly_deriv.roots();
1244
1245 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 let left = (first + poly.xmin) / 2.0;
1260
1261 let right = (last + poly.xmax) / 2.0;
1263
1264 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 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#[cfg(test)]
1295#[path = "poly_tests.rs"]
1296mod poly_tests;