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::burst::SingleChannelBurst;

#[derive(Debug, Clone)]
pub struct CorrelationOptions {
    pub bin_ms: f64,
    pub max_distance_ms: f64,
    pub synchrony_ms: f64,
}

impl Default for CorrelationOptions {
    fn default() -> Self {
        Self { bin_ms: 5.0, max_distance_ms: 500.0, synchrony_ms: 20.0 }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BurstOnsetCorrelogram {
    pub lag_ms: Vec<f64>,
    pub counts: Vec<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelSynchrony {
    pub channel_a: usize,
    pub channel_b: usize,
    pub synchrony_index: f64,
    pub coincident_bursts: usize,
    /// Burst count on channel A (Synchrony Index `total` column).
    pub bursts_a: usize,
}

fn onsets(bursts: &[SingleChannelBurst], channel: usize) -> Vec<f64> {
    bursts.iter().filter(|b| b.channel == channel).map(|b| b.start_ms).collect()
}

/// Burst-onset time cross-correlogram (BOTCC) across all channel pairs, summed.
pub fn burst_onset_correlogram(
    bursts: &[SingleChannelBurst],
    options: &CorrelationOptions,
) -> BurstOnsetCorrelogram {
    let n_bins = ((options.max_distance_ms / options.bin_ms).ceil() as usize * 2 + 1).max(1);
    let center = n_bins / 2;
    let mut counts = vec![0u32; n_bins];

    let mut channels: Vec<usize> = bursts.iter().map(|b| b.channel).collect();
    channels.sort_unstable();
    channels.dedup();

    for (i, &ca) in channels.iter().enumerate() {
        let a = onsets(bursts, ca);
        for &cb in channels.iter().skip(i) {
            let b = if ca == cb { a.clone() } else { onsets(bursts, cb) };
            for &ta in &a {
                for &tb in &b {
                    if ca == cb && (tb - ta).abs() < 1e-9 {
                        continue;
                    }
                    let lag = tb - ta;
                    if lag.abs() > options.max_distance_ms {
                        continue;
                    }
                    let bin = center as i64 + (lag / options.bin_ms).round() as i64;
                    if bin >= 0 && (bin as usize) < n_bins {
                        counts[bin as usize] += 1;
                    }
                }
            }
        }
    }

    let lag_ms = (0..n_bins).map(|i| (i as i64 - center as i64) as f64 * options.bin_ms).collect();
    BurstOnsetCorrelogram { lag_ms, counts }
}

/// Pairwise synchrony: fraction of bursts on A with an onset on B within `synchrony_ms`.
pub fn synchrony_index(
    bursts: &[SingleChannelBurst],
    options: &CorrelationOptions,
) -> Vec<ChannelSynchrony> {
    let mut channels: Vec<usize> = bursts.iter().map(|b| b.channel).collect();
    channels.sort_unstable();
    channels.dedup();

    let mut out = Vec::new();
    for (i, &ca) in channels.iter().enumerate() {
        let a = onsets(bursts, ca);
        if a.is_empty() {
            continue;
        }
        for &cb in channels.iter().skip(i + 1) {
            let b = onsets(bursts, cb);
            if b.is_empty() {
                continue;
            }
            let mut coincident = 0usize;
            for &ta in &a {
                if b.iter().any(|&tb| (tb - ta).abs() <= options.synchrony_ms) {
                    coincident += 1;
                }
            }
            out.push(ChannelSynchrony {
                channel_a: ca,
                channel_b: cb,
                synchrony_index: coincident as f64 / a.len() as f64,
                coincident_bursts: coincident,
                bursts_a: a.len(),
            });
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analysis::burst::SingleChannelBurst;

    #[test]
    fn correlogram_peaks_near_zero_for_aligned_bursts() {
        let bursts = vec![
            SingleChannelBurst {
                channel: 0,
                trace: 0,
                start_ms: 100.0,
                end_ms: 200.0,
                num_spikes: 3,
                interburst_interval_ms: 0.0,
                duration_ms: 100.0,
            },
            SingleChannelBurst {
                channel: 1,
                trace: 0,
                start_ms: 105.0,
                end_ms: 205.0,
                num_spikes: 3,
                interburst_interval_ms: 0.0,
                duration_ms: 100.0,
            },
        ];
        let cg = burst_onset_correlogram(&bursts, &CorrelationOptions::default());
        assert!(cg.counts.iter().any(|&c| c > 0));
        let syn = synchrony_index(&bursts, &CorrelationOptions::default());
        assert_eq!(syn.len(), 1);
        assert!(syn[0].synchrony_index > 0.0);
    }
}