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
//! Spatial spike-rate heatmaps and batch summaries.

use std::path::{Path, PathBuf};

use serde::Serialize;

use crate::analysis::{run_analysis, AnalysisOptions, AnalysisReport};
use crate::error::Result;
use crate::toolkit::poincare::{poincare_isi, PoincareReport};
use crate::toolkit::propagation::{propagation_delay_map, PropagationOptions, PropagationReport};

#[cfg(feature = "layouts")]
use crate::layout::{channel_label, detect_layout};

/// Spatial spike-rate map options.
#[derive(Debug, Clone)]
pub struct RateMapOptions {
    pub max_blocks: Option<usize>,
    pub grid_cols: usize,
    pub grid_rows: usize,
    pub analysis: AnalysisOptions,
    /// When true, map 384-ch plate channels into 24 wells × 16 electrodes labels.
    pub well_plate_24: bool,
}

impl Default for RateMapOptions {
    fn default() -> Self {
        Self {
            max_blocks: None,
            grid_cols: 8,
            grid_rows: 8,
            analysis: AnalysisOptions::default(),
            well_plate_24: false,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct RateMapCell {
    pub channel: usize,
    pub label: String,
    pub row: usize,
    pub col: usize,
    pub well: Option<usize>,
    pub spike_count: usize,
    pub rate_hz: f64,
}

#[derive(Debug, Clone, Serialize)]
pub struct RateMapReport {
    pub path: PathBuf,
    pub duration_sec: f64,
    pub cells: Vec<RateMapCell>,
    pub max_rate_hz: f64,
}

#[derive(Debug, Clone, Serialize)]
pub struct StvMetrics {
    pub channel: usize,
    pub mean_isi_ms: f64,
    pub sd_isi_ms: f64,
    /// Short-term variability: SD of successive ISI differences / √2.
    pub stv_ms: f64,
    pub mean_velocity_mm_per_s: Option<f64>,
}

#[derive(Debug, Clone, Serialize)]
pub struct RateMapFileSummary {
    pub path: PathBuf,
    pub spike_count: usize,
    pub max_rate_hz: f64,
    pub mean_stv_ms: f64,
    pub reference_delay_span_ms: f64,
}

#[derive(Debug, Clone, Serialize)]
pub struct RateMapBatchReport {
    pub files: Vec<RateMapFileSummary>,
    pub maps: Vec<RateMapReport>,
    pub stv: Vec<StvMetrics>,
    pub propagation: Vec<PropagationReport>,
    pub poincare: Vec<PoincareReport>,
}

/// Compute per-electrode spike rates and grid positions.
pub fn compute_rate_map(path: impl AsRef<Path>, options: &RateMapOptions) -> Result<RateMapReport> {
    let path = path.as_ref();
    let mut analysis_opts = options.analysis.clone();
    analysis_opts.max_blocks = options.max_blocks;
    let report = run_analysis(path, &analysis_opts)?;
    build_rate_map_report(path, &report, options)
}

pub fn build_rate_map_report(
    path: &Path,
    report: &AnalysisReport,
    options: &RateMapOptions,
) -> Result<RateMapReport> {
    let duration_sec = report.header.real_trace_duration_ms / 1000.0;
    #[cfg(feature = "layouts")]
    let layout = detect_layout(&report.header, path);

    let mut counts: std::collections::BTreeMap<usize, usize> = std::collections::BTreeMap::new();
    for spike in &report.spikes.spikes {
        *counts.entry(spike.channel).or_default() += 1;
    }

    let mut cells = Vec::new();
    let mut max_rate = 0.0_f64;
    for (channel, count) in counts {
        let rate = if duration_sec > 0.0 { count as f64 / duration_sec } else { 0.0 };
        max_rate = max_rate.max(rate);
        let (row, col) = grid_position(channel, options.grid_rows, options.grid_cols);
        let well = if options.well_plate_24 { Some(channel / 16) } else { None };
        #[cfg(feature = "layouts")]
        let label = if options.well_plate_24 {
            let w = channel / 16 + 1;
            let e = channel % 16 + 1;
            format!("W{w:02}E{e}")
        } else {
            channel_label(layout, channel)
        };
        #[cfg(not(feature = "layouts"))]
        let label = format!("Ch{}", channel + 1);
        cells.push(RateMapCell {
            channel,
            label,
            row,
            col,
            well,
            spike_count: count,
            rate_hz: rate,
        });
    }

    Ok(RateMapReport { path: path.to_path_buf(), duration_sec, cells, max_rate_hz: max_rate })
}

/// ISI short-term variability (+ optional mean conduction velocity from propagation).
pub fn compute_stv_table(
    report: &AnalysisReport,
    propagation: Option<&PropagationReport>,
) -> Vec<StvMetrics> {
    let mut out = Vec::new();
    for (channel, spikes) in report.spikes.by_channel() {
        let isis: Vec<f64> = spikes
            .windows(2)
            .map(|w| w[1].within_trace_time_ms - w[0].within_trace_time_ms)
            .filter(|d| *d > 0.0)
            .collect();
        if isis.is_empty() {
            continue;
        }
        let mean = isis.iter().sum::<f64>() / isis.len() as f64;
        let var = isis.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / isis.len() as f64;
        let sd = var.sqrt();
        let diffs: Vec<f64> = isis.windows(2).map(|w| w[1] - w[0]).collect();
        let stv = if diffs.is_empty() {
            0.0
        } else {
            let m = diffs.iter().sum::<f64>() / diffs.len() as f64;
            let v = diffs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / diffs.len() as f64;
            (v / 2.0).sqrt()
        };
        let mean_velocity = propagation.and_then(|p| {
            p.cells.iter().find(|c| c.channel == channel).and_then(|c| c.velocity_mm_per_s)
        });
        out.push(StvMetrics {
            channel,
            mean_isi_ms: mean,
            sd_isi_ms: sd,
            stv_ms: stv,
            mean_velocity_mm_per_s: mean_velocity,
        });
    }
    out
}

/// Multi-file spike-rate batch: rate maps + STV + propagation + Poincaré per file.
pub fn compute_rate_map_batch(
    paths: &[impl AsRef<Path>],
    options: &RateMapOptions,
) -> Result<RateMapBatchReport> {
    let mut files = Vec::new();
    let mut maps = Vec::new();
    let mut stv_all = Vec::new();
    let mut propagation = Vec::new();
    let mut poincare = Vec::new();

    for path in paths {
        let path = path.as_ref();
        let mut analysis_opts = options.analysis.clone();
        analysis_opts.max_blocks = options.max_blocks;
        let analysis = run_analysis(path, &analysis_opts)?;
        let map = build_rate_map_report(path, &analysis, options)?;
        let prop = propagation_delay_map(
            path,
            &PropagationOptions {
                analysis: analysis_opts.clone(),
                ..PropagationOptions::default()
            },
        )?;
        let stv = compute_stv_table(&analysis, Some(&prop));
        let mean_stv = if stv.is_empty() {
            0.0
        } else {
            stv.iter().map(|s| s.stv_ms).sum::<f64>() / stv.len() as f64
        };
        let delay_span = prop
            .cells
            .iter()
            .filter_map(|c| c.delay_ms)
            .fold(None, |acc: Option<(f64, f64)>, d| match acc {
                None => Some((d, d)),
                Some((lo, hi)) => Some((lo.min(d), hi.max(d))),
            })
            .map(|(lo, hi)| hi - lo)
            .unwrap_or(0.0);

        files.push(RateMapFileSummary {
            path: path.to_path_buf(),
            spike_count: analysis.spikes.len(),
            max_rate_hz: map.max_rate_hz,
            mean_stv_ms: mean_stv,
            reference_delay_span_ms: delay_span,
        });
        maps.push(map);
        stv_all.extend(stv);
        poincare.push(poincare_isi(&analysis.spikes));
        propagation.push(prop);
    }

    Ok(RateMapBatchReport { files, maps, stv: stv_all, propagation, poincare })
}

fn grid_position(channel: usize, rows: usize, cols: usize) -> (usize, usize) {
    let idx = channel % (rows * cols);
    (idx / cols, idx % cols)
}

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

    #[test]
    fn rate_map_sample_data6_subset() {
        let report = compute_rate_map(
            crate::fixture_paths::sample_data6_cap(),
            &RateMapOptions { max_blocks: Some(3), ..Default::default() },
        )
        .unwrap();
        assert!(!report.cells.is_empty());
    }

    #[test]
    fn batch_two_files() {
        let paths =
            [crate::fixture_paths::sample_data1(), crate::fixture_paths::sample_data6_cap()];
        let batch = compute_rate_map_batch(
            &paths,
            &RateMapOptions { max_blocks: Some(2), ..Default::default() },
        )
        .unwrap();
        assert_eq!(batch.files.len(), 2);
        assert_eq!(batch.maps.len(), 2);
    }

    #[test]
    fn well_package_writes_files() {
        let dir = std::env::temp_dir().join("med64_rate_map_well_pkg_test");
        let _ = std::fs::remove_dir_all(&dir);
        let mut analysis_opts = AnalysisOptions::reference();
        analysis_opts.max_blocks = Some(2);
        analysis_opts.retain_filtered = true;
        let analysis = run_analysis(crate::fixture_paths::sample_data1(), &analysis_opts).unwrap();
        let rate_map = build_rate_map_report(
            &crate::fixture_paths::sample_data1(),
            &analysis,
            &RateMapOptions { max_blocks: Some(2), well_plate_24: true, ..Default::default() },
        )
        .unwrap();
        let outs = write_rate_map_well_package(&rate_map, Some(&analysis), &dir).unwrap();
        assert!(outs.iter().any(|p| p.ends_with("wells.html")));
        assert!(outs.iter().any(|p| p.ends_with("rate_summary.csv")));
        assert!(dir.join("wells.html").is_file());
    }
}