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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
//! `result table` result table + channel-level summaries.

use serde::{Deserialize, Serialize};

use super::burst::SingleChannelBurst;
use super::task::AnalysisReport;
use super::SpikeDirection;

#[cfg(feature = "correlation")]
use super::burst::BurstOnsetCorrelogram;

// ─── Channel-level dump (CLI companion; not the result table) ───────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StatKind {
    SpikeCount,
    MeanRateHz,
    MeanIsiMs,
    CvIsi,
    MeanAmplitudeMv,
    BurstCount,
    MeanBurstDurationMs,
    AsdrPeakHz,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelStatRow {
    pub channel: usize,
    pub spike_count: usize,
    pub mean_rate_hz: f64,
    pub mean_isi_ms: f64,
    pub cv_isi: f64,
    pub mean_amplitude_mv: f64,
    pub burst_count: usize,
    pub mean_burst_duration_ms: f64,
    pub active: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatResultReport {
    pub path: std::path::PathBuf,
    pub duration_sec: f64,
    pub total_spikes: usize,
    pub asdr_peak_hz: f64,
    pub channels: Vec<ChannelStatRow>,
}

#[derive(Debug, Clone)]
pub struct ChannelCriteria {
    /// Minimum spikes/s (inclusive). `None` or (0, ∞) disables filtering.
    pub min_rate_hz: f64,
    pub max_rate_hz: f64,
}

impl Default for ChannelCriteria {
    fn default() -> Self {
        Self { min_rate_hz: 0.0, max_rate_hz: f64::MAX }
    }
}

impl ChannelCriteria {
    pub fn is_enabled(&self) -> bool {
        self.min_rate_hz > 0.0 || self.max_rate_hz < f64::MAX
    }

    pub fn satisfy(&self, rate_hz: f64) -> bool {
        if !self.is_enabled() {
            return true;
        }
        rate_hz >= self.min_rate_hz && rate_hz <= self.max_rate_hz
    }
}

/// Per-channel summary (legacy companion to the result table).
pub fn compute_stat_results(report: &AnalysisReport) -> StatResultReport {
    compute_stat_results_with_criteria(report, &ChannelCriteria::default())
}

pub fn compute_stat_results_with_criteria(
    report: &AnalysisReport,
    criteria: &ChannelCriteria,
) -> StatResultReport {
    let duration_sec = (report.header.real_trace_duration_ms / 1000.0).max(1e-9);
    let asdr_peak =
        report.asdr.points.iter().map(|p| p.smoothed_hz.max(p.rate_hz)).fold(0.0_f64, f64::max);

    let mut by_channel: std::collections::BTreeMap<usize, Vec<f64>> =
        std::collections::BTreeMap::new();
    let mut amps: std::collections::BTreeMap<usize, Vec<f64>> = std::collections::BTreeMap::new();
    for spike in &report.spikes.spikes {
        by_channel.entry(spike.channel).or_default().push(spike.within_trace_time_ms);
        amps.entry(spike.channel).or_default().push(spike.peak_mv);
    }

    let mut channels = Vec::new();
    for (&channel, times) in &mut by_channel {
        times.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let mut isis = Vec::new();
        for w in times.windows(2) {
            isis.push(w[1] - w[0]);
        }
        let mean_isi =
            if isis.is_empty() { 0.0 } else { isis.iter().sum::<f64>() / isis.len() as f64 };
        let cv_isi = if mean_isi > 0.0 && !isis.is_empty() {
            let var = isis.iter().map(|v| (v - mean_isi).powi(2)).sum::<f64>() / isis.len() as f64;
            var.sqrt() / mean_isi
        } else {
            0.0
        };
        let channel_bursts: Vec<_> =
            report.single_bursts.iter().filter(|b| b.channel == channel).collect();
        let mean_burst_dur = if channel_bursts.is_empty() {
            0.0
        } else {
            channel_bursts.iter().map(|b| b.duration_ms).sum::<f64>() / channel_bursts.len() as f64
        };
        let amp_vals = amps.get(&channel).map(|v| v.as_slice()).unwrap_or(&[]);
        let mean_amp = if amp_vals.is_empty() {
            0.0
        } else {
            amp_vals.iter().map(|v| v.abs()).sum::<f64>() / amp_vals.len() as f64
        };
        let rate = times.len() as f64 / duration_sec;
        channels.push(ChannelStatRow {
            channel,
            spike_count: times.len(),
            mean_rate_hz: rate,
            mean_isi_ms: mean_isi,
            cv_isi,
            mean_amplitude_mv: mean_amp,
            burst_count: channel_bursts.len(),
            mean_burst_duration_ms: mean_burst_dur,
            active: criteria.satisfy(rate),
        });
    }

    StatResultReport {
        path: report.path.clone(),
        duration_sec,
        total_spikes: report.spikes.len(),
        asdr_peak_hz: asdr_peak,
        channels,
    }
}

// ─── Result table (`ResultRowType` × Mean/Median/SD/CV) ───────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SingleStatType {
    Mean,
    Median,
    Sd,
    Cv,
}

