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
//! Power spectrum / STFT / hum removal (PSA).

use serde::{Deserialize, Serialize};

use crate::error::{Med64Error, Result};
use crate::header::Med64Header;
use crate::recording::Recording;
use std::path::Path;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HumNoiseRemoval {
    #[default]
    None,
    FiftyHz,
    SixtyHz,
}

/// FFT backend for Welch-averaged periodograms.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SpectrumBackend {
    /// Standard Cooley–Tukey (existing Rust path).
    #[default]
    Welch,
    /// Reference FFT path (`psa99.Fft.executeFFT` bit-exact).
    ReferenceFft,
    /// macOS Accelerate / vDSP (falls back to Welch when unavailable).
    #[cfg(all(feature = "accelerate", target_os = "macos"))]
    Accelerate,
}

/// Prefer Accelerate on macOS when the feature is on; otherwise Welch.
pub fn default_fast_backend() -> SpectrumBackend {
    #[cfg(all(feature = "accelerate", target_os = "macos"))]
    {
        SpectrumBackend::Accelerate
    }
    #[cfg(not(all(feature = "accelerate", target_os = "macos")))]
    {
        SpectrumBackend::Welch
    }
}

#[derive(Debug, Clone)]
pub struct SpectrumOptions {
    pub channel: usize,
    pub max_blocks: Option<usize>,
    pub fft_size: usize,
    pub overlap: f64,
    pub hum: HumNoiseRemoval,
    pub window: SpectrumWindow,
    pub backend: SpectrumBackend,
}

