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
//! Well-plate viewers and channel exports.

use std::path::Path;

use crate::analysis::AnalysisReport;
use crate::error::Result;

use super::compute::{RateMapCell, RateMapReport};

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

pub fn write_rate_map_html(report: &RateMapReport, out: impl AsRef<Path>) -> Result<()> {
    let out = out.as_ref();
    let cols = report.cells.iter().map(|c| c.col).max().map(|c| c + 1).unwrap_or(8);
    let mut html = String::from(
        "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Spike-rate map</title>\
         <style>body{font-family:system-ui;margin:1rem}\
         .grid{display:grid;gap:2px;max-width:640px}\
         .cell{aspect-ratio:1;display:flex;align-items:center;justify-content:center;\
         font-size:10px;border-radius:4px;color:#111}</style></head><body>\
         <h1>Spike rate map</h1><p>Source: ",
    );
    html.push_str(&html_escape(&report.path.display().to_string()));
    html.push_str(&format!(
        "</p><p>Duration: {:.2}s — max rate: {:.2} Hz</p>\
         <div class=\"grid\" style=\"grid-template-columns:repeat({cols},1fr)\">",
        report.duration_sec, report.max_rate_hz
    ));

    for cell in &report.cells {
        let t = if report.max_rate_hz > 0.0 { cell.rate_hz / report.max_rate_hz } else { 0.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;
        html.push_str(&format!(
            "<div class=\"cell\" title=\"{}\" style=\"background:rgb({r},{g},{b})\">\
             {:.1}</div>",
            html_escape(&cell.label),
            cell.rate_hz
        ));
    }
    html.push_str("</div></body></html>");
    std::fs::write(out, html)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: out.to_path_buf(), source })?;
    Ok(())
}

/// PRESTO 24-well plate viewer: selectable wells, rate bars, and sparkline mode.
///
/// When `analysis` is provided with `retain_filtered` traces, sparkline mode uses
/// real downsampled waveforms; otherwise bars are synthesized from rate/count.
pub fn write_well_plate_viewer_html(report: &RateMapReport, path: impl AsRef<Path>) -> Result<()> {
    write_well_plate_viewer_html_with_analysis(report, None, path)
}

