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
//! Example gallery: HTML, PNG, and CSV samples from `./data` recordings.

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

use crate::analysis::{run_analysis, AnalysisOptions};
use crate::error::Result;
use crate::export::write_chart_snapshots;
use crate::png::write_heatmap_png;
use crate::toolkit::spectrum::{power_spectrum, SpectrumOptions};
use crate::toolkit::voltage::{voltage_stft_colormap, write_voltage_stft_html, VoltageMapOptions};

pub fn default_sample_modat() -> PathBuf {
    crate::fixture_paths::sample_data6_cap()
}

pub fn sample_data1_modat() -> PathBuf {
    crate::fixture_paths::sample_data1()
}

struct GallerySection {
    title: &'static str,
    blurb: &'static str,
    links: Vec<(String, String)>,
    figures: Vec<(String, String)>,
}

impl GallerySection {
    fn push_link(&mut self, href: impl Into<String>, label: impl Into<String>) {
        self.links.push((href.into(), label.into()));
    }

    fn push_figure(&mut self, src: impl Into<String>, caption: impl Into<String>) {
        self.figures.push((src.into(), caption.into()));
    }
}

fn write_index_html(out_dir: &Path, sections: &[GallerySection]) -> Result<PathBuf> {
    let html = out_dir.join("index.html");
    let mut body = String::from(
        "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>med64 examples</title>\
         <style>\
         body{font-family:system-ui,sans-serif;margin:1.5rem auto;max-width:960px;background:#fafafa;color:#111;line-height:1.5}\
         h1{margin-bottom:.25rem}\
         .lead{color:#475569;margin-top:0}\
         section{background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:1rem 1.25rem;margin:1.25rem 0}\
         section h2{margin-top:0;font-size:1.15rem}\
         section p{color:#475569;font-size:.95rem}\
         ul{margin:.5rem 0;padding-left:1.25rem}\
         figure{margin:1rem 0 1.5rem}\
         img{max-width:100%;border:1px solid #ddd;background:#fff;border-radius:4px}\
         figcaption{font-size:.85rem;color:#64748b;margin-top:.35rem}\
         code{background:#f1f5f9;padding:.1rem .35rem;border-radius:4px;font-size:.9em}\
         </style></head><body>\
         <h1>med64 example outputs</h1>\
         <p class=\"lead\">Sample charts, CSV exports, and HTML reports generated from \
         <code>data/sample data1.modat</code> and <code>data/sample data6/…CAP.modat</code>. \
         Regenerate with <code>med64 examples</code> (see <a href=\"README.md\">README.md</a>).</p>",
    );
    for sec in sections {
        body.push_str(&format!("<section><h2>{}</h2><p>{}</p>", sec.title, sec.blurb));
        if !sec.links.is_empty() {
            body.push_str("<ul>");
            for (href, label) in &sec.links {
                body.push_str(&format!("<li><a href=\"{href}\">{label}</a></li>"));
            }
            body.push_str("</ul>");
        }
        for (src, cap) in &sec.figures {
            if out_dir.join(src).exists() {
                body.push_str(&format!(
                    "<figure><img src=\"{src}\" alt=\"{cap}\"><figcaption>{cap}</figcaption></figure>"
                ));
            }
        }
        body.push_str("</section>");
    }
    body.push_str("</body></html>");
    std::fs::write(&html, body)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: html.clone(), source })?;
    Ok(html)
}

