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
use std::path::{Path, PathBuf};

use crate::analysis::filter::LowPassKind;
use crate::analysis::spike::{
    enabled_channels_from_moflo, parse_active_channels, parse_channel_values, ThresholdMethod,
};
use crate::analysis::{run_analysis, AnalysisOptions};
use crate::error::Result;
use crate::export::{
    write_analysis_bundle, write_frequency_csv, write_spike_timestamps_csv,
    write_spike_timestamps_hdf5, write_spike_timestamps_plus_waveforms_csv,
};
use crate::moflo::MofloProtocol;
use crate::workflow::graph::{parse_links, WorkflowGraph};

#[derive(Debug, Clone)]
pub struct WorkflowOptions {
    pub max_blocks: Option<usize>,
    pub output_dir: Option<PathBuf>,
    pub export_csv: bool,
    pub export_hdf5: bool,
    pub export_bursts: bool,
    /// Write filtered i16/f32/CSV/modat when `export_raw_data` is present (or forced).
    pub export_filtered: bool,
    /// Emit HTML charts for `display_*` workflow nodes.
    pub render_display_charts: bool,
}

impl Default for WorkflowOptions {
    fn default() -> Self {
        Self {
            max_blocks: None,
            output_dir: None,
            export_csv: true,
            export_hdf5: false,
            export_bursts: true,
            export_filtered: false,
            render_display_charts: true,
        }
    }
}

#[derive(Debug, Clone)]
pub struct WorkflowReport {
    pub workflow_path: PathBuf,
    pub replay_paths: Vec<PathBuf>,
    pub replay_path: PathBuf,
    pub execution_order: Vec<String>,
    pub spike_count: usize,
    pub single_burst_count: usize,
    pub multi_burst_count: usize,
    pub outputs: Vec<PathBuf>,
}

