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
//! Rate-map packages, prefs, overlays, and plate HTML.

use std::path::{Path, PathBuf};

use crate::analysis::AnalysisReport;
use crate::error::Result;
use crate::toolkit::poincare::{poincare_isi, PoincareReport};
use crate::toolkit::propagation::PropagationReport;

use super::compute::{compute_stv_table, RateMapBatchReport, RateMapReport, StvMetrics};
use super::tables::{
    write_poincare_isi_csv, write_rate_map_channel_table_csv, write_rate_map_smoothing_csv,
    write_rate_table1_csv, write_rate_table2_csv, write_rate_table2r_csv,
};
#[cfg(feature = "correlation")]
use super::tables::write_synchrony_table_csv;
use super::wells::{
    write_well_plate_channels_bin, write_well_plate_channels_csv, write_well_plate_raw_html,
    write_well_plate_viewer_html_with_analysis,
};

/// Preferences for well packages / map chart.
pub struct RateMapPrefs {
    pub color_min: Option<f64>,
    pub color_max: Option<f64>,
    pub ms_div: Option<f64>,
    pub mv_div: Option<f64>,
    pub duration_ms: Option<f64>,
    /// Max raw well HTML pages (`None` = all active wells; default 6).
    pub well_limit: Option<usize>,
    /// Use A1-style well IDs in rate summary CSV.
    pub alpha_well_labels: bool,
    pub plate: crate::layout::WellPlate,
    /// Also write `well_N_channels.csv` (time Ă— electrodes).
    pub export_raw_csv: bool,
    /// Also write `well_N_channels.bin` (f32 LE) + sidecar JSON.
    pub export_raw_bin: bool,
    /// Poincaré ISI return-map max ISI filter (ms); `None` = no filter.
    pub poincare_max_isi_ms: Option<f64>,
    /// When analysis present, write `poincare_isi.csv`.
    pub poincare_enabled: bool,
    /// Write `rate_table2r.csv` (clipboard rate table 2r with optional ISI column).
    pub write_rate_table2r: bool,
}

impl Default for RateMapPrefs {
    fn default() -> Self {
        Self {
            color_min: None,
            color_max: None,
            ms_div: None,
            mv_div: None,
            duration_ms: None,
            well_limit: Some(6),
            alpha_well_labels: true,
            plate: crate::layout::WellPlate::Wells24,
            export_raw_csv: false,
            export_raw_bin: false,
            poincare_max_isi_ms: None,
            poincare_enabled: true,
            write_rate_table2r: true,
        }
    }
}