/// Run short analyses on sample data and write an HTML gallery plus companion exports.
pub fn write_examples_gallery(out_dir: impl AsRef<Path>) -> Result<Vec<PathBuf>> {
    let out_dir = out_dir.as_ref();
    std::fs::create_dir_all(out_dir).map_err(|source| crate::error::Med64Error::WriteIo {
        path: out_dir.to_path_buf(),
        source,
    })?;

    let data6 = default_sample_modat();
    let data1 = sample_data1_modat();
    let mut written = Vec::new();
    let mut sections = Vec::new();

    let analysis_opts = AnalysisOptions {
        // CAP activity is nearly continuous; max-interval bursts need enough
        // quiet gaps to close. ~30 blocks (~15 s) yields a populated BOTCC.
        max_blocks: Some(30),
        retain_filtered: true,
        ..AnalysisOptions::reference()
    };
    let report = run_analysis(&data6, &analysis_opts)?;

    // --- Burst chart snapshots (PNG / SVG / EPS / BMP) ---
    let charts_dir = out_dir.join("charts");
    std::fs::create_dir_all(&charts_dir)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: charts_dir.clone(), source })?;
    written.extend(write_chart_snapshots(&report, &charts_dir, "data6")?);

    let mut charts = GallerySection {
        title: "Burst analysis charts",
        blurb: "CreateImage-style ASDR, BOTCC, raster, burst profile, frequency, and 64-channel viewer snapshots.",
        links: Vec::new(),
        figures: Vec::new(),
    };
    for (file, cap) in [
        ("charts/data6_asdr.png", "ASDR (smoothed array spike detection rate)"),
        ("charts/data6_botcc.png", "BOTCC burst-onset cross-correlogram"),
        ("charts/data6_raster.png", "Spike raster"),
        ("charts/data6_profile.png", "Burst profile (aligned mean ASDR)"),
        ("charts/data6_freq.png", "Mean spike frequency across channels"),
        ("charts/data6_ch64.png", "64-channel filtered waveforms"),
    ] {
        charts.push_figure(file, cap);
    }
    charts.push_link("charts/data6_asdr.svg", "ASDR SVG");
    charts.push_link("charts/data6_raster.svg", "Raster SVG");
    sections.push(charts);

    // --- Full analysis CSV bundle ---
    let analysis_dir = out_dir.join("analysis");
    written.extend(crate::export::write_analysis_bundle(&report, &analysis_dir, "data6")?);
    let mut analysis_sec = GallerySection {
        title: "Analysis CSV bundle",
        blurb: "Standard burst-analysis exports: spikes, bursts, ASDR, histograms, synchrony, result table.",
        links: vec![
            (
                "analysis/Spike Time Stamp.csv".into(),
                "Spike timestamps".into(),
            ),
            (
                "analysis/Single-Channel Burst.csv".into(),
                "Single-channel bursts".into(),
            ),
            (
                "analysis/Multi-Channel Burst.csv".into(),
                "Multi-channel bursts".into(),
            ),
            (
                "analysis/ASDR Chart.csv".into(),
                "ASDR time series".into(),
            ),
            (
                "analysis/ResultTable.csv".into(),
                "Result table metrics".into(),
            ),
            (
                "analysis/BOTCC.csv".into(),
                "Burst-onset correlogram".into(),
            ),
        ],
        figures: Vec::new(),
    };
    analysis_sec.push_link("analysis/data6_result_table.csv", "Result table (stemmed copy)");
    sections.push(analysis_sec);

    // --- Burst pipeline dashboard ---
    let pipeline_dir = out_dir.join("burst_pipeline");
    std::fs::create_dir_all(&pipeline_dir).map_err(|source| crate::error::Med64Error::WriteIo {
        path: pipeline_dir.clone(),
        source,
    })?;
    let pipeline_report = crate::burst_pipeline::run_burst_pipeline(
        &data6,
        &crate::burst_pipeline::BurstPipelineOptions { analysis: analysis_opts.clone() },
    )?;
    written.extend(crate::burst_pipeline::write_analysis_dashboard_html(
        &pipeline_report,
        &pipeline_dir,
        "data6",
    )?);
    sections.push(GallerySection {
        title: "Burst pipeline charts",
        blurb: "Interactive HTML charts from `run_burst_pipeline` (ASDR/bursts, frequency, ISI, amplitude, correlation).",
        links: vec![
            (
                "burst_pipeline/data6_burst_chart.html".into(),
                "Burst / ASDR chart".into(),
            ),
            (
                "burst_pipeline/data6_freq_chart.html".into(),
                "Spike frequency chart".into(),
            ),
            (
                "burst_pipeline/data6_isi_chart.html".into(),
                "ISI histogram chart".into(),
            ),
            (
                "burst_pipeline/data6_amplitude_chart.html".into(),
                "Amplitude histogram chart".into(),
            ),
            (
                "burst_pipeline/data6_correlation_chart.html".into(),
                "Burst correlation chart".into(),
            ),
        ],
        figures: Vec::new(),
    });

    // --- Rate map ---
    #[cfg(feature = "layouts")]
    {
        let rate_dir = out_dir.join("rate_map");
        std::fs::create_dir_all(&rate_dir).map_err(|source| crate::error::Med64Error::WriteIo {
            path: rate_dir.clone(),
            source,
        })?;
        let map = crate::rate_map::compute_rate_map(
            &data1,
            &crate::rate_map::RateMapOptions { max_blocks: Some(5), ..Default::default() },
        )?;
        let rate_html = rate_dir.join("rate_map.html");
        crate::rate_map::write_rate_map_html(&map, &rate_html)?;
        written.push(rate_html.clone());
        sections.push(GallerySection {
            title: "Spike-rate map",
            blurb: "Spatial heatmap HTML from `compute_rate_map` on sample data1 (5 blocks).",
            links: vec![("rate_map/rate_map.html".into(), "Rate map viewer".into())],
            figures: Vec::new(),
        });
    }

    // --- Power spectrum ---
    let spectrum_dir = out_dir.join("spectrum");
    std::fs::create_dir_all(&spectrum_dir).map_err(|source| crate::error::Med64Error::WriteIo {
        path: spectrum_dir.clone(),
        source,
    })?;
    let spec = power_spectrum(
        &data1,
        &SpectrumOptions { channel: 0, max_blocks: Some(10), ..SpectrumOptions::default() },
    )?;
    let spec_csv = spectrum_dir.join("channel0_spectrum.csv");
    {
        use std::io::Write;
        let mut w = std::fs::File::create(&spec_csv).map_err(|source| {
            crate::error::Med64Error::WriteIo { path: spec_csv.clone(), source }
        })?;
        writeln!(w, "frequency_hz,power").map_err(|source| crate::error::Med64Error::WriteIo {
            path: spec_csv.clone(),
            source,
        })?;
        for b in &spec.bins {
            writeln!(w, "{:.6},{:.12e}", b.frequency_hz, b.power).map_err(|source| {
                crate::error::Med64Error::WriteIo { path: spec_csv.clone(), source }
            })?;
        }
    }
    written.push(spec_csv.clone());
    sections.push(GallerySection {
        title: "Power spectrum (PSA)",
        blurb: "Welch spectrum CSV for channel 0 on sample data1.",
        links: vec![("spectrum/channel0_spectrum.csv".into(), "Channel 0 spectrum CSV".into())],
        figures: Vec::new(),
    });

    // --- Voltage STFT colormap ---
    let voltage_dir = out_dir.join("voltage");
    std::fs::create_dir_all(&voltage_dir).map_err(|source| crate::error::Med64Error::WriteIo {
        path: voltage_dir.clone(),
        source,
    })?;
    let stft = voltage_stft_colormap(
        &data1,
        &VoltageMapOptions {
            max_blocks: Some(2),
            stft_fft_size: 256,
            ..VoltageMapOptions::default()
        },
    )?;
    if let Some(frame) = stft.frames.first() {
        let values: Vec<f64> = frame.cells.iter().map(|c| c.value_mv).collect();
        let png = voltage_dir.join("data1_stft_frame0.png");
        write_heatmap_png(&png, 8, 8, &values, 24)?;
        written.push(png);
    }
    let stft_html = voltage_dir.join("data1_voltage_stft.html");
    write_voltage_stft_html(&stft, &stft_html)?;
    written.push(stft_html.clone());

    let mut voltage_sec = GallerySection {
        title: "Voltage STFT colormap",
        blurb: "Time–frequency voltage color map on sample data1.",
        links: vec![("voltage/data1_voltage_stft.html".into(), "Interactive STFT HTML".into())],
        figures: Vec::new(),
    };
    voltage_sec.push_figure("voltage/data1_stft_frame0.png", "First STFT frame (8×8 heatmap PNG)");
    sections.push(voltage_sec);

    // --- Spike detector package ---
    let sd_dir = out_dir.join("spike_detector");
    let sd = crate::toolkit::run_spike_detector(
        &data6,
        &crate::toolkit::SpikeDetectorOptions {
            max_blocks: Some(8),
            export: crate::toolkit::SpikeDetectorExportOptions {
                filtered_waveforms: false,
                hdf5: false,
                ..crate::toolkit::SpikeDetectorExportOptions::default()
            },
            ..crate::toolkit::SpikeDetectorOptions::toolkit_default()
        },
        Some(&sd_dir),
    )?;
    written.extend(sd.outputs);
    sections.push(GallerySection {
        title: "Spike detector export",
        blurb: "Threshold table, scatter, ISI/autocorr histograms, and panel HTML.",
        links: vec![(
            "spike_detector/spike_detector.html".into(),
            "Spike detector dashboard".into(),
        )],
        figures: Vec::new(),
    });

    written.push(write_index_html(out_dir, &sections)?);
    Ok(written)
}