/// Execute compute nodes from a `.moflo` workflow (filter → spike → burst → export).
pub fn run_workflow(
    workflow_path: impl AsRef<Path>,
    options: &WorkflowOptions,
) -> Result<WorkflowReport> {
    let workflow_path = workflow_path.as_ref().to_path_buf();
    let xml = std::fs::read_to_string(&workflow_path)
        .map_err(|source| crate::error::Med64Error::Io { path: workflow_path.clone(), source })?;
    let protocol = MofloProtocol::parse(&xml).map_err(|message| {
        crate::error::Med64Error::InvalidMoflo { path: workflow_path.clone(), message }
    })?;
    let links = parse_links(&xml).map_err(|message| crate::error::Med64Error::InvalidMoflo {
        path: workflow_path.clone(),
        message,
    })?;

    let graph = WorkflowGraph::from_protocol(&protocol, &links);
    let execution_order = graph.execution_order();

    let replay = graph.replay_node().ok_or_else(|| crate::error::Med64Error::InvalidMoflo {
        path: workflow_path.clone(),
        message: "workflow has no replay_data node".into(),
    })?;

    let replay_paths = protocol.resolve_replay_paths(&workflow_path);
    if replay_paths.is_empty() {
        return Err(crate::error::Med64Error::InvalidMoflo {
            path: workflow_path.clone(),
            message: "replay_data node has no filename".into(),
        });
    }

    let analysis_opts = build_analysis_options(&graph, replay, options);

    let out_dir = options
        .output_dir
        .clone()
        .unwrap_or_else(|| workflow_path.parent().unwrap_or(Path::new(".")).to_path_buf());
    std::fs::create_dir_all(&out_dir)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: out_dir.clone(), source })?;

    let mut total_spikes = 0usize;
    let mut total_single = 0usize;
    let mut total_multi = 0usize;
    let mut outputs = Vec::new();
    let mut primary_replay = replay_paths[0].clone();

    for replay_path in &replay_paths {
        primary_replay = replay_path.clone();
        let report = run_analysis(replay_path, &analysis_opts)?;
        total_spikes += report.spikes.len();
        total_single += report.single_bursts.len();
        total_multi += report.multi_bursts.len();

        let stem = replay_path
            .file_stem()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_else(|| "output".into());

        if options.export_csv || options.export_bursts {
            outputs.extend(write_analysis_bundle(&report, &out_dir, &stem)?);
        }

        for node in graph.save_spike_nodes() {
            if !setting_enabled(node, "storageEnabled") {
                continue;
            }
            let dest = export_path_from_node(node, &out_dir, &stem, "Spike Time Stamp.csv");
            let timestamps_only = node
                .settings
                .iter()
                .any(|(k, v)| k == "timeStampsOnly" && v.eq_ignore_ascii_case("true"));
            if timestamps_only {
                write_spike_timestamps_csv(&report, &dest)?;
            } else {
                write_spike_timestamps_plus_waveforms_csv(&report, &dest)?;
            }
            outputs.push(dest);
        }

        for node in graph.save_freq_nodes() {
            if !setting_enabled(node, "storageEnabled") {
                continue;
            }
            let dest = export_path_from_node(node, &out_dir, &stem, "Spike Frequency Chart.csv");
            write_frequency_csv(&report, &dest)?;
            outputs.push(dest);
        }

        if (options.export_filtered || graph.wants_filtered_export())
            && !report.filtered_by_channel.is_empty()
        {
            use crate::export_waveform::{write_filtered_waveforms, FilteredExportOptions};
            let filt = write_filtered_waveforms(
                &report,
                &out_dir,
                &stem,
                &FilteredExportOptions::default(),
            )?;
            outputs.extend(filt.paths);
        }

        if options.export_hdf5 {
            let h5_path = out_dir.join(format!("{stem}_spikes.h5"));
            write_spike_timestamps_hdf5(&report, &h5_path)?;
            outputs.push(h5_path);
        }

        #[cfg(all(feature = "chart", feature = "analysis"))]
        if options.render_display_charts {
            outputs.extend(render_display_nodes(
                &graph,
                replay_path,
                &report,
                &out_dir,
                &stem,
                options.max_blocks,
            )?);
            if let Ok(dash) =
                crate::burst_pipeline::write_analysis_dashboard_html(&report, &out_dir, &stem)
            {
                outputs.extend(dash);
            }
        }
        #[cfg(all(feature = "chart", not(feature = "analysis")))]
        if options.render_display_charts {
            outputs.extend(render_display_nodes(
                &graph,
                replay_path,
                &report,
                &out_dir,
                &stem,
                options.max_blocks,
            )?);
        }
    }

    Ok(WorkflowReport {
        workflow_path,
        replay_paths,
        replay_path: primary_replay,
        execution_order,
        spike_count: total_spikes,
        single_burst_count: total_single,
        multi_burst_count: total_multi,
        outputs,
    })
}

fn build_analysis_options(
    graph: &WorkflowGraph,
    replay: &crate::workflow::graph::WorkflowNodeRef,
    options: &WorkflowOptions,
) -> AnalysisOptions {
    let mut analysis_opts =
        AnalysisOptions { max_blocks: options.max_blocks, per_trace: true, ..Default::default() };

    if let Some((_, spec)) = replay.settings.iter().find(|(k, _)| k == "active_channels") {
        analysis_opts.enabled_channels = Some(parse_active_channels(spec, 64));
    }
    if let Some((_, from)) = replay.settings.iter().find(|(k, _)| k == "trace_time_from") {
        analysis_opts.time_from_ms = from.parse().unwrap_or(0.0);
    }
    if let Some((_, to)) = replay.settings.iter().find(|(k, _)| k == "trace_time_to") {
        analysis_opts.time_to_ms = Some(to.parse().unwrap_or(f64::MAX));
    }

    let cutoffs = graph.filter_chain_hz();
    if cutoffs.len() >= 2 {
        analysis_opts.highpass_hz = Some(cutoffs[0]);
        analysis_opts.lowpass_hz = Some(cutoffs[1]);
    } else if cutoffs.len() == 1 {
        analysis_opts.highpass_hz = Some(cutoffs[0]);
    }
    if graph.lowpass_is_bessel() {
        analysis_opts.lowpass_kind = LowPassKind::Bessel;
    }

    if let Some(spike_node) = graph.spike_settings() {
        apply_spike_settings(&mut analysis_opts, spike_node);
    }

    if options.export_filtered || graph.wants_filtered_export() {
        analysis_opts.retain_filtered = true;
    }

    if let Some(freq_node) = graph.nodes.values().find(|n| n.key == "compute_spike_freqs") {
        if let Some((_, window)) = freq_node.settings.iter().find(|(k, _)| k == "windowSize_ms") {
            analysis_opts.freq_window_ms = window.parse().unwrap_or(1000.0);
        }
    }

    analysis_opts
}

