use std::f64::consts::PI;
#[derive(Debug, Clone)]
pub enum PsTerm1D {
ExponentialPoly {
alpha: f64,
poly_minus: [f64; 3],
poly_plus: [f64; 3],
power: u8,
},
GaussianCos {
two_a: f64,
two_u: f64,
two_u_a: f64,
amp: f64,
},
GaussianSin {
two_a: f64,
two_u: f64,
two_u_a: f64,
amp: f64,
},
}
impl PsTerm1D {
#[inline]
fn eval_poly(c: &[f64; 3], x: f64) -> f64 {
c[0] + x * (c[1] + x * c[2])
}
#[inline]
fn pow_u8(x: f64, p: u8) -> f64 {
match p {
0 => 1.0,
1 => x,
2 => x * x,
_ => x.powi(p as i32),
}
}
#[inline]
pub fn eval_minus(&self, x: f64) -> (f64, f64) {
match *self {
Self::ExponentialPoly {
alpha,
poly_minus,
power,
..
} => {
let em = (-alpha * x).exp();
let ep = (alpha * x).exp();
(em * Self::eval_poly(&poly_minus, x), ep * Self::pow_u8(x, power))
}
Self::GaussianCos {
two_a,
two_u,
two_u_a,
amp,
} => {
let em = (-two_a * x).exp();
let ep = (two_a * x).exp();
let f = amp * em * (two_u_a - two_u * x).cos();
let g = ep * (two_u * x).cos();
(f, g)
}
Self::GaussianSin {
two_a,
two_u,
two_u_a,
amp,
} => {
let em = (-two_a * x).exp();
let ep = (two_a * x).exp();
let f = -amp * em * (two_u_a - two_u * x).sin();
let g = ep * (two_u * x).sin();
(f, g)
}
}
}
#[inline]
pub fn eval_plus(&self, x: f64) -> (f64, f64) {
match *self {
Self::ExponentialPoly {
alpha,
poly_plus,
power,
..
} => {
let ep = (alpha * x).exp();
let em = (-alpha * x).exp();
(ep * Self::pow_u8(-x, power), em * Self::eval_poly(&poly_plus, x))
}
Self::GaussianCos {
two_a,
two_u,
two_u_a,
amp,
} => {
let ep = (two_a * x).exp();
let em = (-two_a * x).exp();
let f = amp * ep * (two_u_a + two_u * x).cos();
let g = em * (two_u * x).cos();
(f, g)
}
Self::GaussianSin {
two_a,
two_u,
two_u_a,
amp,
} => {
let ep = (two_a * x).exp();
let em = (-two_a * x).exp();
let f = amp * ep * (two_u_a + two_u * x).sin();
let g = em * (two_u * x).sin();
(f, g)
}
}
}
#[inline]
pub fn exp_rate(&self) -> f64 {
match *self {
Self::ExponentialPoly { alpha, .. } => alpha,
Self::GaussianCos { two_a, .. } | Self::GaussianSin { two_a, .. } => two_a,
}
}
}
#[derive(Debug, Clone)]
pub enum Kernel1D {
Laplace { bandwidth: f64 },
Matern32 { bandwidth: f64 },
Matern52 { bandwidth: f64 },
Gaussian { bandwidth: f64, tol: f64 },
}
impl Kernel1D {
pub fn bandwidth(&self) -> f64 {
match *self {
Self::Laplace { bandwidth }
| Self::Matern32 { bandwidth }
| Self::Matern52 { bandwidth }
| Self::Gaussian { bandwidth, .. } => bandwidth,
}
}
#[inline]
pub fn eval_exact(&self, x: f64, y: f64) -> f64 {
let r = (x - y).abs() / self.bandwidth();
match *self {
Self::Laplace { .. } => (-r).exp(),
Self::Matern32 { .. } => {
let t = 3.0_f64.sqrt() * r;
(1.0 + t) * (-t).exp()
}
Self::Matern52 { .. } => {
let t = 5.0_f64.sqrt() * r;
(1.0 + t + t * t / 3.0) * (-t).exp()
}
Self::Gaussian { .. } => (-r * r).exp(),
}
}
pub fn aps_error_bound(&self) -> f64 {
match *self {
Self::Laplace { .. } | Self::Matern32 { .. } | Self::Matern52 { .. } => 0.0,
Self::Gaussian { tol, .. } => {
let (t_param, _l) = gaussian_trapezoidal_params(tol);
4.0 * (-0.5 * PI * PI * t_param * t_param).exp()
}
}
}
pub fn ps_terms(&self) -> Vec<PsTerm1D> {
match *self {
Self::Laplace { .. } => vec![PsTerm1D::ExponentialPoly {
alpha: 1.0,
poly_minus: [1.0, 0.0, 0.0],
poly_plus: [1.0, 0.0, 0.0],
power: 0,
}],
Self::Matern32 { .. } => {
let lam = 3.0_f64.sqrt();
vec![
PsTerm1D::ExponentialPoly {
alpha: lam,
poly_minus: [1.0, lam, 0.0],
poly_plus: [1.0, lam, 0.0],
power: 0,
},
PsTerm1D::ExponentialPoly {
alpha: lam,
poly_minus: [-lam, 0.0, 0.0],
poly_plus: [lam, 0.0, 0.0],
power: 1,
},
]
}
Self::Matern52 { .. } => {
let lam = 5.0_f64.sqrt();
let lam2_3 = (lam * lam) / 3.0;
vec![
PsTerm1D::ExponentialPoly {
alpha: lam,
poly_minus: [1.0, lam, lam2_3],
poly_plus: [1.0, lam, lam2_3],
power: 0,
},
PsTerm1D::ExponentialPoly {
alpha: lam,
poly_minus: [-lam, -2.0 * lam2_3, 0.0],
poly_plus: [lam, 2.0 * lam2_3, 0.0],
power: 1,
},
PsTerm1D::ExponentialPoly {
alpha: lam,
poly_minus: [lam2_3, 0.0, 0.0],
poly_plus: [lam2_3, 0.0, 0.0],
power: 2,
},
]
}
Self::Gaussian { tol, .. } => {
let (t_param, l_max) = gaussian_trapezoidal_params(tol);
let a = PI * t_param / 4.0;
let two_a = 2.0 * a;
let inv_t_sqrt_pi = 1.0 / (t_param * PI.sqrt());
let exp_a2 = (a * a).exp();
let mut terms = Vec::with_capacity(2 * l_max + 1);
let a0 = exp_a2 * inv_t_sqrt_pi;
terms.push(PsTerm1D::ExponentialPoly {
alpha: two_a,
poly_minus: [a0, 0.0, 0.0],
poly_plus: [a0, 0.0, 0.0],
power: 0,
});
for j in 1..=l_max {
let u_j = (j as f64) / t_param;
let amp = 2.0 * (a * a - u_j * u_j).exp() * inv_t_sqrt_pi;
let two_u = 2.0 * u_j;
let two_u_a = two_u * a;
terms.push(PsTerm1D::GaussianCos {
two_a,
two_u,
two_u_a,
amp,
});
terms.push(PsTerm1D::GaussianSin {
two_a,
two_u,
two_u_a,
amp,
});
}
terms
}
}
}
}
pub fn gaussian_trapezoidal_params(tol: f64) -> (f64, usize) {
let clamped_tol = tol.clamp(1e-12, 0.5);
let t_needed = ((2.0 / (PI * PI)) * (4.0 / clamped_tol).ln()).max(1.0).sqrt();
let t_param = t_needed.max(1.0);
let l_max = (0.75 * PI * t_param * t_param).ceil() as usize;
(t_param, l_max.max(1))
}
#[derive(Debug, Clone)]
pub struct ProductKernel {
pub factors: Vec<Kernel1D>,
}
impl ProductKernel {
pub fn new(factors: Vec<Kernel1D>) -> Result<Self, String> {
if factors.is_empty() {
return Err("ProductKernel requires at least one 1D factor".to_string());
}
for (idx, f) in factors.iter().enumerate() {
let bw = f.bandwidth();
if !bw.is_finite() || bw <= 0.0 {
return Err(format!("factor {idx} has non-positive or non-finite bandwidth {bw}"));
}
if let Kernel1D::Gaussian { tol, .. } = *f {
if !tol.is_finite() || tol <= 0.0 {
return Err(format!("factor {idx} has invalid Gaussian tolerance {tol}"));
}
}
}
Ok(Self { factors })
}
pub fn laplace(bandwidths: &[f64]) -> Result<Self, String> {
Self::new(
bandwidths
.iter()
.map(|&bandwidth| Kernel1D::Laplace { bandwidth })
.collect(),
)
}
pub fn matern32(bandwidths: &[f64]) -> Result<Self, String> {
Self::new(
bandwidths
.iter()
.map(|&bandwidth| Kernel1D::Matern32 { bandwidth })
.collect(),
)
}
pub fn matern52(bandwidths: &[f64]) -> Result<Self, String> {
Self::new(
bandwidths
.iter()
.map(|&bandwidth| Kernel1D::Matern52 { bandwidth })
.collect(),
)
}
pub fn gaussian(bandwidths: &[f64], tol: f64) -> Result<Self, String> {
Self::new(
bandwidths
.iter()
.map(|&bandwidth| Kernel1D::Gaussian { bandwidth, tol })
.collect(),
)
}
pub fn dim(&self) -> usize {
self.factors.len()
}
#[inline]
pub fn eval_exact(&self, x: &[f64], y: &[f64]) -> f64 {
let mut prod = 1.0;
for (l, f) in self.factors.iter().enumerate() {
prod *= f.eval_exact(x[l], y[l]);
}
prod
}
pub fn aos_error_bound(&self) -> f64 {
let d = self.factors.len();
let delta_max = self
.factors
.iter()
.map(Kernel1D::aps_error_bound)
.fold(0.0_f64, f64::max);
if delta_max == 0.0 {
return 0.0;
}
(d as f64) * (1.0 + delta_max).powi((d - 1) as i32) * delta_max
}
}