/// Nested agg: per-channel `inner`, then across-channel `outer`.
///
/// `MultiStatType` mapLabel is `{inner}_{outer}` (e.g. `mn_md` = median of means).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct MultiStatType {
    /// Across-channel aggregate (“outer”).
    pub outer: SingleStatType,
    /// Per-channel aggregate (“inner” / first).
    pub inner: SingleStatType,
}

impl MultiStatType {
    pub fn new(inner: SingleStatType, outer: SingleStatType) -> Self {
        Self { outer, inner }
    }

    pub fn map_label(self) -> String {
        format!("{}_{}", label(self.inner), label(self.outer))
    }

    pub fn title(self) -> String {
        format!("{}_{}", title_word(self.inner), title_word(self.outer))
    }

    pub fn parse_map_label(s: &str) -> Option<Self> {
        let (a, b) = s.trim().split_once('_')?;
        Some(Self::new(SingleStatType::parse(a)?, SingleStatType::parse(b)?))
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SingleStatMap {
    pub mean: f64,
    pub median: f64,
    pub sd: f64,
    pub cv: f64,
}

impl SingleStatMap {
    pub fn all_nan() -> Self {
        Self { mean: f64::NAN, median: f64::NAN, sd: f64::NAN, cv: f64::NAN }
    }

    pub fn get(&self, kind: SingleStatType) -> f64 {
        match kind {
            SingleStatType::Mean => self.mean,
            SingleStatType::Median => self.median,
            SingleStatType::Sd => self.sd,
            SingleStatType::Cv => self.cv,
        }
    }
}

/// Sample SD (Welford / n-1) + mean/median/CV matching reference `StatValueMap`.
pub fn create_single_stat_map(values: &[f64]) -> SingleStatMap {
    let mut vals: Vec<f64> = values.iter().copied().filter(|v| v.is_finite()).collect();
    if vals.is_empty() {
        return SingleStatMap::all_nan();
    }
    vals.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let n = vals.len();
    let mean = vals.iter().sum::<f64>() / n as f64;
    let median = if n % 2 == 0 { (vals[n / 2 - 1] + vals[n / 2]) / 2.0 } else { vals[n / 2] };
    let sd = if n == 1 {
        f64::NAN
    } else {
        let mut m2 = 0.0;
        let mut mu = 0.0;
        for (i, &x) in vals.iter().enumerate() {
            let delta = x - mu;
            mu += delta / (i + 1) as f64;
            m2 += delta * (x - mu);
        }
        (m2 / (n - 1) as f64).sqrt()
    };
    let cv = sd / mean;
    SingleStatMap { mean, median, sd, cv }
}

/// Nested `Mean_Mean` … `CV_CV` over per-channel value lists.
///
/// Keys are mapLabels `{inner}_{outer}` (per-channel first).
pub fn create_multi_stat_map(per_channel: &[Vec<f64>]) -> std::collections::BTreeMap<String, f64> {
    let inners: Vec<SingleStatMap> =
        per_channel.iter().map(|v| create_single_stat_map(v)).collect();
    let kinds =
        [SingleStatType::Mean, SingleStatType::Median, SingleStatType::Sd, SingleStatType::Cv];
    let mut out = std::collections::BTreeMap::new();
    for inner in kinds {
        let vector: Vec<f64> = inners.iter().map(|m| m.get(inner)).collect();
        let outer_map = create_single_stat_map(&vector);
        for outer in kinds {
            let key = MultiStatType::new(inner, outer).map_label();
            out.insert(key, outer_map.get(outer));
        }
    }
    out
}

impl SingleStatType {
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "mean" | "mn" | "avg" => Some(Self::Mean),
            "median" | "md" | "med" => Some(Self::Median),
            "sd" | "std" | "stdev" => Some(Self::Sd),
            "cv" => Some(Self::Cv),
            _ => None,
        }
    }

