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
//! Voltage amplitude / color-map grids (Voltage Color Map + STFT).

use serde::{Deserialize, Serialize};

use crate::error::{Med64Error, Result};
use crate::png::write_heatmap_png;
use crate::recording::Recording;
use crate::toolkit::spectrum::{apply_hum_filter, periodogram, HumNoiseRemoval, SpectrumWindow};
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PsdReduce {
    Mean,
    Max,
}

impl PsdReduce {
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "mean" | "avg" => Some(Self::Mean),
            "max" => Some(Self::Max),
            _ => None,
        }
    }
}

#[derive(Debug, Clone)]
pub struct VoltageMapOptions {
    pub max_blocks: Option<usize>,
    pub grid_cols: usize,
    pub grid_rows: usize,
    /// Sample index within the selected block; None = RMS over block.
    pub sample_index: Option<usize>,
    pub use_rms: bool,
    /// Subtract a linear trend per channel (`TrendCutter`).
    pub trend_cut: bool,
    /// When true, compute a time series of maps from STFT band power.
    pub stft: bool,
    pub stft_fft_size: usize,
    pub stft_overlap: f64,
    pub hum: HumNoiseRemoval,
    /// Keep every Nth sample when loading (1 = no downsample).
    pub downsample: usize,
    pub f_min_hz: f64,
    pub f_max_hz: f64,
    pub psd_reduce: PsdReduce,
    pub window: SpectrumWindow,
    /// Optional time-bin RMS map (ms); `None` uses per-block RMS/sample.
    pub time_bin_ms: Option<f64>,
}

