use ndarray::Array1;
use solow_core::error::{Error, Result};
const IQR_NORMALIZE: f64 = 1.349;
const GAUSSIAN_NORMAL_REFERENCE_CONSTANT: f64 = 1.059_223_841_048_812_2;
fn percentile(x: &Array1<f64>, q: f64) -> f64 {
let n = x.len();
debug_assert!(n > 0);
let mut sorted: Vec<f64> = x.to_vec();
sorted.sort_by(|a, b| a.total_cmp(b));
if n == 1 {
return sorted[0];
}
let pos = (q / 100.0) * (n as f64 - 1.0);
let lo = pos.floor() as usize;
let hi = (lo + 1).min(n - 1);
let frac = pos - lo as f64;
sorted[lo] + frac * (sorted[hi] - sorted[lo])
}
fn std_ddof1(x: &Array1<f64>) -> f64 {
let n = x.len();
debug_assert!(n > 1);
let mean = x.sum() / n as f64;
let ss: f64 = x.iter().map(|&v| (v - mean) * (v - mean)).sum();
(ss / (n as f64 - 1.0)).sqrt()
}
pub fn select_sigma(x: &Array1<f64>) -> Result<f64> {
if x.len() < 2 {
return Err(Error::Value(
"bandwidth selection requires at least two observations".into(),
));
}
let iqr = (percentile(x, 75.0) - percentile(x, 25.0)) / IQR_NORMALIZE;
let std_dev = std_ddof1(x);
if iqr > 0.0 {
Ok(std_dev.min(iqr))
} else {
Ok(std_dev)
}
}
pub fn bw_silverman(x: &Array1<f64>) -> Result<f64> {
let a = select_sigma(x)?;
let n = x.len() as f64;
Ok(0.9 * a * n.powf(-0.2))
}
pub fn bw_scott(x: &Array1<f64>) -> Result<f64> {
let a = select_sigma(x)?;
let n = x.len() as f64;
Ok(1.059 * a * n.powf(-0.2))
}
pub fn bw_normal_reference(x: &Array1<f64>) -> Result<f64> {
let a = select_sigma(x)?;
let n = x.len() as f64;
Ok(GAUSSIAN_NORMAL_REFERENCE_CONSTANT * a * n.powf(-0.2))
}
#[cfg(test)]
mod tests {
use super::*;
use ndarray::array;
#[test]
fn percentile_matches_numpy_linear() {
let x = array![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
assert!((percentile(&x, 75.0) - 7.75).abs() < 1e-12);
assert!((percentile(&x, 25.0) - 3.25).abs() < 1e-12);
assert!((percentile(&x, 50.0) - 5.5).abs() < 1e-12);
}
#[test]
fn std_uses_ddof1() {
let x = array![2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
assert!((std_ddof1(&x) - (32.0_f64 / 7.0).sqrt()).abs() < 1e-12);
}
#[test]
fn bandwidth_ordering() {
let x = array![0.1, 0.5, 0.9, 1.3, 2.1, 2.8, 3.0, 3.6, 4.4, 5.0];
let s = bw_silverman(&x).unwrap();
let sc = bw_scott(&x).unwrap();
let nr = bw_normal_reference(&x).unwrap();
assert!(s > 0.0 && sc > 0.0 && nr > 0.0);
assert!(s < sc);
assert!(sc < nr);
}
#[test]
fn too_few_points_errors() {
let x = array![1.0];
assert!(bw_silverman(&x).is_err());
}
}