Skip to main content

med64/analysis/
stats.rs

1//! `result table` result table + channel-level summaries.
2
3use serde::{Deserialize, Serialize};
4
5use super::burst::SingleChannelBurst;
6use super::task::AnalysisReport;
7use super::SpikeDirection;
8
9#[cfg(feature = "correlation")]
10use super::burst::BurstOnsetCorrelogram;
11
12// ─── Channel-level dump (CLI companion; not the result table) ───────
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15pub enum StatKind {
16    SpikeCount,
17    MeanRateHz,
18    MeanIsiMs,
19    CvIsi,
20    MeanAmplitudeMv,
21    BurstCount,
22    MeanBurstDurationMs,
23    AsdrPeakHz,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct ChannelStatRow {
28    pub channel: usize,
29    pub spike_count: usize,
30    pub mean_rate_hz: f64,
31    pub mean_isi_ms: f64,
32    pub cv_isi: f64,
33    pub mean_amplitude_mv: f64,
34    pub burst_count: usize,
35    pub mean_burst_duration_ms: f64,
36    pub active: bool,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct StatResultReport {
41    pub path: std::path::PathBuf,
42    pub duration_sec: f64,
43    pub total_spikes: usize,
44    pub asdr_peak_hz: f64,
45    pub channels: Vec<ChannelStatRow>,
46}
47
48#[derive(Debug, Clone)]
49pub struct ChannelCriteria {
50    /// Minimum spikes/s (inclusive). `None` or (0, ∞) disables filtering.
51    pub min_rate_hz: f64,
52    pub max_rate_hz: f64,
53}
54
55impl Default for ChannelCriteria {
56    fn default() -> Self {
57        Self { min_rate_hz: 0.0, max_rate_hz: f64::MAX }
58    }
59}
60
61impl ChannelCriteria {
62    pub fn is_enabled(&self) -> bool {
63        self.min_rate_hz > 0.0 || self.max_rate_hz < f64::MAX
64    }
65
66    pub fn satisfy(&self, rate_hz: f64) -> bool {
67        if !self.is_enabled() {
68            return true;
69        }
70        rate_hz >= self.min_rate_hz && rate_hz <= self.max_rate_hz
71    }
72}
73
74/// Per-channel summary (legacy companion to the result table).
75pub fn compute_stat_results(report: &AnalysisReport) -> StatResultReport {
76    compute_stat_results_with_criteria(report, &ChannelCriteria::default())
77}
78
79pub fn compute_stat_results_with_criteria(
80    report: &AnalysisReport,
81    criteria: &ChannelCriteria,
82) -> StatResultReport {
83    let duration_sec = (report.header.real_trace_duration_ms / 1000.0).max(1e-9);
84    let asdr_peak =
85        report.asdr.points.iter().map(|p| p.smoothed_hz.max(p.rate_hz)).fold(0.0_f64, f64::max);
86
87    let mut by_channel: std::collections::BTreeMap<usize, Vec<f64>> =
88        std::collections::BTreeMap::new();
89    let mut amps: std::collections::BTreeMap<usize, Vec<f64>> = std::collections::BTreeMap::new();
90    for spike in &report.spikes.spikes {
91        by_channel.entry(spike.channel).or_default().push(spike.within_trace_time_ms);
92        amps.entry(spike.channel).or_default().push(spike.peak_mv);
93    }
94
95    let mut channels = Vec::new();
96    for (&channel, times) in &mut by_channel {
97        times.sort_by(|a, b| a.partial_cmp(b).unwrap());
98        let mut isis = Vec::new();
99        for w in times.windows(2) {
100            isis.push(w[1] - w[0]);
101        }
102        let mean_isi =
103            if isis.is_empty() { 0.0 } else { isis.iter().sum::<f64>() / isis.len() as f64 };
104        let cv_isi = if mean_isi > 0.0 && !isis.is_empty() {
105            let var = isis.iter().map(|v| (v - mean_isi).powi(2)).sum::<f64>() / isis.len() as f64;
106            var.sqrt() / mean_isi
107        } else {
108            0.0
109        };
110        let channel_bursts: Vec<_> =
111            report.single_bursts.iter().filter(|b| b.channel == channel).collect();
112        let mean_burst_dur = if channel_bursts.is_empty() {
113            0.0
114        } else {
115            channel_bursts.iter().map(|b| b.duration_ms).sum::<f64>() / channel_bursts.len() as f64
116        };
117        let amp_vals = amps.get(&channel).map(|v| v.as_slice()).unwrap_or(&[]);
118        let mean_amp = if amp_vals.is_empty() {
119            0.0
120        } else {
121            amp_vals.iter().map(|v| v.abs()).sum::<f64>() / amp_vals.len() as f64
122        };
123        let rate = times.len() as f64 / duration_sec;
124        channels.push(ChannelStatRow {
125            channel,
126            spike_count: times.len(),
127            mean_rate_hz: rate,
128            mean_isi_ms: mean_isi,
129            cv_isi,
130            mean_amplitude_mv: mean_amp,
131            burst_count: channel_bursts.len(),
132            mean_burst_duration_ms: mean_burst_dur,
133            active: criteria.satisfy(rate),
134        });
135    }
136
137    StatResultReport {
138        path: report.path.clone(),
139        duration_sec,
140        total_spikes: report.spikes.len(),
141        asdr_peak_hz: asdr_peak,
142        channels,
143    }
144}
145
146// ─── Result table (`ResultRowType` × Mean/Median/SD/CV) ───────────
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
149pub enum SingleStatType {
150    Mean,
151    Median,
152    Sd,
153    Cv,
154}
155
156/// Nested agg: per-channel `inner`, then across-channel `outer`.
157///
158/// `MultiStatType` mapLabel is `{inner}_{outer}` (e.g. `mn_md` = median of means).
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
160pub struct MultiStatType {
161    /// Across-channel aggregate (“outer”).
162    pub outer: SingleStatType,
163    /// Per-channel aggregate (“inner” / first).
164    pub inner: SingleStatType,
165}
166
167impl MultiStatType {
168    pub fn new(inner: SingleStatType, outer: SingleStatType) -> Self {
169        Self { outer, inner }
170    }
171
172    pub fn map_label(self) -> String {
173        format!("{}_{}", label(self.inner), label(self.outer))
174    }
175
176    pub fn title(self) -> String {
177        format!("{}_{}", title_word(self.inner), title_word(self.outer))
178    }
179
180    pub fn parse_map_label(s: &str) -> Option<Self> {
181        let (a, b) = s.trim().split_once('_')?;
182        Some(Self::new(SingleStatType::parse(a)?, SingleStatType::parse(b)?))
183    }
184}
185
186#[derive(Debug, Clone, Serialize, Deserialize)]
187pub struct SingleStatMap {
188    pub mean: f64,
189    pub median: f64,
190    pub sd: f64,
191    pub cv: f64,
192}
193
194impl SingleStatMap {
195    pub fn all_nan() -> Self {
196        Self { mean: f64::NAN, median: f64::NAN, sd: f64::NAN, cv: f64::NAN }
197    }
198
199    pub fn get(&self, kind: SingleStatType) -> f64 {
200        match kind {
201            SingleStatType::Mean => self.mean,
202            SingleStatType::Median => self.median,
203            SingleStatType::Sd => self.sd,
204            SingleStatType::Cv => self.cv,
205        }
206    }
207}
208
209/// Sample SD (Welford / n-1) + mean/median/CV matching reference `StatValueMap`.
210pub fn create_single_stat_map(values: &[f64]) -> SingleStatMap {
211    let mut vals: Vec<f64> = values.iter().copied().filter(|v| v.is_finite()).collect();
212    if vals.is_empty() {
213        return SingleStatMap::all_nan();
214    }
215    vals.sort_by(|a, b| a.partial_cmp(b).unwrap());
216    let n = vals.len();
217    let mean = vals.iter().sum::<f64>() / n as f64;
218    let median = if n % 2 == 0 { (vals[n / 2 - 1] + vals[n / 2]) / 2.0 } else { vals[n / 2] };
219    let sd = if n == 1 {
220        f64::NAN
221    } else {
222        let mut m2 = 0.0;
223        let mut mu = 0.0;
224        for (i, &x) in vals.iter().enumerate() {
225            let delta = x - mu;
226            mu += delta / (i + 1) as f64;
227            m2 += delta * (x - mu);
228        }
229        (m2 / (n - 1) as f64).sqrt()
230    };
231    let cv = sd / mean;
232    SingleStatMap { mean, median, sd, cv }
233}
234
235/// Nested `Mean_Mean` … `CV_CV` over per-channel value lists.
236///
237/// Keys are mapLabels `{inner}_{outer}` (per-channel first).
238pub fn create_multi_stat_map(per_channel: &[Vec<f64>]) -> std::collections::BTreeMap<String, f64> {
239    let inners: Vec<SingleStatMap> =
240        per_channel.iter().map(|v| create_single_stat_map(v)).collect();
241    let kinds =
242        [SingleStatType::Mean, SingleStatType::Median, SingleStatType::Sd, SingleStatType::Cv];
243    let mut out = std::collections::BTreeMap::new();
244    for inner in kinds {
245        let vector: Vec<f64> = inners.iter().map(|m| m.get(inner)).collect();
246        let outer_map = create_single_stat_map(&vector);
247        for outer in kinds {
248            let key = MultiStatType::new(inner, outer).map_label();
249            out.insert(key, outer_map.get(outer));
250        }
251    }
252    out
253}
254
255impl SingleStatType {
256    pub fn parse(s: &str) -> Option<Self> {
257        match s.trim().to_ascii_lowercase().as_str() {
258            "mean" | "mn" | "avg" => Some(Self::Mean),
259            "median" | "md" | "med" => Some(Self::Median),
260            "sd" | "std" | "stdev" => Some(Self::Sd),
261            "cv" => Some(Self::Cv),
262            _ => None,
263        }
264    }
265
266    pub fn display_title(self) -> &'static str {
267        title_word(self)
268    }
269}
270
271fn label(k: SingleStatType) -> &'static str {
272    match k {
273        SingleStatType::Mean => "mn",
274        SingleStatType::Median => "md",
275        SingleStatType::Sd => "sd",
276        SingleStatType::Cv => "cv",
277    }
278}
279
280fn title_word(k: SingleStatType) -> &'static str {
281    match k {
282        SingleStatType::Mean => "Mean",
283        SingleStatType::Median => "Median",
284        SingleStatType::Sd => "SD",
285        SingleStatType::Cv => "CV",
286    }
287}
288
289#[derive(Debug, Clone, Serialize, Deserialize)]
290pub struct ResultTableRow {
291    pub map_label: String,
292    pub title: String,
293    pub value_type: String,
294    #[serde(default)]
295    pub value: Option<f64>,
296}
297
298#[derive(Debug, Clone, Serialize, Deserialize)]
299pub struct BurstResultTable {
300    pub path: std::path::PathBuf,
301    pub duration_sec: f64,
302    pub active_channels: usize,
303    pub rows: Vec<ResultTableRow>,
304}
305
306#[derive(Debug, Clone)]
307pub struct ResultTableOptions {
308    pub criteria: ChannelCriteria,
309    pub single_burst_agg: SingleStatType,
310    pub single_burst_nested_outer: SingleStatType,
311    pub single_burst_nested_inner: SingleStatType,
312    pub multi_burst_agg: SingleStatType,
313    pub synchrony_window_ms: f64,
314}
315
316impl Default for ResultTableOptions {
317    fn default() -> Self {
318        Self {
319            criteria: ChannelCriteria::default(),
320            single_burst_agg: SingleStatType::Mean,
321            single_burst_nested_outer: SingleStatType::Mean,
322            single_burst_nested_inner: SingleStatType::Mean,
323            multi_burst_agg: SingleStatType::Mean,
324            synchrony_window_ms: 20.0,
325        }
326    }
327}
328
329/// Build the 13-row result table for one analysis.
330pub fn compute_burst_result_table(
331    report: &AnalysisReport,
332    options: &ResultTableOptions,
333) -> BurstResultTable {
334    // Prefer analyzed duration (ASDR span / last spike) over full-file header when subset.
335    let duration_sec = report
336        .asdr
337        .points
338        .last()
339        .map(|p| {
340            (p.time_ms + report.asdr.points.get(1).map(|q| q.time_ms).unwrap_or(50.0)) / 1000.0
341        })
342        .or_else(|| {
343            report
344                .spikes
345                .spikes
346                .iter()
347                .map(|s| s.within_trace_time_ms)
348                .fold(None, |acc: Option<f64>, t| Some(acc.map_or(t, |a| a.max(t))))
349                .map(|t| t / 1000.0)
350        })
351        .unwrap_or_else(|| (report.header.real_trace_duration_ms / 1000.0).max(1e-9))
352        .max(1e-9);
353
354    let channel_stats = compute_stat_results_with_criteria(report, &options.criteria);
355    let mut active_channels: Vec<usize> = report
356        .header
357        .active_channels
358        .iter()
359        .enumerate()
360        .filter(|(_, &on)| on != 0)
361        .map(|(i, _)| i)
362        .collect();
363    if active_channels.is_empty() {
364        active_channels = channel_stats.channels.iter().map(|c| c.channel).collect();
365    }
366    let active_set: std::collections::BTreeSet<usize> = if options.criteria.is_enabled() {
367        channel_stats.channels.iter().filter(|c| c.active).map(|c| c.channel).collect()
368    } else {
369        active_channels.iter().copied().collect()
370    };
371    let n_active = active_set.len().max(1);
372
373    let spikes_active =
374        report.spikes.spikes.iter().filter(|s| active_set.contains(&s.channel)).count();
375    let array_rate = spikes_active as f64 / (n_active as f64 * duration_sec);
376
377    let single = filter_single(&report.single_bursts, &active_set);
378    let multi = &report.multi_bursts;
379
380    // Include every active channel (zeros for silent channels) — matches StatResultService.
381    let ordered: Vec<usize> = active_set.iter().copied().collect();
382    let burst_counts: Vec<f64> = ordered
383        .iter()
384        .map(|&ch| single.iter().filter(|b| b.channel == ch).count() as f64)
385        .collect();
386    let sb_map = create_single_stat_map(&burst_counts);
387
388    let mut spikes_lists = Vec::new();
389    let mut ibi_lists = Vec::new();
390    let mut dur_lists = Vec::new();
391    for &ch in &ordered {
392        let ch_bursts: Vec<&SingleChannelBurst> =
393            single.iter().copied().filter(|b| b.channel == ch).collect();
394        spikes_lists.push(ch_bursts.iter().map(|b| b.num_spikes as f64).collect());
395        ibi_lists.push(ch_bursts.iter().skip(1).map(|b| b.interburst_interval_ms).collect());
396        dur_lists.push(ch_bursts.iter().map(|b| b.duration_ms).collect());
397    }
398    let nested =
399        MultiStatType::new(options.single_burst_nested_inner, options.single_burst_nested_outer);
400    let nested_title = nested.title();
401    let ss = nested_pick(
402        &spikes_lists,
403        options.single_burst_nested_outer,
404        options.single_burst_nested_inner,
405    );
406    let si = nested_pick(
407        &ibi_lists,
408        options.single_burst_nested_outer,
409        options.single_burst_nested_inner,
410    );
411    let sd = nested_pick(
412        &dur_lists,
413        options.single_burst_nested_outer,
414        options.single_burst_nested_inner,
415    );
416
417    let (botc_index, botc_area) = {
418        #[cfg(feature = "correlation")]
419        {
420            botc_metrics(&report.correlogram, options.synchrony_window_ms)
421        }
422        #[cfg(not(feature = "correlation"))]
423        {
424            (f64::NAN, f64::NAN)
425        }
426    };
427
428    let mb = if multi.is_empty() { f64::NAN } else { multi.len() as f64 };
429    let ms = create_single_stat_map(&multi.iter().map(|b| b.num_spikes as f64).collect::<Vec<_>>())
430        .get(options.multi_burst_agg);
431    let mi = {
432        let mut ibis = Vec::new();
433        for w in multi.windows(2) {
434            ibis.push(w[1].start_ms - w[0].end_ms);
435        }
436        create_single_stat_map(&ibis).get(options.multi_burst_agg)
437    };
438    let mp = create_single_stat_map(&multi.iter().map(|b| b.peak_rate_hz).collect::<Vec<_>>())
439        .get(options.multi_burst_agg);
440    let md =
441        create_single_stat_map(&multi.iter().map(|b| b.end_ms - b.start_ms).collect::<Vec<_>>())
442            .get(options.multi_burst_agg);
443
444    let method_title = match report.asdr.method {
445        crate::analysis::burst::MultiBurstMethod::RateThreshold => {
446            "Array-wide spike detection rate (spikes/s)"
447        }
448        crate::analysis::burst::MultiBurstMethod::NetworkBurst => "Network burst product",
449        crate::analysis::burst::MultiBurstMethod::Spikes => "Multi-ch # spikes series",
450        crate::analysis::burst::MultiBurstMethod::ActiveChannels => "Multi-ch # active channels",
451    };
452
453    let rows = vec![
454        row("ac", "Number of active channels", "-", n_active as f64),
455        row("dr", method_title, "-", array_rate),
456        row(
457            "sb",
458            "Single-ch burst - number of burst (bursts)",
459            options.single_burst_agg.display_title(),
460            sb_map.get(options.single_burst_agg),
461        ),
462        row("ss", "Single-ch burst - spikes in a burst (spikes)", &nested_title, ss),
463        row("si", "Single-ch burst - interburst interval (ms)", &nested_title, si),
464        row("sd", "Single-ch burst - duration (ms)", &nested_title, sd),
465        row("ba", "BOTC - % burst synchrony area", "-", botc_area),
466        row("bp", "BOTC - burst synchrony product", "-", botc_index),
467        row("mb", "Multi-ch burst - number of burst (bursts)", "-", mb),
468        row(
469            "ms",
470            "Multi-ch burst - spikes in a burst",
471            options.multi_burst_agg.display_title(),
472            ms,
473        ),
474        row(
475            "mi",
476            "Multi-ch burst - interburst interval (ms)",
477            options.multi_burst_agg.display_title(),
478            mi,
479        ),
480        row("mp", "Multi-ch burst - peak (spikes/s)", options.multi_burst_agg.display_title(), mp),
481        row("md", "Multi-ch burst - duration (ms)", options.multi_burst_agg.display_title(), md),
482    ];
483
484    BurstResultTable { path: report.path.clone(), duration_sec, active_channels: n_active, rows }
485}
486
487fn row(
488    map_label: &str,
489    title: impl Into<String>,
490    value_type: impl Into<String>,
491    value: f64,
492) -> ResultTableRow {
493    ResultTableRow {
494        map_label: map_label.into(),
495        title: title.into(),
496        value_type: value_type.into(),
497        value: if value.is_finite() { Some(value) } else { None },
498    }
499}
500
501fn filter_single<'a>(
502    bursts: &'a [SingleChannelBurst],
503    active: &std::collections::BTreeSet<usize>,
504) -> Vec<&'a SingleChannelBurst> {
505    bursts.iter().filter(|b| active.contains(&b.channel)).collect()
506}
507
508fn nested_pick(lists: &[Vec<f64>], outer: SingleStatType, inner: SingleStatType) -> f64 {
509    let map = create_multi_stat_map(lists);
510    let key = MultiStatType::new(inner, outer).map_label();
511    map.get(&key).copied().unwrap_or(f64::NAN)
512}
513
514#[cfg(feature = "correlation")]
515fn botc_metrics(cg: &BurstOnsetCorrelogram, window_ms: f64) -> (f64, f64) {
516    let total: u64 = cg.counts.iter().map(|&c| c as u64).sum();
517    if total == 0 {
518        return (0.0, 0.0);
519    }
520    let sync: u64 = cg
521        .lag_ms
522        .iter()
523        .zip(&cg.counts)
524        .filter(|(&lag, _)| lag.abs() <= window_ms)
525        .map(|(_, &c)| c as u64)
526        .sum();
527    let index = sync as f64 / total as f64;
528    let area = index * sync as f64;
529    (index, area)
530}
531
532/// % change from baseline (#1): `100 * first / current` (100 for #1 itself).
533pub fn percent_change_from_first(first: f64, current: f64, is_first: bool) -> f64 {
534    if is_first {
535        return 100.0;
536    }
537    if !first.is_finite() || first == 0.0 || !current.is_finite() {
538        return f64::NAN;
539    }
540    100.0 * first / current
541}
542
543/// One analyzed file column in a multi-file result table.
544#[derive(Debug, Clone, Serialize, Deserialize)]
545pub struct MultiFileResultColumn {
546    pub label: String,
547    pub path: std::path::PathBuf,
548    pub table: BurstResultTable,
549}
550
551/// multi-file result table: raw values + `% change from #1` per metric.
552#[derive(Debug, Clone, Serialize, Deserialize)]
553pub struct MultiFileResultTable {
554    pub columns: Vec<MultiFileResultColumn>,
555}
556
557/// Build a multi-file result table from already-computed per-file tables.
558///
559/// Row order follows the first table. Later tables are matched by `map_label`.
560pub fn compare_burst_result_tables(columns: Vec<MultiFileResultColumn>) -> MultiFileResultTable {
561    MultiFileResultTable { columns }
562}
563
564/// Analyze each path and assemble the multi-file result table.
565pub fn run_result_table_compare(
566    paths: &[impl AsRef<std::path::Path>],
567    analysis: &crate::analysis::task::AnalysisOptions,
568    table_opts: &ResultTableOptions,
569) -> crate::error::Result<MultiFileResultTable> {
570    let mut columns = Vec::with_capacity(paths.len());
571    for path in paths {
572        let path = path.as_ref();
573        let report = crate::analysis::task::run_analysis(path, analysis)?;
574        let table = compute_burst_result_table(&report, table_opts);
575        let label = path
576            .file_stem()
577            .map(|s| s.to_string_lossy().into_owned())
578            .unwrap_or_else(|| path.display().to_string());
579        columns.push(MultiFileResultColumn { label, path: path.to_path_buf(), table });
580    }
581    Ok(compare_burst_result_tables(columns))
582}
583
584impl MultiFileResultTable {
585    /// Raw value for metric `map_label` in column `col`, or NaN if missing.
586    pub fn raw_value(&self, col: usize, map_label: &str) -> f64 {
587        self.columns
588            .get(col)
589            .and_then(|c| c.table.rows.iter().find(|r| r.map_label == map_label))
590            .map(|r| r.value.unwrap_or(f64::NAN))
591            .unwrap_or(f64::NAN)
592    }
593
594    /// `% change from #1` for metric `map_label` in column `col`.
595    pub fn percent_change(&self, col: usize, map_label: &str) -> f64 {
596        let first = self.raw_value(0, map_label);
597        let current = self.raw_value(col, map_label);
598        percent_change_from_first(first, current, col == 0)
599    }
600
601    /// Metric row metadata from the first file (title / value_type / map_label).
602    pub fn metric_rows(&self) -> &[ResultTableRow] {
603        self.columns.first().map(|c| c.table.rows.as_slice()).unwrap_or(&[])
604    }
605}
606
607/// Interactive MultiFileResultTable HTML (contenteditable % change).
608pub fn write_result_table_interactive_html(
609    table: &MultiFileResultTable,
610    path: impl AsRef<std::path::Path>,
611) -> crate::error::Result<()> {
612    use std::io::Write;
613    let path = path.as_ref();
614    let mut html = String::from(
615        r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>Result table</title>
616<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>
617</head><body><h1>Multi-file result table</h1><table id="t"><thead><tr><th>Metric</th>"#,
618    );
619    for (i, col) in table.columns.iter().enumerate() {
620        html.push_str(&format!("<th>#{} {}</th><th>%chg</th>", i + 1, col.label));
621    }
622    html.push_str("</tr></thead><tbody>");
623    for metric in table.metric_rows() {
624        html.push_str(&format!("<tr data-m=\"{}\"><td>{}</td>", metric.map_label, metric.title));
625        for (ci, _) in table.columns.iter().enumerate() {
626            let v = table.raw_value(ci, &metric.map_label);
627            let pct = table.percent_change(ci, &metric.map_label);
628            html.push_str(&format!(
629                "<td contenteditable=\"true\" class=\"v\">{v:.4}</td><td class=\"pct\">{pct:.2}</td>",
630                v = if v.is_finite() { v } else { 0.0 },
631                pct = if pct.is_finite() { pct } else { 0.0 }
632            ));
633        }
634        html.push_str("</tr>");
635    }
636    html.push_str(
637        r#"</tbody></table>
638<script>
639function recompute(){
640  document.querySelectorAll('#t tbody tr').forEach(tr=>{
641    const vs=[...tr.querySelectorAll('.v')];
642    const first=parseFloat(vs[0]?.textContent)||0;
643    vs.forEach((td,i)=>{
644      const cur=parseFloat(td.textContent)||0;
645      const pct=i===0?100:(cur===0?0:(first/cur)*100);
646      td.nextElementSibling.textContent=pct.toFixed(2);
647    });
648  });
649}
650document.getElementById('t').addEventListener('input',recompute);
651</script></body></html>"#,
652    );
653    let mut f = std::fs::File::create(path)
654        .map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })?;
655    f.write_all(html.as_bytes())
656        .map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })?;
657    Ok(())
658}
659
660#[derive(Debug, Clone, Serialize, Deserialize)]
661pub struct AmplitudeRankRow {
662    pub rank: usize,
663    pub channel: usize,
664    pub direction: SpikeDirection,
665    pub peak_mv: f64,
666    pub time_ms: f64,
667}
668
669#[derive(Debug, Clone, Serialize, Deserialize)]
670pub struct AmplitudeRankReport {
671    pub rows: Vec<AmplitudeRankRow>,
672}
673
674/// Rank spikes by absolute amplitude (`SpikeAmplitudeFreq` / amplitude histogram companion).
675pub fn amplitude_rank_report(report: &AnalysisReport, top_n: usize) -> AmplitudeRankReport {
676    let mut rows: Vec<AmplitudeRankRow> = report
677        .spikes
678        .spikes
679        .iter()
680        .map(|s| AmplitudeRankRow {
681            rank: 0,
682            channel: s.channel,
683            direction: s.direction,
684            peak_mv: s.peak_mv,
685            time_ms: s.within_trace_time_ms,
686        })
687        .collect();
688    rows.sort_by(|a, b| {
689        b.peak_mv
690            .abs()
691            .partial_cmp(&a.peak_mv.abs())
692            .unwrap()
693            .then(a.time_ms.partial_cmp(&b.time_ms).unwrap())
694    });
695    rows.truncate(top_n.max(1));
696    for (i, row) in rows.iter_mut().enumerate() {
697        row.rank = i + 1;
698    }
699    AmplitudeRankReport { rows }
700}
701
702#[cfg(test)]
703mod tests {
704    use super::*;
705
706    #[test]
707    fn single_stat_sample_sd() {
708        let m = create_single_stat_map(&[1.0, 2.0, 3.0]);
709        assert!((m.mean - 2.0).abs() < 1e-12);
710        assert!((m.median - 2.0).abs() < 1e-12);
711        assert!((m.sd - 1.0).abs() < 1e-12);
712        assert!((m.cv - 0.5).abs() < 1e-12);
713    }
714
715    #[test]
716    fn multi_stat_mean_mean() {
717        let map = create_multi_stat_map(&[vec![1.0, 3.0], vec![5.0, 7.0]]);
718        // per-ch means: 2 and 6 → mean_mean = 4
719        assert!((map["mn_mn"] - 4.0).abs() < 1e-12);
720    }
721
722    #[test]
723    fn multi_stat_median_of_means_is_mn_md() {
724        // ch0 mean=2, ch1 mean=6 → median of means = 4, key mn_md
725        let map = create_multi_stat_map(&[vec![1.0, 3.0], vec![5.0, 7.0]]);
726        assert!((map["mn_md"] - 4.0).abs() < 1e-12);
727        assert_eq!(
728            MultiStatType::new(SingleStatType::Mean, SingleStatType::Median).map_label(),
729            "mn_md"
730        );
731    }
732
733    #[test]
734    fn percent_change_baseline_formula() {
735        assert!((percent_change_from_first(10.0, 10.0, true) - 100.0).abs() < 1e-9);
736        assert!((percent_change_from_first(10.0, 5.0, false) - 200.0).abs() < 1e-9);
737    }
738
739    #[test]
740    fn multi_file_percent_change_from_first_column() {
741        fn col(label: &str, ac: f64, dr: f64) -> MultiFileResultColumn {
742            MultiFileResultColumn {
743                label: label.into(),
744                path: std::path::PathBuf::from(label),
745                table: BurstResultTable {
746                    path: std::path::PathBuf::from(label),
747                    duration_sec: 1.0,
748                    active_channels: ac as usize,
749                    rows: vec![
750                        row("ac", "Number of Active Channels", "", ac),
751                        row("dr", "Array-wide Spike Detection Rate", "spikes/sec/channel", dr),
752                    ],
753                },
754            }
755        }
756        let table =
757            compare_burst_result_tables(vec![col("control", 64.0, 10.0), col("drug", 64.0, 5.0)]);
758        assert!((table.percent_change(0, "dr") - 100.0).abs() < 1e-9);
759        assert!((table.percent_change(1, "dr") - 200.0).abs() < 1e-9);
760        assert!((table.percent_change(1, "ac") - 100.0).abs() < 1e-9);
761    }
762}