impl Default for VoltageMapOptions {
    fn default() -> Self {
        Self {
            max_blocks: Some(5),
            grid_cols: 8,
            grid_rows: 8,
            sample_index: None,
            use_rms: true,
            trend_cut: false,
            stft: true,
            stft_fft_size: 512,
            stft_overlap: 0.5,
            hum: HumNoiseRemoval::None,
            downsample: 1,
            f_min_hz: 0.0,
            f_max_hz: f64::MAX,
            psd_reduce: PsdReduce::Mean,
            window: SpectrumWindow::Hann,
            time_bin_ms: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VoltageCell {
    pub channel: usize,
    pub row: usize,
    pub col: usize,
    pub value_mv: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VoltageMapReport {
    pub path: PathBuf,
    pub cells: Vec<VoltageCell>,
    pub min_mv: f64,
    pub max_mv: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VoltageStftFrame {
    pub time_ms: f64,
    pub cells: Vec<VoltageCell>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VoltageStftReport {
    pub path: PathBuf,
    pub frames: Vec<VoltageStftFrame>,
}

fn trend_cut(samples: &mut [f64]) {
    let n = samples.len() as f64;
    if n < 2.0 {
        return;
    }
    let mean_x = (n - 1.0) / 2.0;
    let mean_y = samples.iter().sum::<f64>() / n;
    let mut num = 0.0;
    let mut den = 0.0;
    for (i, &y) in samples.iter().enumerate() {
        let dx = i as f64 - mean_x;
        num += dx * (y - mean_y);
        den += dx * dx;
    }
    let slope = if den.abs() > 1e-12 { num / den } else { 0.0 };
    for (i, y) in samples.iter_mut().enumerate() {
        *y -= mean_y + slope * (i as f64 - mean_x);
    }
}

/// Spatial voltage / RMS amplitude map for one (or first) data block.
pub fn voltage_colormap(
    path: impl AsRef<Path>,
    options: &VoltageMapOptions,
) -> Result<VoltageMapReport> {
    let path = path.as_ref();
    let mut rec = Recording::open(path)?;
    let header = rec.header().clone();
    let block = rec.blocks().next().ok_or_else(|| Med64Error::InvalidHeader {
        path: path.to_path_buf(),
        message: "no data blocks".into(),
    })??;

    let n = options.grid_rows * options.grid_cols;
    let mut values = vec![0.0_f64; n];
    for (col, &ch) in block.channel_indices.iter().enumerate() {
        if ch >= n {
            continue;
        }
        let mut series: Vec<f64> =
            block.samples.iter().map(|row| header.counts_to_millivolts(row[col])).collect();
        series = downsample_series(series, options.downsample);
        if options.trend_cut {
            trend_cut(&mut series);
        }
        if options.use_rms {
            let sum_sq: f64 = series.iter().map(|mv| mv * mv).sum();
            values[ch] = (sum_sq / series.len().max(1) as f64).sqrt();
        } else {
            let idx = options
                .sample_index
                .unwrap_or(series.len() / 2)
                .min(series.len().saturating_sub(1));
            values[ch] = series[idx];
        }
    }

    Ok(report_from_values(path, options, values))
}

fn report_from_values(
    path: &Path,
    options: &VoltageMapOptions,
    values: Vec<f64>,
) -> VoltageMapReport {
    let min_mv = values.iter().cloned().fold(f64::INFINITY, f64::min);
    let max_mv = values.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
    let cells = values
        .iter()
        .enumerate()
        .map(|(ch, &value_mv)| VoltageCell {
            channel: ch,
            row: ch / options.grid_cols,
            col: ch % options.grid_cols,
            value_mv,
        })
        .collect();
    VoltageMapReport { path: path.to_path_buf(), cells, min_mv, max_mv }
}

/// Time-varying voltage color map from STFT band power (colormap + STFTExecutor).
pub fn voltage_stft_colormap(
    path: impl AsRef<Path>,
    options: &VoltageMapOptions,
) -> Result<VoltageStftReport> {
    let path = path.as_ref();
    let mut rec = Recording::open(path)?;
    let header = rec.header().clone();
    let n = options.grid_rows * options.grid_cols;
    let mut by_ch: Vec<Vec<f64>> = vec![Vec::new(); n];
    for (bi, block) in rec.blocks().enumerate() {
        if options.max_blocks.is_some_and(|m| bi >= m) {
            break;
        }
        let block = block?;
        for (col, &ch) in block.channel_indices.iter().enumerate() {
            if ch >= n {
                continue;
            }
            for row in &block.samples {
                by_ch[ch].push(header.counts_to_millivolts(row[col]));
            }
        }
    }
    let ds = options.downsample.max(1);
    if ds > 1 {
        for ch in &mut by_ch {
            *ch = downsample_series(std::mem::take(ch), ds);
        }
    }
    if options.trend_cut {
        for ch in &mut by_ch {
            trend_cut(ch);
        }
    }
    let fft = options.stft_fft_size.max(32);
    let hop = ((1.0 - options.stft_overlap) * fft as f64).round().max(1.0) as usize;
    let fs = header.sampling_frequency_hz;
    let backend = crate::toolkit::spectrum::default_fast_backend();
    let min_len = by_ch.iter().map(|v| v.len()).min().unwrap_or(0);
    let mut frames = Vec::new();
    let mut start = 0usize;
    while start + fft <= min_len {
        let values = {
            #[cfg(feature = "parallel")]
            {
                use rayon::prelude::*;
                by_ch
                    .par_iter()
                    .map(|series| {
                        if series.len() < start + fft {
                            return 0.0;
                        }
                        let chunk = &series[start..start + fft];
                        let mut bins = periodogram(chunk, fs, options.window, backend);
                        apply_hum_filter(&mut bins, fs, options.hum);
                        let band: Vec<f64> = bins
                            .iter()
                            .filter(|b| {
                                b.frequency_hz >= options.f_min_hz
                                    && b.frequency_hz <= options.f_max_hz
                            })
                            .map(|b| b.power)
                            .collect();
                        if band.is_empty() {
                            0.0
                        } else {
                            match options.psd_reduce {
                                PsdReduce::Mean => band.iter().sum::<f64>() / band.len() as f64,
                                PsdReduce::Max => band.iter().copied().fold(0.0_f64, f64::max),
                            }
                        }
                    })
                    .collect::<Vec<_>>()
            }
            #[cfg(not(feature = "parallel"))]
            {
                let mut values = vec![0.0; n];
                for (ch, series) in by_ch.iter().enumerate() {
                    if series.len() < start + fft {
                        continue;
                    }
                    let chunk = &series[start..start + fft];
                    let mut bins = periodogram(chunk, fs, options.window, backend);
                    apply_hum_filter(&mut bins, fs, options.hum);
                    let band: Vec<f64> = bins
                        .iter()
                        .filter(|b| {
                            b.frequency_hz >= options.f_min_hz && b.frequency_hz <= options.f_max_hz
                        })
                        .map(|b| b.power)
                        .collect();
                    values[ch] = if band.is_empty() {
                        0.0
                    } else {
                        match options.psd_reduce {
                            PsdReduce::Mean => band.iter().sum::<f64>() / band.len() as f64,
                            PsdReduce::Max => band.iter().copied().fold(0.0_f64, f64::max),
                        }
                    };
                }
                values
            }
        };
        let cells = values
            .iter()
            .enumerate()
            .map(|(ch, &value_mv)| VoltageCell {
                channel: ch,
                row: ch / options.grid_cols,
                col: ch % options.grid_cols,
                value_mv,
            })
            .collect();
        frames.push(VoltageStftFrame { time_ms: start as f64 * 1000.0 / fs, cells });
        start += hop;
    }
    Ok(VoltageStftReport { path: path.to_path_buf(), frames })
}

pub fn write_voltage_stft_html(report: &VoltageStftReport, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let mut frames = String::new();
    for (i, frame) in report.frames.iter().enumerate() {
        frames.push_str(&format!(
            "<div class=\"frame\" data-i=\"{i}\"><p>t = {:.1} ms</p><div class=\"g\">",
            frame.time_ms
        ));
        let max = frame.cells.iter().map(|c| c.value_mv).fold(1e-12_f64, f64::max);
        for cell in &frame.cells {
            let t = (cell.value_mv / max).clamp(0.0, 1.0);
            let r = (255.0 * t) as u8;
            let g = (40.0 + 80.0 * (1.0 - t)) as u8;
            let b = (255.0 * (1.0 - t)) as u8;
            frames.push_str(&format!(
                "<div class=\"c\" style=\"background:rgb({r},{g},{b})\"></div>"
            ));
        }
        frames.push_str("</div></div>");
    }
    let html = format!(
        r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>Voltage STFT map</title>
<style>body{{font-family:system-ui;margin:1rem}}.g{{display:grid;grid-template-columns:repeat(8,1fr);gap:2px;max-width:360px}}
.c{{aspect-ratio:1}}</style></head><body>
<h1>Voltage color map (STFT)</h1>
<p>{} · {} frames (scroll)</p>
{frames}</body></html>"#,
        report.path.display(),
        report.frames.len()
    );
    std::fs::write(path, html)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

pub fn write_voltage_frame_png(
    frame: &VoltageStftFrame,
    path: impl AsRef<Path>,
    cols: u32,
) -> Result<()> {
    let values: Vec<f64> = frame.cells.iter().map(|c| c.value_mv).collect();
    let rows = (values.len() as u32).div_ceil(cols.max(1));
    write_heatmap_png(path, cols.max(1), rows.max(1), &values, 24)
}

fn downsample_series(samples: Vec<f64>, keep_every: usize) -> Vec<f64> {
    let n = keep_every.max(1);
    if n <= 1 {
        return samples;
    }
    samples.into_iter().step_by(n).collect()
}

/// CreateImage-style package: `voltage_map.png` + optional STFT HTML + downsample note.
pub fn write_voltage_create_image(
    path: impl AsRef<Path>,
    options: &VoltageMapOptions,
    out_dir: impl AsRef<Path>,
) -> Result<Vec<PathBuf>> {
    let path = path.as_ref();
    let out_dir = out_dir.as_ref();
    std::fs::create_dir_all(out_dir)
        .map_err(|source| Med64Error::WriteIo { path: out_dir.to_path_buf(), source })?;
    let mut outs = Vec::new();

    let map = voltage_colormap(path, options)?;
    let values: Vec<f64> = map.cells.iter().map(|c| c.value_mv).collect();
    let png = out_dir.join("voltage_map.png");
    write_heatmap_png(&png, options.grid_cols as u32, options.grid_rows as u32, &values, 24)?;
    outs.push(png);

    if options.stft {
        let stft = voltage_stft_colormap(path, options)?;
        let html = out_dir.join("voltage_stft.html");
        write_voltage_stft_html(&stft, &html)?;
        outs.push(html);
    }

    let note = out_dir.join("downsample_note.txt");
    let note_text = format!(
        "Voltage CreateImage\nsource={}\ndownsample=keep every {} sample(s)\ngrid={}x{}\nstft={}\n",
        path.display(),
        options.downsample.max(1),
        options.grid_cols,
        options.grid_rows,
        options.stft
    );
    std::fs::write(&note, note_text)
        .map_err(|source| Med64Error::WriteIo { path: note.clone(), source })?;
    outs.push(note);

    let prefer = out_dir.join("voltage_prefer.html");
    crate::toolkit::fft_settings::write_voltage_panel_html(Some(&map), None, &prefer)?;
    outs.push(prefer);

    Ok(outs)
}

/// Write a simple binary double dump (`BinaryexportDouble`-style): little-endian f64 per cell.
pub fn write_voltage_binary(report: &VoltageMapReport, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let mut bytes = Vec::with_capacity(report.cells.len() * 8);
    for cell in &report.cells {
        bytes.extend_from_slice(&cell.value_mv.to_le_bytes());
    }
    std::fs::write(path, bytes)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

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

    #[test]
    fn maps_sample_data1() {
        let report =
            voltage_colormap(crate::fixture_paths::sample_data1(), &VoltageMapOptions::default())
                .unwrap();
        assert_eq!(report.cells.len(), 64);
        assert!(report.max_mv >= report.min_mv);
    }

    #[test]
    fn stft_has_frames() {
        let report = voltage_stft_colormap(
            crate::fixture_paths::sample_data1(),
            &VoltageMapOptions {
                max_blocks: Some(2),
                stft_fft_size: 256,
                ..VoltageMapOptions::default()
            },
        )
        .unwrap();
        assert!(!report.frames.is_empty());
    }
}