#[cfg(feature = "chart")]
fn render_display_nodes(
    graph: &WorkflowGraph,
    replay_path: &Path,
    report: &crate::analysis::AnalysisReport,
    out_dir: &Path,
    stem: &str,
    max_blocks: Option<usize>,
) -> Result<Vec<PathBuf>> {
    use crate::chart::{chart_file, ChartOptions};

    let mut paths = Vec::new();
    for node in graph.nodes.values() {
        if !node.key.starts_with("display_") {
            continue;
        }
        let out = out_dir.join(format!("{stem}_{}.html", node.key));
        match node.key.as_str() {
            "display_all_channels" | "display_spike_waveform" => {
                chart_file(
                    replay_path,
                    &out,
                    &ChartOptions {
                        max_points: 4000,
                        diagnostic_blocks: max_blocks.or(Some(5)),
                        ..Default::default()
                    },
                )?;
                paths.push(out);
            }
            "display_spike_frequencies" | "display_spike_freqs_all_chans" => {
                #[cfg(feature = "analysis")]
                {
                    crate::burst_pipeline::write_freq_count_chart_html(report, &out)?;
                    paths.push(out);
                }
                #[cfg(not(feature = "analysis"))]
                {
                    let _ = (replay_path, report);
                }
            }
            _ => {}
        }
    }
    Ok(paths)
}

fn setting_enabled(node: &crate::workflow::graph::WorkflowNodeRef, key: &str) -> bool {
    node.settings
        .iter()
        .find(|(k, _)| k == key)
        .map(|(_, v)| !v.eq_ignore_ascii_case("false"))
        .unwrap_or(true)
}

fn export_path_from_node(
    node: &crate::workflow::graph::WorkflowNodeRef,
    out_dir: &Path,
    stem: &str,
    default_name: &str,
) -> PathBuf {
    if let Some((_, dir)) = node.settings.iter().find(|(k, _)| k == "exportDirectory") {
        if !dir.is_empty() {
            let p = PathBuf::from(dir).join(default_name);
            if p.parent().is_some() {
                let _ = std::fs::create_dir_all(p.parent().unwrap());
            }
            return p;
        }
    }
    if let Some((_, name)) = node.settings.iter().find(|(k, _)| k == "filename") {
        if !name.is_empty() {
            return out_dir.join(name);
        }
    }
    out_dir.join(format!("{stem}_{default_name}"))
}

