use crate::error::Error;
use crate::matrix::{Mat, Mat3};
#[derive(Debug, Clone)]
pub struct PiecewiseLegendrePoly {
pub(crate) polyorder: usize,
pub(crate) xmin: f64,
pub(crate) xmax: f64,
pub(crate) knots: Vec<f64>,
pub(crate) delta_x: Vec<f64>,
pub(crate) data: Mat<f64>,
pub(crate) symm: i32,
pub(crate) l: i32,
pub(crate) xm: Vec<f64>,
pub(crate) inv_xs: Vec<f64>,
pub(crate) norms: Vec<f64>,
}
fn check_knots(knots: &[f64], nsegments: usize) -> Result<(), Error> {
if knots.len() != nsegments + 1 {
return Err(Error::InvalidParameter {
name: "knots",
value: format!("{} knots", knots.len()),
reason: format!(
"must have {} entries, one more than the segments of data",
nsegments + 1
),
});
}
if let Some((i, k)) = knots.iter().enumerate().find(|(_, k)| !k.is_finite()) {
return Err(Error::InvalidParameter {
name: "knots",
value: format!("{k:?} at index {i}"),
reason: "must be finite".to_string(),
});
}
for i in 1..knots.len() {
let length = knots[i] - knots[i - 1];
if !(length > 0.0 && length.is_normal()) {
return Err(Error::InvalidParameter {
name: "knots",
value: format!("{:?} after {:?} at index {i}", knots[i], knots[i - 1]),
reason: "must be strictly increasing, with each segment length a normal double"
.to_string(),
});
}
}
Ok(())
}
fn check_delta_x(delta_x: &[f64], knots: &[f64]) -> Result<(), Error> {
let nsegments = knots.len() - 1;
if delta_x.len() != nsegments {
return Err(Error::InvalidParameter {
name: "delta_x",
value: format!("{} entries", delta_x.len()),
reason: format!("must have one entry per segment ({nsegments})"),
});
}
for (i, &d) in delta_x.iter().enumerate() {
let expected = knots[i + 1] - knots[i];
let rounding = 8.0 * f64::EPSILON * knots[i].abs().max(knots[i + 1].abs());
let tolerance = (1e-10 * expected.abs()).max(rounding);
if !((d - expected).abs() <= tolerance) {
return Err(Error::InvalidParameter {
name: "delta_x",
value: format!("{d:?} at index {i}"),
reason: format!(
"must equal the knot spacing {expected:?} to a relative 1e-10, or to 8 machine epsilons times the magnitude of the knots"
),
});
}
}
Ok(())
}
impl PiecewiseLegendrePoly {
pub fn new(
data: Mat<f64>,
knots: Vec<f64>,
l: i32,
delta_x: Option<Vec<f64>>,
symm: i32,
) -> Result<Self, Error> {
let polyorder = data.shape().0;
let nsegments = data.shape().1;
if polyorder == 0 || nsegments == 0 {
return Err(Error::EmptyInput { name: "data" });
}
check_knots(&knots, nsegments)?;
let delta_x =
delta_x.unwrap_or_else(|| (1..knots.len()).map(|i| knots[i] - knots[i - 1]).collect());
check_delta_x(&delta_x, &knots)?;
if !matches!(symm, -1..=1) {
return Err(Error::InvalidParameter {
name: "symm",
value: symm.to_string(),
reason: "must be -1, 0 or 1".to_string(),
});
}
let xm: Vec<f64> = (0..nsegments)
.map(|i| 0.5 * (knots[i] + knots[i + 1]))
.collect();
let inv_xs: Vec<f64> = delta_x.iter().map(|&dx| 2.0 / dx).collect();
let norms: Vec<f64> = inv_xs.iter().map(|&inv_x| inv_x.sqrt()).collect();
Ok(Self {
polyorder,
xmin: knots[0],
xmax: knots[knots.len() - 1],
knots,
delta_x,
data,
symm,
l,
xm,
inv_xs,
norms,
})
}
pub(crate) fn with_data(&self, new_data: Mat<f64>) -> Self {
Self {
data: new_data,
..self.clone()
}
}
pub fn symm(&self) -> i32 {
self.symm
}
pub(crate) fn negated(&self) -> Self {
self.with_data(Mat::<f64>::from_fn(self.data.dims(), |idx| -self.data[idx]))
}
pub fn rescale_domain(
&self,
new_knots: Vec<f64>,
new_delta_x: Option<Vec<f64>>,
new_symm: Option<i32>,
) -> Result<Self, Error> {
Self::new(
self.data.clone(),
new_knots,
self.l,
new_delta_x,
new_symm.unwrap_or(self.symm),
)
}
pub fn scale_data(&self, factor: f64) -> Self {
Self::with_data(
self,
Mat::<f64>::from_fn(self.data.dims(), |idx| self.data[idx] * factor),
)
}
fn check_in_domain(&self, name: &'static str, x: f64) -> Result<(), Error> {
if x >= self.xmin && x <= self.xmax {
Ok(())
} else {
Err(Error::OutOfDomain {
name,
value: x,
domain: (self.xmin, self.xmax),
})
}
}
pub fn evaluate(&self, x: f64) -> f64 {
self.try_evaluate(x).unwrap_or_else(|e| panic!("{e}"))
}
pub fn try_evaluate(&self, x: f64) -> Result<f64, Error> {
self.check_in_domain("x", x)?;
Ok(self.evaluate_in_domain(x))
}
fn evaluate_in_domain(&self, x: f64) -> f64 {
let (i, x_tilde) = self.split_in_domain(x);
let coeffs: Vec<f64> = (0..self.data.shape().0)
.map(|row| self.data[[row, i]])
.collect();
let value = self.evaluate_legendre_polynomial(x_tilde, &coeffs);
value * self.norms[i]
}
pub fn evaluate_many(&self, xs: &[f64]) -> Vec<f64> {
self.try_evaluate_many(xs).unwrap_or_else(|e| panic!("{e}"))
}
pub fn try_evaluate_many(&self, xs: &[f64]) -> Result<Vec<f64>, Error> {
for &x in xs {
self.check_in_domain("xs", x)?;
}
Ok(xs.iter().map(|&x| self.evaluate_in_domain(x)).collect())
}
pub fn split(&self, x: f64) -> (usize, f64) {
self.try_split(x).unwrap_or_else(|e| panic!("{e}"))
}
pub fn try_split(&self, x: f64) -> Result<(usize, f64), Error> {
self.check_in_domain("x", x)?;
Ok(self.split_in_domain(x))
}
fn split_in_domain(&self, x: f64) -> (usize, f64) {
for i in 0..self.knots.len() - 1 {
if x >= self.knots[i] && x <= self.knots[i + 1] {
let x_tilde = 2.0 * (x - self.xm[i]) / self.delta_x[i];
return (i, x_tilde);
}
}
let last_idx = self.knots.len() - 2;
let x_tilde = 2.0 * (x - self.xm[last_idx]) / self.delta_x[last_idx];
(last_idx, x_tilde)
}
pub fn evaluate_legendre_polynomial(&self, x: f64, coeffs: &[f64]) -> f64 {
if coeffs.is_empty() {
return 0.0;
}
let mut result = 0.0;
let mut p_prev = 1.0; let mut p_curr = x;
if !coeffs.is_empty() {
result += coeffs[0] * p_prev;
}
if coeffs.len() > 1 {
result += coeffs[1] * p_curr;
}
for n in 1..coeffs.len() - 1 {
let p_next =
((2.0 * (n as f64) + 1.0) * x * p_curr - (n as f64) * p_prev) / ((n + 1) as f64);
result += coeffs[n + 1] * p_next;
p_prev = p_curr;
p_curr = p_next;
}
result
}
pub fn deriv(&self, n: usize) -> Self {
if n == 0 {
return self.clone();
}
let mut ddata = self.data.clone();
for _ in 0..n {
ddata = self.compute_derivative_coefficients(&ddata);
}
let ddata_shape = *ddata.shape();
for i in 0..ddata_shape.1 {
let inv_x_power = self.inv_xs[i].powi(n as i32);
for j in 0..ddata_shape.0 {
ddata[[j, i]] *= inv_x_power;
}
}
let new_symm = if n % 2 == 0 { self.symm } else { -self.symm };
Self {
polyorder: ddata.shape().0,
data: ddata,
symm: new_symm,
..self.clone()
}
}
fn compute_derivative_coefficients(&self, coeffs: &Mat<f64>) -> Mat<f64> {
let mut c = coeffs.clone();
let c_shape = *c.shape();
let mut n = c_shape.0;
if n <= 1 {
return Mat::<f64>::from_elem([1, c.shape().1], 0.0);
}
n -= 1;
let mut der = Mat::<f64>::from_elem([n, c.shape().1], 0.0);
for j in (2..=n).rev() {
for col in 0..c_shape.1 {
der[[j - 1, col]] = (2.0 * (j as f64) - 1.0) * c[[j, col]];
}
for col in 0..c_shape.1 {
c[[j - 2, col]] += c[[j, col]];
}
}
if n > 1 {
for col in 0..c_shape.1 {
der[[1, col]] = 3.0 * c[[2, col]];
}
}
for col in 0..c_shape.1 {
der[[0, col]] = c[[1, col]];
}
der
}
pub fn derivs(&self, x: f64) -> Vec<f64> {
self.try_derivs(x).unwrap_or_else(|e| panic!("{e}"))
}
pub fn try_derivs(&self, x: f64) -> Result<Vec<f64>, Error> {
self.check_in_domain("x", x)?;
let mut results = Vec::new();
for n in 0..self.polyorder {
let deriv_poly = self.deriv(n);
results.push(deriv_poly.evaluate_in_domain(x));
}
Ok(results)
}
pub fn overlap<F>(&self, f: F) -> f64
where
F: Fn(f64) -> f64,
{
let mut integral = 0.0;
for i in 0..self.knots.len() - 1 {
let segment_integral =
self.gauss_legendre_quadrature(self.knots[i], self.knots[i + 1], |x| {
self.evaluate(x) * f(x)
});
integral += segment_integral;
}
integral
}
fn gauss_legendre_quadrature<F>(&self, a: f64, b: f64, f: F) -> f64
where
F: Fn(f64) -> f64,
{
const XG: [f64; 5] = [
-0.906179845938664,
-0.538469310105683,
0.0,
0.538469310105683,
0.906179845938664,
];
const WG: [f64; 5] = [
0.236926885056189,
0.478628670499366,
0.568888888888889,
0.478628670499366,
0.236926885056189,
];
let c1 = (b - a) / 2.0;
let c2 = (b + a) / 2.0;
let mut integral = 0.0;
for j in 0..5 {
let x = c1 * XG[j] + c2;
integral += WG[j] * f(x);
}
integral * c1
}
pub fn roots(&self) -> Vec<f64> {
let xmid = (self.xmax + self.xmin) / 2.0;
let grid = if self.symm != 0 {
let nsegments = self.knots.len() - 1;
let mid_idx = nsegments / 2;
if (self.knots[mid_idx] - xmid).abs() < 1e-15 {
self.knots[mid_idx..].to_vec()
} else {
let mut g = vec![xmid];
g.extend(self.knots.iter().filter(|&&x| x > xmid));
g
}
} else {
self.knots.clone()
};
let refined_grid = self.refine_grid(&grid, 4);
let roots_half = self.find_all_roots(&refined_grid);
if self.symm == 1 {
let mut all_roots: Vec<f64> = roots_half
.iter()
.rev()
.map(|&r| (self.xmax + self.xmin) - r)
.collect();
all_roots.extend_from_slice(&roots_half);
all_roots
} else if self.symm == -1 {
let mut right = roots_half;
if !right.is_empty() {
let f_mid = self.evaluate(xmid);
let f_deriv_mid = self.deriv(1).evaluate(xmid);
if (right[0] - xmid).abs() < 1e-13 || f_mid * f_deriv_mid < 0.0 {
right.remove(0);
}
}
let mut all_roots: Vec<f64> = right
.iter()
.rev()
.map(|&r| (self.xmax + self.xmin) - r)
.collect();
all_roots.push(xmid);
all_roots.extend_from_slice(&right);
all_roots
} else {
let full_grid = self.refine_grid(&self.knots, 4);
self.find_all_roots(&full_grid)
}
}
fn refine_grid(&self, grid: &[f64], alpha: usize) -> Vec<f64> {
let mut refined = Vec::new();
for i in 0..grid.len() - 1 {
let start = grid[i];
let step = (grid[i + 1] - grid[i]) / (alpha as f64);
for j in 0..alpha {
refined.push(start + (j as f64) * step);
}
}
refined.push(grid[grid.len() - 1]);
refined
}
fn find_all_roots(&self, xgrid: &[f64]) -> Vec<f64> {
if xgrid.is_empty() {
return Vec::new();
}
let fx: Vec<f64> = xgrid.iter().map(|&x| self.evaluate(x)).collect();
let mut x_hit = Vec::new();
for i in 0..fx.len() {
if fx[i] == 0.0 {
x_hit.push(xgrid[i]);
}
}
let mut sign_change = Vec::new();
for i in 0..fx.len() - 1 {
let has_sign_change = fx[i].signum() != fx[i + 1].signum();
let not_hit = fx[i] != 0.0 && fx[i + 1] != 0.0;
let sc = has_sign_change && not_hit;
sign_change.push(sc);
}
if sign_change.iter().all(|&sc| !sc) {
x_hit.sort_by(|a, b| a.partial_cmp(b).unwrap());
return x_hit;
}
let mut a_intervals = Vec::new();
let mut b_intervals = Vec::new();
let mut fa_values = Vec::new();
for i in 0..sign_change.len() {
if sign_change[i] {
a_intervals.push(xgrid[i]);
b_intervals.push(xgrid[i + 1]);
fa_values.push(fx[i]);
}
}
let max_elm = xgrid.iter().map(|&x| x.abs()).fold(0.0, f64::max);
let epsilon_x = f64::EPSILON * max_elm;
for i in 0..a_intervals.len() {
let root = self.bisect(a_intervals[i], b_intervals[i], fa_values[i], epsilon_x);
x_hit.push(root);
}
x_hit.sort_by(|a, b| a.partial_cmp(b).unwrap());
x_hit
}
fn bisect(&self, a: f64, b: f64, fa: f64, eps: f64) -> f64 {
let mut a = a;
let mut b = b;
let mut fa = fa;
loop {
let mid = (a + b) / 2.0;
if self.close_enough(a, mid, eps) {
return mid;
}
let fmid = self.evaluate(mid);
if fa.signum() != fmid.signum() {
b = mid;
} else {
a = mid;
fa = fmid;
}
}
}
fn close_enough(&self, a: f64, b: f64, eps: f64) -> bool {
(a - b).abs() <= eps
}
pub fn get_xmin(&self) -> f64 {
self.xmin
}
pub fn get_xmax(&self) -> f64 {
self.xmax
}
pub fn get_l(&self) -> i32 {
self.l
}
pub fn get_domain(&self) -> (f64, f64) {
(self.xmin, self.xmax)
}
pub fn get_knots(&self) -> &[f64] {
&self.knots
}
pub fn get_delta_x(&self) -> &[f64] {
&self.delta_x
}
pub fn get_symm(&self) -> i32 {
self.symm
}
pub fn get_data(&self) -> &Mat<f64> {
&self.data
}
pub fn get_norms(&self) -> &[f64] {
&self.norms
}
pub fn get_polyorder(&self) -> usize {
self.polyorder
}
}
#[derive(Debug, Clone)]
pub struct PiecewiseLegendrePolyVector {
pub(crate) polyvec: Vec<PiecewiseLegendrePoly>,
}
impl PiecewiseLegendrePolyVector {
pub fn new(polyvec: Vec<PiecewiseLegendrePoly>) -> Result<Self, Error> {
let Some(first) = polyvec.first() else {
return Err(Error::EmptyInput { name: "polyvec" });
};
if let Some(i) = polyvec
.iter()
.position(|p| p.knots != first.knots || p.data.shape() != first.data.shape())
{
return Err(Error::InvalidParameter {
name: "polyvec",
value: format!("polynomial {i}"),
reason: "must have the knots and the data shape of polynomial 0".to_string(),
});
}
Ok(Self { polyvec })
}
pub(crate) fn from_polys_unchecked(polyvec: Vec<PiecewiseLegendrePoly>) -> Self {
Self { polyvec }
}
pub fn get_polys(&self) -> &[PiecewiseLegendrePoly] {
&self.polyvec
}
pub fn from_3d_data(
data3d: Mat3<f64>,
knots: Vec<f64>,
symm: Option<Vec<i32>>,
) -> Result<Self, Error> {
let npolys = data3d.shape().2;
if npolys == 0 {
return Err(Error::EmptyInput { name: "data3d" });
}
let mut polyvec = Vec::with_capacity(npolys);
if let Some(ref symm_vec) = symm {
if symm_vec.len() != npolys {
return Err(Error::InvalidParameter {
name: "symm",
value: format!("{} entries", symm_vec.len()),
reason: format!("must have one entry per polynomial ({npolys})"),
});
}
}
let delta_x: Vec<f64> = (1..knots.len()).map(|i| knots[i] - knots[i - 1]).collect();
for i in 0..npolys {
let data3d_shape = data3d.shape();
let mut data = Mat::<f64>::from_elem([data3d_shape.0, data3d_shape.1], 0.0);
for j in 0..data3d_shape.0 {
for k in 0..data3d_shape.1 {
data[[j, k]] = data3d[[j, k, i]];
}
}
let poly = PiecewiseLegendrePoly::new(
data,
knots.clone(),
i as i32,
Some(delta_x.clone()),
symm.as_ref().map_or(0, |s| s[i]),
)?;
polyvec.push(poly);
}
Ok(Self { polyvec })
}
pub fn size(&self) -> usize {
self.polyvec.len()
}
pub fn rescale_domain(
&self,
new_knots: Vec<f64>,
new_delta_x: Option<Vec<f64>>,
new_symm: Option<Vec<i32>>,
) -> Result<Self, Error> {
if let Some(symm) = &new_symm {
if symm.len() != self.polyvec.len() {
return Err(Error::InvalidParameter {
name: "new_symm",
value: format!("{} entries", symm.len()),
reason: format!(
"must have one entry per polynomial ({})",
self.polyvec.len()
),
});
}
}
let polyvec = self
.polyvec
.iter()
.enumerate()
.map(|(i, poly)| {
let symm = new_symm.as_ref().map(|s| s[i]);
poly.rescale_domain(new_knots.clone(), new_delta_x.clone(), symm)
})
.collect::<Result<_, _>>()?;
Ok(Self { polyvec })
}
pub fn scale_data(&self, factor: f64) -> Self {
let polyvec = self
.polyvec
.iter()
.map(|poly| poly.scale_data(factor))
.collect();
Self { polyvec }
}
pub fn get(&self, index: usize) -> Option<&PiecewiseLegendrePoly> {
self.polyvec.get(index)
}
#[deprecated(
note = "PiecewiseLegendrePolyVector is designed to be immutable. Use get() and create new instances for modifications."
)]
pub fn get_mut(&mut self, index: usize) -> Option<&mut PiecewiseLegendrePoly> {
self.polyvec.get_mut(index)
}
pub fn slice_single(&self, index: usize) -> Option<Self> {
self.polyvec.get(index).map(|poly| Self {
polyvec: vec![poly.clone()],
})
}
pub fn slice_multi(&self, indices: &[usize]) -> Result<Self, Error> {
if indices.is_empty() {
return Err(Error::EmptyInput { name: "indices" });
}
let len = self.polyvec.len();
let mut seen = vec![false; len];
for &idx in indices {
if idx >= len {
return Err(Error::InvalidParameter {
name: "indices",
value: format!("{idx}"),
reason: format!("must be less than the size {len}"),
});
}
if seen[idx] {
return Err(Error::InvalidParameter {
name: "indices",
value: format!("{idx}"),
reason: "must not repeat".to_string(),
});
}
seen[idx] = true;
}
let new_polyvec: Vec<_> = indices
.iter()
.map(|&idx| self.polyvec[idx].clone())
.collect();
Ok(Self {
polyvec: new_polyvec,
})
}
pub fn evaluate_at(&self, x: f64) -> Vec<f64> {
self.try_evaluate_at(x).unwrap_or_else(|e| panic!("{e}"))
}
pub fn try_evaluate_at(&self, x: f64) -> Result<Vec<f64>, Error> {
self.polyvec
.iter()
.map(|poly| poly.try_evaluate(x))
.collect()
}
pub fn evaluate_at_many(&self, xs: &[f64]) -> Mat<f64> {
self.try_evaluate_at_many(xs)
.unwrap_or_else(|e| panic!("{e}"))
}
pub fn try_evaluate_at_many(&self, xs: &[f64]) -> Result<Mat<f64>, Error> {
if let Some(first) = self.polyvec.first() {
for &x in xs {
first.check_in_domain("xs", x)?;
}
}
let n_funcs = self.polyvec.len();
let n_points = xs.len();
let mut results = Mat::<f64>::from_elem([n_funcs, n_points], 0.0);
for (i, poly) in self.polyvec.iter().enumerate() {
for (j, &x) in xs.iter().enumerate() {
results[[i, j]] = poly.evaluate_in_domain(x);
}
}
Ok(results)
}
pub fn xmin(&self) -> f64 {
if self.polyvec.is_empty() {
panic!("Cannot get xmin from empty PiecewiseLegendrePolyVector");
}
self.polyvec[0].xmin
}
pub fn xmax(&self) -> f64 {
if self.polyvec.is_empty() {
panic!("Cannot get xmax from empty PiecewiseLegendrePolyVector");
}
self.polyvec[0].xmax
}
pub fn get_knots(&self, tolerance: Option<f64>) -> Vec<f64> {
if self.polyvec.is_empty() {
panic!("Cannot get knots from empty PiecewiseLegendrePolyVector");
}
const DEFAULT_TOLERANCE: f64 = 1e-10;
let tolerance = tolerance.unwrap_or(DEFAULT_TOLERANCE);
let mut all_knots = Vec::new();
for poly in &self.polyvec {
for &knot in &poly.knots {
all_knots.push(knot);
}
}
{
all_knots.sort_by(|a, b| a.partial_cmp(b).unwrap());
all_knots.dedup_by(|a, b| (*a - *b).abs() < tolerance);
}
all_knots
}
pub fn get_delta_x(&self) -> Vec<f64> {
if self.polyvec.is_empty() {
panic!("Cannot get delta_x from empty PiecewiseLegendrePolyVector");
}
self.polyvec[0].delta_x.clone()
}
pub fn get_polyorder(&self) -> usize {
if self.polyvec.is_empty() {
panic!("Cannot get polyorder from empty PiecewiseLegendrePolyVector");
}
self.polyvec[0].polyorder
}
pub fn get_norms(&self) -> &[f64] {
if self.polyvec.is_empty() {
panic!("Cannot get norms from empty PiecewiseLegendrePolyVector");
}
&self.polyvec[0].norms
}
pub fn get_symm(&self) -> Vec<i32> {
if self.polyvec.is_empty() {
panic!("Cannot get symm from empty PiecewiseLegendrePolyVector");
}
self.polyvec.iter().map(|poly| poly.symm).collect()
}
pub fn get_data(&self) -> Mat3<f64> {
if self.polyvec.is_empty() {
panic!("Cannot get data from empty PiecewiseLegendrePolyVector");
}
let nsegments = self.polyvec[0].data.shape().1;
let polyorder = self.polyvec[0].polyorder;
let npolys = self.polyvec.len();
let mut data = Mat3::<f64>::from_elem([nsegments, polyorder, npolys], 0.0);
for (poly_idx, poly) in self.polyvec.iter().enumerate() {
for segment in 0..nsegments {
for degree in 0..polyorder {
data[[segment, degree, poly_idx]] = poly.data[[degree, segment]];
}
}
}
data
}
pub fn roots(&self, tolerance: Option<f64>) -> Vec<f64> {
if self.polyvec.is_empty() {
panic!("Cannot get roots from empty PiecewiseLegendrePolyVector");
}
const DEFAULT_TOLERANCE: f64 = 1e-10;
let tolerance = tolerance.unwrap_or(DEFAULT_TOLERANCE);
let mut all_roots = Vec::new();
for poly in &self.polyvec {
let poly_roots = poly.roots();
for root in poly_roots {
all_roots.push(root);
}
}
{
all_roots.sort_by(|a, b| b.partial_cmp(a).unwrap());
all_roots.dedup_by(|a, b| (*a - *b).abs() < tolerance);
}
all_roots
}
pub fn last(&self) -> &PiecewiseLegendrePoly {
self.polyvec
.last()
.expect("Cannot get last from empty PiecewiseLegendrePolyVector")
}
pub fn nroots(&self, tolerance: Option<f64>) -> usize {
if self.polyvec.is_empty() {
panic!("Cannot get nroots from empty PiecewiseLegendrePolyVector");
}
self.roots(tolerance).len()
}
}
impl std::ops::Index<usize> for PiecewiseLegendrePolyVector {
type Output = PiecewiseLegendrePoly;
fn index(&self, index: usize) -> &Self::Output {
&self.polyvec[index]
}
}
pub(crate) fn default_sampling_points(
u: &PiecewiseLegendrePolyVector,
name: &'static str,
l: usize,
) -> Result<Vec<f64>, Error> {
if (u.xmin() - (-1.0)).abs() > 1e-10 || (u.xmax() - 1.0).abs() > 1e-10 {
return Err(Error::InvalidParameter {
name,
value: format!("functions on [{:?}, {:?}]", u.xmin(), u.xmax()),
reason: "must be the unscaled functions of an SVE, on [-1, 1]".to_string(),
});
}
let x0 = if l < u.polyvec.len() {
u[l].roots()
} else {
let poly = u.last();
let poly_deriv = poly.deriv(1);
let maxima = poly_deriv.roots();
let (Some(&first), Some(&last)) = (maxima.first(), maxima.last()) else {
return Err(Error::NotSupported {
what: format!(
"default sampling points for {l} basis functions: the last singular \
function (l = {}) has no extrema to stand in for the roots of the \
missing function l = {l} (an SVE truncated to too few functions)",
poly.l
),
});
};
let left = (first + poly.xmin) / 2.0;
let right = (last + poly.xmax) / 2.0;
let mut x0_vec = Vec::with_capacity(maxima.len() + 2);
x0_vec.push(left);
x0_vec.extend_from_slice(&maxima);
x0_vec.push(right);
x0_vec
};
if x0.len() != l {
debug_warn!(
"Expecting to get {} sampling points for corresponding basis function, \
instead got {}. This may happen if not enough precision is left in the polynomial.",
l,
x0.len()
);
}
Ok(x0)
}
#[cfg(test)]
#[path = "poly_tests.rs"]
mod poly_tests;