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
//! Peri-event time histograms (PETH / PSTH).

use serde::{Deserialize, Serialize};

use crate::analysis::spike::SpikeTrain;
use crate::error::Result;
use crate::recording::Recording;
use std::path::Path;

#[derive(Debug, Clone)]
pub struct PethOptions {
    pub pre_ms: f64,
    pub post_ms: f64,
    pub bin_ms: f64,
    /// Optional explicit event times (ms). If empty, use stim markers from blocks.
    pub event_times_ms: Vec<f64>,
    pub max_blocks: Option<usize>,
}

impl Default for PethOptions {
    fn default() -> Self {
        Self {
            pre_ms: 50.0,
            post_ms: 200.0,
            bin_ms: 5.0,
            event_times_ms: Vec::new(),
            max_blocks: Some(50),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PethBin {
    pub lag_ms: f64,
    pub count: u64,
    pub rate_hz: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PethReport {
    pub events: usize,
    pub bins: Vec<PethBin>,
}

/// Build a peri-event histogram from spikes and event times.
pub fn peri_event_histogram(
    train: &SpikeTrain,
    events_ms: &[f64],
    options: &PethOptions,
) -> PethReport {
    let n_bins = ((options.pre_ms + options.post_ms) / options.bin_ms).ceil() as usize;
    let mut counts = vec![0u64; n_bins.max(1)];
    for &event in events_ms {
        for spike in &train.spikes {
            let lag = spike.within_session_time_ms - event;
            if lag < -options.pre_ms || lag > options.post_ms {
                continue;
            }
            let idx = ((lag + options.pre_ms) / options.bin_ms).floor() as isize;
            if idx >= 0 && (idx as usize) < counts.len() {
                counts[idx as usize] += 1;
            }
        }
    }
    let n_events = events_ms.len().max(1) as f64;
    let bins = counts
        .iter()
        .enumerate()
        .map(|(i, &count)| {
            let lag = -options.pre_ms + i as f64 * options.bin_ms;
            PethBin {
                lag_ms: lag,
                count,
                rate_hz: count as f64 / (n_events * options.bin_ms / 1000.0),
            }
        })
        .collect();
    PethReport { events: events_ms.len(), bins }
}

/// Extract stimulation event times from block markers (loop/step changes).
pub fn stim_events_from_recording(
    path: impl AsRef<Path>,
    max_blocks: Option<usize>,
) -> Result<Vec<f64>> {
    let path = path.as_ref();
    let mut rec = Recording::open(path)?;
    let header = rec.header().clone();
    let interval = header.interval_ms();
    let mut events = Vec::new();
    let mut last_key = None;
    let mut session_ms = 0.0;
    for (i, block) in rec.blocks().enumerate() {
        if max_blocks.is_some_and(|m| i >= m) {
            break;
        }
        let block = block?;
        let key = (block.stimulation_loop_number, block.stimulation_step_number);
        if last_key.map(|k| k != key).unwrap_or(true)
            && (block.stimulation_loop_number > 0 || block.stimulation_step_number > 0)
        {
            events.push(session_ms + block.block_offset_ms + block.trace_offset_ms);
        }
        last_key = Some(key);
        session_ms += block.samples.len() as f64 * interval;
    }
    // Fall back: treat each first-block-of-trace as an event.
    if events.is_empty() {
        let mut rec = Recording::open(path)?;
        let mut session_ms = 0.0;
        for (i, block) in rec.blocks().enumerate() {
            if max_blocks.is_some_and(|m| i >= m) {
                break;
            }
            let block = block?;
            if block.first_block == 1 {
                events.push(session_ms + block.block_offset_ms);
            }
            session_ms += block.samples.len() as f64 * interval;
        }
    }
    Ok(events)
}

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

    #[test]
    fn peaks_near_zero_lag() {
        let mut train = SpikeTrain::default();
        for t in [100.0, 102.0, 200.0, 201.0] {
            train.push(Spike {
                within_session_time_ms: t,
                within_trace_time_ms: t,
                ..Default::default()
            });
        }
        let report = peri_event_histogram(
            &train,
            &[100.0, 200.0],
            &PethOptions { pre_ms: 20.0, post_ms: 20.0, bin_ms: 5.0, ..Default::default() },
        );
        let zero = report.bins.iter().find(|b| (b.lag_ms).abs() < 5.0).unwrap();
        assert!(zero.count >= 2);
    }
}