    pub fn display_title(self) -> &'static str {
        title_word(self)
    }
}

fn label(k: SingleStatType) -> &'static str {
    match k {
        SingleStatType::Mean => "mn",
        SingleStatType::Median => "md",
        SingleStatType::Sd => "sd",
        SingleStatType::Cv => "cv",
    }
}

fn title_word(k: SingleStatType) -> &'static str {
    match k {
        SingleStatType::Mean => "Mean",
        SingleStatType::Median => "Median",
        SingleStatType::Sd => "SD",
        SingleStatType::Cv => "CV",
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResultTableRow {
    pub map_label: String,
    pub title: String,
    pub value_type: String,
    #[serde(default)]
    pub value: Option<f64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BurstResultTable {
    pub path: std::path::PathBuf,
    pub duration_sec: f64,
    pub active_channels: usize,
    pub rows: Vec<ResultTableRow>,
}

#[derive(Debug, Clone)]
pub struct ResultTableOptions {
    pub criteria: ChannelCriteria,
    pub single_burst_agg: SingleStatType,
    pub single_burst_nested_outer: SingleStatType,
    pub single_burst_nested_inner: SingleStatType,
    pub multi_burst_agg: SingleStatType,
    pub synchrony_window_ms: f64,
}

impl Default for ResultTableOptions {
    fn default() -> Self {
        Self {
            criteria: ChannelCriteria::default(),
            single_burst_agg: SingleStatType::Mean,
            single_burst_nested_outer: SingleStatType::Mean,
            single_burst_nested_inner: SingleStatType::Mean,
            multi_burst_agg: SingleStatType::Mean,
            synchrony_window_ms: 20.0,
        }
    }
}

/// Build the 13-row result table for one analysis.
pub fn compute_burst_result_table(
    report: &AnalysisReport,
    options: &ResultTableOptions,
) -> BurstResultTable {
    // Prefer analyzed duration (ASDR span / last spike) over full-file header when subset.
    let duration_sec = report
        .asdr
        .points
        .last()
        .map(|p| {
            (p.time_ms + report.asdr.points.get(1).map(|q| q.time_ms).unwrap_or(50.0)) / 1000.0
        })
        .or_else(|| {
            report
                .spikes
                .spikes
                .iter()
                .map(|s| s.within_trace_time_ms)
                .fold(None, |acc: Option<f64>, t| Some(acc.map_or(t, |a| a.max(t))))
                .map(|t| t / 1000.0)
        })
        .unwrap_or_else(|| (report.header.real_trace_duration_ms / 1000.0).max(1e-9))
        .max(1e-9);

    let channel_stats = compute_stat_results_with_criteria(report, &options.criteria);
    let mut active_channels: Vec<usize> = report
        .header
        .active_channels
        .iter()
        .enumerate()
        .filter(|(_, &on)| on != 0)
        .map(|(i, _)| i)
        .collect();
    if active_channels.is_empty() {
        active_channels = channel_stats.channels.iter().map(|c| c.channel).collect();
    }
    let active_set: std::collections::BTreeSet<usize> = if options.criteria.is_enabled() {
        channel_stats.channels.iter().filter(|c| c.active).map(|c| c.channel).collect()
    } else {
        active_channels.iter().copied().collect()
    };
    let n_active = active_set.len().max(1);

    let spikes_active =
        report.spikes.spikes.iter().filter(|s| active_set.contains(&s.channel)).count();
    let array_rate = spikes_active as f64 / (n_active as f64 * duration_sec);

    let single = filter_single(&report.single_bursts, &active_set);
    let multi = &report.multi_bursts;

    // Include every active channel (zeros for silent channels) — matches StatResultService.
    let ordered: Vec<usize> = active_set.iter().copied().collect();
    let burst_counts: Vec<f64> = ordered
        .iter()
        .map(|&ch| single.iter().filter(|b| b.channel == ch).count() as f64)
        .collect();
    let sb_map = create_single_stat_map(&burst_counts);

    let mut spikes_lists = Vec::new();
    let mut ibi_lists = Vec::new();
    let mut dur_lists = Vec::new();
    for &ch in &ordered {
        let ch_bursts: Vec<&SingleChannelBurst> =
            single.iter().copied().filter(|b| b.channel == ch).collect();
        spikes_lists.push(ch_bursts.iter().map(|b| b.num_spikes as f64).collect());
        ibi_lists.push(ch_bursts.iter().skip(1).map(|b| b.interburst_interval_ms).collect());
        dur_lists.push(ch_bursts.iter().map(|b| b.duration_ms).collect());
    }
    let nested =
        MultiStatType::new(options.single_burst_nested_inner, options.single_burst_nested_outer);
    let nested_title = nested.title();
    let ss = nested_pick(
        &spikes_lists,
        options.single_burst_nested_outer,
        options.single_burst_nested_inner,
    );
    let si = nested_pick(
        &ibi_lists,
        options.single_burst_nested_outer,
        options.single_burst_nested_inner,
    );
    let sd = nested_pick(
        &dur_lists,
        options.single_burst_nested_outer,
        options.single_burst_nested_inner,
    );

    let (botc_index, botc_area) = {
        #[cfg(feature = "correlation")]
        {
            botc_metrics(&report.correlogram, options.synchrony_window_ms)
        }
        #[cfg(not(feature = "correlation"))]
        {
            (f64::NAN, f64::NAN)
        }
    };

    let mb = if multi.is_empty() { f64::NAN } else { multi.len() as f64 };
    let ms = create_single_stat_map(&multi.iter().map(|b| b.num_spikes as f64).collect::<Vec<_>>())
        .get(options.multi_burst_agg);
    let mi = {
        let mut ibis = Vec::new();
        for w in multi.windows(2) {
            ibis.push(w[1].start_ms - w[0].end_ms);
        }
        create_single_stat_map(&ibis).get(options.multi_burst_agg)
    };
    let mp = create_single_stat_map(&multi.iter().map(|b| b.peak_rate_hz).collect::<Vec<_>>())
        .get(options.multi_burst_agg);
    let md =
        create_single_stat_map(&multi.iter().map(|b| b.end_ms - b.start_ms).collect::<Vec<_>>())
            .get(options.multi_burst_agg);

    let method_title = match report.asdr.method {
        crate::analysis::burst::MultiBurstMethod::RateThreshold => {
            "Array-wide spike detection rate (spikes/s)"
        }
        crate::analysis::burst::MultiBurstMethod::NetworkBurst => "Network burst product",
        crate::analysis::burst::MultiBurstMethod::Spikes => "Multi-ch # spikes series",
        crate::analysis::burst::MultiBurstMethod::ActiveChannels => "Multi-ch # active channels",
    };

    let rows = vec![
        row("ac", "Number of active channels", "-", n_active as f64),
        row("dr", method_title, "-", array_rate),
        row(
            "sb",
            "Single-ch burst - number of burst (bursts)",
            options.single_burst_agg.display_title(),
            sb_map.get(options.single_burst_agg),
        ),
        row("ss", "Single-ch burst - spikes in a burst (spikes)", &nested_title, ss),
        row("si", "Single-ch burst - interburst interval (ms)", &nested_title, si),
        row("sd", "Single-ch burst - duration (ms)", &nested_title, sd),
        row("ba", "BOTC - % burst synchrony area", "-", botc_area),
        row("bp", "BOTC - burst synchrony product", "-", botc_index),
        row("mb", "Multi-ch burst - number of burst (bursts)", "-", mb),
        row(
            "ms",
            "Multi-ch burst - spikes in a burst",
            options.multi_burst_agg.display_title(),
            ms,
        ),
        row(
            "mi",
            "Multi-ch burst - interburst interval (ms)",
            options.multi_burst_agg.display_title(),
            mi,
        ),
        row("mp", "Multi-ch burst - peak (spikes/s)", options.multi_burst_agg.display_title(), mp),
        row("md", "Multi-ch burst - duration (ms)", options.multi_burst_agg.display_title(), md),
    ];

    BurstResultTable { path: report.path.clone(), duration_sec, active_channels: n_active, rows }
}

fn row(
    map_label: &str,
    title: impl Into<String>,
    value_type: impl Into<String>,
    value: f64,
) -> ResultTableRow {
    ResultTableRow {
        map_label: map_label.into(),
        title: title.into(),
        value_type: value_type.into(),
        value: if value.is_finite() { Some(value) } else { None },
    }
}

fn filter_single<'a>(
    bursts: &'a [SingleChannelBurst],
    active: &std::collections::BTreeSet<usize>,
) -> Vec<&'a SingleChannelBurst> {
    bursts.iter().filter(|b| active.contains(&b.channel)).collect()
}

