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
//! Propagation PAID — pairwise activation interval delay (PAID preferences).

use serde::{Deserialize, Serialize};

use crate::analysis::{run_analysis, AnalysisOptions, SpikeTrain};
use crate::error::Result;
use std::path::Path;

#[derive(Debug, Clone)]
pub struct PaidOptions {
    pub analysis: AnalysisOptions,
    pub grid_cols: usize,
    pub grid_rows: usize,
    /// Smoothing window for first-spike times (ms); 0 = none.
    pub smoothing_ms: f64,
    /// Electrode pitch (µm) for velocity estimates.
    pub electrode_pitch_um: f64,
}

impl Default for PaidOptions {
    fn default() -> Self {
        Self {
            analysis: AnalysisOptions { max_blocks: Some(10), ..AnalysisOptions::default() },
            grid_cols: 8,
            grid_rows: 8,
            smoothing_ms: 20.0,
            electrode_pitch_um: 150.0,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaidCell {
    pub channel_a: usize,
    pub channel_b: usize,
    pub mean_interval_ms: f64,
    pub std_interval_ms: f64,
    pub n_pairs: usize,
    pub distance_um: f64,
    pub velocity_mm_per_s: Option<f64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaidReport {
    pub path: std::path::PathBuf,
    pub cells: Vec<PaidCell>,
}

pub fn analyze_paid(path: impl AsRef<Path>, options: &PaidOptions) -> Result<PaidReport> {
    let path = path.as_ref();
    let report = run_analysis(path, &options.analysis)?;
    Ok(paid_from_spikes(path, &report.spikes, options))
}

pub fn paid_from_spikes(
    path: impl AsRef<Path>,
    train: &SpikeTrain,
    options: &PaidOptions,
) -> PaidReport {
    let mut by_ch: std::collections::BTreeMap<usize, Vec<f64>> = std::collections::BTreeMap::new();
    for spike in &train.spikes {
        by_ch.entry(spike.channel).or_default().push(spike.within_trace_time_ms);
    }
    for times in by_ch.values_mut() {
        times.sort_by(|a, b| a.partial_cmp(b).unwrap());
        if options.smoothing_ms > 0.0 {
            smooth_times(times, options.smoothing_ms);
        }
    }
    let channels: Vec<usize> = by_ch.keys().copied().collect();
    let mut cells = Vec::new();
    for (i, &a) in channels.iter().enumerate() {
        for &b in &channels[i + 1..] {
            let Some(cell) = pairwise_interval(a, b, &by_ch, options) else {
                continue;
            };
            cells.push(cell);
        }
    }
    PaidReport { path: path.as_ref().to_path_buf(), cells }
}

fn smooth_times(times: &mut [f64], window_ms: f64) {
    if times.len() < 3 || window_ms <= 0.0 {
        return;
    }
    let raw = times.to_vec();
    for (i, t) in times.iter_mut().enumerate() {
        let lo = raw[i] - window_ms;
        let hi = raw[i] + window_ms;
        let subset: Vec<f64> = raw.iter().copied().filter(|v| *v >= lo && *v <= hi).collect();
        if !subset.is_empty() {
            *t = subset.iter().sum::<f64>() / subset.len() as f64;
        }
    }
}

fn pairwise_interval(
    a: usize,
    b: usize,
    by_ch: &std::collections::BTreeMap<usize, Vec<f64>>,
    options: &PaidOptions,
) -> Option<PaidCell> {
    let ta = by_ch.get(&a)?;
    let tb = by_ch.get(&b)?;
    if ta.is_empty() || tb.is_empty() {
        return None;
    }
    let mut diffs = Vec::new();
    for &t in ta {
        let nearest =
            tb.iter().min_by(|x, y| (*x - t).abs().partial_cmp(&(*y - t).abs()).unwrap())?;
        diffs.push(nearest - t);
    }
    let n = diffs.len();
    let mean = diffs.iter().sum::<f64>() / n as f64;
    let var = diffs.iter().map(|d| (d - mean).powi(2)).sum::<f64>() / n as f64;
    let (ra, ca) = grid_pos(a, options.grid_rows, options.grid_cols);
    let (rb, cb) = grid_pos(b, options.grid_rows, options.grid_cols);
    let dr = (ra as f64 - rb as f64).abs();
    let dc = (ca as f64 - cb as f64).abs();
    let dist = dr.hypot(dc) * options.electrode_pitch_um;
    let velocity =
        if mean.abs() > 1e-6 { Some(dist / 1000.0 / (mean.abs() / 1000.0)) } else { None };
    Some(PaidCell {
        channel_a: a,
        channel_b: b,
        mean_interval_ms: mean,
        std_interval_ms: var.sqrt(),
        n_pairs: n,
        distance_um: dist,
        velocity_mm_per_s: velocity,
    })
}

fn grid_pos(ch: usize, rows: usize, cols: usize) -> (usize, usize) {
    let cols = cols.max(1);
    let rows = rows.max(1);
    (ch / cols % rows, ch % cols)
}

pub fn write_paid_csv(report: &PaidReport, path: impl AsRef<Path>) -> Result<()> {
    use std::io::Write;
    let path = path.as_ref();
    let mut w = std::io::BufWriter::new(std::fs::File::create(path).map_err(|source| {
        crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source }
    })?);
    writeln!(
        w,
        "channel_a,channel_b,mean_interval_ms,std_interval_ms,n_pairs,distance_um,velocity_mm_per_s"
    )
    .ok();
    for c in &report.cells {
        writeln!(
            w,
            "{},{},{:.4},{:.4},{},{:.2},{}",
            c.channel_a + 1,
            c.channel_b + 1,
            c.mean_interval_ms,
            c.std_interval_ms,
            c.n_pairs,
            c.distance_um,
            c.velocity_mm_per_s.map(|v| format!("{v:.4}")).unwrap_or_default()
        )
        .ok();
    }
    Ok(())
}