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::spike::AutocorrReport;
use crate::analysis::waveform_avg::{AverageWaveform, SpikeHeatmap};
use crate::analysis::{AnalysisReport, SpikePostHocReport};
use crate::error::{Med64Error, Result};
#[cfg(not(feature = "hdf5"))]
use crate::export::write_spike_timestamps_hdf5;
use crate::export::{
    write_amplitude_rank_csv, write_autocorr_csv, write_average_waveforms_csv,
    write_spike_timestamps_csv, write_spike_timestamps_plus_waveforms_csv,
};
use crate::export_waveform::{write_filtered_waveforms, FilteredExportOptions};
use crate::recording::Recording;
use crate::toolkit::cluster::ClusterReport;

use super::panel::{
    write_spike_detector_html, write_spike_detector_panel_html,
    write_spike_detector_result_table_html,
};
use super::threshold::{write_settings_table_csv, write_threshold_properties};
use super::types::{
    ChannelThresholdRow, Histogram, SpikeDetectorExportMatrix, SpikeDetectorOptions,
    SpikeDetectorPanelPrefs,
};

/// Capture-image style package: settings CSV + 64ch / 16ch rate PNG + mean-wave CSV.
pub fn write_spike_detector_create_image(
    _report: &AnalysisReport,
    thresholds: &[ChannelThresholdRow],
    heatmap: &SpikeHeatmap,
    mean_waveforms: &[AverageWaveform],
    out_dir: impl AsRef<Path>,
) -> Result<Vec<PathBuf>> {
    let dir = out_dir.as_ref();
    std::fs::create_dir_all(dir)
        .map_err(|source| Med64Error::WriteIo { path: dir.to_path_buf(), source })?;
    let mut outs = Vec::new();
    let settings = dir.join("settings_table.csv");
    write_settings_table_csv(thresholds, &settings)?;
    outs.push(settings);
    let png64 = dir.join("channels_64.png");
    let values: Vec<f64> = heatmap.cells.iter().map(|c| c.mean_rate_hz).collect();
    let cols = ((heatmap.cells.len() as f64).sqrt().ceil() as u32).max(1);
    let rows = (values.len() as u32).div_ceil(cols).max(1);
    crate::png::write_heatmap_png(&png64, cols, rows, &values, 12)?;
    outs.push(png64);
    if values.len() >= 16 {
        let slice: Vec<f64> = values.iter().copied().take(16).collect();
        let png16 = dir.join("channels_16.png");
        crate::png::write_heatmap_png(&png16, 4, 4, &slice, 24)?;
        outs.push(png16);
    }
    if !mean_waveforms.is_empty() {
        let avg = dir.join("AverageSpikeWaveform.csv");
        write_average_waveforms_csv(mean_waveforms, &avg)?;
        outs.push(avg);
    }
    Ok(outs)
}

