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 serde::{Deserialize, Serialize};

use crate::analysis::spike::{Spike, SpikeTrain};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SingleChannelBurst {
    pub channel: usize,
    pub trace: u32,
    pub start_ms: f64,
    pub end_ms: f64,
    pub num_spikes: usize,
    pub interburst_interval_ms: f64,
    pub duration_ms: f64,
}

#[derive(Debug, Clone)]
pub struct SingleChannelBurstOptions {
    /// Max inter-spike interval to *start* a burst (ms). Wire `maxIntervalStartMSec`.
    pub max_interval_start_ms: f64,
    /// Max inter-spike interval before ending a burst (ms). Wire `maxIntervalEndMSec`.
    pub max_interval_end_ms: f64,
    pub min_spikes: usize,
    pub min_duration_ms: f64,
    /// Minimum gap after a closed burst before a new one may start (ms).
    pub min_interburst_ms: f64,
    /// Trace end (ms). When `None`, open bursts at EOF are closed without the
    /// End-gap check (keeps unit tests simple).
    pub trace_end_ms: Option<f64>,
}

impl Default for SingleChannelBurstOptions {
    fn default() -> Self {
        Self {
            max_interval_start_ms: 150.0,
            max_interval_end_ms: 300.0,
            min_spikes: 3,
            min_duration_ms: 30.0,
            min_interburst_ms: 10.0,
            trace_end_ms: None,
        }
    }
}

/// Max-interval burst detection matching `SingleChannelBurstService.detectPerChannel`.
pub fn detect_single_channel_bursts(
    train: &SpikeTrain,
    options: &SingleChannelBurstOptions,
) -> Vec<SingleChannelBurst> {
    let mut bursts = Vec::new();
    for (channel, spikes) in train.by_channel() {
        bursts.extend(detect_channel_bursts(channel, &spikes, options));
    }
    bursts
}

fn detect_channel_bursts(
    channel: usize,
    spikes: &[&Spike],
    options: &SingleChannelBurstOptions,
) -> Vec<SingleChannelBurst> {
    if spikes.is_empty() {
        return Vec::new();
    }

    // Ensure time order (train may be sorted by peak index globally, but keep this robust).
    let mut spikes = spikes.to_vec();
    spikes.sort_by(|a, b| {
        a.within_trace_time_ms
            .partial_cmp(&b.within_trace_time_ms)
            .unwrap()
            .then(a.peak_index.cmp(&b.peak_index))
    });

    let mut result = Vec::new();
    let mut open: Option<Vec<&Spike>> = None;
    let mut prev: Option<&Spike> = None;
    let mut earliest_next = -1.0_f64;

    for &spike in &spikes {
        let t = spike.within_trace_time_ms;
        if open.is_none() {
            if let Some(prev_spike) = prev {
                let ibi_ok = earliest_next < 0.0 || earliest_next <= t;
                // ReferenceBurstExport / MaxInterval: gap <= maxIntervalStart.
                let gap = t - prev_spike.within_trace_time_ms;
                if ibi_ok && gap <= options.max_interval_start_ms {
                    open = Some(vec![prev_spike, spike]);
                }
            }
        } else {
            let group = open.as_mut().unwrap();
            let last = group.last().unwrap().within_trace_time_ms;
            // Close when gap > maxIntervalEnd (strict).
            if t - last > options.max_interval_end_ms {
                let last_for_ibi = last;
                if let Some(burst) = finalize_group(channel, group, options) {
                    earliest_next = burst.end_ms + options.min_interburst_ms;
                    result.push(burst);
                } else {
                    earliest_next = last_for_ibi + options.min_interburst_ms;
                }
                open = None;
                // Current spike becomes `prev` only — no same-iter reopen.
            } else {
                group.push(spike);
            }
        }
        prev = Some(spike);
    }

    if let Some(group) = open.as_ref() {
        let last = group.last().unwrap().within_trace_time_ms;
        let should_close = match options.trace_end_ms {
            Some(end) => end - last > options.max_interval_end_ms,
            None => true,
        };
        if should_close {
            if let Some(burst) = finalize_group(channel, group, options) {
                result.push(burst);
            }
        }
    }

    for i in 0..result.len() {
        result[i].interburst_interval_ms =
            if i == 0 { 0.0 } else { result[i].start_ms - result[i - 1].end_ms };
    }
    result
}

fn finalize_group(
    channel: usize,
    group: &[&Spike],
    options: &SingleChannelBurstOptions,
) -> Option<SingleChannelBurst> {
    if group.len() < options.min_spikes {
        return None;
    }
    let start = group.first().unwrap().within_trace_time_ms;
    let end = group.last().unwrap().within_trace_time_ms;
    let duration = end - start;
    if duration < options.min_duration_ms {
        return None;
    }
    Some(SingleChannelBurst {
        channel,
        trace: group[0].trace,
        start_ms: start,
        end_ms: end,
        num_spikes: group.len(),
        interburst_interval_ms: 0.0,
        duration_ms: duration,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analysis::spike::{Spike, SpikeDirection, SpikeTrain};

    #[test]
    fn groups_nearby_spikes() {
        let mut train = SpikeTrain::default();
        for t in [0.0, 50.0, 100.0, 450.0, 500.0, 550.0] {
            train.push(Spike {
                channel: 0,
                trace: 0,
                direction: SpikeDirection::Plus,
                peak_index: 0,
                start_index: 0,
                end_index: 0,
                peak_mv: 1.0,
                within_trace_time_ms: t,
                within_session_time_ms: t,
                ..Default::default()
            });
        }
        let bursts = detect_single_channel_bursts(&train, &SingleChannelBurstOptions::default());
        assert_eq!(bursts.len(), 2);
        assert_eq!(bursts[0].num_spikes, 3);
        assert_eq!(bursts[1].num_spikes, 3);
    }

    #[test]
    fn start_interval_stricter_than_end() {
        // Gaps of 200 ms: can continue an open burst (end=300) but cannot start one (start=150).
        let mut train = SpikeTrain::default();
        for t in [0.0, 200.0, 400.0, 600.0] {
            train.push(Spike {
                channel: 0,
                within_trace_time_ms: t,
                within_session_time_ms: t,
                peak_mv: 1.0,
                ..Default::default()
            });
        }
        let bursts = detect_single_channel_bursts(&train, &SingleChannelBurstOptions::default());
        assert!(bursts.is_empty());
    }
}