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
//! Continuous Morlet wavelet transform (wavelet).

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 WaveletOptions {
    pub channel: usize,
    pub max_blocks: Option<usize>,
    pub f_min_hz: f64,
    pub f_max_hz: f64,
    pub n_per_octave: usize,
    pub sigma: f64,
    pub skip_samples: usize,
    pub max_time_points: usize,
}

impl Default for WaveletOptions {
    fn default() -> Self {
        Self {
            channel: 0,
            max_blocks: Some(5),
            f_min_hz: 10.0,
            f_max_hz: 200.0,
            n_per_octave: 4,
            sigma: 6.0,
            skip_samples: 4,
            max_time_points: 256,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WaveletBand {
    pub frequency_hz: f64,
    /// Power over time (downsampled).
    pub power: Vec<f64>,
    pub times_ms: Vec<f64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WaveletReport {
    pub path: std::path::PathBuf,
    pub channel: usize,
    pub bands: Vec<WaveletBand>,
    /// Blocks analyzed (for waveform re-export).
    #[serde(default)]
    pub max_blocks: Option<usize>,
}

/// Export matrix for Wavelet CreateImage package writer (mirrors Beta).
#[derive(Debug, Clone)]
pub struct WaveletExportOptions {
    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,
    pub name: String,
}

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

/// Morlet CWT power spectrogram (`WaveletAnalysis` style).
pub fn continuous_wavelet(
    path: impl AsRef<Path>,
    options: &WaveletOptions,
) -> Result<WaveletReport> {
    let path = path.as_ref();
    let (header, samples) = load_channel_mv(path, options.channel, options.max_blocks)?;
    let fs = header.sampling_frequency_hz;
    let freqs = log_spaced_freqs(options.f_min_hz, options.f_max_hz, options.n_per_octave);
    let step = options.skip_samples.max(1);
    let times: Vec<usize> =
        (0..samples.len()).step_by(step).take(options.max_time_points).collect();
    let times_ms: Vec<f64> = times.iter().map(|&i| i as f64 * 1000.0 / fs).collect();

    let mut bands = Vec::new();
    for &freq in &freqs {
        let scale = options.sigma / (2.0 * std::f64::consts::PI * freq);
        let mut power = Vec::with_capacity(times.len());
        for &t in &times {
            let (re, im) = morlet_coeff(&samples, t, fs, scale, options.sigma);
            power.push(re * re + im * im);
        }
        bands.push(WaveletBand { frequency_hz: freq, power, times_ms: times_ms.clone() });
    }
    Ok(WaveletReport {
        path: path.to_path_buf(),
        channel: options.channel,
        bands,
        max_blocks: options.max_blocks,
    })
}

/// CreateImage-style package: scalogram HTML, bands CSV, summary text.
pub fn write_wavelet_create_image(
    report: &WaveletReport,
    out_dir: impl AsRef<Path>,
) -> Result<Vec<std::path::PathBuf>> {
    let dir = out_dir.as_ref();
    std::fs::create_dir_all(dir)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: dir.to_path_buf(), source })?;
    let mut outs = Vec::new();

    let bands_csv = dir.join("bands.csv");
    {
        let mut w = String::from("frequency_hz,mean_power,max_power\n");
        for b in &report.bands {
            let mean = if b.power.is_empty() {
                0.0
            } else {
                b.power.iter().sum::<f64>() / b.power.len() as f64
            };
            let maxp = b.power.iter().copied().fold(0.0_f64, f64::max);
            w.push_str(&format!("{:.6},{:.8},{:.8}\n", b.frequency_hz, mean, maxp));
        }
        std::fs::write(&bands_csv, w).map_err(|source| crate::error::Med64Error::WriteIo {
            path: bands_csv.clone(),
            source,
        })?;
    }
    outs.push(bands_csv);

    let summary = dir.join("wavelet_summary.txt");
    {
        let n_t = report.bands.first().map(|b| b.power.len()).unwrap_or(0);
        let text = format!(
            "path: {}\nchannel: {}\nbands: {}\ntime_points: {}\nf_min_hz: {:.3}\nf_max_hz: {:.3}\n",
            report.path.display(),
            report.channel + 1,
            report.bands.len(),
            n_t,
            report.bands.first().map(|b| b.frequency_hz).unwrap_or(0.0),
            report.bands.last().map(|b| b.frequency_hz).unwrap_or(0.0),
        );
        std::fs::write(&summary, text).map_err(|source| crate::error::Med64Error::WriteIo {
            path: summary.clone(),
            source,
        })?;
    }
    outs.push(summary);

    let global_max =
        report.bands.iter().flat_map(|b| b.power.iter().copied()).fold(1e-12_f64, f64::max);
    let n_bands = report.bands.len().max(1);
    let n_t = report.bands.first().map(|b| b.power.len()).unwrap_or(1).max(1);
    let mut cells = String::new();
    for (bi, band) in report.bands.iter().enumerate() {
        for (ti, &p) in band.power.iter().enumerate() {
            let t = (p / global_max).clamp(0.0, 1.0);
            let r = (20.0 + 220.0 * t) as u8;
            let g = (30.0 + 100.0 * (1.0 - t)) as u8;
            let b = (80.0 + 140.0 * (1.0 - t)) as u8;
            cells.push_str(&format!(
                "<div class=\"c\" style=\"grid-row:{};grid-column:{};background:rgb({r},{g},{b})\" title=\"{:.1} Hz · p={:.4}\"></div>",
                n_bands - bi,
                ti + 1,
                band.frequency_hz,
                p
            ));
        }
    }
    let freq_labels: String = report
        .bands
        .iter()
        .enumerate()
        .map(|(i, b)| {
            format!(
                "<div style=\"grid-row:{};grid-column:1\">{:.0}</div>",
                n_bands - i,
                b.frequency_hz
            )
        })
        .collect();
    let scalogram = dir.join("scalogram.html");
    let html = format!(
        r#"<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Wavelet scalogram</title>
<style>
body{{font-family:system-ui;margin:1rem;background:#fafafa}}
.wrap{{display:grid;grid-template-columns:3rem 1fr;gap:4px;align-items:stretch;max-width:960px}}
.freqs{{display:grid;grid-template-rows:repeat({nb},1fr);font-size:.65rem;color:#64748b;text-align:right;padding-right:4px}}
.heat{{display:grid;grid-template-columns:repeat({nt},1fr);grid-template-rows:repeat({nb},1fr);gap:1px;background:#e2e8f0;min-height:280px}}
.c{{min-height:4px}}
</style></head><body>
<h1>Wavelet scalogram</h1>
<p>{} · ch{} · {nb} bands × {nt} time</p>
<div class="wrap">
  <div class="freqs">{freq}</div>
  <div class="heat">{cells}</div>
</div>
</body></html>"#,
        report.path.display(),
        report.channel + 1,
        nb = n_bands,
        nt = n_t,
        freq = freq_labels,
        cells = cells
    );
    std::fs::write(&scalogram, html)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: scalogram.clone(), source })?;
    outs.push(scalogram);

    let prefer = dir.join("wavelet_prefer.html");
    {
        let display = serde_json::json!({
            "channel": report.channel + 1,
            "bands": report.bands.len(),
            "times": report.bands.first().map(|b| b.times_ms.len()).unwrap_or(0),
        });
        let html = format!(
            r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>Wavelet Prefer</title>
<style>body{{font-family:system-ui;margin:1rem}}pre{{background:#f8fafc;padding:1rem}}</style></head>
<body><h1>Wavelet Prefer</h1>
<label>Preview scale <input id="scale" type="range" min="50" max="200" value="100"></label>
<pre>{opts}</pre>
<div id="preview">scalogram display options</div>
<script>document.getElementById('scale').oninput=e=>{{document.getElementById('preview').style.transform=`scale(${{e.target.value/100}})`;}};</script>
</body></html>"#,
            opts = serde_json::to_string_pretty(&display).unwrap_or_else(|_| "{}".into()),
        );
        std::fs::write(&prefer, html)
            .map_err(|source| crate::error::Med64Error::WriteIo { path: prefer.clone(), source })?;
        outs.push(prefer);
    }
    Ok(outs)
}

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

/// Write CreateImage package plus optional filtered/raw waveform exports.
pub fn write_wavelet_package(
    report: &WaveletReport,
    out_dir: impl AsRef<Path>,
    options: &WaveletExportOptions,
) -> Result<Vec<PathBuf>> {
    let mut outs = write_wavelet_create_image(report, &out_dir)?;
    let dir = out_dir.as_ref();

    if needs_waveforms(options) {
        let analysis_opts = AnalysisOptions {
            max_blocks: report.max_blocks.or(Some(40)),
            retain_filtered: true,
            ..AnalysisOptions::reference()
        };
        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;
            }
        }
    }

    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 })
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscreteWaveletReport {
    pub path: std::path::PathBuf,
    pub channel: usize,
    pub levels: usize,
    /// Approximation coefficients at the deepest level.
    pub approx: Vec<f64>,
    /// Detail coefficients per level (level 1 = finest).
    pub details: Vec<Vec<f64>>,
}

/// Haar discrete wavelet transform (DWT / wavelet discrete path).
pub fn discrete_wavelet(
    path: impl AsRef<Path>,
    channel: usize,
    levels: usize,
    max_blocks: Option<usize>,
) -> Result<DiscreteWaveletReport> {
    let path = path.as_ref();
    let (_header, samples) = load_channel_mv(path, channel, max_blocks)?;
    let (approx, details) = haar_dwt(&samples, levels.max(1));
    Ok(DiscreteWaveletReport {
        path: path.to_path_buf(),
        channel,
        levels: details.len(),
        approx,
        details,
    })
}

fn haar_dwt(samples: &[f64], levels: usize) -> (Vec<f64>, Vec<Vec<f64>>) {
    let mut approx = samples.to_vec();
    if approx.len() % 2 == 1 {
        approx.push(*approx.last().unwrap_or(&0.0));
    }
    let mut details = Vec::new();
    for _ in 0..levels {
        if approx.len() < 2 {
            break;
        }
        let mut next = Vec::with_capacity(approx.len() / 2);
        let mut detail = Vec::with_capacity(approx.len() / 2);
        for pair in approx.chunks_exact(2) {
            next.push((pair[0] + pair[1]) * std::f64::consts::FRAC_1_SQRT_2);
            detail.push((pair[0] - pair[1]) * std::f64::consts::FRAC_1_SQRT_2);
        }
        details.push(detail);
        approx = next;
        if approx.len() % 2 == 1 {
            approx.push(*approx.last().unwrap_or(&0.0));
        }
    }
    (approx, details)
}

fn log_spaced_freqs(f_min: f64, f_max: f64, n_per_octave: usize) -> Vec<f64> {
    if f_min <= 0.0 || f_max <= f_min {
        return vec![f_min.max(1.0)];
    }
    let octaves = (f_max / f_min).log2();
    let n = (octaves * n_per_octave as f64).ceil().max(1.0) as usize;
    (0..=n)
        .map(|i| f_min * 2.0_f64.powf(i as f64 / n_per_octave as f64))
        .filter(|&f| f <= f_max * 1.001)
        .collect()
}

fn morlet_coeff(samples: &[f64], center: usize, fs: f64, scale: f64, sigma: f64) -> (f64, f64) {
    let half = (scale * sigma * 3.0 * fs).ceil() as isize;
    let mut re = 0.0;
    let mut im = 0.0;
    let mut norm = 0.0;
    for dt in -half..=half {
        let idx = center as isize + dt;
        if idx < 0 || idx as usize >= samples.len() {
            continue;
        }
        let t = dt as f64 / fs;
        let env = (-0.5 * (t / scale).powi(2)).exp();
        let omega = sigma * t / scale;
        let w_re = env * omega.cos();
        let w_im = env * omega.sin();
        let x = samples[idx as usize];
        re += x * w_re;
        im += x * w_im;
        norm += env;
    }
    if norm > 0.0 {
        (re / norm, im / norm)
    } else {
        (0.0, 0.0)
    }
}

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

    #[test]
    fn freqs_are_log_spaced() {
        let f = log_spaced_freqs(10.0, 160.0, 2);
        assert!(f.first().copied().unwrap() <= 10.1);
        assert!(f.last().copied().unwrap() >= 80.0);
        assert!(f.len() >= 4);
    }

    #[test]
    fn haar_splits_constant_to_approx() {
        let (a, d) = haar_dwt(&[2.0, 2.0, 2.0, 2.0], 1);
        assert_eq!(d.len(), 1);
        assert!(d[0].iter().all(|v| v.abs() < 1e-12));
        assert!(a
            .iter()
            .all(|v| (v - 2.0 * std::f64::consts::SQRT_2).abs() < 1e-9 || (v - 2.0).abs() < 1.0));
    }

    #[test]
    fn wavelet_create_image_package() {
        let report = continuous_wavelet(
            crate::fixture_paths::sample_data1(),
            &WaveletOptions {
                max_blocks: Some(2),
                max_time_points: 32,
                n_per_octave: 2,
                ..Default::default()
            },
        )
        .unwrap();
        let dir = std::env::temp_dir().join("med64_wavelet_create_image_test");
        let _ = std::fs::remove_dir_all(&dir);
        let outs = write_wavelet_create_image(&report, &dir).unwrap();
        assert!(outs.iter().any(|p| p.ends_with("scalogram.html")));
        assert!(outs.iter().any(|p| p.ends_with("bands.csv")));
        assert!(dir.join("wavelet_summary.txt").is_file());
    }
}