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
use serde::{Deserialize, Serialize};

use crate::analysis::spike::SpikeTrain;

/// Multi-channel burst detection series (`BurstMultiDetectionMethod`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum MultiBurstMethod {
    /// Array spike detection rate (spikes/s). Id 0 / ASDR.
    #[default]
    RateThreshold,
    /// Product of spike count × unique channels in bin. Id 1 / NetworkBurst.
    NetworkBurst,
    /// Raw spike count per bin. Id 2.
    Spikes,
    /// Unique active channels per bin. Id 3.
    ActiveChannels,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiChannelBurst {
    pub trace: u32,
    pub start_ms: f64,
    pub end_ms: f64,
    pub peak_rate_hz: f64,
    pub num_spikes: usize,
    /// Peak of the detection series (ASDR Hz, product, spike count, or active chs).
    pub peak_series: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsdrPoint {
    pub time_ms: f64,
    /// Raw detection-series value (Hz for RateThreshold).
    pub rate_hz: f64,
    pub smoothed_hz: f64,
    pub spike_count: usize,
    pub active_channels: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsdrTrace {
    pub points: Vec<AsdrPoint>,
    pub threshold_hz: f64,
    pub lower_threshold: f64,
    pub method: MultiBurstMethod,
    pub bursts: Vec<MultiChannelBurst>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AutoThresholdBase {
    Mean,
    /// Median / 0.6745 (`% median`).
    MedianMad,
    /// Population SD (default non-mean/median path).
    PopulationSd,
}

#[derive(Debug, Clone)]
pub struct MultiChannelBurstOptions {
    pub bin_width_ms: f64,
    /// Wire `smoothingBin` W: moving average uses window 2W+1 with NaN margins of width W.
    pub smoothing_bins: usize,
    pub auto_threshold_percent: f64,
    pub auto_threshold_percent_low: f64,
    pub auto_threshold_base: AutoThresholdBase,
    pub manual_upper: Option<f64>,
    pub manual_lower: Option<f64>,
    pub method: MultiBurstMethod,
    /// Minimum unique channels required to mark a bin channel (wire `multiburstingchannel`).
    pub min_bursting_channels: usize,
}

impl Default for MultiChannelBurstOptions {
    fn default() -> Self {
        Self {
            bin_width_ms: 50.0,
            smoothing_bins: 5,
            auto_threshold_percent: 200.0,
            auto_threshold_percent_low: 100.0,
            auto_threshold_base: AutoThresholdBase::Mean,
            manual_upper: None,
            manual_lower: None,
            method: MultiBurstMethod::RateThreshold,
            min_bursting_channels: 1,
        }
    }
}

/// Network-wide burst detection (`MultiChannelBurstService`).
pub fn detect_multi_channel_bursts(
    train: &SpikeTrain,
    trace_duration_ms: f64,
    options: &MultiChannelBurstOptions,
) -> Vec<MultiChannelBurst> {
    compute_asdr(train, trace_duration_ms, options).bursts
}

pub fn compute_asdr(
    train: &SpikeTrain,
    trace_duration_ms: f64,
    options: &MultiChannelBurstOptions,
) -> AsdrTrace {
    if train.is_empty() || trace_duration_ms <= 0.0 || options.bin_width_ms <= 0.0 {
        return AsdrTrace {
            points: Vec::new(),
            threshold_hz: 0.0,
            lower_threshold: 0.0,
            method: options.method,
            bursts: Vec::new(),
        };
    }

    let bin_count = (trace_duration_ms / options.bin_width_ms).ceil() as usize;
    let bin_count = bin_count.max(1);
    let mut spike_counts = vec![0usize; bin_count];
    let mut channel_sets: Vec<std::collections::BTreeSet<usize>> =
        vec![std::collections::BTreeSet::new(); bin_count];

    // `min_bursting_channels` (wire `multiburstingchannel`) requires a channel
    // to fire at least that many times WITHIN THE BIN before it counts as
    // active. That needs per-(bin, channel) counts, so bin first and derive the
    // active sets afterwards.
    //
    // This used to be stubbed: both arms of the gate inserted unconditionally,
    // so the option was silently ignored and `NetworkBurst`/`ActiveChannels`
    // behaved as if it were 1 no matter what the caller passed.
    let gate =
        matches!(options.method, MultiBurstMethod::NetworkBurst | MultiBurstMethod::ActiveChannels)
            && options.min_bursting_channels > 1;

    let mut per_bin_channel: Vec<std::collections::BTreeMap<usize, usize>> =
        vec![std::collections::BTreeMap::new(); bin_count];
    for spike in &train.spikes {
        let idx = (spike.within_trace_time_ms / options.bin_width_ms) as usize;
        if idx < bin_count {
            spike_counts[idx] += 1;
            *per_bin_channel[idx].entry(spike.channel).or_insert(0) += 1;
        }
    }
    for (idx, counts) in per_bin_channel.iter().enumerate() {
        for (&channel, &n) in counts {
            if !gate || n >= options.min_bursting_channels {
                channel_sets[idx].insert(channel);
            }
        }
    }

    let active: Vec<usize> = channel_sets.iter().map(|s| s.len()).collect();
    let series: Vec<f64> = (0..bin_count)
        .map(|i| match options.method {
            MultiBurstMethod::RateThreshold => {
                // count * (1000/binMs) with BigDecimal HALF_UP 3 dp.
                let scale = 1000.0 / options.bin_width_ms;
                round_half_up_3(spike_counts[i] as f64 * scale)
            }
            MultiBurstMethod::NetworkBurst => spike_counts[i] as f64 * active[i] as f64,
            MultiBurstMethod::Spikes => spike_counts[i] as f64,
            MultiBurstMethod::ActiveChannels => active[i] as f64,
        })
        .collect();

    let w = options.smoothing_bins;
    let smoothed = calc_moving_average(&series, w);
    let (upper, lower) = thresholds(&series, options);

    let points: Vec<AsdrPoint> = (0..bin_count)
        .map(|i| AsdrPoint {
            time_ms: i as f64 * options.bin_width_ms,
            rate_hz: series[i],
            smoothed_hz: if smoothed[i].is_nan() { series[i] } else { smoothed[i] },
            spike_count: spike_counts[i],
            active_channels: active[i],
        })
        .collect();

    let bursts = detect_rate_bursts(
        &series,
        &smoothed,
        &spike_counts,
        upper,
        lower,
        w,
        options.bin_width_ms,
        train.spikes.first().map(|s| s.trace).unwrap_or(0),
    );

    AsdrTrace {
        points,
        threshold_hz: upper,
        lower_threshold: lower,
        method: options.method,
        bursts,
    }
}

fn round_half_up_3(v: f64) -> f64 {
    (v * 1000.0).round() / 1000.0
}

/// `AnalysisUtils.calcMovingAverage`: NaN margins of width W; center uses [i-W, i+W].
pub fn calc_moving_average(values: &[f64], window: usize) -> Vec<f64> {
    if window == 0 {
        return values.to_vec();
    }
    let n = values.len();
    let mut out = vec![f64::NAN; n];
    if n <= 2 * window {
        return out;
    }
    for i in window..(n - window) {
        let start = i - window;
        let end = i + window + 1;
        let slice = &values[start..end];
        out[i] = slice.iter().sum::<f64>() / slice.len() as f64;
    }
    out
}

fn thresholds(raw: &[f64], options: &MultiChannelBurstOptions) -> (f64, f64) {
    if let (Some(u), Some(l)) = (options.manual_upper, options.manual_lower) {
        return (u, l);
    }
    if let Some(u) = options.manual_upper {
        return (u, options.manual_lower.unwrap_or(u * 0.5));
    }
    let base = match options.auto_threshold_base {
        AutoThresholdBase::Mean => {
            if raw.is_empty() {
                0.0
            } else {
                raw.iter().sum::<f64>() / raw.len() as f64
            }
        }
        AutoThresholdBase::MedianMad => {
            let mut sorted = raw.to_vec();
            sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
            median_sorted(&sorted) / 0.6744999885559082
        }
        AutoThresholdBase::PopulationSd => population_sd(raw),
    };
    let upper = base * options.auto_threshold_percent / 100.0;
    let lower = base * options.auto_threshold_percent_low / 100.0;
    (upper, lower)
}

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

fn population_sd(values: &[f64]) -> f64 {
    if values.is_empty() {
        return 0.0;
    }
    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;
    var.sqrt()
}

/// Dual-threshold hysteresis on smoothed series (`SpikeDetectUtils.detectSpikes` on ASDR).
fn detect_rate_bursts(
    raw: &[f64],
    smoothed: &[f64],
    spike_counts: &[usize],
    upper: f64,
    lower: f64,
    margin: usize,
    bin_ms: f64,
    trace: u32,
) -> Vec<MultiChannelBurst> {
    let n = raw.len();
    if n == 0 {
        return Vec::new();
    }
    let start = margin.min(n);
    let end = n.saturating_sub(margin).max(start);
    let mut bursts = Vec::new();
    let mut in_burst = false;
    let mut burst_start = 0usize;

    for i in start..end {
        let v = if smoothed[i].is_finite() {
            smoothed[i]
        } else {
            continue;
        };
        if !in_burst {
            if v >= upper {
                in_burst = true;
                burst_start = i;
            }
        } else if v < lower {
            push_burst(&mut bursts, raw, spike_counts, burst_start, i, bin_ms, trace);
            in_burst = false;
        }
    }
    if in_burst {
        push_burst(&mut bursts, raw, spike_counts, burst_start, end, bin_ms, trace);
    }
    bursts
}

fn push_burst(
    out: &mut Vec<MultiChannelBurst>,
    raw: &[f64],
    spike_counts: &[usize],
    start: usize,
    end: usize,
    bin_ms: f64,
    trace: u32,
) {
    if end <= start {
        return;
    }
    let mut peak = f64::NEG_INFINITY;
    let mut spikes = 0usize;
    for i in start..end {
        peak = peak.max(raw[i]);
        spikes += spike_counts[i];
    }
    out.push(MultiChannelBurst {
        trace,
        start_ms: start as f64 * bin_ms,
        end_ms: end as f64 * bin_ms,
        peak_rate_hz: peak,
        num_spikes: spikes,
        peak_series: peak,
    });
}

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

    #[test]
    fn finds_rate_burst() {
        let mut train = SpikeTrain::default();
        for t in (0..200).map(|i| i as f64 * 5.0) {
            train.push(Spike {
                channel: (t as usize) % 8,
                within_trace_time_ms: t,
                within_session_time_ms: t,
                peak_mv: 1.0,
                ..Default::default()
            });
        }
        let bursts = detect_multi_channel_bursts(
            &train,
            1000.0,
            &MultiChannelBurstOptions {
                auto_threshold_percent: 50.0,
                auto_threshold_percent_low: 25.0,
                smoothing_bins: 2,
                ..Default::default()
            },
        );
        assert!(!bursts.is_empty());
    }

    #[test]
    fn moving_average_has_nan_margins() {
        let v = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
        let s = calc_moving_average(&v, 2);
        assert!(s[0].is_nan() && s[1].is_nan());
        assert!(s[8].is_nan() && s[9].is_nan());
        assert!((s[2] - 3.0).abs() < 1e-9); // avg of 1..5
    }

    #[test]
    fn product_method_uses_count_times_channels() {
        let mut train = SpikeTrain::default();
        for ch in 0..4usize {
            for k in 0..10 {
                train.push(Spike {
                    channel: ch,
                    within_trace_time_ms: k as f64 * 10.0,
                    within_session_time_ms: k as f64 * 10.0,
                    peak_mv: 1.0,
                    ..Default::default()
                });
            }
        }
        let asdr = compute_asdr(
            &train,
            100.0,
            &MultiChannelBurstOptions {
                method: MultiBurstMethod::NetworkBurst,
                smoothing_bins: 0,
                auto_threshold_percent: 10.0,
                auto_threshold_percent_low: 5.0,
                ..Default::default()
            },
        );
        assert!(asdr.points.iter().any(|p| p.rate_hz > 0.0));
        assert!(asdr.points.iter().any(|p| p.active_channels >= 1));
    }

    /// `min_bursting_channels` used to be a no-op: both arms of the gate
    /// inserted the channel unconditionally, so callers who asked for a
    /// minimum got none and were told nothing. One channel here fires 10x in
    /// the first bin, three fire once each; with the gate at 3 only the busy
    /// channel may count as active.
    #[test]
    fn min_bursting_channels_actually_gates() {
        let mut train = SpikeTrain::default();
        for k in 0..10 {
            train.push(Spike {
                channel: 0,
                within_trace_time_ms: k as f64 * 2.0,
                within_session_time_ms: k as f64 * 2.0,
                peak_mv: 1.0,
                ..Default::default()
            });
        }
        for ch in 1..4 {
            train.push(Spike {
                channel: ch,
                within_trace_time_ms: 5.0,
                within_session_time_ms: 5.0,
                peak_mv: 1.0,
                ..Default::default()
            });
        }

        let active = |min_ch: usize, method: MultiBurstMethod| {
            compute_asdr(
                &train,
                100.0,
                &MultiChannelBurstOptions {
                    method,
                    bin_width_ms: 50.0,
                    smoothing_bins: 0,
                    min_bursting_channels: min_ch,
                    ..Default::default()
                },
            )
            .points[0]
                .active_channels
        };

        assert_eq!(active(1, MultiBurstMethod::NetworkBurst), 4, "ungated");
        assert_eq!(
            active(3, MultiBurstMethod::NetworkBurst),
            1,
            "gate at 3 must drop the three single-spike channels"
        );
        assert_eq!(
            active(11, MultiBurstMethod::NetworkBurst),
            0,
            "a gate above every channel count leaves nothing active"
        );
        assert_eq!(active(3, MultiBurstMethod::ActiveChannels), 1, "ActiveChannels gates too");
        // RateThreshold is explicitly ungated: it counts spikes, not channels.
        assert_eq!(
            active(3, MultiBurstMethod::RateThreshold),
            4,
            "RateThreshold must ignore the gate"
        );
    }
}