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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Beta-cell / slow oscillation detection (beta oscillation /
//! `rectification99`).

use serde::{Deserialize, Serialize};

use crate::analysis::{
    run_analysis, AnalysisOptions, BandpassFilter, FilterAlgorithm, LowPassKind,
};
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, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BetaThresholdMethod {
    /// SD of noise × percent, both polarities after rectify.
    SdPlusMinus,
    /// SD, negative only (on rectified signal = below mean).
    SdMinusOnly,
    /// Median absolute deviation style via median(|x|)/0.6745.
    MedianPlusMinus,
}

impl BetaThresholdMethod {
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "sd" | "sd_pm" | "sd+/-" | "sd_plus_minus" => Some(Self::SdPlusMinus),
            "sd_m" | "sd-" | "sd_minus" => Some(Self::SdMinusOnly),
            "median" | "median_pm" | "mad" => Some(Self::MedianPlusMinus),
            _ => None,
        }
    }
}

#[derive(Debug, Clone)]
pub struct BetaOscillationOptions {
    pub channel: usize,
    pub max_blocks: Option<usize>,
    /// Legacy moving-abs envelope cutoff (Hz); used when `use_burst_detector` is false.
    pub envelope_cutoff_hz: f64,
    pub plus_threshold_mv: f64,
    pub min_interval_ms: f64,
    pub highpass_hz: Option<f64>,
    pub lowpass_hz: Option<f64>,
    pub lowpass_kind: LowPassKind,
    pub rectify: bool,
    pub threshold_method: BetaThresholdMethod,
    /// Percent of SD / MAD used for threshold (wire `textsdpercent`, default 300 = 3σ).
    pub sd_percent: f64,
    pub min_duration_ms: f64,
    /// Exit burst after this much continuous sub-threshold silence.
    pub silent_interval_ms: f64,
    pub end_detect: bool,
    /// Prefer segment burst detector (rectification99) over peak-only envelope.
    pub use_burst_detector: bool,
}