fn nested_pick(lists: &[Vec<f64>], outer: SingleStatType, inner: SingleStatType) -> f64 {
    let map = create_multi_stat_map(lists);
    let key = MultiStatType::new(inner, outer).map_label();
    map.get(&key).copied().unwrap_or(f64::NAN)
}

#[cfg(feature = "correlation")]
fn botc_metrics(cg: &BurstOnsetCorrelogram, window_ms: f64) -> (f64, f64) {
    let total: u64 = cg.counts.iter().map(|&c| c as u64).sum();
    if total == 0 {
        return (0.0, 0.0);
    }
    let sync: u64 = cg
        .lag_ms
        .iter()
        .zip(&cg.counts)
        .filter(|(&lag, _)| lag.abs() <= window_ms)
        .map(|(_, &c)| c as u64)
        .sum();
    let index = sync as f64 / total as f64;
    let area = index * sync as f64;
    (index, area)
}

/// % change from baseline (#1): `100 * first / current` (100 for #1 itself).
pub fn percent_change_from_first(first: f64, current: f64, is_first: bool) -> f64 {
    if is_first {
        return 100.0;
    }
    if !first.is_finite() || first == 0.0 || !current.is_finite() {
        return f64::NAN;
    }
    100.0 * first / current
}

/// One analyzed file column in a multi-file result table.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiFileResultColumn {
    pub label: String,
    pub path: std::path::PathBuf,
    pub table: BurstResultTable,
}

