use crate::header::Med64Header;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThresholdMethod {
Median,
MedianMad,
StandardDeviation,
Fixed,
}
#[derive(Debug, Clone)]
pub struct ThresholdOptions {
pub method: ThresholdMethod,
pub magnification_percent: f64,
pub median_factor: f64,
}
impl Default for ThresholdOptions {
fn default() -> Self {
Self {
method: ThresholdMethod::Median,
magnification_percent: 500.0,
median_factor: 0.6745,
}
}
}
#[derive(Debug, Clone)]
pub struct ChannelThresholds {
pub plus_mv: f64,
pub minus_mv: f64,
}
pub fn calc_thresholds(
samples_mv: &[f64],
options: &ThresholdOptions,
fixed: Option<(f64, f64)>,
) -> ChannelThresholds {
if let Some((plus, minus)) = fixed {
return ChannelThresholds { plus_mv: plus, minus_mv: minus };
}
let scale = options.magnification_percent / 100.0;
match options.method {
ThresholdMethod::Fixed => ChannelThresholds { plus_mv: 0.5, minus_mv: -0.5 },
ThresholdMethod::Median | ThresholdMethod::MedianMad => {
let mut abs: Vec<f64> = samples_mv.iter().map(|v| v.abs()).collect();
abs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let median = abs.get(abs.len() / 2).copied().unwrap_or(0.0);
let t = if options.method == ThresholdMethod::MedianMad {
if options.median_factor.abs() > f64::EPSILON {
median / options.median_factor * scale
} else {
0.0
}
} else {
median * options.median_factor * scale
};
ChannelThresholds { plus_mv: t, minus_mv: -t }
}
ThresholdMethod::StandardDeviation => {
let n = samples_mv.len().max(1) as f64;
let mean = samples_mv.iter().sum::<f64>() / n;
let var = samples_mv.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / n;
let sd = var.sqrt();
let t = sd * scale;
ChannelThresholds { plus_mv: t, minus_mv: -t }
}
}
}
pub fn parse_channel_values(text: &str, channels: usize) -> Vec<f64> {
let mut values: Vec<f64> =
text.split_whitespace().filter_map(|part| part.parse().ok()).collect();
if values.is_empty() {
values.resize(channels, 0.0);
} else if values.len() < channels {
let last = *values.last().unwrap();
values.resize(channels, last);
}
values
}
pub fn parse_active_channels(spec: &str, max_channels: usize) -> Vec<usize> {
if let Some((from, to)) = spec.split_once('-') {
if let (Ok(start), Ok(end)) = (from.trim().parse::<usize>(), to.trim().parse::<usize>()) {
let start = start.saturating_sub(1);
let end = end.min(max_channels);
return (start..end).collect();
}
}
spec.split(',')
.filter_map(|part| part.trim().parse::<usize>().ok().map(|ch| ch.saturating_sub(1)))
.filter(|&ch| ch < max_channels)
.collect()
}
pub fn enabled_channels_from_moflo(values: &str, max_channels: usize) -> Vec<usize> {
let flags: Vec<bool> =
values.split_whitespace().map(|part| part.eq_ignore_ascii_case("true")).collect();
if flags.is_empty() {
return (0..max_channels).collect();
}
flags
.into_iter()
.enumerate()
.filter_map(|(ch, enabled)| enabled.then_some(ch))
.take(max_channels)
.collect()
}
pub fn index_to_ms(header: &Med64Header, index: usize, block_offset_ms: f64) -> f64 {
block_offset_ms + index as f64 * header.interval_ms()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn median_threshold_scales() {
let samples: Vec<f64> = (0..1000).map(|i| (i as f64 * 0.001).sin() * 0.01).collect();
let t = calc_thresholds(&samples, &ThresholdOptions::default(), None);
assert!(t.plus_mv > 0.0);
assert!(t.minus_mv < 0.0);
}
#[test]
fn parses_channel_range() {
assert_eq!(parse_active_channels("1-4", 64), vec![0, 1, 2, 3]);
}
}