impl Default for BetaOscillationOptions {
    fn default() -> Self {
        Self {
            channel: 0,
            max_blocks: Some(40),
            envelope_cutoff_hz: 2.0,
            plus_threshold_mv: 0.05,
            min_interval_ms: 500.0,
            highpass_hz: Some(0.1),
            lowpass_hz: Some(20.0),
            lowpass_kind: LowPassKind::Butterworth,
            rectify: true,
            threshold_method: BetaThresholdMethod::SdPlusMinus,
            sd_percent: 300.0,
            min_duration_ms: 100.0,
            silent_interval_ms: 200.0,
            end_detect: true,
            use_burst_detector: true,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OscillationEvent {
    pub peak_ms: f64,
    pub amplitude_mv: f64,
    pub interval_ms: Option<f64>,
    #[serde(default)]
    pub start_ms: Option<f64>,
    #[serde(default)]
    pub end_ms: Option<f64>,
    #[serde(default)]
    pub integ: Option<f64>,
    #[serde(default)]
    pub rms: Option<f64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BetaOscillationReport {
    pub path: PathBuf,
    pub channel: usize,
    pub events: Vec<OscillationEvent>,
    pub mean_period_ms: f64,
    pub rate_per_min: f64,
    #[serde(default)]
    pub threshold_plus_mv: f64,
    #[serde(default)]
    pub threshold_minus_mv: f64,
    #[serde(default)]
    pub mean_integ: f64,
    #[serde(default)]
    pub cv_period: f64,
    /// Blocks analyzed (for waveform re-export).
    #[serde(default)]
    pub max_blocks: Option<usize>,
}

/// Export matrix for Beta CreateImage package writer.
#[derive(Debug, Clone)]
pub struct BetaExportOptions {
    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 BetaExportOptions {
    fn default() -> Self {
        Self {
            filterexport: false,
            rawdataexport: false,
            binary_shorts: false,
            binary_doubles: false,
            ascii_csv: false,
            mobius_modat: false,
            hdf5: false,
            name: "beta".into(),
        }
    }
}

/// Detect slow oscillations: filter → optional rectify → SD/median threshold → bursts.
pub fn detect_beta_oscillations(
    path: impl AsRef<Path>,
    options: &BetaOscillationOptions,
) -> Result<BetaOscillationReport> {
    let path = path.as_ref();
    let (header, samples) = load_channel_mv(path, options.channel, options.max_blocks)?;
    let fs = header.sampling_frequency_hz;
    let interval = header.interval_ms();
    let period_sec = 1.0 / fs.max(1e-9);

    let mut work = samples;
    if options.highpass_hz.is_some() || options.lowpass_hz.is_some() {
        let hp = options.highpass_hz.unwrap_or(0.01);
        let lp = options.lowpass_hz.unwrap_or(fs * 0.4);
        let mut bp = BandpassFilter::with_algorithm(
            period_sec,
            hp,
            lp,
            options.lowpass_kind,
            FilterAlgorithm::SecondPole,
        );
        for s in &mut work {
            *s = bp.filter_sample(*s);
        }
    }
    if options.rectify {
        for s in &mut work {
            *s = s.abs();
        }
    }

    if options.use_burst_detector {
        return Ok(detect_rectified_bursts(path, &work, interval, options));
    }

    // Legacy envelope peak path.
    let win = ((fs / options.envelope_cutoff_hz.max(0.1)).round() as usize).max(3);
    let envelope = moving_abs_avg(&work, win);
    let refractory = (options.min_interval_ms / interval).round().max(1.0) as usize;
    let mut events = Vec::new();
    let mut last = -(refractory as isize);
    for i in 1..envelope.len().saturating_sub(1) {
        if envelope[i] >= options.plus_threshold_mv
            && envelope[i] >= envelope[i - 1]
            && envelope[i] >= envelope[i + 1]
            && i as isize >= last + refractory as isize
        {
            let peak_ms = i as f64 * interval;
            let interval_ms = events.last().map(|e: &OscillationEvent| peak_ms - e.peak_ms);
            events.push(OscillationEvent {
                peak_ms,
                amplitude_mv: envelope[i],
                interval_ms,
                start_ms: None,
                end_ms: None,
                integ: None,
                rms: None,
            });
            last = i as isize;
        }
    }
    Ok(summarize(path, options.channel, events, 0.0, 0.0, options.max_blocks))
}

fn detect_rectified_bursts(
    path: &Path,
    samples: &[f64],
    interval_ms: f64,
    options: &BetaOscillationOptions,
) -> BetaOscillationReport {
    let (plus, minus) = compute_thresholds(samples, options);
    let thr = plus.max(minus.abs()).max(1e-12);
    let min_dur = ((options.min_duration_ms / interval_ms).round() as usize).max(1);
    let silent_n = ((options.silent_interval_ms / interval_ms).round() as usize).max(1);
    let min_gap = ((options.min_interval_ms / interval_ms).round() as usize).max(1);

    let mut events = Vec::new();
    let mut i = 0usize;
    let mut last_end = 0usize;
    while i < samples.len() {
        if samples[i] < thr {
            i += 1;
            continue;
        }
        let start = i;
        let mut peak_i = i;
        let mut peak_v = samples[i];
        let mut silent = 0usize;
        i += 1;
        while i < samples.len() {
            if samples[i] >= thr {
                silent = 0;
                if samples[i] > peak_v {
                    peak_v = samples[i];
                    peak_i = i;
                }
            } else {
                silent += 1;
                if options.end_detect && silent >= silent_n {
                    break;
                }
            }
            i += 1;
        }
        let end = if options.end_detect { i.saturating_sub(silent) } else { i }.max(start + 1);
        if end - start >= min_dur && start >= last_end.saturating_add(min_gap) {
            let slice = &samples[start..end];
            let integ = slice.iter().map(|v| v.abs()).sum::<f64>() * interval_ms;
            let mean = slice.iter().sum::<f64>() / slice.len() as f64;
            let rms =
                (slice.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / slice.len() as f64).sqrt();
            let peak_ms = peak_i as f64 * interval_ms;
            let interval_ms_ev = events.last().map(|e: &OscillationEvent| peak_ms - e.peak_ms);
            events.push(OscillationEvent {
                peak_ms,
                amplitude_mv: peak_v,
                interval_ms: interval_ms_ev,
                start_ms: Some(start as f64 * interval_ms),
                end_ms: Some(end as f64 * interval_ms),
                integ: Some(integ),
                rms: Some(rms),
            });
            last_end = end;
        }
        i = end.max(i);
    }
    summarize(path, options.channel, events, plus, -thr, options.max_blocks)
}

fn compute_thresholds(samples: &[f64], options: &BetaOscillationOptions) -> (f64, f64) {
    let pct = (options.sd_percent / 100.0).max(0.01);
    match options.threshold_method {
        BetaThresholdMethod::SdPlusMinus | BetaThresholdMethod::SdMinusOnly => {
            let mean = samples.iter().sum::<f64>() / samples.len().max(1) as f64;
            let var = samples.iter().map(|v| (v - mean).powi(2)).sum::<f64>()
                / samples.len().max(1) as f64;
            let sd = var.sqrt();
            let t = sd * pct;
            if matches!(options.threshold_method, BetaThresholdMethod::SdMinusOnly) {
                (t, -t)
            } else {
                (t, -t)
            }
        }
        BetaThresholdMethod::MedianPlusMinus => {
            let mut abs: Vec<f64> = samples.iter().map(|v| v.abs()).collect();
            abs.sort_by(|a, b| a.partial_cmp(b).unwrap());
            let med = abs[abs.len() / 2];
            let sigma = med / 0.6745;
            let t = sigma * pct;
            (t, -t)
        }
    }
}

fn summarize(
    path: &Path,
    channel: usize,
    events: Vec<OscillationEvent>,
    thr_plus: f64,
    thr_minus: f64,
    max_blocks: Option<usize>,
) -> BetaOscillationReport {
    let periods: Vec<f64> = events.iter().filter_map(|e| e.interval_ms).collect();
    let mean_period =
        if periods.is_empty() { 0.0 } else { periods.iter().sum::<f64>() / periods.len() as f64 };
    let cv_period = if mean_period > 0.0 && periods.len() > 1 {
        let var = periods.iter().map(|p| (p - mean_period).powi(2)).sum::<f64>()
            / (periods.len() - 1) as f64;
        var.sqrt() / mean_period
    } else {
        0.0
    };
    let rate = if mean_period > 0.0 { 60_000.0 / mean_period } else { 0.0 };
    let integs: Vec<f64> = events.iter().filter_map(|e| e.integ).collect();
    let mean_integ =
        if integs.is_empty() { 0.0 } else { integs.iter().sum::<f64>() / integs.len() as f64 };
    BetaOscillationReport {
        path: path.to_path_buf(),
        channel,
        events,
        mean_period_ms: mean_period,
        rate_per_min: rate,
        threshold_plus_mv: thr_plus,
        threshold_minus_mv: thr_minus,
        mean_integ,
        cv_period,
        max_blocks,
    }
}

fn moving_abs_avg(samples: &[f64], win: usize) -> Vec<f64> {
    let mut out = vec![0.0; samples.len()];
    let mut sum = 0.0;
    for i in 0..samples.len() {
        sum += samples[i].abs();
        if i >= win {
            sum -= samples[i - win].abs();
        }
        let n = (i + 1).min(win) as f64;
        out[i] = sum / n;
    }
    out
}

/// CreateImage-style package: events CSV, beta HTML timeline, optional envelope SVG.
pub fn write_beta_create_image(
    report: &BetaOscillationReport,
    samples_mv: Option<&[f64]>,
    out_dir: impl AsRef<Path>,
) -> Result<Vec<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 events_csv = dir.join("events.csv");
    {
        let mut w = String::from("peak_ms,amplitude_mv,interval_ms,start_ms,end_ms,integ,rms\n");
        for e in &report.events {
            let iv = e.interval_ms.map(|v| format!("{v:.6}")).unwrap_or_default();
            w.push_str(&format!(
                "{:.6},{:.6},{},{},{},{},{}\n",
                e.peak_ms,
                e.amplitude_mv,
                iv,
                e.start_ms.map(|v| format!("{v:.6}")).unwrap_or_default(),
                e.end_ms.map(|v| format!("{v:.6}")).unwrap_or_default(),
                e.integ.map(|v| format!("{v:.6}")).unwrap_or_default(),
                e.rms.map(|v| format!("{v:.6}")).unwrap_or_default(),
            ));
        }
        std::fs::write(&events_csv, w).map_err(|source| crate::error::Med64Error::WriteIo {
            path: events_csv.clone(),
            source,
        })?;
        outs.push(events_csv);
    }

    let summary = dir.join("summary.txt");
    {
        let body = format!(
            "path: {}\nchannel: {}\nevents: {}\nmean_period_ms: {:.6}\nrate_per_min: {:.6}\ncv_period: {:.6}\nmean_integ: {:.6}\nthreshold_plus_mv: {:.6}\n",
            report.path.display(),
            report.channel + 1,
            report.events.len(),
            report.mean_period_ms,
            report.rate_per_min,
            report.cv_period,
            report.mean_integ,
            report.threshold_plus_mv,
        );
        std::fs::write(&summary, body).map_err(|source| crate::error::Med64Error::WriteIo {
            path: summary.clone(),
            source,
        })?;
        outs.push(summary);
    }

    let html = dir.join("beta.html");
    {
        let mut points = String::new();
        for e in &report.events {
            points.push_str(&format!("<li>{:.1} ms · {:.3} mV</li>", e.peak_ms, e.amplitude_mv));
        }
        let body = format!(
            r#"<!doctype html><html><head><meta charset="utf-8"><title>Beta oscillations</title>
<style>body{{font-family:system-ui;margin:1.5rem}} li{{margin:.2rem 0}}</style></head>
<body><h1>Beta-cell oscillations</h1>
<p class="meta">ch {} · {} events · {:.2}/min · CV {:.3}</p>
<ul>{points}</ul></body></html>"#,
            report.channel + 1,
            report.events.len(),
            report.rate_per_min,
            report.cv_period,
        );
        std::fs::write(&html, body)
            .map_err(|source| crate::error::Med64Error::WriteIo { path: html.clone(), source })?;
        outs.push(html);
    }

    if let Some(samples) = samples_mv {
        let env_svg = dir.join("envelope.svg");
        let step = (samples.len() / 800).max(1);
        let max = samples.iter().map(|v| v.abs()).fold(1e-12, f64::max);
        let mut poly = String::new();
        for (xi, chunk) in samples.chunks(step).enumerate() {
            let y = chunk.iter().map(|v| v.abs()).sum::<f64>() / chunk.len() as f64;
            let px = xi as f64;
            let py = 120.0 - (y / max) * 110.0;
            if xi == 0 {
                poly.push_str(&format!("{px:.1},{py:.1}"));
            } else {
                poly.push_str(&format!(" {px:.1},{py:.1}"));
            }
        }
        let svg = format!(
            r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 130"><polyline fill="none" stroke="#2563eb" stroke-width="1.2" points="{}"/></svg>"##,
            poly
        );
        std::fs::write(&env_svg, svg).map_err(|source| crate::error::Med64Error::WriteIo {
            path: env_svg.clone(),
            source,
        })?;
        outs.push(env_svg);
    }

    let prefer = dir.join("beta_prefer.html");
    {
        let display = serde_json::json!({
            "channel": report.channel + 1,
            "events": report.events.len(),
            "rate_per_min": report.rate_per_min,
        });
        let html = format!(
            r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>Beta Prefer</title>
<style>body{{font-family:system-ui;margin:1rem}}pre{{background:#f8fafc;padding:1rem}}</style></head>
<body><h1>Beta Prefer</h1>
<label>Preview scale <input id="scale" type="range" min="50" max="200" value="100"></label>
<pre id="opts">{opts}</pre>
<div id="preview">display options · Prefer UX substitute</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: &BetaExportOptions) -> 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_beta_package(
    report: &BetaOscillationReport,
    out_dir: impl AsRef<Path>,
    options: &BetaExportOptions,
) -> Result<Vec<PathBuf>> {
    let mut outs = write_beta_create_image(report, None, &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 })
}

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

    #[test]
    fn rectified_bursts_on_synthetic() {
        let mut samples = vec![0.01; 5000];
        for i in 1000..1300 {
            samples[i] = 1.0;
        }
        for i in 3000..3400 {
            samples[i] = 1.2;
        }
        let opts = BetaOscillationOptions {
            use_burst_detector: true,
            rectify: false,
            sd_percent: 200.0,
            min_duration_ms: 50.0,
            silent_interval_ms: 20.0,
            min_interval_ms: 100.0,
            highpass_hz: None,
            lowpass_hz: None,
            ..Default::default()
        };
        let report = detect_rectified_bursts(Path::new("synth"), &samples, 1.0, &opts);
        assert!(report.events.len() >= 2, "got {}", report.events.len());
        assert!(report.events[0].integ.unwrap_or(0.0) > 0.0);
    }
}