/// multi-file result table: raw values + `% change from #1` per metric.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiFileResultTable {
    pub columns: Vec<MultiFileResultColumn>,
}

/// Build a multi-file result table from already-computed per-file tables.
///
/// Row order follows the first table. Later tables are matched by `map_label`.
pub fn compare_burst_result_tables(columns: Vec<MultiFileResultColumn>) -> MultiFileResultTable {
    MultiFileResultTable { columns }
}

/// Analyze each path and assemble the multi-file result table.
pub fn run_result_table_compare(
    paths: &[impl AsRef<std::path::Path>],
    analysis: &crate::analysis::task::AnalysisOptions,
    table_opts: &ResultTableOptions,
) -> crate::error::Result<MultiFileResultTable> {
    let mut columns = Vec::with_capacity(paths.len());
    for path in paths {
        let path = path.as_ref();
        let report = crate::analysis::task::run_analysis(path, analysis)?;
        let table = compute_burst_result_table(&report, table_opts);
        let label = path
            .file_stem()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_else(|| path.display().to_string());
        columns.push(MultiFileResultColumn { label, path: path.to_path_buf(), table });
    }
    Ok(compare_burst_result_tables(columns))
}

impl MultiFileResultTable {
    /// Raw value for metric `map_label` in column `col`, or NaN if missing.
    pub fn raw_value(&self, col: usize, map_label: &str) -> f64 {
        self.columns
            .get(col)
            .and_then(|c| c.table.rows.iter().find(|r| r.map_label == map_label))
            .map(|r| r.value.unwrap_or(f64::NAN))
            .unwrap_or(f64::NAN)
    }