pub fn write_rate_map_prefs_json(prefs: &RateMapPrefs, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let body = format!(
        "{{\n  \"color_min\": {:?},\n  \"color_max\": {:?},\n  \"ms_div\": {:?},\n  \"mv_div\": {:?},\n  \"duration_ms\": {:?},\n  \"well_limit\": {:?},\n  \"alpha_well_labels\": {},\n  \"plate\": \"{:?}\",\n  \"export_raw_csv\": {},\n  \"export_raw_bin\": {},\n  \"poincare_max_isi_ms\": {:?},\n  \"poincare_enabled\": {},\n  \"write_rate_table2r\": {}\n}}\n",
        prefs.color_min,
        prefs.color_max,
        prefs.ms_div,
        prefs.mv_div,
        prefs.duration_ms,
        prefs.well_limit,
        prefs.alpha_well_labels,
        prefs.plate,
        prefs.export_raw_csv,
        prefs.export_raw_bin,
        prefs.poincare_max_isi_ms,
        prefs.poincare_enabled,
        prefs.write_rate_table2r
    );
    std::fs::write(path, body)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// Write well-plate package: `wells.html`, active `well_N_raw.html`, `rate_summary.csv`.
pub fn write_rate_map_well_package(
    rate_map: &RateMapReport,
    analysis: Option<&AnalysisReport>,
    out_dir: impl AsRef<Path>,
) -> Result<Vec<PathBuf>> {
    write_rate_map_well_package_with_prefs(rate_map, analysis, out_dir, &RateMapPrefs::default())
}

pub fn write_rate_map_well_package_with_prefs(
    rate_map: &RateMapReport,
    analysis: Option<&AnalysisReport>,
    out_dir: impl AsRef<Path>,
    prefs: &RateMapPrefs,
) -> 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 wells_html = dir.join("wells.html");
    write_well_plate_viewer_html_with_analysis(rate_map, analysis, &wells_html)?;
    outs.push(wells_html);

    let prefs_path = dir.join("rate_map_prefs.json");
    write_rate_map_prefs_json(prefs, &prefs_path)?;
    outs.push(prefs_path);

    let well_count = prefs.plate.well_count();
    let mut well_activity: Vec<(usize, usize)> = (0..well_count)
        .map(|w| {
            let spikes: usize = rate_map
                .cells
                .iter()
                .filter(|c| c.well.unwrap_or(c.channel / prefs.plate.electrodes_per_well()) == w)
                .map(|c| c.spike_count)
                .sum();
            (w, spikes)
        })
        .collect();
    well_activity.sort_by_key(|a| std::cmp::Reverse(a.1));
    let limit = prefs.well_limit.unwrap_or(usize::MAX);
    let active: Vec<usize> =
        well_activity.into_iter().filter(|(_, n)| *n > 0).take(limit).map(|(w, _)| w).collect();

    if let Some(report) = analysis {
        for w in &active {
            let raw = dir.join(format!("well_{}_raw.html", w + 1));
            write_well_plate_raw_html(&rate_map.path, *w, report, rate_map, &raw)?;
            outs.push(raw);
            if prefs.export_raw_csv {
                let csv = dir.join(format!("well_{}_channels.csv", w + 1));
                write_well_plate_channels_csv(report, *w, prefs.plate, &csv)?;
                outs.push(csv);
            }
            if prefs.export_raw_bin {
                let bin = dir.join(format!("well_{}_channels.bin", w + 1));
                let meta = dir.join(format!("well_{}_channels.json", w + 1));
                write_well_plate_channels_bin(report, *w, prefs.plate, &bin, &meta)?;
                outs.push(bin);
                outs.push(meta);
            }
        }
    }

    let syu = dir.join("rate_summary.csv");
    let mut w = String::from("channel,label,well,well_id,rate_hz,spike_count\n");
    for cell in &rate_map.cells {
        let well_idx = cell.well.unwrap_or(cell.channel / prefs.plate.electrodes_per_well());
        let well_id = if prefs.alpha_well_labels {
            prefs.plate.alpha_well_label(well_idx)
        } else {
            format!("W{}", well_idx + 1)
        };
        w.push_str(&format!(
            "{},{},{},{},{:.6},{}\n",
            cell.channel + 1,
            cell.label.replace(',', ";"),
            well_idx + 1,
            well_id,
            cell.rate_hz,
            cell.spike_count
        ));
    }
    std::fs::write(&syu, w)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: syu.clone(), source })?;
    outs.push(syu);

    let channel_table = dir.join("rate_map_channel_table.csv");
    write_rate_map_channel_table_csv(rate_map, &channel_table)?;
    outs.push(channel_table);

    let rate_table1 = dir.join("rate_table1.csv");
    write_rate_table1_csv(rate_map, &rate_table1)?;
    outs.push(rate_table1);

    let rate_table2 = dir.join("rate_table2.csv");
    write_rate_table2_csv(rate_map, &rate_table2)?;
    outs.push(rate_table2);

    let smoothing = dir.join("smoothingdata.csv");
    write_rate_map_smoothing_csv(rate_map, 3, &smoothing)?;
    outs.push(smoothing);

    // Tablestv-shaped wide STV CSV when analysis available.
    if let Some(report) = analysis {
        let stv_rows = compute_stv_table(report, None);
        let stv = dir.join("stv_metrics.csv");
        write_stv_metrics_csv(&stv_rows, &stv)?;
        outs.push(stv);

        if prefs.write_rate_table2r {
            let rate_table2r = dir.join("rate_table2r.csv");
            write_rate_table2r_csv(rate_map, Some(&stv_rows), &rate_table2r)?;
            outs.push(rate_table2r);
        }

        if prefs.poincare_enabled {
            let mut poi = poincare_isi(&report.spikes);
            if let Some(max_isi) = prefs.poincare_max_isi_ms {
                poi.points.retain(|p| p.isi_n_ms <= max_isi && p.isi_n1_ms <= max_isi);
            }
            let poi_path = dir.join("poincare_isi.csv");
            write_poincare_isi_csv(&poi, &poi_path)?;
            outs.push(poi_path);
        }

        #[cfg(feature = "correlation")]
        {
            let syn = crate::analysis::synchrony_index(
                &report.single_bursts,
                &crate::analysis::CorrelationOptions::default(),
            );
            if !syn.is_empty() {
                let syn_path = dir.join("synchrony_table.csv");
                write_synchrony_table_csv(&syn, &syn_path)?;
                outs.push(syn_path);
            }
        }
    } else if prefs.write_rate_table2r {
        let rate_table2r = dir.join("rate_table2r.csv");
        write_rate_table2r_csv(rate_map, None, &rate_table2r)?;
        outs.push(rate_table2r);
    }
    Ok(outs)
}

