use crate::common::vec_f64::median;
const LANCZOS_G: f64 = 7.0;
#[allow(clippy::excessive_precision)]
const LANCZOS_COEFFS: [f64; 9] = [
0.999_999_999_999_809_93,
676.520_368_121_885_1,
-1_259.139_216_722_402_8,
771.323_428_777_653_1,
-176.615_029_162_140_6,
12.507_343_278_686_905,
-0.138_571_095_265_720_12,
9.984_369_578_019_572e-6,
1.505_632_735_149_311_6e-7,
];
pub(crate) fn ln_gamma(x: f64) -> f64 {
let x = x - 1.0;
let mut a = LANCZOS_COEFFS[0];
let t = x + LANCZOS_G + 0.5;
for (i, &c) in LANCZOS_COEFFS.iter().enumerate().skip(1) {
a += c / (x + i as f64);
}
0.5 * (2.0 * std::f64::consts::PI).ln() + (x + 0.5) * t.ln() - t + a.ln()
}
pub(crate) fn reg_lower_gamma(a: f64, x: f64) -> f64 {
if x <= 0.0 {
return 0.0;
}
if x < a + 1.0 {
gamma_series(a, x)
} else {
1.0 - gamma_cont_frac(a, x)
}
}
pub(crate) fn reg_upper_gamma(a: f64, x: f64) -> f64 {
1.0 - reg_lower_gamma(a, x)
}
pub(crate) fn upper_gamma(a: f64, x: f64) -> f64 {
reg_upper_gamma(a, x) * ln_gamma(a).exp()
}
fn gamma_series(a: f64, x: f64) -> f64 {
const MAX_ITER: usize = 200;
const EPS: f64 = 1e-15;
let mut ap = a;
let mut sum = 1.0 / a;
let mut del = sum;
for _ in 0..MAX_ITER {
ap += 1.0;
del *= x / ap;
sum += del;
if del.abs() < sum.abs() * EPS {
break;
}
}
sum * (-x + a * x.ln() - ln_gamma(a)).exp()
}
fn gamma_cont_frac(a: f64, x: f64) -> f64 {
const MAX_ITER: usize = 200;
const EPS: f64 = 1e-15;
const TINY: f64 = 1e-300;
let mut b = x + 1.0 - a;
let mut c = 1.0 / TINY;
let mut d = 1.0 / b;
let mut h = d;
for i in 1..MAX_ITER {
let an = -(i as f64) * (i as f64 - a);
b += 2.0;
d = an * d + b;
if d.abs() < TINY {
d = TINY;
}
c = b + an / c;
if c.abs() < TINY {
c = TINY;
}
d = 1.0 / d;
let del = d * c;
h *= del;
if (del - 1.0).abs() < EPS {
break;
}
}
(-x + a * x.ln() - ln_gamma(a)).exp() * h
}
fn chi2_quantile(p: f64, dof: usize) -> f64 {
let a = dof as f64 / 2.0;
let target = p;
let (mut lo, mut hi) = (0.0_f64, 1.0_f64);
while reg_lower_gamma(a, hi / 2.0) < target && hi < 1e6 {
hi *= 2.0;
}
for _ in 0..100 {
let mid = 0.5 * (lo + hi);
if reg_lower_gamma(a, mid / 2.0) < target {
lo = mid;
} else {
hi = mid;
}
}
0.5 * (lo + hi)
}
pub(crate) struct MagsacWeight {
two_sigma_sq: f64,
a: f64,
coeff: f64,
cutoff: f64,
gamma_at_cutoff: f64,
}
impl MagsacWeight {
pub(crate) fn new(sigma_max: f64, dof: usize) -> Self {
let nu = dof as f64;
let a = (nu - 1.0) / 2.0;
let k = chi2_quantile(0.99, dof).sqrt();
let two_sigma_sq = 2.0 * sigma_max * sigma_max;
let c_nu = 1.0 / (2.0_f64.powf(nu / 2.0 - 1.0) * ln_gamma(nu / 2.0).exp());
let coeff = c_nu * 2.0_f64.powf((nu - 1.0) / 2.0) / sigma_max;
let x_cutoff = k * k / 2.0;
let gamma_at_cutoff = upper_gamma(a, x_cutoff);
Self {
two_sigma_sq,
a,
coeff,
cutoff: k * sigma_max,
gamma_at_cutoff,
}
}
pub(crate) fn cutoff(&self) -> f64 {
self.cutoff
}
pub(crate) fn weight(&self, r: f64) -> f64 {
if r >= self.cutoff {
return 0.0;
}
let x = r * r / self.two_sigma_sq;
(self.coeff * (upper_gamma(self.a, x) - self.gamma_at_cutoff)).max(0.0)
}
}
pub(crate) const MAD_TO_SIGMA: f64 = 1.4826;
pub(crate) fn estimate_sigma_max(residuals: &[f64]) -> Option<f64> {
let center = median(residuals)?;
let deviations: Vec<f64> = residuals.iter().map(|r| (r - center).abs()).collect();
let sigma = MAD_TO_SIGMA * median(&deviations)?;
(sigma.is_finite() && sigma > 0.0).then_some(sigma)
}
#[cfg(test)]
mod tests {
use super::*;
use approx::assert_relative_eq;
#[test]
fn sigma_estimate_is_robust_to_outliers() {
let mut values: Vec<f64> = (-5..=5).map(|i| i as f64).collect();
let clean = estimate_sigma_max(&values).unwrap();
values.push(10_000.0);
let contaminated = estimate_sigma_max(&values).unwrap();
assert!(
(contaminated - clean).abs() < 0.5 * clean,
"outlier moved the estimate too far: {clean} -> {contaminated}"
);
}
#[test]
fn sigma_estimate_rejects_degenerate_spread() {
assert_eq!(estimate_sigma_max(&[2.0; 10]), None);
assert_eq!(estimate_sigma_max(&[]), None);
}
#[test]
fn ln_gamma_known_values() {
assert_relative_eq!(ln_gamma(1.0).exp(), 1.0, epsilon = 1e-10);
assert_relative_eq!(ln_gamma(2.0).exp(), 1.0, epsilon = 1e-10);
assert_relative_eq!(
ln_gamma(0.5).exp(),
std::f64::consts::PI.sqrt(),
epsilon = 1e-10
);
assert_relative_eq!(ln_gamma(5.0).exp(), 24.0, epsilon = 1e-9);
}
#[test]
fn upper_gamma_known_values() {
for &x in &[0.25_f64, 1.0, 3.0, 7.0] {
assert_relative_eq!(upper_gamma(1.0, x), (-x).exp(), epsilon = 1e-9);
}
assert_relative_eq!(
upper_gamma(0.5, 0.0),
std::f64::consts::PI.sqrt(),
epsilon = 1e-9
);
assert_relative_eq!(
reg_lower_gamma(2.5, 1.3) + reg_upper_gamma(2.5, 1.3),
1.0,
epsilon = 1e-12
);
}
#[test]
fn chi2_quantile_known_values() {
let expected = -2.0 * 0.01_f64.ln();
assert_relative_eq!(chi2_quantile(0.99, 2), expected, epsilon = 1e-6);
}
#[test]
fn weight_is_positive_and_decreasing_then_zero() {
let w = MagsacWeight::new(0.1, 2);
let cutoff = w.cutoff();
let mut prev = f64::INFINITY;
let mut r = 0.0;
while r < 0.95 * cutoff {
let val = w.weight(r);
assert!(val > 0.0, "weight should be positive inside the support");
assert!(val < prev, "weight should be strictly decreasing");
prev = val;
r += cutoff / 50.0;
}
assert_eq!(w.weight(cutoff), 0.0);
assert_eq!(w.weight(cutoff * 2.0), 0.0);
}
}