    /// `% change from #1` for metric `map_label` in column `col`.
    pub fn percent_change(&self, col: usize, map_label: &str) -> f64 {
        let first = self.raw_value(0, map_label);
        let current = self.raw_value(col, map_label);
        percent_change_from_first(first, current, col == 0)
    }

    /// Metric row metadata from the first file (title / value_type / map_label).
    pub fn metric_rows(&self) -> &[ResultTableRow] {
        self.columns.first().map(|c| c.table.rows.as_slice()).unwrap_or(&[])
    }
}

/// Interactive MultiFileResultTable HTML (contenteditable % change).
pub fn write_result_table_interactive_html(
    table: &MultiFileResultTable,
    path: impl AsRef<std::path::Path>,
) -> crate::error::Result<()> {
    use std::io::Write;
    let path = path.as_ref();
    let mut html = String::from(
        r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>Result table</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>Multi-file result table</h1><table id="t"><thead><tr><th>Metric</th>"#,
    );
    for (i, col) in table.columns.iter().enumerate() {
        html.push_str(&format!("<th>#{} {}</th><th>%chg</th>", i + 1, col.label));
    }
    html.push_str("</tr></thead><tbody>");
    for metric in table.metric_rows() {
        html.push_str(&format!("<tr data-m=\"{}\"><td>{}</td>", metric.map_label, metric.title));
        for (ci, _) in table.columns.iter().enumerate() {
            let v = table.raw_value(ci, &metric.map_label);
            let pct = table.percent_change(ci, &metric.map_label);
            html.push_str(&format!(
                "<td contenteditable=\"true\" class=\"v\">{v:.4}</td><td class=\"pct\">{pct:.2}</td>",
                v = if v.is_finite() { v } else { 0.0 },
                pct = if pct.is_finite() { pct } else { 0.0 }
            ));
        }
        html.push_str("</tr>");
    }
    html.push_str(
        r#"</tbody></table>
<script>
function recompute(){
  document.querySelectorAll('#t tbody tr').forEach(tr=>{
    const vs=[...tr.querySelectorAll('.v')];
    const first=parseFloat(vs[0]?.textContent)||0;
    vs.forEach((td,i)=>{
      const cur=parseFloat(td.textContent)||0;
      const pct=i===0?100:(cur===0?0:(first/cur)*100);
      td.nextElementSibling.textContent=pct.toFixed(2);
    });
  });
}
document.getElementById('t').addEventListener('input',recompute);
</script></body></html>"#,
    );
    let mut f = std::fs::File::create(path)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })?;
    f.write_all(html.as_bytes())
        .map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })?;
    Ok(())
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AmplitudeRankRow {
    pub rank: usize,
    pub channel: usize,
    pub direction: SpikeDirection,
    pub peak_mv: f64,
    pub time_ms: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AmplitudeRankReport {
    pub rows: Vec<AmplitudeRankRow>,
}

/// Rank spikes by absolute amplitude (`SpikeAmplitudeFreq` / amplitude histogram companion).
pub fn amplitude_rank_report(report: &AnalysisReport, top_n: usize) -> AmplitudeRankReport {
    let mut rows: Vec<AmplitudeRankRow> = report
        .spikes
        .spikes
        .iter()
        .map(|s| AmplitudeRankRow {
            rank: 0,
            channel: s.channel,
            direction: s.direction,
            peak_mv: s.peak_mv,
            time_ms: s.within_trace_time_ms,
        })
        .collect();
    rows.sort_by(|a, b| {
        b.peak_mv
            .abs()
            .partial_cmp(&a.peak_mv.abs())
            .unwrap()
            .then(a.time_ms.partial_cmp(&b.time_ms).unwrap())
    });
    rows.truncate(top_n.max(1));
    for (i, row) in rows.iter_mut().enumerate() {
        row.rank = i + 1;
    }
    AmplitudeRankReport { rows }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn single_stat_sample_sd() {
        let m = create_single_stat_map(&[1.0, 2.0, 3.0]);
        assert!((m.mean - 2.0).abs() < 1e-12);
        assert!((m.median - 2.0).abs() < 1e-12);
        assert!((m.sd - 1.0).abs() < 1e-12);
        assert!((m.cv - 0.5).abs() < 1e-12);
    }

    #[test]
    fn multi_stat_mean_mean() {
        let map = create_multi_stat_map(&[vec![1.0, 3.0], vec![5.0, 7.0]]);
        // per-ch means: 2 and 6 → mean_mean = 4
        assert!((map["mn_mn"] - 4.0).abs() < 1e-12);
    }

    #[test]
    fn multi_stat_median_of_means_is_mn_md() {
        // ch0 mean=2, ch1 mean=6 → median of means = 4, key mn_md
        let map = create_multi_stat_map(&[vec![1.0, 3.0], vec![5.0, 7.0]]);
        assert!((map["mn_md"] - 4.0).abs() < 1e-12);
        assert_eq!(
            MultiStatType::new(SingleStatType::Mean, SingleStatType::Median).map_label(),
            "mn_md"
        );
    }

    #[test]
    fn percent_change_baseline_formula() {
        assert!((percent_change_from_first(10.0, 10.0, true) - 100.0).abs() < 1e-9);
        assert!((percent_change_from_first(10.0, 5.0, false) - 200.0).abs() < 1e-9);
    }

    #[test]
    fn multi_file_percent_change_from_first_column() {
        fn col(label: &str, ac: f64, dr: f64) -> MultiFileResultColumn {
            MultiFileResultColumn {
                label: label.into(),
                path: std::path::PathBuf::from(label),
                table: BurstResultTable {
                    path: std::path::PathBuf::from(label),
                    duration_sec: 1.0,
                    active_channels: ac as usize,
                    rows: vec![
                        row("ac", "Number of Active Channels", "", ac),
                        row("dr", "Array-wide Spike Detection Rate", "spikes/sec/channel", dr),
                    ],
                },
            }
        }
        let table =
            compare_burst_result_tables(vec![col("control", 64.0, 10.0), col("drug", 64.0, 5.0)]);
        assert!((table.percent_change(0, "dr") - 100.0).abs() < 1e-9);
        assert!((table.percent_change(1, "dr") - 200.0).abs() < 1e-9);
        assert!((table.percent_change(1, "ac") - 100.0).abs() < 1e-9);
    }
}