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;

use crate::analysis::spike::{AutocorrReport, SpikeDirection};
use crate::analysis::waveform_avg::{AverageWaveform, SpikeHeatmap};
use crate::analysis::{AnalysisReport, SpikePostHocReport};
use crate::error::{Med64Error, Result};
use crate::toolkit::cluster::ClusterReport;

use super::types::{ChannelThresholdRow, Histogram, SpikeDetectorPanelPrefs};

pub fn write_spike_detector_panel_html(
    prefs: &SpikeDetectorPanelPrefs,
    path: impl AsRef<Path>,
) -> Result<()> {
    let path = path.as_ref();
    let html = format!(
        r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>Spike Detector Prefer</title>
<style>body{{font-family:system-ui;margin:1rem}}label{{display:block;margin:.4rem 0}}</style></head><body>
<h1>Spike Detector Prefer</h1>
<label>Plus color <input type="color" id="plus" value="{plus}"></label>
<label>Minus color <input type="color" id="minus" value="{minus}"></label>
<label><input type="checkbox" id="th" {th}> Show thresholds</label>
<label><input type="checkbox" id="cl" {cl}> Show clusters</label>
<pre id="out"></pre>
<script>
function sync(){{document.getElementById('out').textContent=JSON.stringify({{
  color_plus:document.getElementById('plus').value,
  color_minus:document.getElementById('minus').value,
  show_thresholds:document.getElementById('th').checked,
  show_clusters:document.getElementById('cl').checked
}},null,2);}}
document.querySelectorAll('input').forEach(i=>i.addEventListener('input',sync)); sync();
</script></body></html>"#,
        plus = prefs.color_plus,
        minus = prefs.color_minus,
        th = if prefs.show_thresholds { "checked" } else { "" },
        cl = if prefs.show_clusters { "checked" } else { "" },
    );
    std::fs::write(path, html)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

pub fn write_spike_detector_result_table_html(
    report: &AnalysisReport,
    thresholds: &[ChannelThresholdRow],
    path: impl AsRef<Path>,
) -> Result<()> {
    let path = path.as_ref();
    let mut rows = String::new();
    for t in thresholds {
        let n = report.spikes.spikes.iter().filter(|s| s.channel == t.channel).count();
        rows.push_str(&format!(
            "<tr><td>{}</td><td contenteditable=\"true\">{}</td><td>{:.4}</td><td>{:.4}</td><td contenteditable=\"true\">{n}</td></tr>",
            t.channel + 1,
            if t.enabled { "on" } else { "off" },
            t.plus_mv.unwrap_or(0.0),
            t.minus_mv.unwrap_or(0.0),
            n = n
        ));
    }
    let html = format!(
        r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>Spike Detector ResultTable</title>
<style>body{{font-family:system-ui;margin:1rem}}td[contenteditable]{{background:#fffbeb}}table{{border-collapse:collapse}}td,th{{border:1px solid #cbd5e1;padding:.3rem}}</style></head>
<body><h1>Result table</h1>
<table><thead><tr><th>Ch</th><th>On</th><th>+mV</th><th>-mV</th><th>Spikes</th></tr></thead>
<tbody>{rows}</tbody></table></body></html>"#
    );
    std::fs::write(path, html)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

#[allow(clippy::too_many_arguments)]
pub(super) fn write_spike_detector_html(
    report: &AnalysisReport,
    posthoc: &SpikePostHocReport,
    mean_waveforms: &[AverageWaveform],
    heatmap: &SpikeHeatmap,
    autocorr: &AutocorrReport,
    isi: Option<&Histogram>,
    amplitude: Option<&Histogram>,
    clusters: Option<&ClusterReport>,
    thresholds: &[ChannelThresholdRow],
    path: impl AsRef<Path>,
) -> Result<()> {
    let path = path.as_ref();
    let scatter_json = serde_json::to_string(
        &posthoc
            .scatter
            .iter()
            .take(5000)
            .map(|p| serde_json::json!({"x": p.duration_ms, "y": p.peak_mv, "ch": p.channel + 1}))
            .collect::<Vec<_>>(),
    )
    .unwrap_or_else(|_| "[]".into());

    let mut heat_cells = String::new();
    let max_c = heatmap.cells.iter().map(|c| c.spike_count).max().unwrap_or(1).max(1);
    for c in &heatmap.cells {
        let t = c.spike_count as f64 / max_c as f64;
        let r = (40.0 + 215.0 * t) as u8;
        let g = (40.0 + 80.0 * (1.0 - t)) as u8;
        let b = (255.0 * (1.0 - t)) as u8;
        heat_cells.push_str(&format!(
            "<div class=\"h\" title=\"Ch{}: {}\" style=\"background:rgb({r},{g},{b})\"></div>",
            c.channel + 1,
            c.spike_count
        ));
    }

    let mut mean_svg = String::new();
    for (i, w) in mean_waveforms.iter().take(16).enumerate() {
        if w.mean_mv.len() < 2 {
            continue;
        }
        let min_y = w.mean_mv.iter().cloned().fold(f64::INFINITY, f64::min);
        let max_y = w.mean_mv.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
        let span = (max_y - min_y).abs().max(1e-9);
        let mut pts = String::new();
        for (j, &y) in w.mean_mv.iter().enumerate() {
            let x = j as f64 / (w.mean_mv.len() - 1) as f64 * 180.0;
            let py = 40.0 - (y - min_y) / span * 36.0;
            pts.push_str(&format!("{x:.1},{py:.1} "));
        }
        let color = if w.direction == SpikeDirection::Minus { "#2563eb" } else { "#dc2626" };
        mean_svg.push_str(&format!(
            "<div class=\"mw\"><div class=\"ml\">Ch{} {:?}</div>\
             <svg width=\"190\" height=\"44\"><polyline fill=\"none\" stroke=\"{color}\" stroke-width=\"1.2\" points=\"{pts}\"/></svg></div>",
            w.channel + 1,
            w.direction
        ));
        let _ = i;
    }

    let mut auto_rows = String::new();
    for ch in autocorr.channels.iter().take(8) {
        let max = ch.counts.iter().copied().max().unwrap_or(1).max(1) as f64;
        let mut bars = String::new();
        for (i, &c) in ch.counts.iter().enumerate() {
            let h = (c as f64 / max * 40.0) as u32;
            let x = i as f64 / ch.counts.len().max(1) as f64 * 200.0;
            bars.push_str(&format!(
                "<rect x=\"{x:.1}\" y=\"{}\" width=\"1.5\" height=\"{h}\" fill=\"#0ea5e9\"/>",
                44 - h
            ));
        }
        auto_rows.push_str(&format!(
            "<div class=\"mw\"><div class=\"ml\">Ch{} autocorr</div><svg width=\"210\" height=\"48\">{bars}</svg></div>",
            ch.channel + 1
        ));
    }

    let isi_note = isi
        .map(|h| format!("{} bins, {} counts", h.counts.len(), h.counts.iter().sum::<u64>()))
        .unwrap_or_else(|| "histograms feature off".into());
    let amp_note = amplitude.map(|h| format!("{} bins", h.counts.len())).unwrap_or_default();
    let cluster_note = clusters
        .map(|c| format!("{} assignments, {} centroids", c.assignments.len(), c.centroids.len()))
        .unwrap_or_else(|| "clustering off".into());

    let thr_rows: String = thresholds
        .iter()
        .filter(|t| t.enabled)
        .take(64)
        .map(|t| {
            format!(
                "<tr><td>{}</td><td>{:.5}</td><td>{:.5}</td></tr>",
                t.channel + 1,
                t.plus_mv.unwrap_or(0.0),
                t.minus_mv.unwrap_or(0.0)
            )
        })
        .collect();

    let raster = &posthoc.raster_histogram;
    let rmax = raster.counts.iter().copied().max().unwrap_or(1).max(1) as f64;
    let mut raster_bars = String::new();
    for (i, &c) in raster.counts.iter().enumerate() {
        let h = (c as f64 / rmax * 80.0) as u32;
        let x = i as f64 / raster.counts.len().max(1) as f64 * 640.0;
        raster_bars.push_str(&format!(
            "<rect x=\"{x:.1}\" y=\"{}\" width=\"3\" height=\"{h}\" fill=\"#334155\"/>",
            90 - h
        ));
    }

    let html = format!(
        r##"<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Spike Detector</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body{{font-family:system-ui,sans-serif;margin:1.25rem;background:#f8fafc;color:#0f172a}}
h1{{font-size:1.4rem;margin:0 0 .25rem}} .sub{{color:#64748b;margin-bottom:1.25rem}}
section{{margin:1.5rem 0;padding:1rem;background:#fff;border:1px solid #e2e8f0;border-radius:8px}}
h2{{font-size:1.05rem;margin:0 0 .75rem}}
.grid8{{display:grid;grid-template-columns:repeat(8,1fr);gap:2px;max-width:360px}}
.h{{aspect-ratio:1;border-radius:2px}}
.mws{{display:flex;flex-wrap:wrap;gap:.5rem}}
.mw{{border:1px solid #e2e8f0;padding:.25rem;border-radius:4px}}
.ml{{font-size:11px;color:#64748b}}
table{{border-collapse:collapse;font-size:12px}} td,th{{border:1px solid #e2e8f0;padding:2px 6px}}
canvas{{max-width:100%}}
</style></head><body>
<h1>Spike Detector</h1>
<div class="sub">{src} · {nspikes} spikes · Toolkit-style package</div>

<section><h2>Channel heatmap</h2>
<div class="grid8">{heat_cells}</div></section>

<section><h2>Scatter (amplitude vs duration)</h2>
<canvas id="scatter" height="120"></canvas></section>

<section><h2>Raster time histogram ({rbin} ms bins)</h2>
<svg width="660" height="96" style="background:#fafafa;border:1px solid #e2e8f0">{raster_bars}</svg></section>

<section><h2>Mean spike waveforms</h2>
<div class="mws">{mean_svg}</div></section>

<section><h2>Autocorrelograms</h2>
<div class="mws">{auto_rows}</div></section>

<section><h2>ISI / Amplitude / Clusters</h2>
<p>ISI: {isi_note}. Amplitude: {amp_note}. Clusters: {cluster_note}.</p></section>

<section><h2>Threshold table</h2>
<table><tr><th>Ch</th><th>+ mV</th><th>− mV</th></tr>{thr_rows}</table></section>

<script>
const pts = {scatter_json};
new Chart(document.getElementById('scatter'), {{
  type: 'scatter',
  data: {{ datasets: [{{
    label: 'spikes',
    data: pts.map(p => ({{x:p.x, y:p.y}})),
    pointRadius: 1.5,
    backgroundColor: 'rgba(37,99,235,.45)'
  }}] }},
  options: {{
    plugins: {{ legend: {{ display: false }} }},
    scales: {{
      x: {{ title: {{ display: true, text: 'Duration (ms)' }} }},
      y: {{ title: {{ display: true, text: '|Peak| (mV)' }} }}
    }}
  }}
}});
</script>
</body></html>"##,
        src = report.path.display(),
        nspikes = report.spikes.len(),
        rbin = raster.bin_ms,
    );

    std::fs::write(path, html)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}