fn apply_spike_settings(
    opts: &mut AnalysisOptions,
    node: &crate::workflow::graph::WorkflowNodeRef,
) {
    // Mobius merges multiple <node_settings> blocks; later values override earlier ones.
    let mut plus_text = None;
    let mut minus_text = None;
    let mut pre_text = None;
    let mut post_text = None;
    let mut enabled = None;
    let mut limit_hz = opts.channel_spike_limit_hz;
    let mut rms_percent = opts.threshold_percent;
    let mut max_spikes = None;
    let mut threshold_type = None;

    for (key, value) in &node.settings {
        match key.as_str() {
            "posThresholds_mV" => plus_text = Some(value.as_str()),
            "negThresholds_mV" => minus_text = Some(value.as_str()),
            "pre_ms" => pre_text = Some(value.as_str()),
            "post_ms" => post_text = Some(value.as_str()),
            "enabled_channels" => enabled = Some(value.clone()),
            "channelSpikeLimit_Hz" => {
                limit_hz = value.parse().unwrap_or(limit_hz);
            }
            "rmsPercentage" => {
                rms_percent = value.parse().unwrap_or(rms_percent);
            }
            "maxSpikes" => {
                max_spikes = value.parse().ok();
            }
            "thresholdType" | "ThresholdType" => threshold_type = Some(value.clone()),
            _ => {}
        }
    }

    if let Some(spec) = enabled {
        opts.enabled_channels = Some(enabled_channels_from_moflo(&spec, 64));
    }

    opts.channel_spike_limit_hz = limit_hz;
    opts.threshold_percent = rms_percent;
    opts.max_spikes_per_channel = max_spikes;

    if let Some(text) = pre_text {
        opts.pre_ms_per_channel = Some(parse_channel_values(text, 64));
    }
    if let Some(text) = post_text {
        opts.post_ms_per_channel = Some(parse_channel_values(text, 64));
    }

    if let Some(tt) = threshold_type {
        if tt.eq_ignore_ascii_case("StandardDeviation") || tt == "1" {
            opts.threshold_method = ThresholdMethod::StandardDeviation;
        }
    }

    if let (Some(plus), Some(minus)) = (plus_text, minus_text) {
        let plus_vals = parse_channel_values(plus, 64);
        let minus_vals = parse_channel_values(minus, 64);
        let has_fixed =
            plus_vals.iter().zip(minus_vals.iter()).any(|(p, m)| *p != 0.0 || *m != 0.0);
        if has_fixed {
            opts.threshold_method = ThresholdMethod::Fixed;
            opts.plus_thresholds_mv = Some(plus_vals);
            opts.minus_thresholds_mv = Some(minus_vals);
        } else if opts.threshold_method != ThresholdMethod::StandardDeviation {
            opts.threshold_method = ThresholdMethod::Median;
            opts.plus_thresholds_mv = None;
            opts.minus_thresholds_mv = None;
        }
    } else if opts.threshold_method != ThresholdMethod::StandardDeviation {
        opts.threshold_method = ThresholdMethod::Median;
    }
}

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

    #[test]
    fn workflow_equivalent_options_find_spikes() {
        use crate::analysis::{run_analysis, AnalysisOptions};

        let path = crate::fixture_paths::sample_data6_cap();
        let base = AnalysisOptions { max_blocks: Some(5), ..Default::default() };

        let default_report = run_analysis(&path, &base).unwrap();
        assert!(!default_report.spikes.is_empty(), "default options should detect spikes");

        let filtered = run_analysis(
            &path,
            &AnalysisOptions { highpass_hz: Some(100.0), lowpass_hz: Some(2000.0), ..base },
        )
        .unwrap();

        assert!(!filtered.spikes.is_empty(), "100/2000 filter: {}", filtered.spikes.len());
    }

    #[test]
    fn sample_moflo_uses_adaptive_thresholds() {
        use crate::analysis::spike::ThresholdMethod;
        use crate::moflo::MofloProtocol;
        use crate::workflow::graph::WorkflowGraph;

        let path = crate::fixture_paths::sample_data6_moflo();
        let xml = std::fs::read_to_string(path).unwrap();
        let protocol = MofloProtocol::parse(&xml).unwrap();
        let links = crate::workflow::graph::parse_links(&xml).unwrap();
        let graph = WorkflowGraph::from_protocol(&protocol, &links);
        let spike = graph.spike_settings().unwrap();

        let mut opts = AnalysisOptions::default();
        apply_spike_settings(&mut opts, spike);

        assert_eq!(opts.threshold_method, ThresholdMethod::Median);
        assert_eq!(opts.threshold_percent, 500.0);
        assert!(opts.plus_thresholds_mv.is_none());
        assert!(opts.minus_thresholds_mv.is_none());
    }

    #[test]
    fn runs_sample_data6_workflow_subset() {
        let report = run_workflow(
            crate::fixture_paths::sample_data6_moflo(),
            &WorkflowOptions {
                max_blocks: Some(5),
                export_csv: false,
                export_hdf5: false,
                export_bursts: false,
                ..Default::default()
            },
        )
        .unwrap();
        assert!(report.replay_path.exists());
        assert!(!report.execution_order.is_empty());
        assert!(
            report.spike_count > 0,
            "expected spikes from workflow settings, got {}",
            report.spike_count
        );
    }
}