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
//! Import burst-analysis spike timestamp CSV for re-analysis.

use std::path::Path;

use crate::analysis::spike::{Spike, SpikeDirection, SpikeTrain};
use crate::error::{Med64Error, Result};
use crate::header::{HeaderBuilder, Med64Header};

/// Parsed spike CSV plus a synthetic header for downstream burst analysis.
#[derive(Debug, Clone)]
pub struct ImportedSpikes {
    pub header: Med64Header,
    pub spikes: SpikeTrain,
    pub source: std::path::PathBuf,
}

/// Load spikes from a med64 spike-timestamp CSV.
///
/// Expected columns (header row, case-insensitive substrings):
/// `trace#`, `channel`, `within_trace_time_ms`, optional `within_session_time_ms`,
/// `peak_mv`, `duration_ms`.
pub fn import_spike_csv(path: impl AsRef<Path>) -> Result<ImportedSpikes> {
    let path = path.as_ref();
    let text = std::fs::read_to_string(path)
        .map_err(|source| Med64Error::Io { path: path.to_path_buf(), source })?;
    let mut lines = text.lines().filter(|l| !l.trim().is_empty());
    let header_line = lines
        .find(|l| {
            let lower = l.to_ascii_lowercase();
            lower.contains("channel") && (lower.contains("within_trace") || lower.contains("trace"))
        })
        .ok_or_else(|| Med64Error::InvalidHeader {
            path: path.to_path_buf(),
            message: "spike CSV missing table header row".into(),
        })?;
    let cols: Vec<&str> = header_line.split(',').map(|s| s.trim()).collect();
    let idx = |needle: &str| {
        cols.iter().position(|c| {
            c.eq_ignore_ascii_case(needle)
                || c.to_ascii_lowercase().contains(&needle.to_ascii_lowercase())
        })
    };
    let i_trace =
        idx("trace_num").or_else(|| idx("trace#")).or_else(|| idx("trace")).ok_or_else(|| {
            Med64Error::InvalidHeader {
                path: path.to_path_buf(),
                message: "missing trace column".into(),
            }
        })?;
    let i_channel = idx("channel").ok_or_else(|| Med64Error::InvalidHeader {
        path: path.to_path_buf(),
        message: "missing channel column".into(),
    })?;
    let i_within =
        idx("within_trace_time_ms").or_else(|| idx("within_trace_time")).ok_or_else(|| {
            Med64Error::InvalidHeader {
                path: path.to_path_buf(),
                message: "missing within_trace_time_ms column".into(),
            }
        })?;
    let i_session = idx("within_session_time_ms").or_else(|| idx("within_session_time"));
    let i_peak = idx("peak_mv").or_else(|| idx("peak")).or_else(|| idx("y1_mV"));
    let i_dur = idx("duration_ms").or_else(|| idx("duration"));
    let i_trace_dur = idx("Trace Duration");

    let mut train = SpikeTrain::default();
    let mut max_trace_ms = 0.0_f64;
    let mut max_channel = 0usize;
    let mut declared_trace_dur = None;

    for line in lines {
        if line.starts_with('#')
            || line.starts_with("File Format")
            || line.starts_with("Session Start")
        {
            continue;
        }
        let parts: Vec<&str> = line.split(',').map(|s| s.trim()).collect();
        if parts.len() <= i_within.max(i_channel).max(i_trace) {
            continue;
        }
        // Skip residual preamble / header echoes.
        if parts[i_channel].eq_ignore_ascii_case("channel") {
            continue;
        }
        let trace = parse_u32(parts[i_trace]).unwrap_or(1).saturating_sub(1);
        let channel = parse_usize(parts[i_channel]).unwrap_or(1).saturating_sub(1);
        let within = parse_f64(parts[i_within]).unwrap_or(0.0);
        let session =
            i_session.and_then(|i| parts.get(i).copied()).and_then(parse_f64).unwrap_or(within);
        let peak = i_peak.and_then(|i| parts.get(i).copied()).and_then(parse_f64).unwrap_or(1.0);
        let duration = i_dur.and_then(|i| parts.get(i).copied()).and_then(parse_f64).unwrap_or(0.5);
        if let Some(i) = i_trace_dur {
            if declared_trace_dur.is_none() {
                declared_trace_dur = parts.get(i).copied().and_then(parse_f64);
            }
        }
        max_trace_ms = max_trace_ms.max(within);
        max_channel = max_channel.max(channel);
        train.push(Spike {
            channel,
            trace,
            direction: if peak < 0.0 { SpikeDirection::Minus } else { SpikeDirection::Plus },
            peak_mv: peak,
            within_trace_time_ms: within,
            within_session_time_ms: session,
            duration_ms: duration,
            ..Default::default()
        });
    }

    let mut header = HeaderBuilder::new()
        .path(path)
        .trace_duration_ms(declared_trace_dur.unwrap_or(max_trace_ms.max(1.0)))
        .build();
    header.number_of_real_data_blocks = 1;
    header.real_trace_duration_ms = declared_trace_dur.unwrap_or(max_trace_ms.max(1.0));
    let _ = max_channel;

    Ok(ImportedSpikes { header, spikes: train, source: path.to_path_buf() })
}

fn parse_f64(s: &str) -> Option<f64> {
    s.parse().ok()
}

fn parse_u32(s: &str) -> Option<u32> {
    s.parse().ok()
}

fn parse_usize(s: &str) -> Option<usize> {
    s.parse().ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analysis::{format_spike_csv_row, spike_timestamp_csv_header};

    #[test]
    fn roundtrips_spike_csv() {
        let mut header = HeaderBuilder::new().build();
        header.real_trace_duration_ms = 1000.0;
        let csv = format!(
            "{}{}\n{}\n{}",
            crate::analysis::spike_timestamp_preamble(&header),
            spike_timestamp_csv_header(),
            format_spike_csv_row(
                &header,
                &Spike {
                    channel: 0,
                    trace: 0,
                    peak_mv: 1.2,
                    within_trace_time_ms: 10.0,
                    within_session_time_ms: 10.0,
                    duration_ms: 0.4,
                    ..Default::default()
                }
            ),
            format_spike_csv_row(
                &header,
                &Spike {
                    channel: 1,
                    trace: 0,
                    peak_mv: -0.8,
                    within_trace_time_ms: 25.0,
                    within_session_time_ms: 25.0,
                    duration_ms: 0.3,
                    ..Default::default()
                }
            )
        );
        let dir = std::env::temp_dir().join(format!("med64-import-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("spikes.csv");
        std::fs::write(&path, csv).unwrap();
        let imported = import_spike_csv(&path).unwrap();
        assert_eq!(imported.spikes.len(), 2);
        assert_eq!(imported.spikes.spikes[0].channel, 0);
        assert_eq!(imported.spikes.spikes[1].channel, 1);
        let _ = std::fs::remove_dir_all(dir);
    }
}