const OVER_NOISE: f64 = 6.0;
const ON_POINT: f64 = 4.0;
const MIN_VALUES: usize = 3;
const MIN_STEP: f64 = 24.0;
const SMALLEST: std::ops::RangeInclusive<u32> = 1..=8;
pub(super) const WHOLE_STEP: f64 = 0.05;
#[derive(Clone, Copy)]
pub(super) enum BandStep {
Untested,
Off,
On(f64),
}
impl BandStep {
pub(super) fn tested(self) -> bool {
!matches!(self, Self::Untested)
}
pub(super) fn step(self) -> Option<f64> {
match self {
Self::On(step) => Some(step),
Self::Untested | Self::Off => None,
}
}
}
#[derive(Default)]
pub(super) struct BandScratch {
values: Vec<f64>,
points: Vec<f64>,
}
pub(super) fn band_step(lines: &[f64], sigma: f64, scratch: &mut BandScratch) -> BandStep {
let BandScratch { values, points } = scratch;
values.clear();
values.extend(
lines
.iter()
.map(|line| line.abs())
.filter(|value| *value > OVER_NOISE * sigma),
);
if values.len() < MIN_VALUES {
return BandStep::Untested;
}
let smallest = values.iter().copied().fold(f64::INFINITY, f64::min);
let mut tested = false;
for whole in SMALLEST {
let step = smallest / f64::from(whole).powf(4.0 / 3.0);
if step < MIN_STEP * sigma {
break;
}
tested = true;
points.clear();
points.extend(
values
.iter()
.map(|value| (value / step).powf(0.75).round().max(1.0).powf(4.0 / 3.0)),
);
let squares: f64 = points.iter().map(|point| point * point).sum();
let step = values.iter().zip(&*points).map(|(v, p)| v * p).sum::<f64>() / squares;
let near = |point: f64| ON_POINT * sigma * (1.0 + point / squares.sqrt());
if values
.iter()
.zip(&*points)
.all(|(value, point)| (value - point * step).abs() < near(*point))
{
return BandStep::On(step);
}
}
if tested {
BandStep::Off
} else {
BandStep::Untested
}
}