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
//! LTP / EPSP slope and pop-spike metrics (LTP).

use serde::{Deserialize, Serialize};

use crate::error::Result;
use crate::toolkit::spectrum::load_channel_mv;
use std::path::Path;

#[derive(Debug, Clone)]
pub struct LtpOptions {
    pub channel: usize,
    pub max_blocks: Option<usize>,
    /// Window after stim (or segment start) for EPSP slope fit (ms).
    pub slope_start_ms: f64,
    pub slope_end_ms: f64,
    /// Window for pop-spike peak search (ms).
    pub pop_start_ms: f64,
    pub pop_end_ms: f64,
    pub segment_ms: f64,
}

impl Default for LtpOptions {
    fn default() -> Self {
        Self {
            channel: 0,
            max_blocks: Some(40),
            slope_start_ms: 1.0,
            slope_end_ms: 3.0,
            pop_start_ms: 3.0,
            pop_end_ms: 8.0,
            segment_ms: 100.0,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LtpPoint {
    pub time_ms: f64,
    pub epsp_slope_mv_per_ms: f64,
    pub pop_spike_mv: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LtpReport {
    pub path: std::path::PathBuf,
    pub channel: usize,
    pub points: Vec<LtpPoint>,
}

/// Measure EPSP rising-slope and population-spike amplitude per segment.
pub fn analyze_ltp(path: impl AsRef<Path>, options: &LtpOptions) -> Result<LtpReport> {
    let path = path.as_ref();
    let (header, samples) = load_channel_mv(path, options.channel, options.max_blocks)?;
    let interval = header.interval_ms();
    let seg = (options.segment_ms / interval).round().max(1.0) as usize;
    let mut points = Vec::new();
    let mut start = 0usize;
    while start + seg <= samples.len() {
        let chunk = &samples[start..start + seg];
        let slope = linear_slope(chunk, interval, options.slope_start_ms, options.slope_end_ms);
        let pop = window_extremum(chunk, interval, options.pop_start_ms, options.pop_end_ms);
        points.push(LtpPoint {
            time_ms: start as f64 * interval,
            epsp_slope_mv_per_ms: slope,
            pop_spike_mv: pop,
        });
        start += seg;
    }
    Ok(LtpReport { path: path.to_path_buf(), channel: options.channel, points })
}

fn linear_slope(chunk: &[f64], interval_ms: f64, start_ms: f64, end_ms: f64) -> f64 {
    let i0 = (start_ms / interval_ms).round().max(0.0) as usize;
    let i1 = (end_ms / interval_ms).round().min((chunk.len().saturating_sub(1)) as f64) as usize;
    if i1 <= i0 {
        return 0.0;
    }
    let n = (i1 - i0 + 1) as f64;
    let mut sum_x = 0.0;
    let mut sum_y = 0.0;
    let mut sum_xy = 0.0;
    let mut sum_xx = 0.0;
    for i in i0..=i1 {
        let x = i as f64 * interval_ms;
        let y = chunk[i];
        sum_x += x;
        sum_y += y;
        sum_xy += x * y;
        sum_xx += x * x;
    }
    let denom = n * sum_xx - sum_x * sum_x;
    if denom.abs() < 1e-12 {
        0.0
    } else {
        (n * sum_xy - sum_x * sum_y) / denom
    }
}

fn window_extremum(chunk: &[f64], interval_ms: f64, start_ms: f64, end_ms: f64) -> f64 {
    let i0 = (start_ms / interval_ms).round().max(0.0) as usize;
    let i1 = (end_ms / interval_ms).round().min((chunk.len().saturating_sub(1)) as f64) as usize;
    if i1 <= i0 {
        return 0.0;
    }
    let slice = &chunk[i0..=i1];
    let min = slice.iter().cloned().fold(f64::INFINITY, f64::min);
    let max = slice.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
    if min.abs() > max.abs() {
        min
    } else {
        max
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn slope_of_ramp() {
        let chunk: Vec<f64> = (0..100).map(|i| i as f64 * 0.1).collect();
        let s = linear_slope(&chunk, 1.0, 10.0, 30.0);
        assert!((s - 0.1).abs() < 1e-6, "slope={s}");
    }
}