med64 0.0.2

Headless MED64 electrophysiology toolkit: .modat I/O, spike/burst analysis, assays, spike-rate maps, and CSV/HTML/SVG/HDF5 export
Documentation
use crate::header::Med64Header;

/// Threshold calculation method (`ThresholdType`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThresholdMethod {
    /// Median absolute deviation scaled (`thresholdRate` percent).
    ///
    /// BIT-EXACT WITH THE LEGACY REFERENCE, AND STATISTICALLY WRONG. Computes
    /// `median(|x|) * medianFactor * scale`, i.e. it MULTIPLIES by 0.6745
    /// where the robust estimator `sigma = median(|x|) / 0.6745` divides. The
    /// resulting threshold is `1/0.6745^2 = 2.20x` LOWER than the nominal
    /// `magnification_percent` implies -- a "500%" setting cuts at 2.27 MAD,
    /// not 5. On real 20 kHz MED64 data that is inside the noise: measured
    /// 462 raw crossings/channel/s against 0.54 at a true 5 sigma, which the
    /// refractory then collapses into a uniform ~50 Hz/channel on EVERY
    /// channel, with a one-sample spike-triggered average and zero bursts.
    ///
    /// Kept, and kept as the default, because `tests/spike_detect_parity.rs`
    /// asserts equality with the reference detector and this crate's
    /// contract is a faithful port. Use [`ThresholdMethod::MedianMad`] to
    /// detect actual spikes.
    Median,
    /// `median(|x|) / 0.6745 * scale` -- the standard robust noise estimate,
    /// and the same convention this crate already uses for the ASDR
    /// auto-threshold (`analysis::burst::multi`, `AutoThresholdBase::MedianMad`).
    /// DIVERGES FROM THE LEGACY MEDIAN PATH BY 2.20x BY DESIGN. Prefer this for analysis.
    MedianMad,
    /// Standard deviation scaled (`thresholdRate` percent).
    StandardDeviation,
    /// Fixed per-channel millivolt thresholds from workflow settings.
    Fixed,
}

#[derive(Debug, Clone)]
pub struct ThresholdOptions {
    pub method: ThresholdMethod,
    /// `thresholdRate` / `rmsPercentage` (500 = 500%).
    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,
}

/// Compute per-channel spike thresholds in millivolts.
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);
            // Median multiplies (legacy); MedianMad divides (correct).
            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 }
        }
    }
}

/// Parse space-separated per-channel floats from node settings.
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
}

/// Parse `1-64` or comma-separated channel spec from replay node.
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()
}

/// Convert sample index to within-trace milliseconds.
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]);
    }
}