/// Write the spike detector export package + HTML dashboard.
#[allow(clippy::too_many_arguments)]
pub fn write_spike_detector_bundle(
    report: &AnalysisReport,
    posthoc: &SpikePostHocReport,
    mean_waveforms: &[AverageWaveform],
    heatmap: &SpikeHeatmap,
    autocorr: &AutocorrReport,
    isi: Option<&Histogram>,
    amplitude: Option<&Histogram>,
    clusters: Option<&ClusterReport>,
    thresholds: &[ChannelThresholdRow],
    dir: impl AsRef<Path>,
    options: &SpikeDetectorOptions,
) -> Result<Vec<PathBuf>> {
    let dir = dir.as_ref();
    std::fs::create_dir_all(dir)
        .map_err(|source| Med64Error::WriteIo { path: dir.to_path_buf(), source })?;
    let stem = report
        .path
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "spikes".into());
    let mut outs = Vec::new();

    write_threshold_properties(thresholds, dir.join("thresholds.properties"))?;
    outs.push(dir.join("thresholds.properties"));
    let settings_csv = dir.join("settings_table.csv");
    write_settings_table_csv(thresholds, &settings_csv)?;
    outs.push(settings_csv);

    if options.export.timestamps_only {
        let p = dir.join(format!("{stem}_SpikeTimeStamp.csv"));
        write_spike_timestamps_csv(report, &p)?;
        outs.push(p);
    }
    if options.export.timestamps_plus_spikes {
        let p = dir.join(format!("{stem}_SpikeTimeStampPlusSpikes.csv"));
        write_spike_timestamps_plus_waveforms_csv(report, &p)?;
        outs.push(p);
        let p2 = dir.join(format!("{stem}_AverageSpikeWaveform.csv"));
        write_average_waveforms_csv(mean_waveforms, &p2)?;
        outs.push(p2);
    }
    if options.export.amplitude_rank {
        let p = dir.join(format!("{stem}_amplitude_rank.csv"));
        write_amplitude_rank_csv(report, &p)?;
        outs.push(p);
    }
    if options.export.filtered_waveforms && !report.filtered_by_channel.is_empty() {
        let filt = write_filtered_waveforms(
            report,
            dir,
            &stem,
            &FilteredExportOptions { write_modat: true, ..FilteredExportOptions::default() },
        )?;
        outs.extend(filt.paths);
    }
    if options.export.raw_waveforms {
        let raw_path = dir.join(format!("{stem}_raw_i16.bin"));
        write_raw_i16_export(&report.path, options.max_blocks, &raw_path)?;
        outs.push(raw_path);
    }
    if options.export.hdf5 {
        let p = dir.join(format!("{stem}_spikes.h5"));
        #[cfg(feature = "hdf5")]
        {
            use crate::export::{write_spike_hdf5, SpikeHdf5Options};
            write_spike_hdf5(
                report,
                &p,
                &SpikeHdf5Options {
                    include_raw: options.export.raw_waveforms,
                    include_filtered: options.export.filtered_waveforms,
                    merge_traces: options.export.merge_traces,
                    ..SpikeHdf5Options::default()
                },
            )?;
        }
        #[cfg(not(feature = "hdf5"))]
        {
            write_spike_timestamps_hdf5(report, &p)?;
        }
        outs.push(p);
    }
    // filterexport / rawdataexport named aliases.
    if options.export.filtered_waveforms && !report.filtered_by_channel.is_empty() {
        let filt_csv = dir.join("filterexport.csv");
        crate::export::write_filtered_raw_csv(report, &filt_csv)?;
        outs.push(filt_csv);
    }
    if options.export.raw_waveforms {
        let raw_csv = dir.join("rawdataexport.csv");
        // Best-effort: reuse filtered CSV shape when raw map absent.
        if !report.filtered_by_channel.is_empty() {
            crate::export::write_filtered_raw_csv(report, &raw_csv)?;
            outs.push(raw_csv);
        }
        let raw_dat = dir.join("rawdataexport.dat");
        write_raw_i16_export(&report.path, options.max_blocks, &raw_dat)?;
        outs.push(raw_dat);
    }
    if options.export.analysis_csvs {
        crate::analysis::write_scatter_csv(&posthoc.scatter, dir.join("scatter.csv"))?;
        outs.push(dir.join("scatter.csv"));
        crate::analysis::write_raster_histogram_csv(
            &posthoc.raster_histogram,
            dir.join("raster_hist.csv"),
        )?;
        outs.push(dir.join("raster_hist.csv"));
        write_autocorr_csv(autocorr, dir.join("autocorrelogram.csv"))?;
        outs.push(dir.join("autocorrelogram.csv"));
        if let Some(h) = isi {
            write_hist_csv(h, dir.join("isi_histogram.csv"), "isi_ms")?;
            outs.push(dir.join("isi_histogram.csv"));
        }
        if let Some(h) = amplitude {
            write_hist_csv(h, dir.join("amplitude_histogram.csv"), "peak_mv")?;
            outs.push(dir.join("amplitude_histogram.csv"));
        }
        if let Some(c) = clusters {
            write_cluster_csv(c, dir.join("clusters.csv"))?;
            outs.push(dir.join("clusters.csv"));
        }
        write_heatmap_csv(heatmap, dir.join("heatmap.csv"))?;
        outs.push(dir.join("heatmap.csv"));
    }
    // ExportSettingController parity
    {
        let settings = dir.join("export_settings.json");
        let matrix = SpikeDetectorExportMatrix::from_options(&options.export);
        std::fs::write(
            &settings,
            serde_json::to_string_pretty(&matrix).unwrap_or_else(|_| "{}".into()),
        )
        .map_err(|source| Med64Error::WriteIo { path: settings.clone(), source })?;
        outs.push(settings);
    }
    if options.export.html_dashboard {
        let html = dir.join("spike_detector.html");
        write_spike_detector_html(
            report,
            posthoc,
            mean_waveforms,
            heatmap,
            autocorr,
            isi,
            amplitude,
            clusters,
            thresholds,
            &html,
        )?;
        outs.push(html);
        let prefer = dir.join("spike_detector_prefer.html");
        write_spike_detector_panel_html(&SpikeDetectorPanelPrefs::default(), &prefer)?;
        outs.push(prefer);
        let result_html = dir.join("spike_detector_result_table.html");
        write_spike_detector_result_table_html(report, thresholds, &result_html)?;
        outs.push(result_html);
    }
    Ok(outs)
}

fn write_hist_csv(h: &Histogram, path: impl AsRef<Path>, edge_name: &str) -> Result<()> {
    let path = path.as_ref();
    let mut w = format!("{edge_name},count\n");
    for (i, &c) in h.counts.iter().enumerate() {
        let edge = h.edges.get(i).copied().unwrap_or(0.0);
        w.push_str(&format!("{edge:.6},{c}\n"));
    }
    std::fs::write(path, w)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

fn write_cluster_csv(c: &ClusterReport, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let mut w = String::from("spike_index,channel,cluster,peak_mv,duration_ms\n");
    for a in &c.assignments {
        w.push_str(&format!(
            "{},{},{},{:.6},{:.6}\n",
            a.spike_index,
            a.channel + 1,
            a.cluster,
            a.peak_mv,
            a.duration_ms
        ));
    }
    std::fs::write(path, w)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

fn write_heatmap_csv(h: &SpikeHeatmap, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let mut w = String::from("channel,row,col,count,rate_hz\n");
    for c in &h.cells {
        w.push_str(&format!(
            "{},{},{},{},{:.6}\n",
            c.channel + 1,
            c.row,
            c.col,
            c.spike_count,
            c.mean_rate_hz
        ));
    }
    std::fs::write(path, w)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// Write interleaved little-endian i16 samples from recording blocks (raw, unfiltered).
fn write_raw_i16_export(
    path: &Path,
    max_blocks: Option<usize>,
    out: impl AsRef<Path>,
) -> Result<()> {
    let out = out.as_ref();
    let mut rec = Recording::open(path)?;
    let mut bytes = Vec::new();
    for (bi, block) in rec.blocks().enumerate() {
        if max_blocks.is_some_and(|m| bi >= m) {
            break;
        }
        let block = block?;
        for row in &block.samples {
            for &s in row {
                bytes.extend_from_slice(&s.to_le_bytes());
            }
        }
    }
    std::fs::write(out, bytes)
        .map_err(|source| Med64Error::WriteIo { path: out.to_path_buf(), source })
}