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
//! spike detector variant 3 — 4-well ASDR freq map + Schmitt network bursts
//! (`spikedetectorvariant3` CreateFreqMap / DetectBurst / MapCreator).

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

use serde::{Deserialize, Serialize};

use crate::analysis::burst::calc_moving_average;
use crate::analysis::spike::SpikeTrain;
use crate::analysis::{run_analysis, AnalysisReport, AutoThresholdBase};
use crate::error::{Med64Error, Result};
use crate::header::Med64Header;
use crate::toolkit::spike_detector::{
    analysis_options_from, compute_threshold_table, SpikeDetectorOptions, SpikePolarity,
};

/// MED64 standard: 4 wells × 16 channels (1-based ch 1–16 … 49–64).
pub const WELLS_4X16: usize = 4;
pub const CH_PER_WELL: usize = 16;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum AsdrValueType {
    #[default]
    Asdr,
    SpikeCount,
}

#[derive(Debug, Clone)]
pub struct FourWellAsdrOptions {
    pub bin_ms: f64,
    pub smooth_bin: usize,
    pub value_type: AsdrValueType,
    /// Schmitt: lower = upper/2; Normal: lower = upper.
    pub schmitt: bool,
    pub auto_base: AutoThresholdBase,
    /// Toolkit default 300%.
    pub auto_percent: f64,
    /// Optional per-well (upper, lower) integer thresholds.
    pub manual_thresholds: Option<[(i32, i32); WELLS_4X16]>,
    pub mintime_ms: f64,
    pub maxtime_ms: Option<f64>,
    pub spike: SpikeDetectorOptions,
}

