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
//! Cardiac beat / FPD detection (beat detector).

use serde::{Deserialize, Serialize};

use crate::analysis::{run_analysis, AnalysisOptions};
use crate::error::{Med64Error, Result};
use crate::export::write_filtered_raw_csv;
use crate::export_waveform::{
    write_filtered_i16_binary, write_filtered_waveforms, FilteredExportOptions,
};
use crate::toolkit::spectrum::load_channel_mv;
use crate::toolkit::voltage_chart::write_filtered_f64_binary;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone)]
pub struct BeatOptions {
    pub channel: usize,
    pub max_blocks: Option<usize>,
    pub plus_threshold_mv: f64,
    pub minus_threshold_mv: f64,
    pub refractory_ms: f64,
    /// Optional smoothing flag from `conf_beatdetectorsetting` (stored; detection uses thresholds).
    pub smoothing: bool,
}

impl Default for BeatOptions {
    fn default() -> Self {
        Self {
            channel: 0,
            max_blocks: Some(50),
            plus_threshold_mv: 0.2,
            minus_threshold_mv: -0.2,
            refractory_ms: 200.0,
            smoothing: false,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Beat {
    pub depolarization_ms: f64,
    pub repolarization_ms: Option<f64>,
    pub fpd_ms: Option<f64>,
    pub isi_ms: Option<f64>,
    pub amplitude_mv: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BeatReport {
    pub path: std::path::PathBuf,
    pub channel: usize,
    pub beats: Vec<Beat>,
    pub mean_isi_ms: f64,
    pub mean_fpd_ms: f64,
    pub rate_bpm: f64,
    /// Blocks analyzed (for waveform re-export).
    #[serde(default)]
    pub max_blocks: Option<usize>,
}

/// Export matrix for Beat/FPD package writer.
#[derive(Debug, Clone)]
pub struct BeatExportOptions {
    pub filterexport: bool,
    pub rawdataexport: bool,
    pub binary_shorts: bool,
    pub binary_doubles: bool,
    pub ascii_csv: bool,
    pub mobius_modat: bool,
    pub hdf5: bool,
    /// Write `{name}_SpikeTimeStamp.csv` from beat depolarization times (default true).
    pub timestamps: bool,
    pub name: String,
}

impl Default for BeatExportOptions {
    fn default() -> Self {
        Self {
            filterexport: false,
            rawdataexport: false,
            binary_shorts: false,
            binary_doubles: false,
            ascii_csv: false,
            mobius_modat: false,
            hdf5: false,
            timestamps: true,
            name: "beat".into(),
        }
    }
}

/// Detect field-potential beats and field-potential duration (FPD).
pub fn detect_beats(path: impl AsRef<Path>, options: &BeatOptions) -> Result<BeatReport> {
    let path = path.as_ref();
    let (header, samples) = load_channel_mv(path, options.channel, options.max_blocks)?;
    let interval = header.interval_ms();
    let refractory = (options.refractory_ms / interval).round().max(1.0) as usize;

    let mut beats = Vec::new();
    let mut i = 1usize;
    let mut last_peak = -(refractory as isize);
    while i + 1 < samples.len() {
        let v = samples[i];
        if v >= options.plus_threshold_mv
            && samples[i] >= samples[i - 1]
            && samples[i] >= samples[i + 1]
            && (i as isize) >= last_peak + refractory as isize
        {
            let depol = i as f64 * interval;
            let mut repo = None;
            let search_end = (i + refractory).min(samples.len());
            for j in i + 1..search_end {
                if samples[j] <= options.minus_threshold_mv
                    && j + 1 < samples.len()
                    && samples[j] <= samples[j - 1]
                    && samples[j] <= samples[j + 1]
                {
                    repo = Some(j as f64 * interval);
                    break;
                }
            }
            let isi = beats.last().map(|b: &Beat| depol - b.depolarization_ms);
            beats.push(Beat {
                depolarization_ms: depol,
                repolarization_ms: repo,
                fpd_ms: repo.map(|r| r - depol),
                isi_ms: isi,
                amplitude_mv: v,
            });
            last_peak = i as isize;
            i += refractory / 2;
            continue;
        }
        i += 1;
    }

    let isis: Vec<f64> = beats.iter().filter_map(|b| b.isi_ms).collect();
    let fpds: Vec<f64> = beats.iter().filter_map(|b| b.fpd_ms).collect();
    let mean_isi = mean(&isis);
    let mean_fpd = mean(&fpds);
    let rate_bpm = if mean_isi > 0.0 { 60_000.0 / mean_isi } else { 0.0 };

    Ok(BeatReport {
        path: path.to_path_buf(),
        channel: options.channel,
        beats,
        mean_isi_ms: mean_isi,
        mean_fpd_ms: mean_fpd,
        rate_bpm,
        max_blocks: options.max_blocks,
    })
}

fn mean(xs: &[f64]) -> f64 {
    if xs.is_empty() {
        0.0
    } else {
        xs.iter().sum::<f64>() / xs.len() as f64
    }
}

/// Write beat events CSV (`depolarization_ms`, amplitude, optional FPD/ISI).
pub fn write_beat_csv(report: &BeatReport, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let mut w =
        String::from("index,depolarization_ms,repolarization_ms,fpd_ms,isi_ms,amplitude_mv\n");
    for (i, b) in report.beats.iter().enumerate() {
        w.push_str(&format!(
            "{},{:.3},{},{},{},{:.6}\n",
            i + 1,
            b.depolarization_ms,
            opt_f64(b.repolarization_ms),
            opt_f64(b.fpd_ms),
            opt_f64(b.isi_ms),
            b.amplitude_mv
        ));
    }
    std::fs::write(path, w)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// Beats with explicit `fpd_ms` and `isi_ms` columns (FPD/ISI package).
pub fn write_beat_fpd_isi_csv(report: &BeatReport, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let mut w = String::from("beat,depolarization_ms,fpd_ms,isi_ms\n");
    for (i, b) in report.beats.iter().enumerate() {
        w.push_str(&format!(
            "{},{:.3},{},{}\n",
            i + 1,
            b.depolarization_ms,
            opt_f64(b.fpd_ms),
            opt_f64(b.isi_ms)
        ));
    }
    std::fs::write(path, w)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// Simple HTML dashboard: rate, mean FPD/ISI, FPD vs ISI scatter, timeline.
pub fn write_beat_html(report: &BeatReport, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let scatter: Vec<_> = report
        .beats
        .iter()
        .filter_map(|b| match (b.fpd_ms, b.isi_ms) {
            (Some(fpd), Some(isi)) => Some(serde_json::json!({"fpd": fpd, "isi": isi})),
            _ => None,
        })
        .collect();
    let timeline: Vec<_> = report
        .beats
        .iter()
        .map(|b| {
            serde_json::json!({
                "t": b.depolarization_ms,
                "fpd": b.fpd_ms,
                "amp": b.amplitude_mv,
            })
        })
        .collect();
    let html = format!(
        r##"<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Beat / FPD</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.35rem;margin:0 0 .25rem}} .sub{{color:#64748b;margin-bottom:1rem}}
.stats{{display:flex;gap:1.5rem;flex-wrap:wrap;margin-bottom:1.25rem}}
.stat{{background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:.75rem 1rem;min-width:8rem}}
.stat b{{display:block;font-size:1.25rem}} .stat span{{font-size:.75rem;color:#64748b}}
section{{margin:1.25rem 0;padding:1rem;background:#fff;border:1px solid #e2e8f0;border-radius:8px}}
canvas{{max-width:100%}}
</style></head><body>
<h1>Beat / FPD detector</h1>
<div class="sub">{src} · ch{ch} · {n} beats</div>
<div class="stats">
  <div class="stat"><b>{rate:.1}</b><span>Rate (BPM)</span></div>
  <div class="stat"><b>{mfpd:.1}</b><span>Mean FPD (ms)</span></div>
  <div class="stat"><b>{misi:.1}</b><span>Mean ISI (ms)</span></div>
</div>
<section><h2>FPD vs ISI</h2><canvas id="scatter" height="140"></canvas></section>
<section><h2>Beat timeline</h2><canvas id="tl" height="100"></canvas></section>
<script>
const scatter = {scatter_json};
const timeline = {timeline_json};
new Chart(document.getElementById('scatter'), {{
  type: 'scatter',
  data: {{ datasets: [{{
    label: 'FPD vs ISI',
    data: scatter.map(p => ({{x:p.isi, y:p.fpd}})),
    pointRadius: 3,
    backgroundColor: 'rgba(37,99,235,.55)'
  }}] }},
  options: {{
    plugins: {{ legend: {{ display: false }} }},
    scales: {{
      x: {{ title: {{ display: true, text: 'ISI (ms)' }} }},
      y: {{ title: {{ display: true, text: 'FPD (ms)' }} }}
    }}
  }}
}});
new Chart(document.getElementById('tl'), {{
  type: 'scatter',
  data: {{ datasets: [{{
    label: 'amplitude',
    data: timeline.map(p => ({{x:p.t, y:p.amp}})),
    pointRadius: 2.5,
    backgroundColor: 'rgba(220,38,38,.55)'
  }}] }},
  options: {{
    plugins: {{ legend: {{ display: false }} }},
    scales: {{
      x: {{ title: {{ display: true, text: 'Time (ms)' }} }},
      y: {{ title: {{ display: true, text: 'Amplitude (mV)' }} }}
    }}
  }}
}});
</script>
</body></html>"##,
        src = report.path.display(),
        ch = report.channel + 1,
        n = report.beats.len(),
        rate = report.rate_bpm,
        mfpd = report.mean_fpd_ms,
        misi = report.mean_isi_ms,
        scatter_json = serde_json::to_string(&scatter).unwrap_or_else(|_| "[]".into()),
        timeline_json = serde_json::to_string(&timeline).unwrap_or_else(|_| "[]".into()),
    );
    std::fs::write(path, html)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

fn needs_waveforms(options: &BeatExportOptions) -> bool {
    options.filterexport
        || options.rawdataexport
        || options.binary_shorts
        || options.binary_doubles
        || options.ascii_csv
        || options.mobius_modat
        || options.hdf5
}

/// Write the full Beat/FPD package under `out_dir`.
pub fn write_beat_package(
    report: &BeatReport,
    out_dir: impl AsRef<Path>,
    options: &BeatExportOptions,
) -> 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 outs = Vec::new();
    let csv = dir.join("beats.csv");
    write_beat_csv(report, &csv)?;
    outs.push(csv);
    let fpd = dir.join("beat_fpd_isi.csv");
    write_beat_fpd_isi_csv(report, &fpd)?;
    outs.push(fpd);
    let html = dir.join("beat.html");
    write_beat_html(report, &html)?;
    outs.push(html);

    // Peakline-style FPD/ISI TSV.
    let peakline = dir.join("peakline_fpd_isi.tsv");
    {
        let mut w = String::from("beat\tdepolarization_ms\tfpd_ms\tisi_ms\n");
        for (i, b) in report.beats.iter().enumerate() {
            w.push_str(&format!(
                "{}\t{:.3}\t{}\t{}\n",
                i + 1,
                b.depolarization_ms,
                opt_f64(b.fpd_ms),
                opt_f64(b.isi_ms)
            ));
        }
        std::fs::write(&peakline, w)
            .map_err(|source| Med64Error::WriteIo { path: peakline.clone(), source })?;
        outs.push(peakline);
    }

    if options.timestamps {
        let ts = dir.join(format!("{}_SpikeTimeStamp.csv", options.name));
        let mut w = String::from("channel,time_ms\n");
        for b in &report.beats {
            w.push_str(&format!("{},{:.6}\n", report.channel + 1, b.depolarization_ms));
        }
        std::fs::write(&ts, w)
            .map_err(|source| Med64Error::WriteIo { path: ts.clone(), source })?;
        outs.push(ts);
    }

    if needs_waveforms(options) {
        let mut analysis_opts = AnalysisOptions {
            max_blocks: report.max_blocks.or(Some(50)),
            retain_filtered: true,
            ..AnalysisOptions::reference()
        };
        // Prefer BeatOptions max_blocks already on report.
        let analysis = run_analysis(&report.path, &analysis_opts)?;

        if options.filterexport {
            let p = dir.join("filterexport.csv");
            write_filtered_raw_csv(&analysis, &p)?;
            outs.push(p);
        }
        if options.rawdataexport {
            let p = dir.join("rawdataexport.csv");
            write_filtered_raw_csv(&analysis, &p)?;
            outs.push(p);
            let raw_bin = dir.join(format!("{}_raw.i16.bin", options.name));
            write_raw_i16_export(&report.path, analysis_opts.max_blocks, &raw_bin)?;
            outs.push(raw_bin);
        }
        if options.binary_shorts {
            let p = dir.join(format!("{}_filtered.i16.bin", options.name));
            write_filtered_i16_binary(&analysis, &p)?;
            outs.push(p);
        }
        if options.binary_doubles {
            let p = dir.join(format!("{}_filtered.f64.bin", options.name));
            write_filtered_f64_binary(&analysis, &p)?;
            outs.push(p);
        }
        if options.ascii_csv || options.mobius_modat {
            let filt = write_filtered_waveforms(
                &analysis,
                dir,
                &options.name,
                &FilteredExportOptions {
                    write_i16: false,
                    write_f32: false,
                    write_csv: options.ascii_csv,
                    write_modat: options.mobius_modat,
                    points_per_block: 0,
                },
            )?;
            outs.extend(filt.paths);
        }
        if options.hdf5 {
            let p = dir.join(format!("{}.h5", options.name));
            #[cfg(feature = "hdf5")]
            {
                use crate::export::{write_spike_hdf5, SpikeHdf5Options};
                write_spike_hdf5(&analysis, &p, &SpikeHdf5Options::default())?;
                outs.push(p);
            }
            #[cfg(not(feature = "hdf5"))]
            {
                let _ = p;
                let _ = &analysis;
            }
        }
        let _ = &mut analysis_opts;
    }

    Ok(outs)
}

fn write_raw_i16_export(
    path: &Path,
    max_blocks: Option<usize>,
    out: impl AsRef<Path>,
) -> Result<()> {
    use crate::recording::Recording;
    let out = out.as_ref();
    let mut rec = Recording::open(path)?;
    let mut bytes = Vec::new();
    for (bi, block) in rec.blocks().enumerate() {
        if max_blocks.is_some_and(|m| bi >= m) {
            break;
        }
        let block = block?;
        for row in &block.samples {
            for &s in row {
                bytes.extend_from_slice(&s.to_le_bytes());
            }
        }
    }
    std::fs::write(out, bytes)
        .map_err(|source| Med64Error::WriteIo { path: out.to_path_buf(), source })
}

fn opt_f64(v: Option<f64>) -> String {
    v.map(|x| format!("{x:.3}")).unwrap_or_default()
}

#[cfg(test)]
mod tests {
    #[test]
    fn finds_synthetic_beats() {
        let mut samples = vec![0.0_f64; 3000];
        for peak in [500usize, 1500, 2500] {
            samples[peak] = 1.0;
            if peak + 80 < samples.len() {
                samples[peak + 80] = -0.5;
            }
        }
        let mut beats = 0;
        let mut last = -1000isize;
        for i in 1..samples.len() - 1 {
            if samples[i] >= 0.2
                && samples[i] >= samples[i - 1]
                && samples[i] >= samples[i + 1]
                && i as isize >= last + 200
            {
                beats += 1;
                last = i as isize;
            }
        }
        assert_eq!(beats, 3);
    }
}