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
use std::path::{Path, PathBuf};

use crate::analysis::filter::FilterAlgorithm;
use crate::analysis::spike::{spike_autocorrelogram, ThresholdMethod};
use crate::analysis::waveform_avg::spike_heatmap;
#[cfg(feature = "histograms")]
use crate::analysis::{amplitude_histogram, isi_histogram, HistogramOptions};
use crate::analysis::{average_spike_waveforms, run_analysis, spike_posthoc, AnalysisOptions};
use crate::error::Result;
use crate::toolkit::cluster::{cluster_spikes, ClusterOptions};

use super::bundle::write_spike_detector_bundle;
use super::threshold::compute_threshold_table;
use super::types::{
    ChannelThresholdRow, Histogram, SpikeDetectorOptions, SpikeDetectorReport, SpikePolarity,
};

/// Run the full spike detector pipeline on a recording.
pub fn run_spike_detector(
    path: impl AsRef<Path>,
    options: &SpikeDetectorOptions,
    out_dir: Option<&Path>,
) -> Result<SpikeDetectorReport> {
    let path = path.as_ref();
    let thresholds = compute_threshold_table(path, options)?;
    let analysis_opts = analysis_options_from(options, &thresholds);
    let report = run_analysis(path, &analysis_opts)?;

    let posthoc = spike_posthoc(&report.spikes, options.raster_bin_ms);
    let mean_waveforms = average_spike_waveforms(&report.spikes, true);
    let duration_sec = report
        .header
        .real_trace_duration_ms
        .max(report.spikes.spikes.iter().map(|s| s.within_trace_time_ms).fold(0.0, f64::max))
        / 1000.0;
    let n_ch = report.header.num_channel_slots().max(1);
    let (grid_rows, grid_cols) = heatmap_grid(n_ch);
    let heatmap = spike_heatmap(&report.spikes, duration_sec.max(1e-9), grid_rows, grid_cols);
    let autocorr = spike_autocorrelogram(&report.spikes, &options.autocorr);

    #[cfg(feature = "histograms")]
    let (isi, amplitude) = {
        let hopts = HistogramOptions::default();
        (
            Some(isi_histogram(&report.spikes, &hopts)),
            Some(amplitude_histogram(&report.spikes, &hopts)),
        )
    };
    #[cfg(not(feature = "histograms"))]
    let (isi, amplitude): (Option<Histogram>, Option<Histogram>) = (None, None);

    let clusters = options.cluster_k.map(|k| {
        cluster_spikes(&report.spikes, &ClusterOptions { k, ..ClusterOptions::default() })
    });

    let mut outputs = Vec::new();
    if let Some(dir) = out_dir {
        outputs.extend(write_spike_detector_bundle(
            &report,
            &posthoc,
            &mean_waveforms,
            &heatmap,
            &autocorr,
            isi.as_ref(),
            amplitude.as_ref(),
            clusters.as_ref(),
            &thresholds,
            dir,
            options,
        )?);
    }

    Ok(SpikeDetectorReport {
        path: path.to_path_buf(),
        spike_count: report.spikes.len(),
        thresholds,
        posthoc,
        isi,
        amplitude,
        heatmap,
        mean_waveforms,
        autocorr,
        clusters,
        outputs,
    })
}

/// Build `AnalysisOptions` from Toolkit spike-detector settings.
pub fn analysis_options_from(
    options: &SpikeDetectorOptions,
    thresholds: &[ChannelThresholdRow],
) -> AnalysisOptions {
    let n = thresholds.len().max(64);
    let mut plus = vec![0.5_f64; n];
    let mut minus = vec![-0.5_f64; n];
    let mut enabled = Vec::new();
    for row in thresholds {
        if row.channel >= n {
            continue;
        }
        if row.enabled {
            enabled.push(row.channel);
        }
        plus[row.channel] = row.plus_mv.unwrap_or(0.5).abs();
        minus[row.channel] = -row.minus_mv.unwrap_or(0.5).abs();
    }

    let (detect_plus, detect_minus) = match options.polarity {
        SpikePolarity::Both => (true, true),
        // Minus-only: disable Greater-gate (`plusThreshold=null` / second arg).
        // Less-gate still uses the +T threshold (ReferenceAnalysis argument order).
        SpikePolarity::MinusOnly => (false, true),
        SpikePolarity::PlusOnly => (true, false),
    };

    AnalysisOptions {
        highpass_hz: options.highpass_hz,
        // Toolkit "None" LPF → wide Butterworth (same unwrap as run_analysis).
        lowpass_hz: options.lowpass_hz.or(Some(5000.0)),
        lowpass_kind: options.lowpass_kind,
        threshold_method: ThresholdMethod::Fixed,
        threshold_percent: options.threshold_percent,
        threshold_window_sec: 0.0,
        plus_thresholds_mv: Some(plus),
        minus_thresholds_mv: Some(minus),
        detect_plus,
        detect_minus,
        enabled_channels: if enabled.len() == n || enabled.is_empty() {
            None
        } else {
            Some(enabled)
        },
        channel_spike_limit_hz: options.channel_spike_limit_hz,
        pre_ms: options.pre_ms,
        post_ms: options.post_ms,
        max_blocks: options.max_blocks,
        retain_filtered: options.export.filtered_waveforms,
        reset_filter_each_block: true,
        filter_algorithm: FilterAlgorithm::SecondPole,
        // merge_traces=true → single-pass accumulation; false → per_trace.
        per_trace: !options.export.merge_traces,
        ..AnalysisOptions::reference()
    }
}

fn heatmap_grid(n_channels: usize) -> (usize, usize) {
    if n_channels <= 16 {
        (4, 4)
    } else if n_channels <= 64 {
        (8, 8)
    } else {
        (16, 24)
    }
}