/// Same as [`write_well_plate_viewer_html`] with optional filtered waveforms.
pub fn write_well_plate_viewer_html_with_analysis(
    report: &RateMapReport,
    analysis: Option<&AnalysisReport>,
    path: impl AsRef<Path>,
) -> Result<()> {
    let path = path.as_ref();
    let max = report.max_rate_hz.max(1e-9);
    let mut by_well: Vec<Vec<Option<&RateMapCell>>> = vec![vec![None; 16]; 24];
    for cell in &report.cells {
        let well = cell.well.unwrap_or(cell.channel / 16);
        let elec = cell.channel % 16;
        if well < 24 && elec < 16 {
            by_well[well][elec] = Some(cell);
        }
    }

    let mut wells_json = Vec::new();
    for well in 0..24 {
        let mut electrodes = Vec::new();
        let mut well_rate_sum = 0.0_f64;
        for elec in 0..16 {
            let (ch, label, rate, count) = match by_well[well][elec] {
                Some(c) => (c.channel, c.label.clone(), c.rate_hz, c.spike_count),
                None => (well * 16 + elec, format!("W{:02}E{}", well + 1, elec + 1), 0.0, 0),
            };
            well_rate_sum += rate;
            let spark = sparkline_points(analysis, ch, rate, count, max);
            electrodes.push(serde_json::json!({
                "ch": ch,
                "label": label,
                "rate": rate,
                "count": count,
                "spark": spark,
            }));
        }
        wells_json.push(serde_json::json!({
            "well": well,
            "label": format!("W{}", well + 1),
            "mean_rate": well_rate_sum / 16.0,
            "electrodes": electrodes,
        }));
    }

    let html = format!(
        r#"<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>PRESTO 24-well viewer</title>
<style>
body{{font-family:system-ui;margin:1rem;background:#fafafa;color:#111}}
h1{{font-size:1.2rem;margin:0 0 .25rem}}
.sub{{color:#555;margin-bottom:1rem;font-size:.9rem}}
.layout{{display:flex;gap:1.25rem;flex-wrap:wrap;align-items:flex-start}}
.plate{{display:grid;grid-template-columns:repeat(6,1fr);gap:6px;max-width:420px}}
.wellbtn{{border:1px solid #cbd5e1;background:#fff;border-radius:6px;padding:6px 4px;
cursor:pointer;text-align:center;font-size:.7rem}}
.wellbtn:hover,.wellbtn.active{{border-color:#2563eb;box-shadow:0 0 0 2px #bfdbfe}}
.wellbtn .strip{{height:5px;border-radius:2px;margin-top:4px}}
.detail{{flex:1;min-width:280px;background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:1rem}}
.modes{{display:flex;gap:.5rem;margin-bottom:.75rem}}
.modes button{{font:inherit;font-size:.8rem;padding:.25rem .6rem;border:1px solid #cbd5e1;
background:#f8fafc;border-radius:4px;cursor:pointer}}
.modes button.active{{background:#2563eb;color:#fff;border-color:#2563eb}}
.bars{{display:flex;flex-direction:column;gap:4px}}
.barrow{{display:grid;grid-template-columns:4.5rem 1fr 3.5rem;gap:6px;align-items:center;font-size:.75rem}}
.bartrack{{height:10px;background:#e2e8f0;border-radius:3px;overflow:hidden}}
.barfill{{height:100%;background:#2563eb}}
.sparks{{display:grid;grid-template-columns:repeat(4,1fr);gap:8px}}
.spark{{border:1px solid #e2e8f0;border-radius:4px;padding:4px;background:#fafafa}}
.spark label{{display:block;font-size:.65rem;color:#64748b;margin-bottom:2px}}
.spark svg{{width:100%;height:36px;display:block}}
</style></head><body>
<h1>PRESTO 24-well spike-rate viewer</h1>
<p class="sub">{src} · max {max:.2} Hz · {dur:.2}s</p>
<div class="layout">
  <div>
    <div class="plate" id="plate"></div>
  </div>
  <div class="detail">
    <div class="modes">
      <button type="button" id="mode-bars" class="active">Rate bars</button>
      <button type="button" id="mode-spark">Sparklines</button>
    </div>
    <h2 id="well-title" style="font-size:1rem;margin:.25rem 0 .75rem">Select a well</h2>
    <div id="panel"></div>
  </div>
</div>
<script>
const wells = {wells};
const maxRate = {max};
let selected = 0;
let mode = 'bars';
const plate = document.getElementById('plate');
const panel = document.getElementById('panel');
const title = document.getElementById('well-title');
wells.forEach((w,i) => {{
  const b = document.createElement('button');
  b.type = 'button';
  b.className = 'wellbtn' + (i===0?' active':'');
  b.dataset.i = i;
  const t = (w.mean_rate/maxRate);
  const r = Math.round(255*t), g = Math.round(40+80*(1-t)), bl = Math.round(255*(1-t));
  b.innerHTML = w.label + '<div class="strip" style="background:rgb('+r+','+g+','+bl+')"></div>';
  b.onclick = () => {{ selected = i; render(); }};
  plate.appendChild(b);
}});
document.getElementById('mode-bars').onclick = () => {{ mode='bars'; setMode(); render(); }};
document.getElementById('mode-spark').onclick = () => {{ mode='spark'; setMode(); render(); }};
function setMode() {{
  document.getElementById('mode-bars').classList.toggle('active', mode==='bars');
  document.getElementById('mode-spark').classList.toggle('active', mode==='spark');
}}
function render() {{
  [...plate.children].forEach((el,i) => el.classList.toggle('active', i===selected));
  const w = wells[selected];
  title.textContent = w.label + ' · mean ' + w.mean_rate.toFixed(2) + ' Hz';
  if (mode === 'bars') {{
    panel.innerHTML = '<div class="bars">' + w.electrodes.map(e => {{
      const pct = Math.min(100, (e.rate/maxRate)*100);
      return '<div class="barrow"><span>'+e.label+'</span><div class="bartrack"><div class="barfill" style="width:'+pct+'%"></div></div><span>'+e.rate.toFixed(2)+' Hz</span></div>';
    }}).join('') + '</div>';
  }} else {{
    panel.innerHTML = '<div class="sparks">' + w.electrodes.map(e => {{
      const pts = (e.spark||[]).map((p,i)=>{{
        const x = (i/Math.max(1,(e.spark.length-1)))*100;
        const y = 36 - p*34;
        return x.toFixed(1)+','+y.toFixed(1);
      }}).join(' ');
      return '<div class="spark"><label>'+e.label+' · '+e.rate.toFixed(2)+' Hz</label><svg viewBox="0 0 100 36" preserveAspectRatio="none"><polyline fill="none" stroke='#2563eb' stroke-width="1.2" points="'+pts+'"/></svg></div>';
    }}).join('') + '</div>';
  }}
}}
render();
</script></body></html>"#,
        src = html_escape(&report.path.display().to_string()),
        max = report.max_rate_hz,
        dur = report.duration_sec,
        wells = serde_json::to_string(&wells_json).unwrap_or_else(|_| "[]".into()),
    );
    std::fs::write(path, html)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })?;
    Ok(())
}

/// Normalized 0..1 sparkline samples for one channel (real waveform or rate placeholder).
fn sparkline_points(
    analysis: Option<&AnalysisReport>,
    channel: usize,
    rate: f64,
    count: usize,
    max_rate: f64,
) -> Vec<f64> {
    const N: usize = 48;
    if let Some(report) = analysis {
        if let Some(samples) = report.filtered_by_channel.get(&channel) {
            if samples.len() >= 2 {
                let step = (samples.len() / N).max(1);
                let chunk: Vec<f64> = samples.iter().copied().step_by(step).take(N).collect();
                let min_y = chunk.iter().copied().fold(f64::INFINITY, f64::min);
                let max_y = chunk.iter().copied().fold(f64::NEG_INFINITY, f64::max);
                let span = (max_y - min_y).abs().max(1e-9);
                return chunk.iter().map(|y| ((y - min_y) / span).clamp(0.0, 1.0)).collect();
            }
        }
    }
    // Placeholder: height from rate, with mild count-based modulation.
    let h = (rate / max_rate.max(1e-9)).clamp(0.05, 1.0);
    let modu = ((count % 7) as f64 + 1.0) / 8.0;
    (0..N)
        .map(|i| {
            let t = i as f64 / (N - 1) as f64;
            let wave = (t * std::f64::consts::PI * 4.0).sin().abs();
            (h * (0.35 + 0.65 * wave) * (0.7 + 0.3 * modu)).clamp(0.0, 1.0)
        })
        .collect()
}

/// Wide CSV: `time_ms,e1_mV,…,eN_mV` for one PRESTO well's electrodes.
pub fn write_well_plate_channels_csv(
    report: &AnalysisReport,
    well_index: usize,
    plate: crate::layout::WellPlate,
    path: impl AsRef<Path>,
) -> Result<()> {
    let path = path.as_ref();
    let per = plate.electrodes_per_well();
    let channels: Vec<usize> = (0..per).map(|e| well_index * per + e).collect();
    let n = channels
        .iter()
        .filter_map(|ch| report.filtered_by_channel.get(ch).map(|v| v.len()))
        .max()
        .unwrap_or(0);
    let interval = report.header.interval_ms();
    let mut out = String::from("time_ms");
    for e in 0..per {
        out.push_str(&format!(",e{}", e + 1));
    }
    out.push('\n');
    for i in 0..n {
        out.push_str(&format!("{:.6}", i as f64 * interval));
        for &ch in &channels {
            let mv =
                report.filtered_by_channel.get(&ch).and_then(|v| v.get(i).copied()).unwrap_or(0.0);
            out.push_str(&format!(",{mv:.8}"));
        }
        out.push('\n');
    }
    std::fs::write(path, out)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// Little-endian f32 `[n_samples × electrodes]` + JSON sidecar (`fs`, well, channels).
pub fn write_well_plate_channels_bin(
    report: &AnalysisReport,
    well_index: usize,
    plate: crate::layout::WellPlate,
    bin_path: impl AsRef<Path>,
    meta_path: impl AsRef<Path>,
) -> Result<()> {
    let bin_path = bin_path.as_ref();
    let meta_path = meta_path.as_ref();
    let per = plate.electrodes_per_well();
    let channels: Vec<usize> = (0..per).map(|e| well_index * per + e).collect();
    let n = channels
        .iter()
        .filter_map(|ch| report.filtered_by_channel.get(ch).map(|v| v.len()))
        .max()
        .unwrap_or(0);
    let mut bytes = Vec::with_capacity(n * per * 4);
    for i in 0..n {
        for &ch in &channels {
            let mv =
                report.filtered_by_channel.get(&ch).and_then(|v| v.get(i).copied()).unwrap_or(0.0)
                    as f32;
            bytes.extend_from_slice(&mv.to_le_bytes());
        }
    }
    std::fs::write(bin_path, bytes).map_err(|source| crate::error::Med64Error::WriteIo {
        path: bin_path.to_path_buf(),
        source,
    })?;
    let meta = serde_json::json!({
        "well_index": well_index,
        "well_label": plate.alpha_well_label(well_index),
        "electrodes": per,
        "channels_1based": channels.iter().map(|c| c + 1).collect::<Vec<_>>(),
        "n_samples": n,
        "sample_rate_hz": report.header.sampling_frequency_hz,
        "dtype": "f32le",
        "layout": "sample_major_x_electrode",
    });
    std::fs::write(meta_path, serde_json::to_string_pretty(&meta).unwrap()).map_err(|source| {
        crate::error::Med64Error::WriteIo { path: meta_path.to_path_buf(), source }
    })
}

/// Plot filtered waveforms for the 16 electrodes in one PRESTO well (SVG, downsampled).
pub fn write_well_plate_raw_html(
    path: impl AsRef<Path>,
    well_index: usize,
    report: &AnalysisReport,
    rate_map: &RateMapReport,
    out: impl AsRef<Path>,
) -> Result<()> {
    let out = out.as_ref();
    let well = well_index.min(23);
    let interval = report.header.interval_ms().max(1e-9);
    let max_pts = 400usize;
    let mut panels = String::new();
    for elec in 0..16 {
        let ch = well * 16 + elec;
        let label = rate_map
            .cells
            .iter()
            .find(|c| c.channel == ch)
            .map(|c| c.label.clone())
            .unwrap_or_else(|| format!("W{:02}E{}", well + 1, elec + 1));
        let rate =
            rate_map.cells.iter().find(|c| c.channel == ch).map(|c| c.rate_hz).unwrap_or(0.0);
        let samples = report.filtered_by_channel.get(&ch);
        let polyline = if let Some(samples) = samples {
            if samples.len() >= 2 {
                let step = (samples.len() / max_pts).max(1);
                let series: Vec<(f64, f64)> = samples
                    .iter()
                    .enumerate()
                    .step_by(step)
                    .map(|(i, &mv)| (i as f64 * interval, mv))
                    .collect();
                let min_x = series[0].0;
                let max_x = series.last().map(|s| s.0).unwrap_or(1.0).max(min_x + 1.0);
                let min_y = series.iter().map(|(_, y)| *y).fold(f64::INFINITY, f64::min);
                let max_y = series.iter().map(|(_, y)| *y).fold(f64::NEG_INFINITY, f64::max);
                let span_y = (max_y - min_y).abs().max(1e-9);
                let mut pts = String::new();
                for &(x, y) in &series {
                    let px = (x - min_x) / (max_x - min_x) * 280.0;
                    let py = 60.0 - (y - min_y) / span_y * 56.0;
                    pts.push_str(&format!("{px:.1},{py:.1} "));
                }
                format!(
                    r#"<polyline fill="none" stroke='#2563eb' stroke-width="1" points="{pts}"/>"#
                )
            } else {
                String::new()
            }
        } else {
            // Placeholder bars from rate when waveforms absent.
            let h = (rate / rate_map.max_rate_hz.max(1e-9)).clamp(0.05, 1.0) * 50.0;
            format!(
                r#"<rect x="20" y="{y:.1}" width="240" height="{h:.1}" fill='#93c5fd'/>"#,
                y = 58.0 - h
            )
        };
        panels.push_str(&format!(
            r#"<div class="ch"><div class="lab">{label} · {rate:.2} Hz</div>
<svg viewBox="0 0 280 64" width="100%" height="64">{polyline}</svg></div>"#
        ));
    }
    let html = format!(
        r#"<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Well {wn} raw</title>
<style>
body{{font-family:system-ui;margin:1rem;background:#fafafa}}
h1{{font-size:1.1rem}}
.grid{{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;max-width:960px}}
.ch{{background:#fff;border:1px solid #e2e8f0;border-radius:6px;padding:4px}}
.lab{{font-size:.7rem;color:#64748b}}
</style></head><body>
<h1>Well {wn} · filtered waveforms</h1>
<p>{src}</p>
<label>Amp scale <input id="amp" type="range" min="1" max="20" value="10"></label>
<label>Scrubber <input id="scrubber" type="range" min="0" max="100" value="0"></label>
<div class="grid">{panels}</div>
<script>
const amp=document.getElementById('amp'), scrub=document.getElementById('scrubber');
function apply(){{
  const a=+amp.value/10, s=+scrub.value;
  document.querySelectorAll('svg polyline').forEach(p=>{{
    p.style.transform=`scaleY(${{a}}) translateX(${{-s}}%)`;
    p.style.transformOrigin='center';
  }});
}}
amp.addEventListener('input',apply); scrub.addEventListener('input',apply);
</script>
</body></html>"#,
        wn = well + 1,
        src = html_escape(&path.as_ref().display().to_string()),
        panels = panels
    );
    std::fs::write(out, html)
        .map_err(|source| crate::error::Med64Error::WriteIo { path: out.to_path_buf(), source })?;
    Ok(())
}