impl Default for FourWellAsdrOptions {
    fn default() -> Self {
        Self {
            bin_ms: 50.0,
            smooth_bin: 10,
            value_type: AsdrValueType::Asdr,
            schmitt: true,
            auto_base: AutoThresholdBase::Mean,
            auto_percent: 300.0,
            manual_thresholds: None,
            mintime_ms: 0.0,
            maxtime_ms: None,
            spike: SpikeDetectorOptions {
                polarity: SpikePolarity::MinusOnly,
                ..SpikeDetectorOptions::toolkit_default()
            },
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FreqSeries {
    pub well: usize,
    pub start_ms: Vec<f64>,
    pub end_ms: Vec<f64>,
    pub freq_hz: Vec<f64>,
    pub spike_count: Vec<usize>,
    pub smooth: Vec<f64>,
    pub upper: i32,
    pub lower: i32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WellBurst {
    pub well: usize,
    pub start_ms: f64,
    pub duration_ms: f64,
    pub end_ms: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FourWellAsdrReport {
    pub path: PathBuf,
    pub spike_count: usize,
    pub wells: Vec<FreqSeries>,
    pub bursts: Vec<WellBurst>,
    pub summary: BTreeMap<String, String>,
}

/// 0-based channel → well index 0..3 for MED64 4×16.
pub fn well_of_channel(channel: usize) -> Option<usize> {
    if channel >= 64 {
        return None;
    }
    Some(channel / CH_PER_WELL)
}

#[allow(dead_code)]
pub fn channels_in_well(well: usize) -> impl Iterator<Item = usize> {
    let start = well * CH_PER_WELL;
    start..(start + CH_PER_WELL)
}

pub fn run_four_well_asdr(
    path: impl AsRef<Path>,
    options: &FourWellAsdrOptions,
) -> Result<FourWellAsdrReport> {
    let path = path.as_ref();
    let thresholds = compute_threshold_table(path, &options.spike)?;
    let analysis_opts = analysis_options_from(&options.spike, &thresholds);
    let analysis = run_analysis(path, &analysis_opts)?;
    Ok(four_well_asdr_from_analysis(&analysis, options))
}

pub fn four_well_asdr_from_analysis(
    analysis: &AnalysisReport,
    options: &FourWellAsdrOptions,
) -> FourWellAsdrReport {
    let max_ms = options.maxtime_ms.unwrap_or_else(|| {
        analysis
            .spikes
            .spikes
            .iter()
            .map(|s| s.within_trace_time_ms)
            .fold(analysis.header.real_trace_duration_ms, f64::max)
            .max(options.mintime_ms + options.bin_ms)
    });
    let wells = create_freq_map(&analysis.spikes, options.mintime_ms, max_ms, options);
    let bursts = detect_well_bursts(&wells, options);
    let summary = burst_summary_map(
        &analysis.path,
        &analysis.header,
        &analysis.spikes,
        &wells,
        &bursts,
        options,
    );
    FourWellAsdrReport {
        path: analysis.path.clone(),
        spike_count: analysis.spikes.len(),
        wells,
        bursts,
        summary,
    }
}

/// `CreateFreqMap.createfreqmap` for 4 wells.
pub fn create_freq_map(
    train: &SpikeTrain,
    mintime_ms: f64,
    maxtime_ms: f64,
    options: &FourWellAsdrOptions,
) -> Vec<FreqSeries> {
    let bin = options.bin_ms.max(1.0);
    let n_bins = ((maxtime_ms - mintime_ms) / bin).floor() as usize;
    let n_bins = n_bins.max(1);
    let mut out = Vec::with_capacity(WELLS_4X16);

    for well in 0..WELLS_4X16 {
        let mut freq = vec![0.0_f64; n_bins];
        let mut counts = vec![0usize; n_bins];
        let mut start_ms = Vec::with_capacity(n_bins);
        let mut end_ms = Vec::with_capacity(n_bins);
        for i in 0..n_bins {
            start_ms.push(mintime_ms + i as f64 * bin);
            end_ms.push(mintime_ms + (i + 1) as f64 * bin);
        }
        for sp in &train.spikes {
            let Some(w) = well_of_channel(sp.channel) else {
                continue;
            };
            if w != well {
                continue;
            }
            let t = sp.within_trace_time_ms;
            if t < mintime_ms || t > maxtime_ms {
                continue;
            }
            let j = ((t - mintime_ms) / bin) as usize;
            if j < n_bins {
                freq[j] += 1.0;
                counts[j] += 1;
            }
        }
        // ASDR scale: spikes → spikes/s
        for v in &mut freq {
            *v = *v * 1000.0 / bin;
        }
        let smooth = if options.smooth_bin == 0 {
            match options.value_type {
                AsdrValueType::Asdr => freq.clone(),
                AsdrValueType::SpikeCount => counts.iter().map(|&c| c as f64).collect(),
            }
        } else {
            let series: Vec<f64> = match options.value_type {
                AsdrValueType::Asdr => freq.clone(),
                AsdrValueType::SpikeCount => counts.iter().map(|&c| c as f64).collect(),
            };
            calc_moving_average(&series, options.smooth_bin)
        };

        let (upper, lower) = well_thresholds(&freq, &counts, well, options);
        out.push(FreqSeries {
            well,
            start_ms,
            end_ms,
            freq_hz: freq,
            spike_count: counts,
            smooth,
            upper,
            lower,
        });
    }
    out
}

fn well_thresholds(
    freq: &[f64],
    counts: &[usize],
    well: usize,
    options: &FourWellAsdrOptions,
) -> (i32, i32) {
    if let Some(manual) = options.manual_thresholds {
        return manual[well];
    }
    let series: Vec<f64> = match options.value_type {
        AsdrValueType::Asdr => freq.to_vec(),
        AsdrValueType::SpikeCount => counts.iter().map(|&c| c as f64).collect(),
    };
    // Toolkit: base / 0.6745 * percent / 100 for BOTH mean and median.
    let base = match options.auto_base {
        AutoThresholdBase::Mean | AutoThresholdBase::PopulationSd => {
            if series.is_empty() {
                0.0
            } else {
                series.iter().sum::<f64>() / series.len() as f64
            }
        }
        AutoThresholdBase::MedianMad => {
            let mut sorted = series.clone();
            sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
            median_sorted(&sorted)
        }
    };
    let upper = (base / 0.6745 * options.auto_percent / 100.0) as i32;
    let lower = if options.schmitt { upper / 2 } else { upper };
    (upper, lower)
}

fn median_sorted(sorted: &[f64]) -> f64 {
    if sorted.is_empty() {
        return 0.0;
    }
    let n = sorted.len();
    if n % 2 == 0 {
        (sorted[n / 2 - 1] + sorted[n / 2]) / 2.0
    } else {
        sorted[n / 2]
    }
}

/// `DetectBurst.detectburst`: strict `>` enter, `<` exit; discard open bursts.
pub fn detect_well_bursts(wells: &[FreqSeries], options: &FourWellAsdrOptions) -> Vec<WellBurst> {
    let mut out = Vec::new();
    for series in wells {
        let values: Vec<f64> = if options.smooth_bin != 0 {
            series.smooth.clone()
        } else {
            match options.value_type {
                AsdrValueType::Asdr => series.freq_hz.clone(),
                AsdrValueType::SpikeCount => series.spike_count.iter().map(|&c| c as f64).collect(),
            }
        };
        let upper = series.upper as f64;
        let lower = series.lower as f64;
        let mut in_burst = false;
        let mut start_bin = 0usize;
        let mut starts: Vec<f64> = Vec::new();
        let mut durations: Vec<f64> = Vec::new();

        for (i, &v) in values.iter().enumerate() {
            if !v.is_finite() {
                continue;
            }
            if !in_burst {
                if v > upper {
                    in_burst = true;
                    start_bin = i;
                    starts.push(series.start_ms[i]);
                }
            } else if v < lower {
                durations.push(series.start_ms[i] - starts[starts.len() - 1]);
                in_burst = false;
            }
        }
        // Drop open burst with no end.
        if starts.len() > durations.len() {
            starts.pop();
        }
        for (s, d) in starts.into_iter().zip(durations) {
            out.push(WellBurst { well: series.well, start_ms: s, duration_ms: d, end_ms: s + d });
            let _ = start_bin;
        }
    }
    out
}

fn burst_summary_map(
    path: &Path,
    header: &Med64Header,
    train: &SpikeTrain,
    wells: &[FreqSeries],
    bursts: &[WellBurst],
    options: &FourWellAsdrOptions,
) -> BTreeMap<String, String> {
    let mut m = BTreeMap::new();
    m.insert(
        "Filename".into(),
        path.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(),
    );
    m.insert("Trace".into(), "1".into());
    m.insert("Chs".into(), header.active_channel_indices().len().to_string());
    m.insert("Wells".into(), WELLS_4X16.to_string());
    m.insert("TotalNumberOfSpikes".into(), train.len().to_string());
    m.insert("TotalOfBurst".into(), bursts.len().to_string());
    m.insert("Number of Network Bursts".into(), bursts.len().to_string());

    let durs: Vec<f64> = bursts.iter().map(|b| b.duration_ms).collect();
    insert_stats(&mut m, "Network Duration", &durs);

    let mut ibis = Vec::new();
    for well in 0..WELLS_4X16 {
        let mut wb: Vec<&WellBurst> = bursts.iter().filter(|b| b.well == well).collect();
        wb.sort_by(|a, b| a.start_ms.partial_cmp(&b.start_ms).unwrap());
        for w in wb.windows(2) {
            ibis.push(w[1].start_ms - w[0].end_ms);
        }
    }
    insert_stats(&mut m, "Network IBI", &ibis);

    let mut ibiss = Vec::new();
    for well in 0..WELLS_4X16 {
        let mut wb: Vec<&WellBurst> = bursts.iter().filter(|b| b.well == well).collect();
        wb.sort_by(|a, b| a.start_ms.partial_cmp(&b.start_ms).unwrap());
        for w in wb.windows(2) {
            ibiss.push(w[1].start_ms - w[0].start_ms);
        }
    }
    insert_stats(&mut m, "Network IBI (start to start)", &ibiss);

    // Spikes per burst (area under window).
    let mut area = Vec::new();
    for b in bursts {
        let n = train
            .spikes
            .iter()
            .filter(|s| {
                well_of_channel(s.channel) == Some(b.well)
                    && s.within_trace_time_ms >= b.start_ms
                    && s.within_trace_time_ms < b.end_ms
            })
            .count();
        area.push(n as f64);
    }
    insert_stats(&mut m, "Number of Spikes per Network Burst", &area);

    // Peak spikes in burst (max ASDR bin under each burst window).
    let mut peak_spikes = Vec::new();
    let mut elecs = Vec::new();
    let mut isi_within = Vec::new();
    let mut ipis = Vec::new();
    let mut spikes_per_ch = Vec::new();
    let mut in_burst_spike_count = 0usize;
    for b in bursts {
        let mut chs = std::collections::BTreeSet::new();
        let mut times = Vec::new();
        let mut peak = 0.0_f64;
        if let Some(series) = wells.get(b.well) {
            for (i, &t0) in series.start_ms.iter().enumerate() {
                if t0 >= b.start_ms && t0 < b.end_ms {
                    peak = peak.max(series.freq_hz[i]);
                    peak = peak.max(series.spike_count[i] as f64);
                }
            }
        }
        peak_spikes.push(peak);
        for s in &train.spikes {
            if well_of_channel(s.channel) == Some(b.well)
                && s.within_trace_time_ms >= b.start_ms
                && s.within_trace_time_ms < b.end_ms
            {
                chs.insert(s.channel);
                times.push(s.within_trace_time_ms);
                in_burst_spike_count += 1;
            }
        }
        elecs.push(chs.len() as f64);
        let n_ch = chs.len().max(1) as f64;
        spikes_per_ch.push(times.len() as f64 / n_ch);
        times.sort_by(|a, b| a.partial_cmp(b).unwrap());
        for w in times.windows(2) {
            isi_within.push(w[1] - w[0]);
        }
    }
    for well in 0..WELLS_4X16 {
        let mut wb: Vec<&WellBurst> = bursts.iter().filter(|b| b.well == well).collect();
        wb.sort_by(|a, b| a.start_ms.partial_cmp(&b.start_ms).unwrap());
        for w in wb.windows(2) {
            // IPI: inter-peak interval approx as start-to-start (Toolkit Network IPI).
            ipis.push(w[1].start_ms - w[0].start_ms);
        }
    }
    insert_stats(&mut m, "PeakSpikesinBurst", &peak_spikes);
    insert_stats(&mut m, "Number of Elecs Participation in Burst", &elecs);
    insert_stats(&mut m, "ISI within Network Burst", &isi_within);
    insert_stats(&mut m, "Network IPI", &ipis);
    insert_stats(&mut m, "Spikes per Network Burst per Channel", &spikes_per_ch);

    // MapCreator typo keys preserved for Toolkit CSV parity.
    if let Some(v) = m.get("Network IBI-Median").cloned() {
        m.insert("IBI-Meidan".into(), v);
    }
    if let Some(v) = m.get("Network Duration-CV").cloned() {
        m.insert("Duraiton-CV".into(), v);
    }

    let total_spikes = train.len().max(1) as f64;
    let pct_network = in_burst_spike_count as f64 / total_spikes * 100.0;
    let pct_isolated = 100.0 - pct_network;
    m.insert("NetworkBurstPercentage".into(), format!("{pct_network:.6}"));
    m.insert("PercentIsolatedSpikes".into(), format!("{pct_isolated:.6}"));

    // Normalized duration IQR.
    if durs.len() >= 4 {
        let mut sorted = durs.clone();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let q1 = sorted[sorted.len() / 4];
        let q3 = sorted[(sorted.len() * 3) / 4];
        let med = median_sorted(&sorted).max(1e-9);
        m.insert("Network Normalized Duration IQR".into(), format!("{:.6}", (q3 - q1) / med));
    } else {
        m.insert("Network Normalized Duration IQR".into(), "0".into());
    }

    let span_ms =
        options.maxtime_ms.unwrap_or(header.real_trace_duration_ms).max(1.0) - options.mintime_ms;
    let freq = if span_ms > 0.0 { bursts.len() as f64 / (span_ms / 1000.0) } else { 0.0 };
    m.insert("Network Burst Frequency".into(), format!("{freq:.6}"));

    for (i, w) in wells.iter().enumerate() {
        m.insert(format!("Well{}Upper", i + 1), w.upper.to_string());
        m.insert(format!("Well{}Lower", i + 1), w.lower.to_string());
        let wb = bursts.iter().filter(|b| b.well == i).count();
        m.insert(format!("Well{}Bursts", i + 1), wb.to_string());
    }
    m
}

fn insert_stats(map: &mut BTreeMap<String, String>, prefix: &str, values: &[f64]) {
    if values.is_empty() {
        map.insert(format!("{prefix}-Ave"), "0".into());
        map.insert(format!("{prefix}-SD"), "0".into());
        map.insert(format!("{prefix}-SEM"), "0".into());
        map.insert(format!("{prefix}-Median"), "0".into());
        map.insert(format!("{prefix}-CV"), "0".into());
        return;
    }
    let mean = values.iter().sum::<f64>() / values.len() as f64;
    let var = values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / values.len() as f64;
    let sd = var.sqrt();
    let sem = sd / (values.len() as f64).sqrt();
    let mut sorted = values.to_vec();
    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let med = median_sorted(&sorted);
    let cv = if mean.abs() > 1e-12 { sd / mean * 100.0 } else { 0.0 };
    map.insert(format!("{prefix}-Ave"), format!("{mean:.6}"));
    map.insert(format!("{prefix}-SD"), format!("{sd:.6}"));
    map.insert(format!("{prefix}-SEM"), format!("{sem:.6}"));
    map.insert(format!("{prefix}-Median"), format!("{med:.6}"));
    map.insert(format!("{prefix}-CV"), format!("{cv:.6}"));
}

pub fn write_burst_table_csv(report: &FourWellAsdrReport, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let mut out = String::from("key,value\n");
    for (k, v) in &report.summary {
        out.push_str(&format!("{},{}\n", csv_escape(k), csv_escape(v)));
    }
    std::fs::write(path, out)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

pub fn write_well_asdr_csv(report: &FourWellAsdrReport, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let mut out = String::from("well,time_ms,asdr_hz,smooth,spike_count\n");
    for w in &report.wells {
        for i in 0..w.start_ms.len() {
            let sm =
                if w.smooth[i].is_finite() { format!("{:.6}", w.smooth[i]) } else { String::new() };
            out.push_str(&format!(
                "{},{:.3},{:.6},{},{}\n",
                w.well + 1,
                w.start_ms[i],
                w.freq_hz[i],
                sm,
                w.spike_count[i]
            ));
        }
    }
    std::fs::write(path, out)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

pub fn write_well_bursts_csv(report: &FourWellAsdrReport, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let mut out = String::from("well,start_ms,duration_ms,end_ms\n");
    for b in &report.bursts {
        out.push_str(&format!(
            "{},{:.3},{:.3},{:.3}\n",
            b.well + 1,
            b.start_ms,
            b.duration_ms,
            b.end_ms
        ));
    }
    std::fs::write(path, out)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// Burst4well-style HTML: 2×2 ASDR charts with burst overlays (headless export).
pub fn write_burst4well_html(report: &FourWellAsdrReport, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let mut panels = String::new();
    for w in &report.wells {
        let xs: Vec<String> = w.start_ms.iter().map(|t| format!("{t:.1}")).collect();
        let ys: Vec<String> = w
            .freq_hz
            .iter()
            .map(|v| if v.is_finite() { format!("{v:.4}") } else { "null".into() })
            .collect();
        let bursts: Vec<String> = report
            .bursts
            .iter()
            .filter(|b| b.well == w.well)
            .map(|b| format!("[{:.1},{:.1}]", b.start_ms, b.end_ms))
            .collect();
        panels.push_str(&format!(
            r#"<div class="well"><h3>Well {} (upper={} lower={})</h3>
<canvas id="w{}"></canvas>
<script>
(() => {{
  const xs=[{xs}];
  const ys=[{ys}];
  const bursts=[{bursts}];
  const c=document.getElementById('w{id}');
  const ctx=c.getContext('2d');
  c.width=c.parentElement.clientWidth||480; c.height=160;
  const maxY=Math.max(1,...ys.filter(v=>v!=null));
  const minX=xs[0]||0, maxX=xs[xs.length-1]||1;
  const x=t=>(t-minX)/(maxX-minX||1)*(c.width-40)+30;
  const y=v=>c.height-20-(v/maxY)*(c.height-40);
  ctx.strokeStyle='#1a5f7a'; ctx.beginPath();
  for(let i=0;i<xs.length;i++){{
    if(ys[i]==null) continue;
    const X=x(xs[i]), Y=y(ys[i]);
    if(i===0) ctx.moveTo(X,Y); else ctx.lineTo(X,Y);
  }}
  ctx.stroke();
  ctx.fillStyle='rgba(200,60,60,0.18)';
  for(const [a,b] of bursts){{
    const X0=x(a), X1=x(b);
    ctx.fillRect(X0,10,Math.max(1,X1-X0),c.height-30);
  }}
  ctx.fillStyle='#333'; ctx.font='11px sans-serif';
  ctx.fillText('ASDR spikes/s', 8, 12);
}})();
</script></div>
"#,
            w.well + 1,
            w.upper,
            w.lower,
            w.well,
            xs = xs.join(","),
            ys = ys.join(","),
            bursts = bursts.join(","),
            id = w.well,
        ));
    }
    let html = format!(
        r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>Burst4well</title>
<style>
body{{font-family:system-ui,sans-serif;margin:16px;background:#f7f7f7}}
.grid{{display:grid;grid-template-columns:1fr 1fr;gap:12px}}
.well{{background:#fff;padding:8px 12px;border:1px solid #ddd}}
h3{{margin:0 0 6px;font-size:14px}}
canvas{{width:100%;background:#fafafa;border:1px solid #eee}}
</style></head><body>
<h2>Burst4well ASDR</h2>
<p>{} spikes · {} network bursts · {}</p>
<div class="grid">{}</div>
</body></html>"#,
        report.spike_count,
        report.bursts.len(),
        report.path.display(),
        panels
    );
    std::fs::write(path, html)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// Per-well workflow timestamp CSVs (`_Well1.csv` … `_Well4.csv`).
pub fn write_well_timestamp_csvs(
    analysis: &AnalysisReport,
    out_dir: impl AsRef<Path>,
    stem: &str,
) -> 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 h = &analysis.header;
    let mut paths = Vec::new();
    for well in 0..WELLS_4X16 {
        let path = dir.join(format!("{stem}_Well{}.csv", well + 1));
        let mut out = format!(
            "File Format Version,20071201\nSession Start Time,{}\nTrace Duration (ms),{:.3}\n",
            h.start_date_time(),
            h.real_trace_duration_ms
        ); // Session Start Time as epoch ms (numeric; reference formats calendar string)
        out.push_str(
            "channel,time_of_day,within_session_time,within_session_time_ms,within_trace_time_ms,cluster_id,trace_num,pre_ms,post_ms,y0_mV,y1_mV\n",
        );
        for sp in &analysis.spikes.spikes {
            if well_of_channel(sp.channel) != Some(well) {
                continue;
            }
            out.push_str(&format!(
                "{},,{:.6},{:.6},{:.6},0,{},,,,{:.6},\n",
                sp.channel + 1,
                sp.within_session_time_ms / 1000.0,
                sp.within_session_time_ms,
                sp.within_trace_time_ms,
                sp.trace + 1,
                sp.peak_mv
            ));
        }
        std::fs::write(&path, out)
            .map_err(|source| Med64Error::WriteIo { path: path.clone(), source })?;
        paths.push(path);
    }
    Ok(paths)
}

pub fn write_four_well_asdr_package(
    report: &FourWellAsdrReport,
    analysis: Option<&AnalysisReport>,
    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 paths = Vec::new();
    let table = dir.join("Burst Table.csv");
    write_burst_table_csv(report, &table)?;
    paths.push(table);
    let asdr = dir.join("well_asdr.csv");
    write_well_asdr_csv(report, &asdr)?;
    paths.push(asdr);
    let bursts = dir.join("well_bursts.csv");
    write_well_bursts_csv(report, &bursts)?;
    paths.push(bursts);
    let html = dir.join("burst4well.html");
    write_burst4well_html(report, &html)?;
    paths.push(html);
    if let Some(a) = analysis {
        let stem = report.path.file_stem().and_then(|s| s.to_str()).unwrap_or("spikes");
        paths.extend(write_well_timestamp_csvs(a, dir, stem)?);
    }
    Ok(paths)
}

fn csv_escape(s: &str) -> String {
    if s.contains(',') || s.contains('"') {
        format!("\"{}\"", s.replace('"', "\"\""))
    } else {
        s.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analysis::spike::{Spike, SpikeDirection};

    #[test]
    fn well_partition_and_schmitt_burst() {
        let mut train = SpikeTrain::default();
        // Dense spikes in well 0 (chs 0-15) mid-recording.
        for t in (500..800).step_by(2) {
            for ch in 0..8 {
                train.push(Spike {
                    channel: ch,
                    within_trace_time_ms: t as f64,
                    direction: SpikeDirection::Minus,
                    ..Default::default()
                });
            }
        }
        let opts = FourWellAsdrOptions {
            bin_ms: 50.0,
            smooth_bin: 0,
            schmitt: true,
            auto_percent: 50.0,
            manual_thresholds: Some([(5, 2); 4]),
            maxtime_ms: Some(1000.0),
            ..Default::default()
        };
        let wells = create_freq_map(&train, 0.0, 1000.0, &opts);
        assert_eq!(wells.len(), 4);
        assert!(wells[0].freq_hz.iter().any(|&v| v > 0.0));
        let bursts = detect_well_bursts(&wells, &opts);
        assert!(!bursts.is_empty(), "expected at least one well burst");
        assert!(bursts.iter().all(|b| b.well == 0 || b.duration_ms >= 0.0));
    }

    #[test]
    fn discards_open_burst() {
        let series = FreqSeries {
            well: 0,
            start_ms: vec![0.0, 50.0, 100.0, 150.0],
            end_ms: vec![50.0, 100.0, 150.0, 200.0],
            freq_hz: vec![0.0, 20.0, 20.0, 20.0],
            spike_count: vec![0, 1, 1, 1],
            smooth: vec![0.0, 20.0, 20.0, 20.0],
            upper: 10,
            lower: 5,
        };
        let opts = FourWellAsdrOptions { smooth_bin: 0, ..Default::default() };
        let bursts = detect_well_bursts(&[series], &opts);
        assert!(bursts.is_empty(), "open burst at EOF must be discarded, got {bursts:?}");
    }
}