/// `Tablestv` multi-column synchrony-style CSV (Ch1… groups of 8).
pub fn write_stv_metrics_csv(rows: &[StvMetrics], path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let mut out =
        String::from("channel,mean_isi_ms,sd_isi_ms,stv_ms,mean_velocity_mm_per_s,group8\n");
    for r in rows {
        let vel = r.mean_velocity_mm_per_s.map(|v| format!("{v:.6}")).unwrap_or_default();
        out.push_str(&format!(
            "{},{:.6},{:.6},{:.6},{},{}\n",
            r.channel + 1,
            r.mean_isi_ms,
            r.sd_isi_ms,
            r.stv_ms,
            vel,
            r.channel / 8 + 1
        ));
    }
    std::fs::write(path, out)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })
}

pub fn write_rate_map_summary_csv(
    batch: &RateMapBatchReport,
    path: impl AsRef<Path>,
) -> Result<()> {
    let path = path.as_ref();
    let mut w = String::from("path,spikes,max_rate_hz,mean_stv_ms,delay_span_ms\n");
    for f in &batch.files {
        w.push_str(&format!(
            "{},{},{:.6},{:.6},{:.6}\n",
            f.path.display(),
            f.spike_count,
            f.max_rate_hz,
            f.mean_stv_ms,
            f.reference_delay_span_ms
        ));
    }
    std::fs::write(path, w)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// `Tablestv`–style per-channel STV / ISI / velocity CSV.
pub fn write_stv_table_csv(rows: &[StvMetrics], path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let mut w = String::from("channel,mean_isi_ms,sd_isi_ms,stv_ms,mean_velocity_mm_per_s\n");
    for r in rows {
        let vel = r.mean_velocity_mm_per_s.map(|v| format!("{v:.6}")).unwrap_or_default();
        w.push_str(&format!(
            "{},{:.6},{:.6},{:.6},{}\n",
            r.channel + 1,
            r.mean_isi_ms,
            r.sd_isi_ms,
            r.stv_ms,
            vel
        ));
    }
    std::fs::write(path, w)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// `Syuukei`–style wide table: one row per channel, rate columns per file.
pub fn write_rate_summary_csv(batch: &RateMapBatchReport, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let mut channels = std::collections::BTreeSet::new();
    for map in &batch.maps {
        for c in &map.cells {
            channels.insert(c.channel);
        }
    }
    let mut header = String::from("channel");
    for f in &batch.files {
        let stem = f
            .path
            .file_stem()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_else(|| f.path.display().to_string());
        header.push(',');
        header.push_str(&stem.replace(',', ";"));
        header.push_str("_rate_hz");
    }
    header.push('\n');
    let mut w = header;
    for ch in channels {
        w.push_str(&(ch + 1).to_string());
        for map in &batch.maps {
            let rate = map.cells.iter().find(|c| c.channel == ch).map(|c| c.rate_hz).unwrap_or(0.0);
            w.push_str(&format!(",{rate:.6}"));
        }
        w.push('\n');
    }
    std::fs::write(path, w)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// Overlay spike-rate maps: rate grid + Poincaré scatter + propagation delay grid + optional extra files.
pub fn write_rate_map_overlay_html(
    maps: &[RateMapReport],
    poincare: Option<&PoincareReport>,
    propagation: Option<&PropagationReport>,
    path: impl AsRef<Path>,
) -> Result<()> {
    let path = path.as_ref();
    let mut body = String::from(
        "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Spike-rate map overlays</title>\
         <style>body{font-family:system-ui;margin:1rem}.g{display:grid;gap:2px;max-width:320px}\
         .c{aspect-ratio:1}.row{display:flex;flex-wrap:wrap;gap:1.5rem}</style></head><body>\
         <h1>Spike-rate map overlays</h1>",
    );
    body.push_str("<div class=\"row\">");
    for (i, map) in maps.iter().enumerate() {
        let cols = map.cells.iter().map(|c| c.col).max().unwrap_or(7) + 1;
        body.push_str(&format!(
            "<section><h2>Rate #{}</h2><p>{}</p><div class=\"g\" style=\"grid-template-columns:repeat({cols},1fr)\">",
            i + 1,
            html_escape(&map.path.display().to_string())
        ));
        let max = map.max_rate_hz.max(1e-12);
        for cell in &map.cells {
            let t = (cell.rate_hz / 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;
            body.push_str(&format!(
                "<div class=\"c\" title=\"{}\" style=\"background:rgb({r},{g},{b})\"></div>",
                html_escape(&cell.label)
            ));
        }
        body.push_str("</div></section>");
    }
    body.push_str("</div>");
    if let Some(p) = poincare {
        body.push_str(&format!(
            "<h2>Poincaré ISI</h2><p>SD1={:.3} SD2={:.3} mean ISI={:.2} ms · {} points</p>\
             <svg width=\"360\" height=\"360\" viewBox=\"0 0 360 360\" style=\"background:#fff;border:1px solid #ddd\">",
            p.sd1, p.sd2, p.mean_isi_ms, p.points.len()
        ));
        let max =
            p.points.iter().flat_map(|pt| [pt.isi_n_ms, pt.isi_n1_ms]).fold(1.0_f64, f64::max);
        for pt in p.points.iter().take(2000) {
            let x = 20.0 + pt.isi_n_ms / max * 320.0;
            let y = 340.0 - pt.isi_n1_ms / max * 320.0;
            body.push_str(&format!(
                "<circle cx=\"{x:.1}\" cy=\"{y:.1}\" r=\"2\" fill=\"#2563eb\" opacity=\"0.5\"/>"
            ));
        }
        body.push_str("</svg>");
    }
    if let Some(pr) = propagation {
        body.push_str("<h2>Propagation delay</h2><div class=\"g\" style=\"grid-template-columns:repeat(8,1fr)\">");
        let max_d = pr.cells.iter().filter_map(|c| c.delay_ms).fold(1e-6_f64, f64::max);
        for cell in &pr.cells {
            let t = cell.delay_ms.unwrap_or(0.0) / max_d;
            let r = (255.0 * t.clamp(0.0, 1.0)) as u8;
            let b = (255.0 * (1.0 - t.clamp(0.0, 1.0))) as u8;
            body.push_str(&format!("<div class=\"c\" style=\"background:rgb({r},80,{b})\"></div>"));
        }
        body.push_str("</div>");
    }
    body.push_str("</body></html>");
    std::fs::write(path, body)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })
}

#[cfg(feature = "layouts")]
pub fn write_well_plate_html(
    report: &RateMapReport,
    plate: crate::layout::WellPlate,
    path: impl AsRef<Path>,
) -> Result<()> {
    let path = path.as_ref();
    let wells = plate.well_count();
    let elec = plate.electrodes_per_well();
    let cols = plate.plate_cols();
    let max = report.max_rate_hz.max(1e-9);
    let mut by: Vec<Vec<f64>> = vec![vec![0.0; elec]; wells];
    for cell in &report.cells {
        let w = plate.well_of_channel(cell.channel);
        let e = plate.electrode_in_well(cell.channel);
        if w < wells && e < elec {
            by[w][e] = cell.rate_hz;
        }
    }
    let ecols = (elec as f64).sqrt().round() as usize;
    let ecols = ecols.max(1);
    let mut wells_html = String::new();
    for w in 0..wells {
        wells_html.push_str(&format!(
            "<div class=\"well\"><div class=\"wlabel\">W{}</div><div class=\"eg\" style=\"grid-template-columns:repeat({ecols},1fr)\">",
            w + 1
        ));
        for e in 0..elec {
            let rate = by[w][e];
            let t = (rate / 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;
            wells_html.push_str(&format!(
                "<div class=\"e\" style=\"background:rgb({r},{g},{b})\"></div>"
            ));
        }
        wells_html.push_str("</div></div>");
    }
    let html = format!(
        r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>{plate:?} viewer</title>
<style>body{{font-family:system-ui;margin:1rem}}
.plate{{display:grid;grid-template-columns:repeat({cols},1fr);gap:8px;max-width:1100px}}
.well{{background:#fff;border:1px solid #ddd;border-radius:6px;padding:4px}}
.eg{{display:grid;gap:1px}}.e{{aspect-ratio:1}}</style></head><body>
<h1>{plate:?} spike-rate plate</h1>
<p>{}</p><div class="plate">{wells}</div></body></html>"#,
        html_escape(&report.path.display().to_string()),
        wells = wells_html
    );
    std::fs::write(path, html)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })
}

fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}