1use crate::error::Error;
7use crate::matrix::{Mat, Mat3};
8
9#[derive(Debug, Clone)]
11pub struct PiecewiseLegendrePoly {
12 pub(crate) polyorder: usize,
14 pub(crate) xmin: f64,
16 pub(crate) xmax: f64,
18 pub(crate) knots: Vec<f64>,
20 pub(crate) delta_x: Vec<f64>,
22 pub(crate) data: Mat<f64>,
24 pub(crate) symm: i32,
26 pub(crate) l: i32,
33 pub(crate) xm: Vec<f64>,
35 pub(crate) inv_xs: Vec<f64>,
37 pub(crate) norms: Vec<f64>,
39}
40
41fn check_knots(knots: &[f64], nsegments: usize) -> Result<(), Error> {
44 if knots.len() != nsegments + 1 {
45 return Err(Error::InvalidParameter {
46 name: "knots",
47 value: format!("{} knots", knots.len()),
48 reason: format!(
49 "must have {} entries, one more than the segments of data",
50 nsegments + 1
51 ),
52 });
53 }
54 if let Some((i, k)) = knots.iter().enumerate().find(|(_, k)| !k.is_finite()) {
55 return Err(Error::InvalidParameter {
56 name: "knots",
57 value: format!("{k:?} at index {i}"),
58 reason: "must be finite".to_string(),
59 });
60 }
61 for i in 1..knots.len() {
62 let length = knots[i] - knots[i - 1];
63 if !(length > 0.0 && length.is_normal()) {
64 return Err(Error::InvalidParameter {
65 name: "knots",
66 value: format!("{:?} after {:?} at index {i}", knots[i], knots[i - 1]),
67 reason: "must be strictly increasing, with each segment length a normal double"
68 .to_string(),
69 });
70 }
71 }
72 Ok(())
73}
74
75fn check_delta_x(delta_x: &[f64], knots: &[f64]) -> Result<(), Error> {
87 let nsegments = knots.len() - 1;
88 if delta_x.len() != nsegments {
89 return Err(Error::InvalidParameter {
90 name: "delta_x",
91 value: format!("{} entries", delta_x.len()),
92 reason: format!("must have one entry per segment ({nsegments})"),
93 });
94 }
95 for (i, &d) in delta_x.iter().enumerate() {
96 let expected = knots[i + 1] - knots[i];
97 let rounding = 8.0 * f64::EPSILON * knots[i].abs().max(knots[i + 1].abs());
98 let tolerance = (1e-10 * expected.abs()).max(rounding);
99 if !((d - expected).abs() <= tolerance) {
100 return Err(Error::InvalidParameter {
101 name: "delta_x",
102 value: format!("{d:?} at index {i}"),
103 reason: format!(
104 "must equal the knot spacing {expected:?} to a relative 1e-10, or to 8 machine epsilons times the magnitude of the knots"
105 ),
106 });
107 }
108 }
109 Ok(())
110}
111
112impl PiecewiseLegendrePoly {
113 pub fn new(
132 data: Mat<f64>,
133 knots: Vec<f64>,
134 l: i32,
135 delta_x: Option<Vec<f64>>,
136 symm: i32,
137 ) -> Result<Self, Error> {
138 let polyorder = data.shape().0;
139 let nsegments = data.shape().1;
140 if polyorder == 0 || nsegments == 0 {
141 return Err(Error::EmptyInput { name: "data" });
142 }
143 check_knots(&knots, nsegments)?;
144
145 let delta_x =
147 delta_x.unwrap_or_else(|| (1..knots.len()).map(|i| knots[i] - knots[i - 1]).collect());
148 check_delta_x(&delta_x, &knots)?;
149 if !matches!(symm, -1..=1) {
150 return Err(Error::InvalidParameter {
151 name: "symm",
152 value: symm.to_string(),
153 reason: "must be -1, 0 or 1".to_string(),
154 });
155 }
156
157 let xm: Vec<f64> = (0..nsegments)
159 .map(|i| 0.5 * (knots[i] + knots[i + 1]))
160 .collect();
161
162 let inv_xs: Vec<f64> = delta_x.iter().map(|&dx| 2.0 / dx).collect();
164
165 let norms: Vec<f64> = inv_xs.iter().map(|&inv_x| inv_x.sqrt()).collect();
167
168 Ok(Self {
169 polyorder,
170 xmin: knots[0],
171 xmax: knots[knots.len() - 1],
172 knots,
173 delta_x,
174 data,
175 symm,
176 l,
177 xm,
178 inv_xs,
179 norms,
180 })
181 }
182
183 pub(crate) fn with_data(&self, new_data: Mat<f64>) -> Self {
188 Self {
189 data: new_data,
190 ..self.clone()
191 }
192 }
193
194 pub fn symm(&self) -> i32 {
196 self.symm
197 }
198
199 pub(crate) fn negated(&self) -> Self {
204 self.with_data(Mat::<f64>::from_fn(self.data.dims(), |idx| -self.data[idx]))
205 }
206
207 pub fn rescale_domain(
226 &self,
227 new_knots: Vec<f64>,
228 new_delta_x: Option<Vec<f64>>,
229 new_symm: Option<i32>,
230 ) -> Result<Self, Error> {
231 Self::new(
232 self.data.clone(),
233 new_knots,
234 self.l,
235 new_delta_x,
236 new_symm.unwrap_or(self.symm),
237 )
238 }
239
240 pub fn scale_data(&self, factor: f64) -> Self {
253 Self::with_data(
254 self,
255 Mat::<f64>::from_fn(self.data.dims(), |idx| self.data[idx] * factor),
256 )
257 }
258
259 fn check_in_domain(&self, name: &'static str, x: f64) -> Result<(), Error> {
261 if x >= self.xmin && x <= self.xmax {
262 Ok(())
263 } else {
264 Err(Error::OutOfDomain {
265 name,
266 value: x,
267 domain: (self.xmin, self.xmax),
268 })
269 }
270 }
271
272 pub fn evaluate(&self, x: f64) -> f64 {
278 self.try_evaluate(x).unwrap_or_else(|e| panic!("{e}"))
279 }
280
281 pub fn try_evaluate(&self, x: f64) -> Result<f64, Error> {
287 self.check_in_domain("x", x)?;
288 Ok(self.evaluate_in_domain(x))
289 }
290
291 fn evaluate_in_domain(&self, x: f64) -> f64 {
293 let (i, x_tilde) = self.split_in_domain(x);
294 let coeffs: Vec<f64> = (0..self.data.shape().0)
296 .map(|row| self.data[[row, i]])
297 .collect();
298 let value = legendre_series(x_tilde, &coeffs);
299 value * self.norms[i]
300 }
301
302 pub fn evaluate_many(&self, xs: &[f64]) -> Vec<f64> {
309 self.try_evaluate_many(xs).unwrap_or_else(|e| panic!("{e}"))
310 }
311
312 pub fn try_evaluate_many(&self, xs: &[f64]) -> Result<Vec<f64>, Error> {
319 for &x in xs {
320 self.check_in_domain("xs", x)?;
321 }
322 Ok(xs.iter().map(|&x| self.evaluate_in_domain(x)).collect())
323 }
324
325 pub fn split(&self, x: f64) -> (usize, f64) {
331 self.try_split(x).unwrap_or_else(|e| panic!("{e}"))
332 }
333
334 pub fn try_split(&self, x: f64) -> Result<(usize, f64), Error> {
340 self.check_in_domain("x", x)?;
341 Ok(self.split_in_domain(x))
342 }
343
344 fn split_in_domain(&self, x: f64) -> (usize, f64) {
346 for i in 0..self.knots.len() - 1 {
348 if x >= self.knots[i] && x <= self.knots[i + 1] {
349 let x_tilde = 2.0 * (x - self.xm[i]) / self.delta_x[i];
351 return (i, x_tilde);
352 }
353 }
354
355 let last_idx = self.knots.len() - 2;
357 let x_tilde = 2.0 * (x - self.xm[last_idx]) / self.delta_x[last_idx];
358 (last_idx, x_tilde)
359 }
360
361 pub fn deriv(&self, n: usize) -> Self {
366 if n == 0 {
367 return self.clone();
368 }
369
370 let mut ddata = self.data.clone();
372 for _ in 0..n {
373 ddata = self.compute_derivative_coefficients(&ddata);
374 }
375
376 let ddata_shape = *ddata.shape();
378 for i in 0..ddata_shape.1 {
379 let inv_x_power = self.inv_xs[i].powi(n as i32);
380 for j in 0..ddata_shape.0 {
381 ddata[[j, i]] *= inv_x_power;
382 }
383 }
384
385 let new_symm = if n % 2 == 0 { self.symm } else { -self.symm };
387
388 Self {
389 polyorder: ddata.shape().0,
390 data: ddata,
391 symm: new_symm,
392 ..self.clone()
393 }
394 }
395
396 fn compute_derivative_coefficients(&self, coeffs: &Mat<f64>) -> Mat<f64> {
398 let (nrows, ncols) = *coeffs.shape();
399 let ders: Vec<Vec<f64>> = (0..ncols)
400 .map(|col| legder(&(0..nrows).map(|row| coeffs[[row, col]]).collect::<Vec<_>>()))
401 .collect();
402 let der_rows = nrows.saturating_sub(1).max(1);
403 Mat::<f64>::from_fn([der_rows, ncols], |idx| ders[idx[1]][idx[0]])
404 }
405
406 pub fn derivs(&self, x: f64) -> Vec<f64> {
414 self.try_derivs(x).unwrap_or_else(|e| panic!("{e}"))
415 }
416
417 pub fn try_derivs(&self, x: f64) -> Result<Vec<f64>, Error> {
423 let (i, x_tilde) = self.try_split(x)?;
424 let mut coeffs: Vec<f64> = (0..self.data.shape().0)
427 .map(|row| self.data[[row, i]])
428 .collect();
429 let mut results = Vec::with_capacity(self.polyorder);
430 for n in 0..self.polyorder {
431 if n > 0 {
432 coeffs = legder(&coeffs);
433 }
434 let inv_x_power = self.inv_xs[i].powi(n as i32);
435 let scaled: Vec<f64> = coeffs.iter().map(|&c| c * inv_x_power).collect();
436 results.push(legendre_series(x_tilde, &scaled) * self.norms[i]);
437 }
438 Ok(results)
439 }
440
441 pub fn overlap<F>(&self, f: F) -> f64
443 where
444 F: Fn(f64) -> f64,
445 {
446 let mut integral = 0.0;
447
448 for i in 0..self.knots.len() - 1 {
449 let segment_integral =
450 self.gauss_legendre_quadrature(self.knots[i], self.knots[i + 1], |x| {
451 self.evaluate(x) * f(x)
452 });
453 integral += segment_integral;
454 }
455
456 integral
457 }
458
459 fn gauss_legendre_quadrature<F>(&self, a: f64, b: f64, f: F) -> f64
461 where
462 F: Fn(f64) -> f64,
463 {
464 const XG: [f64; 5] = [
466 -0.906179845938664,
467 -0.538469310105683,
468 0.0,
469 0.538469310105683,
470 0.906179845938664,
471 ];
472 const WG: [f64; 5] = [
473 0.236926885056189,
474 0.478628670499366,
475 0.568888888888889,
476 0.478628670499366,
477 0.236926885056189,
478 ];
479
480 let c1 = (b - a) / 2.0;
481 let c2 = (b + a) / 2.0;
482
483 let mut integral = 0.0;
484 for j in 0..5 {
485 let x = c1 * XG[j] + c2;
486 integral += WG[j] * f(x);
487 }
488
489 integral * c1
490 }
491
492 pub fn roots(&self) -> Vec<f64> {
494 let xmid = (self.xmax + self.xmin) / 2.0;
495
496 let grid = if self.symm != 0 {
500 let nsegments = self.knots.len() - 1;
501 let mid_idx = nsegments / 2;
502 if (self.knots[mid_idx] - xmid).abs() < 1e-15 {
503 self.knots[mid_idx..].to_vec()
504 } else {
505 let mut g = vec![xmid];
506 g.extend(self.knots.iter().filter(|&&x| x > xmid));
507 g
508 }
509 } else {
510 self.knots.clone()
511 };
512
513 let refined_grid = self.refine_grid(&grid, 4);
514 let roots_half = self.find_all_roots(&refined_grid);
515
516 if self.symm == 1 {
517 let mut all_roots: Vec<f64> = roots_half
519 .iter()
520 .rev()
521 .map(|&r| (self.xmax + self.xmin) - r)
522 .collect();
523 all_roots.extend_from_slice(&roots_half);
524 all_roots
525 } else if self.symm == -1 {
526 let mut right = roots_half;
528 if !right.is_empty() {
529 let f_mid = self.evaluate(xmid);
532 let f_deriv_mid = self.deriv(1).evaluate(xmid);
533 if (right[0] - xmid).abs() < 1e-13 || f_mid * f_deriv_mid < 0.0 {
534 right.remove(0);
535 }
536 }
537 let mut all_roots: Vec<f64> = right
538 .iter()
539 .rev()
540 .map(|&r| (self.xmax + self.xmin) - r)
541 .collect();
542 all_roots.push(xmid);
543 all_roots.extend_from_slice(&right);
544 all_roots
545 } else {
546 let full_grid = self.refine_grid(&self.knots, 4);
548 self.find_all_roots(&full_grid)
549 }
550 }
551
552 fn refine_grid(&self, grid: &[f64], alpha: usize) -> Vec<f64> {
554 let mut refined = Vec::new();
555
556 for i in 0..grid.len() - 1 {
557 let start = grid[i];
558 let step = (grid[i + 1] - grid[i]) / (alpha as f64);
559 for j in 0..alpha {
560 refined.push(start + (j as f64) * step);
561 }
562 }
563 refined.push(grid[grid.len() - 1]);
564 refined
565 }
566
567 fn find_all_roots(&self, xgrid: &[f64]) -> Vec<f64> {
569 if xgrid.is_empty() {
570 return Vec::new();
571 }
572
573 let fx: Vec<f64> = xgrid.iter().map(|&x| self.evaluate(x)).collect();
575
576 let mut x_hit = Vec::new();
578 for i in 0..fx.len() {
579 if fx[i] == 0.0 {
580 x_hit.push(xgrid[i]);
581 }
582 }
583
584 let mut sign_change = Vec::new();
586 for i in 0..fx.len() - 1 {
587 let has_sign_change = fx[i].signum() != fx[i + 1].signum();
588 let not_hit = fx[i] != 0.0 && fx[i + 1] != 0.0;
589 let sc = has_sign_change && not_hit;
590 sign_change.push(sc);
591 }
592
593 if sign_change.iter().all(|&sc| !sc) {
595 x_hit.sort_by(|a, b| a.partial_cmp(b).unwrap());
596 return x_hit;
597 }
598
599 let mut a_intervals = Vec::new();
601 let mut b_intervals = Vec::new();
602 let mut fa_values = Vec::new();
603
604 for i in 0..sign_change.len() {
605 if sign_change[i] {
606 a_intervals.push(xgrid[i]);
607 b_intervals.push(xgrid[i + 1]);
608 fa_values.push(fx[i]);
609 }
610 }
611
612 let max_elm = xgrid.iter().map(|&x| x.abs()).fold(0.0, f64::max);
614 let epsilon_x = f64::EPSILON * max_elm;
615
616 for i in 0..a_intervals.len() {
618 let root = self.bisect(a_intervals[i], b_intervals[i], fa_values[i], epsilon_x);
619 x_hit.push(root);
620 }
621
622 x_hit.sort_by(|a, b| a.partial_cmp(b).unwrap());
624 x_hit
625 }
626
627 fn bisect(&self, a: f64, b: f64, fa: f64, eps: f64) -> f64 {
629 let mut a = a;
630 let mut b = b;
631 let mut fa = fa;
632
633 loop {
634 let mid = (a + b) / 2.0;
635 if self.close_enough(a, mid, eps) {
636 return mid;
637 }
638
639 let fmid = self.evaluate(mid);
640 if fa.signum() != fmid.signum() {
641 b = mid;
642 } else {
643 a = mid;
644 fa = fmid;
645 }
646 }
647 }
648
649 fn close_enough(&self, a: f64, b: f64, eps: f64) -> bool {
651 (a - b).abs() <= eps
652 }
653
654 pub fn xmin(&self) -> f64 {
656 self.xmin
657 }
658 pub fn xmax(&self) -> f64 {
660 self.xmax
661 }
662 pub fn l(&self) -> i32 {
665 self.l
666 }
667 pub fn domain(&self) -> (f64, f64) {
669 (self.xmin, self.xmax)
670 }
671 pub fn knots(&self) -> &[f64] {
673 &self.knots
674 }
675 pub fn delta_x(&self) -> &[f64] {
677 &self.delta_x
678 }
679 pub fn data(&self) -> &Mat<f64> {
682 &self.data
683 }
684 pub fn norms(&self) -> &[f64] {
686 &self.norms
687 }
688 pub fn polyorder(&self) -> usize {
690 self.polyorder
691 }
692}
693
694pub(crate) fn legendre_series(x: f64, coeffs: &[f64]) -> f64 {
696 if coeffs.is_empty() {
697 return 0.0;
698 }
699
700 let mut result = 0.0;
701 let mut p_prev = 1.0; let mut p_curr = x; if !coeffs.is_empty() {
706 result += coeffs[0] * p_prev;
707 }
708 if coeffs.len() > 1 {
709 result += coeffs[1] * p_curr;
710 }
711
712 for n in 1..coeffs.len() - 1 {
714 let p_next =
715 ((2.0 * (n as f64) + 1.0) * x * p_curr - (n as f64) * p_prev) / ((n + 1) as f64);
716 result += coeffs[n + 1] * p_next;
717 p_prev = p_curr;
718 p_curr = p_next;
719 }
720
721 result
722}
723
724fn legder(c: &[f64]) -> Vec<f64> {
727 if c.len() <= 1 {
728 return vec![0.0];
729 }
730 let mut c = c.to_vec();
731 let n = c.len() - 1;
732 let mut der = vec![0.0; n];
733 for j in (2..=n).rev() {
734 der[j - 1] = (2.0 * (j as f64) - 1.0) * c[j];
735 c[j - 2] += c[j];
736 }
737 if n > 1 {
738 der[1] = 3.0 * c[2];
739 }
740 der[0] = c[1];
741 der
742}
743
744#[derive(Debug, Clone)]
746pub struct PiecewiseLegendrePolyVector {
747 pub(crate) polyvec: Vec<PiecewiseLegendrePoly>,
749}
750
751impl PiecewiseLegendrePolyVector {
752 pub fn new(polyvec: Vec<PiecewiseLegendrePoly>) -> Result<Self, Error> {
761 let Some(first) = polyvec.first() else {
762 return Err(Error::EmptyInput { name: "polyvec" });
763 };
764 if let Some(i) = polyvec
765 .iter()
766 .position(|p| p.knots != first.knots || p.data.shape() != first.data.shape())
767 {
768 return Err(Error::InvalidParameter {
769 name: "polyvec",
770 value: format!("polynomial {i}"),
771 reason: "must have the knots and the data shape of polynomial 0".to_string(),
772 });
773 }
774 Ok(Self { polyvec })
775 }
776
777 pub(crate) fn from_polys_unchecked(polyvec: Vec<PiecewiseLegendrePoly>) -> Self {
784 Self { polyvec }
785 }
786
787 pub fn polys(&self) -> &[PiecewiseLegendrePoly] {
789 &self.polyvec
790 }
791
792 pub fn from_3d_data(
804 data3d: Mat3<f64>,
805 knots: Vec<f64>,
806 symm: Option<Vec<i32>>,
807 ) -> Result<Self, Error> {
808 let npolys = data3d.shape().2;
809 if npolys == 0 {
810 return Err(Error::EmptyInput { name: "data3d" });
811 }
812 let mut polyvec = Vec::with_capacity(npolys);
813
814 if let Some(ref symm_vec) = symm {
815 if symm_vec.len() != npolys {
816 return Err(Error::InvalidParameter {
817 name: "symm",
818 value: format!("{} entries", symm_vec.len()),
819 reason: format!("must have one entry per polynomial ({npolys})"),
820 });
821 }
822 }
823
824 let delta_x: Vec<f64> = (1..knots.len()).map(|i| knots[i] - knots[i - 1]).collect();
826
827 for i in 0..npolys {
828 let data3d_shape = data3d.shape();
830 let mut data = Mat::<f64>::from_elem([data3d_shape.0, data3d_shape.1], 0.0);
831 for j in 0..data3d_shape.0 {
832 for k in 0..data3d_shape.1 {
833 data[[j, k]] = data3d[[j, k, i]];
834 }
835 }
836
837 let poly = PiecewiseLegendrePoly::new(
838 data,
839 knots.clone(),
840 i as i32,
841 Some(delta_x.clone()),
842 symm.as_ref().map_or(0, |s| s[i]),
843 )?;
844
845 polyvec.push(poly);
846 }
847
848 Ok(Self { polyvec })
849 }
850
851 pub fn len(&self) -> usize {
853 self.polyvec.len()
854 }
855
856 pub fn is_empty(&self) -> bool {
858 self.polyvec.is_empty()
859 }
860
861 pub fn rescale_domain(
882 &self,
883 new_knots: Vec<f64>,
884 new_delta_x: Option<Vec<f64>>,
885 new_symm: Option<Vec<i32>>,
886 ) -> Result<Self, Error> {
887 if let Some(symm) = &new_symm {
888 if symm.len() != self.polyvec.len() {
889 return Err(Error::InvalidParameter {
890 name: "new_symm",
891 value: format!("{} entries", symm.len()),
892 reason: format!(
893 "must have one entry per polynomial ({})",
894 self.polyvec.len()
895 ),
896 });
897 }
898 }
899 let polyvec = self
900 .polyvec
901 .iter()
902 .enumerate()
903 .map(|(i, poly)| {
904 let symm = new_symm.as_ref().map(|s| s[i]);
905 poly.rescale_domain(new_knots.clone(), new_delta_x.clone(), symm)
906 })
907 .collect::<Result<_, _>>()?;
908 Ok(Self { polyvec })
909 }
910
911 pub fn scale_data(&self, factor: f64) -> Self {
923 let polyvec = self
924 .polyvec
925 .iter()
926 .map(|poly| poly.scale_data(factor))
927 .collect();
928
929 Self { polyvec }
930 }
931
932 pub fn get(&self, index: usize) -> Option<&PiecewiseLegendrePoly> {
934 self.polyvec.get(index)
935 }
936
937 #[deprecated(
939 note = "PiecewiseLegendrePolyVector is designed to be immutable. Use get() and create new instances for modifications."
940 )]
941 pub fn get_mut(&mut self, index: usize) -> Option<&mut PiecewiseLegendrePoly> {
942 self.polyvec.get_mut(index)
943 }
944
945 pub fn slice_single(&self, index: usize) -> Option<Self> {
947 self.polyvec.get(index).map(|poly| Self {
948 polyvec: vec![poly.clone()],
949 })
950 }
951
952 pub fn slice_multi(&self, indices: &[usize]) -> Result<Self, Error> {
960 if indices.is_empty() {
961 return Err(Error::EmptyInput { name: "indices" });
962 }
963 let len = self.polyvec.len();
964 let mut seen = vec![false; len];
965 for &idx in indices {
966 if idx >= len {
967 return Err(Error::InvalidParameter {
968 name: "indices",
969 value: format!("{idx}"),
970 reason: format!("must be less than the size {len}"),
971 });
972 }
973 if seen[idx] {
974 return Err(Error::InvalidParameter {
975 name: "indices",
976 value: format!("{idx}"),
977 reason: "must not repeat".to_string(),
978 });
979 }
980 seen[idx] = true;
981 }
982
983 let new_polyvec: Vec<_> = indices
984 .iter()
985 .map(|&idx| self.polyvec[idx].clone())
986 .collect();
987
988 Ok(Self {
989 polyvec: new_polyvec,
990 })
991 }
992
993 pub fn evaluate_at(&self, x: f64) -> Vec<f64> {
1000 self.try_evaluate_at(x).unwrap_or_else(|e| panic!("{e}"))
1001 }
1002
1003 pub fn try_evaluate_at(&self, x: f64) -> Result<Vec<f64>, Error> {
1010 self.polyvec
1011 .iter()
1012 .map(|poly| poly.try_evaluate(x))
1013 .collect()
1014 }
1015
1016 pub fn evaluate_at_many(&self, xs: &[f64]) -> Mat<f64> {
1025 self.try_evaluate_at_many(xs)
1026 .unwrap_or_else(|e| panic!("{e}"))
1027 }
1028
1029 pub fn try_evaluate_at_many(&self, xs: &[f64]) -> Result<Mat<f64>, Error> {
1037 if let Some(first) = self.polyvec.first() {
1040 for &x in xs {
1041 first.check_in_domain("xs", x)?;
1042 }
1043 }
1044 let n_funcs = self.polyvec.len();
1045 let n_points = xs.len();
1046 let mut results = Mat::<f64>::from_elem([n_funcs, n_points], 0.0);
1047
1048 for (i, poly) in self.polyvec.iter().enumerate() {
1049 for (j, &x) in xs.iter().enumerate() {
1050 results[[i, j]] = poly.evaluate_in_domain(x);
1051 }
1052 }
1053
1054 Ok(results)
1055 }
1056
1057 pub fn xmin(&self) -> f64 {
1058 if self.polyvec.is_empty() {
1059 panic!("Cannot get xmin from empty PiecewiseLegendrePolyVector");
1060 }
1061 self.polyvec[0].xmin
1062 }
1063
1064 pub fn xmax(&self) -> f64 {
1065 if self.polyvec.is_empty() {
1066 panic!("Cannot get xmax from empty PiecewiseLegendrePolyVector");
1067 }
1068 self.polyvec[0].xmax
1069 }
1070
1071 pub fn knots(&self, tolerance: Option<f64>) -> Vec<f64> {
1074 if self.polyvec.is_empty() {
1075 panic!("Cannot get knots from empty PiecewiseLegendrePolyVector");
1076 }
1077 const DEFAULT_TOLERANCE: f64 = 1e-10;
1078 let tolerance = tolerance.unwrap_or(DEFAULT_TOLERANCE);
1079
1080 let mut all_knots = Vec::new();
1082 for poly in &self.polyvec {
1083 for &knot in &poly.knots {
1084 all_knots.push(knot);
1085 }
1086 }
1087
1088 {
1090 all_knots.sort_by(|a, b| a.partial_cmp(b).unwrap());
1091 all_knots.dedup_by(|a, b| (*a - *b).abs() < tolerance);
1092 }
1093 all_knots
1094 }
1095
1096 pub fn 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 polyorder(&self) -> usize {
1106 if self.polyvec.is_empty() {
1107 panic!("Cannot get polyorder from empty PiecewiseLegendrePolyVector");
1108 }
1109 self.polyvec[0].polyorder
1110 }
1111
1112 pub fn norms(&self) -> &[f64] {
1114 if self.polyvec.is_empty() {
1115 panic!("Cannot get norms from empty PiecewiseLegendrePolyVector");
1116 }
1117 &self.polyvec[0].norms
1118 }
1119
1120 pub fn symm(&self) -> Vec<i32> {
1122 if self.polyvec.is_empty() {
1123 panic!("Cannot get symm from empty PiecewiseLegendrePolyVector");
1124 }
1125 self.polyvec.iter().map(|poly| poly.symm).collect()
1126 }
1127
1128 pub fn data(&self) -> Mat3<f64> {
1136 if self.polyvec.is_empty() {
1137 panic!("Cannot get data from empty PiecewiseLegendrePolyVector");
1138 }
1139
1140 let nsegments = self.polyvec[0].data.shape().1;
1141 let polyorder = self.polyvec[0].polyorder;
1142 let npolys = self.polyvec.len();
1143
1144 let mut data = Mat3::<f64>::from_elem([nsegments, polyorder, npolys], 0.0);
1145
1146 for (poly_idx, poly) in self.polyvec.iter().enumerate() {
1147 for segment in 0..nsegments {
1148 for degree in 0..polyorder {
1149 data[[segment, degree, poly_idx]] = poly.data[[degree, segment]];
1150 }
1151 }
1152 }
1153
1154 data
1155 }
1156
1157 pub fn roots(&self, tolerance: Option<f64>) -> Vec<f64> {
1159 if self.polyvec.is_empty() {
1160 panic!("Cannot get roots from empty PiecewiseLegendrePolyVector");
1161 }
1162 const DEFAULT_TOLERANCE: f64 = 1e-10;
1163 let tolerance = tolerance.unwrap_or(DEFAULT_TOLERANCE);
1164 let mut all_roots = Vec::new();
1165
1166 for poly in &self.polyvec {
1167 let poly_roots = poly.roots();
1168 for root in poly_roots {
1169 all_roots.push(root);
1170 }
1171 }
1172
1173 {
1175 all_roots.sort_by(|a, b| b.partial_cmp(a).unwrap());
1176 all_roots.dedup_by(|a, b| (*a - *b).abs() < tolerance);
1177 }
1178 all_roots
1179 }
1180
1181 pub fn last(&self) -> &PiecewiseLegendrePoly {
1185 self.polyvec
1186 .last()
1187 .expect("Cannot get last from empty PiecewiseLegendrePolyVector")
1188 }
1189
1190 pub fn nroots(&self, tolerance: Option<f64>) -> usize {
1192 if self.polyvec.is_empty() {
1193 panic!("Cannot get nroots from empty PiecewiseLegendrePolyVector");
1194 }
1195 self.roots(tolerance).len()
1196 }
1197}
1198
1199impl std::ops::Index<usize> for PiecewiseLegendrePolyVector {
1200 type Output = PiecewiseLegendrePoly;
1201
1202 fn index(&self, index: usize) -> &Self::Output {
1203 &self.polyvec[index]
1204 }
1205}
1206
1207#[cfg(test)]
1208#[path = "poly_tests.rs"]
1209mod poly_tests;