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
//! Network burst profiles (`multi-channel burst profile`).

use serde::{Deserialize, Serialize};

use crate::analysis::burst::{AsdrTrace, MultiChannelBurst};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BurstProfileAlignment {
    #[default]
    Onset,
    Peak,
}

#[derive(Debug, Clone)]
pub struct BurstProfileOptions {
    pub alignment: BurstProfileAlignment,
    pub pre_bins: usize,
    pub post_bins: usize,
}

impl Default for BurstProfileOptions {
    fn default() -> Self {
        Self { alignment: BurstProfileAlignment::Onset, pre_bins: 20, post_bins: 40 }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BurstProfilePoint {
    pub lag_ms: f64,
    pub mean_rate_hz: f64,
    pub n_bursts: usize,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BurstProfile {
    pub points: Vec<BurstProfilePoint>,
}

/// Average ASDR windows aligned to each multi-channel burst onset or peak.
pub fn multi_channel_burst_profile(
    asdr: &AsdrTrace,
    bursts: &[MultiChannelBurst],
    options: &BurstProfileOptions,
) -> BurstProfile {
    if asdr.points.is_empty() || bursts.is_empty() {
        return BurstProfile::default();
    }
    let bin_ms = if asdr.points.len() > 1 {
        (asdr.points[1].time_ms - asdr.points[0].time_ms).abs().max(1e-9)
    } else {
        50.0
    };
    let width = options.pre_bins + options.post_bins + 1;
    let mut sums = vec![0.0_f64; width];
    let mut counts = vec![0usize; width];

    for burst in bursts {
        let align_ms = match options.alignment {
            BurstProfileAlignment::Onset => burst.start_ms,
            BurstProfileAlignment::Peak => {
                // peak = max smoothed rate within burst window
                let start = (burst.start_ms / bin_ms) as usize;
                let end = ((burst.end_ms / bin_ms) as usize + 1).min(asdr.points.len());
                asdr.points[start..end]
                    .iter()
                    .max_by(|a, b| a.smoothed_hz.partial_cmp(&b.smoothed_hz).unwrap())
                    .map(|p| p.time_ms)
                    .unwrap_or(burst.start_ms)
            }
        };
        let center = (align_ms / bin_ms).round() as isize;
        for offset in -(options.pre_bins as isize)..=(options.post_bins as isize) {
            let idx = center + offset;
            if idx < 0 || idx as usize >= asdr.points.len() {
                continue;
            }
            let slot = (offset + options.pre_bins as isize) as usize;
            sums[slot] += asdr.points[idx as usize].smoothed_hz;
            counts[slot] += 1;
        }
    }

    let points = (0..width)
        .map(|i| {
            let lag = (i as isize - options.pre_bins as isize) as f64 * bin_ms;
            let n = counts[i];
            BurstProfilePoint {
                lag_ms: lag,
                mean_rate_hz: if n > 0 { sums[i] / n as f64 } else { 0.0 },
                n_bursts: n,
            }
        })
        .collect();
    BurstProfile { points }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analysis::burst::{AsdrPoint, AsdrTrace, MultiChannelBurst};

    #[test]
    fn averages_aligned_windows() {
        let asdr = AsdrTrace {
            points: (0..100)
                .map(|i| AsdrPoint {
                    time_ms: i as f64 * 50.0,
                    rate_hz: if (40..50).contains(&i) { 100.0 } else { 1.0 },
                    smoothed_hz: if (40..50).contains(&i) { 100.0 } else { 1.0 },
                    spike_count: if (40..50).contains(&i) { 5 } else { 0 },
                    active_channels: if (40..50).contains(&i) { 4 } else { 0 },
                })
                .collect(),
            threshold_hz: 10.0,
            lower_threshold: 5.0,
            method: crate::analysis::burst::MultiBurstMethod::RateThreshold,
            bursts: Vec::new(),
        };
        let bursts = vec![MultiChannelBurst {
            trace: 0,
            start_ms: 2000.0,
            end_ms: 2500.0,
            peak_rate_hz: 100.0,
            num_spikes: 50,
            peak_series: 100.0,
        }];
        let profile = multi_channel_burst_profile(&asdr, &bursts, &BurstProfileOptions::default());
        assert!(!profile.points.is_empty());
        assert!(profile.points.iter().any(|p| p.mean_rate_hz > 10.0));
    }
}