impl Default for SpectrumOptions {
    fn default() -> Self {
        Self {
            channel: 0,
            max_blocks: Some(20),
            fft_size: 2048,
            overlap: 0.5,
            hum: HumNoiseRemoval::None,
            window: SpectrumWindow::Hann,
            backend: SpectrumBackend::Welch,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SpectrumWindow {
    #[default]
    Hann,
    Rectangular,
    Hamming,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpectrumBin {
    pub frequency_hz: f64,
    pub power: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpectrumReport {
    pub path: std::path::PathBuf,
    pub channel: usize,
    pub sample_rate_hz: f64,
    pub bins: Vec<SpectrumBin>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpectrogramFrame {
    pub time_ms: f64,
    pub bins: Vec<SpectrumBin>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpectrogramReport {
    pub path: std::path::PathBuf,
    pub channel: usize,
    pub frames: Vec<SpectrogramFrame>,
}

/// Welch-style averaged power spectrum for one channel.
pub fn power_spectrum(path: impl AsRef<Path>, options: &SpectrumOptions) -> Result<SpectrumReport> {
    let path = path.as_ref();
    let (header, samples) = load_channel_mv(path, options.channel, options.max_blocks)?;
    let bins = average_psd(
        &samples,
        header.sampling_frequency_hz,
        options.fft_size,
        options.overlap,
        options.window,
        options.hum,
        options.backend,
    );
    Ok(SpectrumReport {
        path: path.to_path_buf(),
        channel: options.channel,
        sample_rate_hz: header.sampling_frequency_hz,
        bins,
    })
}

/// Short-time Fourier transform spectrogram.
pub fn spectrogram(path: impl AsRef<Path>, options: &SpectrumOptions) -> Result<SpectrogramReport> {
    let path = path.as_ref();
    let (header, samples) = load_channel_mv(path, options.channel, options.max_blocks)?;
    let fs = header.sampling_frequency_hz;
    let hop = ((1.0 - options.overlap) * options.fft_size as f64).round().max(1.0) as usize;
    let mut frames = Vec::new();
    let mut start = 0usize;
    while start + options.fft_size <= samples.len() {
        let chunk = &samples[start..start + options.fft_size];
        let mut bins = periodogram(chunk, fs, options.window, options.backend);
        apply_hum_filter(&mut bins, fs, options.hum);
        frames.push(SpectrogramFrame { time_ms: start as f64 * 1000.0 / fs, bins });
        start += hop;
    }
    Ok(SpectrogramReport { path: path.to_path_buf(), channel: options.channel, frames })
}

/// Notch / harmonic removal in the frequency domain (`HamFilter.cutoffHamFrq`).
/// Averages adjacent bins at each harmonic rather than zeroing a band.
pub fn apply_hum_filter(bins: &mut [SpectrumBin], sample_rate_hz: f64, mode: HumNoiseRemoval) {
    let target = match mode {
        HumNoiseRemoval::None => return,
        HumNoiseRemoval::FiftyHz => 50.0,
        HumNoiseRemoval::SixtyHz => 60.0,
    };
    let nyquist = sample_rate_hz / 2.0;
    let mut harm = target;
    while harm < nyquist {
        // Find nearest bin to harm and average with neighbors (HamFilter).
        if let Some((best_i, _)) = bins.iter().enumerate().min_by(|(_, a), (_, b)| {
            (a.frequency_hz - harm).abs().partial_cmp(&(b.frequency_hz - harm).abs()).unwrap()
        }) {
            let left = if best_i > 0 { bins[best_i - 1].power } else { bins[best_i].power };
            let right =
                if best_i + 1 < bins.len() { bins[best_i + 1].power } else { bins[best_i].power };
            bins[best_i].power = 0.5 * (left + right);
        }
        harm += target;
    }
}

pub fn load_channel_mv(
    path: &Path,
    channel: usize,
    max_blocks: Option<usize>,
) -> Result<(Med64Header, Vec<f64>)> {
    let mut rec = Recording::open(path)?;
    let header = rec.header().clone();
    let mut out = Vec::new();
    for (i, block) in rec.blocks().enumerate() {
        if max_blocks.is_some_and(|m| i >= m) {
            break;
        }
        let block = block?;
        let Some(col) = block.channel_indices.iter().position(|&ch| ch == channel) else {
            continue;
        };
        for row in &block.samples {
            out.push(header.counts_to_millivolts(row[col]));
        }
    }
    if out.is_empty() {
        return Err(Med64Error::InvalidHeader {
            path: path.to_path_buf(),
            message: format!("no samples for channel {channel}"),
        });
    }
    Ok((header, out))
}

fn average_psd(
    samples: &[f64],
    fs: f64,
    fft_size: usize,
    overlap: f64,
    window: SpectrumWindow,
    hum: HumNoiseRemoval,
    backend: SpectrumBackend,
) -> Vec<SpectrumBin> {
    let hop = ((1.0 - overlap) * fft_size as f64).round().max(1.0) as usize;
    let mut acc = vec![0.0; fft_size / 2 + 1];
    let mut n = 0usize;
    let mut start = 0usize;
    while start + fft_size <= samples.len() {
        let bins = periodogram(&samples[start..start + fft_size], fs, window, backend);
        for (i, bin) in bins.iter().enumerate() {
            acc[i] += bin.power;
        }
        n += 1;
        start += hop;
    }
    if n == 0 && !samples.is_empty() {
        let mut padded = samples.to_vec();
        padded.resize(fft_size, 0.0);
        return {
            let mut bins = periodogram(&padded, fs, window, backend);
            apply_hum_filter(&mut bins, fs, hum);
            bins
        };
    }
    let mut bins: Vec<SpectrumBin> = acc
        .iter()
        .enumerate()
        .map(|(i, &p)| SpectrumBin {
            frequency_hz: i as f64 * fs / fft_size as f64,
            power: if n > 0 { p / n as f64 } else { 0.0 },
        })
        .collect();
    apply_hum_filter(&mut bins, fs, hum);
    bins
}

pub(crate) fn periodogram(
    chunk: &[f64],
    fs: f64,
    window: SpectrumWindow,
    backend: SpectrumBackend,
) -> Vec<SpectrumBin> {
    let n = chunk.len().next_power_of_two();
    let mut re = vec![0.0; n];
    let mut im = vec![0.0; n];
    for (i, &v) in chunk.iter().enumerate() {
        let w = match window {
            SpectrumWindow::Rectangular => 1.0,
            SpectrumWindow::Hann => {
                // Hann window: 0.5 - 0.5*cos(2Ď€ i / N).
                let n = chunk.len().max(1) as f64;
                0.5 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / n).cos()
            }
            SpectrumWindow::Hamming => {
                let n = chunk.len().max(1) as f64;
                0.54 - 0.46 * (2.0 * std::f64::consts::PI * i as f64 / n).cos()
            }
        };
        re[i] = v * w;
    }
    match backend {
        SpectrumBackend::Welch => fft_inplace(&mut re, &mut im),
        SpectrumBackend::ReferenceFft => reference_fft_inplace(&mut re, &mut im),
        #[cfg(all(feature = "accelerate", target_os = "macos"))]
        SpectrumBackend::Accelerate => {
            crate::accelerate_fft::accelerate_fft_inplace(&mut re, &mut im)
        }
    }
    (0..=n / 2)
        .map(|k| {
            let power = (re[k] * re[k] + im[k] * im[k]) / (n as f64 * n as f64);
            SpectrumBin { frequency_hz: k as f64 * fs / n as f64, power }
        })
        .collect()
}

/// `psa99.Fft.executeFFT` (forward) — bit-reversal + stages with
/// `theta` starting at π, halved each stage; `wr=cos(theta)`, `wi=+sin(theta)`.
pub fn reference_fft_inplace(re: &mut [f64], im: &mut [f64]) {
    execute_fft(re, im, false);
}

/// Port of `Fft.executeFFT` working in-place on `(re, im)`.
/// When `inverse` is true, twiddle imag uses `-sin` and results are divided by N
/// (matching the reference output-copy path); callers typically use forward only.
pub fn execute_fft(re: &mut [f64], im: &mut [f64], inverse: bool) {
    let n = re.len();
    assert_eq!(n, im.len());
    assert!(n.is_power_of_two() && n >= 1);
    let sign = if inverse { -1.0 } else { 1.0 };

    // Bit-reversal permute (loop: i = 0 .. n-2).
    let mut j = 0usize;
    for i in 0..n.saturating_sub(1) {
        if i <= j {
            re.swap(i, j);
            im.swap(i, j);
        }
        let mut k = n / 2;
        while k <= j {
            j -= k;
            k /= 2;
        }
        j += k;
    }

    let mut theta = std::f64::consts::PI;
    let mut m = 1usize;
    while m <= n / 2 {
        let wr0 = theta.cos();
        let wi0 = sign * theta.sin();
        let mut wr = 1.0;
        let mut wi = 0.0;
        for _j in 0..m {
            let mut i = _j;
            while i < n {
                let k = i + m;
                let tr = re[k] * wr - im[k] * wi;
                let ti = im[k] * wr + re[k] * wi;
                re[k] = re[i] - tr;
                im[k] = im[i] - ti;
                re[i] += tr;
                im[i] += ti;
                i += 2 * m;
            }
            let next_wr = wr0 * wr - wi0 * wi;
            wi = wi0 * wr + wr0 * wi;
            wr = next_wr;
        }
        m *= 2;
        theta /= 2.0;
    }

    if inverse {
        let inv_n = 1.0 / n as f64;
        for i in 0..n {
            re[i] *= inv_n;
            im[i] *= inv_n;
        }
    }
}

/// In-place radix-2 Cooley–Tukey FFT.
pub fn fft_inplace(re: &mut [f64], im: &mut [f64]) {
    let n = re.len();
    assert_eq!(n, im.len());
    assert!(n.is_power_of_two());
    let mut j = 0usize;
    for i in 1..n {
        let mut bit = n >> 1;
        while j & bit != 0 {
            j ^= bit;
            bit >>= 1;
        }
        j ^= bit;
        if i < j {
            re.swap(i, j);
            im.swap(i, j);
        }
    }
    let mut len = 2;
    while len <= n {
        let ang = -2.0 * std::f64::consts::PI / len as f64;
        let (wlen_re, wlen_im) = (ang.cos(), ang.sin());
        let mut i = 0;
        while i < n {
            let mut w_re = 1.0;
            let mut w_im = 0.0;
            for j in 0..len / 2 {
                let u_re = re[i + j];
                let u_im = im[i + j];
                let v_re = re[i + j + len / 2] * w_re - im[i + j + len / 2] * w_im;
                let v_im = re[i + j + len / 2] * w_im + im[i + j + len / 2] * w_re;
                re[i + j] = u_re + v_re;
                im[i + j] = u_im + v_im;
                re[i + j + len / 2] = u_re - v_re;
                im[i + j + len / 2] = u_im - v_im;
                let next_re = w_re * wlen_re - w_im * wlen_im;
                w_im = w_re * wlen_im + w_im * wlen_re;
                w_re = next_re;
            }
            i += len;
        }
        len <<= 1;
    }
}

/// Simple time-domain notch (biquad) for analysis pipelines.
#[derive(Debug, Clone)]
pub struct NotchFilter {
    b0: f64,
    b1: f64,
    b2: f64,
    a1: f64,
    a2: f64,
    x1: f64,
    x2: f64,
    y1: f64,
    y2: f64,
}

impl NotchFilter {
    pub fn new(sample_rate_hz: f64, notch_hz: f64, q: f64) -> Self {
        let w0 = 2.0 * std::f64::consts::PI * notch_hz / sample_rate_hz;
        let alpha = w0.sin() / (2.0 * q.max(0.1));
        let cos_w0 = w0.cos();
        let b0 = 1.0;
        let b1 = -2.0 * cos_w0;
        let b2 = 1.0;
        let a0 = 1.0 + alpha;
        let a1 = -2.0 * cos_w0;
        let a2 = 1.0 - alpha;
        Self {
            b0: b0 / a0,
            b1: b1 / a0,
            b2: b2 / a0,
            a1: a1 / a0,
            a2: a2 / a0,
            x1: 0.0,
            x2: 0.0,
            y1: 0.0,
            y2: 0.0,
        }
    }

    pub fn for_hum(sample_rate_hz: f64, mode: HumNoiseRemoval) -> Option<Self> {
        let hz = match mode {
            HumNoiseRemoval::None => return None,
            HumNoiseRemoval::FiftyHz => 50.0,
            HumNoiseRemoval::SixtyHz => 60.0,
        };
        Some(Self::new(sample_rate_hz, hz, 30.0))
    }

    pub fn filter_sample(&mut self, x: f64) -> f64 {
        let y = self.b0 * x + self.b1 * self.x1 + self.b2 * self.x2
            - self.a1 * self.y1
            - self.a2 * self.y2;
        self.x2 = self.x1;
        self.x1 = x;
        self.y2 = self.y1;
        self.y1 = y;
        y
    }

    pub fn filter_block(&mut self, samples: &mut [f64]) {
        for s in samples {
            *s = self.filter_sample(*s);
        }
    }
}

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

    #[test]
    fn detects_sine_peak() {
        let fs = 1000.0;
        let f0 = 40.0;
        let samples: Vec<f64> =
            (0..4096).map(|i| (2.0 * std::f64::consts::PI * f0 * i as f64 / fs).sin()).collect();
        let bins = average_psd(
            &samples,
            fs,
            1024,
            0.5,
            SpectrumWindow::Hann,
            HumNoiseRemoval::None,
            SpectrumBackend::Welch,
        );
        let peak = bins.iter().max_by(|a, b| a.power.partial_cmp(&b.power).unwrap()).unwrap();
        assert!((peak.frequency_hz - f0).abs() < 5.0, "peak at {}", peak.frequency_hz);
    }

    #[test]
    fn hum_averages_neighbors_at_50hz_harmonics() {
        let mut bins = vec![
            SpectrumBin { frequency_hz: 49.0, power: 1.0 },
            SpectrumBin { frequency_hz: 50.0, power: 10.0 },
            SpectrumBin { frequency_hz: 51.0, power: 3.0 },
            SpectrumBin { frequency_hz: 100.0, power: 5.0 },
            SpectrumBin { frequency_hz: 101.0, power: 1.0 },
        ];
        apply_hum_filter(&mut bins, 1000.0, HumNoiseRemoval::FiftyHz);
        // Nearest to 50 Hz averaged with neighbors (49 Hz / 51 Hz).
        assert!((bins[1].power - 2.0).abs() < 1e-9);
        // 100 Hz bin is interpolated (not left as the raw peak).
        assert!(bins[3].power < 5.0);
        assert!(bins[3].power > 0.0);
    }
}