use serde::{Deserialize, Serialize};
use crate::analysis::{run_analysis, AnalysisOptions, SpikeTrain};
use crate::error::{Med64Error, Result};
use crate::layout::WellPlate;
use crate::toolkit::propagation_oversample::{
upsample_delay_grid, OversampleGrid, OversampleMode, ShihyouBins,
};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone)]
pub struct PropagationOptions {
pub analysis: AnalysisOptions,
pub electrode_pitch_um: f64,
pub grid_cols: usize,
pub grid_rows: usize,
pub reference_channel: Option<usize>,
pub average_bin: AverageBinKind,
pub well_plate: WellPlate,
pub conduction_bins: usize,
pub oversample: OversampleMode,
pub shihyou: ShihyouBins,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AverageBinKind {
#[default]
None,
Bin16,
Bin32,
Presto,
}
impl AverageBinKind {
pub fn parse(s: &str) -> Option<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"none" | "off" => Some(Self::None),
"16" | "bin16" => Some(Self::Bin16),
"32" | "bin32" => Some(Self::Bin32),
"presto" | "24" => Some(Self::Presto),
_ => None,
}
}
}
impl Default for PropagationOptions {
fn default() -> Self {
Self {
analysis: AnalysisOptions { max_blocks: Some(10), ..AnalysisOptions::default() },
electrode_pitch_um: 150.0,
grid_cols: 8,
grid_rows: 8,
reference_channel: None,
average_bin: AverageBinKind::None,
well_plate: WellPlate::Wells24,
conduction_bins: 1,
oversample: OversampleMode::None,
shihyou: ShihyouBins::Off,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PropagationCell {
pub channel: usize,
pub row: usize,
pub col: usize,
pub first_spike_ms: Option<f64>,
pub delay_ms: Option<f64>,
pub velocity_mm_per_s: Option<f64>,
pub color_index: u16,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PropagationReport {
pub path: std::path::PathBuf,
pub reference_channel: usize,
pub reference_time_ms: f64,
pub cells: Vec<PropagationCell>,
pub oversample: Option<OversampleGrid>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConductionFrame {
pub bin_index: usize,
pub start_ms: f64,
pub end_ms: f64,
pub report: PropagationReport,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConductionSeries {
pub path: PathBuf,
pub frames: Vec<ConductionFrame>,
}
pub fn propagation_delay_map(
path: impl AsRef<Path>,
options: &PropagationOptions,
) -> Result<PropagationReport> {
let path = path.as_ref();
let report = run_analysis(path, &options.analysis)?;
Ok(propagation_from_spikes(path, &report.spikes, options))
}
pub fn propagation_from_spikes(
path: impl AsRef<Path>,
train: &SpikeTrain,
options: &PropagationOptions,
) -> PropagationReport {
let mut first: std::collections::BTreeMap<usize, f64> = std::collections::BTreeMap::new();
for spike in &train.spikes {
first
.entry(spike.channel)
.and_modify(|t| *t = t.min(spike.within_trace_time_ms))
.or_insert(spike.within_trace_time_ms);
}
let (ref_ch, ref_t) = if let Some(ch) = options.reference_channel {
(ch, first.get(&ch).copied().unwrap_or(0.0))
} else {
first
.iter()
.min_by(|a, b| a.1.partial_cmp(b.1).unwrap())
.map(|(&c, &t)| (c, t))
.unwrap_or((0, 0.0))
};
let (ref_r, ref_c) = grid_pos(ref_ch, options.grid_rows, options.grid_cols);
let mut cells = Vec::new();
let n = options.grid_rows * options.grid_cols;
for ch in 0..n {
let (row, col) = grid_pos(ch, options.grid_rows, options.grid_cols);
let first_spike = first.get(&ch).copied();
let delay = first_spike.map(|t| t - ref_t);
let velocity = delay.map(|d| {
if d.abs() < 1e-6 {
return 0.0;
}
let dist_um = (((row as f64 - ref_r as f64).powi(2)
+ (col as f64 - ref_c as f64).powi(2))
.sqrt())
* options.electrode_pitch_um;
(dist_um / 1000.0) / (d / 1000.0) });
cells.push(PropagationCell {
channel: ch,
row,
col,
first_spike_ms: first_spike,
delay_ms: delay,
velocity_mm_per_s: velocity,
color_index: 0,
});
}
let mut report = PropagationReport {
path: path.as_ref().to_path_buf(),
reference_channel: ref_ch,
reference_time_ms: ref_t,
cells,
oversample: None,
};
report.cells = apply_average_bins(&report.cells, options.average_bin, options);
apply_color_and_oversample(&mut report, options);
report
}
fn apply_color_and_oversample(report: &mut PropagationReport, options: &PropagationOptions) {
let maxamp = report.cells.iter().filter_map(|c| c.delay_ms).fold(0.0_f64, f64::max);
for c in &mut report.cells {
if let Some(d) = c.delay_ms {
c.color_index =
crate::toolkit::propagation_oversample::color_bin(d, maxamp, options.shihyou);
}
}
if matches!(options.oversample, OversampleMode::None) {
return;
}
let rows = report.cells.iter().map(|c| c.row).max().unwrap_or(0) + 1;
let cols = report.cells.iter().map(|c| c.col).max().unwrap_or(0) + 1;
let mut grid = vec![f64::NAN; rows * cols];
for c in &report.cells {
if let Some(d) = c.delay_ms {
if c.row < rows && c.col < cols {
grid[c.row * cols + c.col] = d;
}
}
}
report.oversample =
Some(upsample_delay_grid(&grid, rows, cols, options.oversample, options.shihyou));
}
pub fn conduction_series_from_spikes(
path: impl AsRef<Path>,
train: &SpikeTrain,
options: &PropagationOptions,
) -> ConductionSeries {
let path = path.as_ref();
let n_bins = options.conduction_bins.max(1);
if n_bins <= 1 || train.spikes.is_empty() {
let report = propagation_from_spikes(path, train, options);
return ConductionSeries {
path: path.to_path_buf(),
frames: vec![ConductionFrame {
bin_index: 0,
start_ms: 0.0,
end_ms: train.spikes.iter().map(|s| s.within_trace_time_ms).fold(0.0, f64::max),
report,
}],
};
}
let t_min = train.spikes.iter().map(|s| s.within_trace_time_ms).fold(f64::INFINITY, f64::min);
let t_max =
train.spikes.iter().map(|s| s.within_trace_time_ms).fold(f64::NEG_INFINITY, f64::max);
let span = (t_max - t_min).max(1e-9);
let mut frames = Vec::with_capacity(n_bins);
for b in 0..n_bins {
let start = t_min + span * b as f64 / n_bins as f64;
let end = t_min + span * (b + 1) as f64 / n_bins as f64;
let mut subset = SpikeTrain::default();
for spike in &train.spikes {
let t = spike.within_trace_time_ms;
if t >= start && (t < end || (b + 1 == n_bins && t <= end)) {
subset.spikes.push(spike.clone());
}
}
let report = propagation_from_spikes(path, &subset, options);
frames.push(ConductionFrame { bin_index: b, start_ms: start, end_ms: end, report });
}
ConductionSeries { path: path.to_path_buf(), frames }
}
pub fn conduction_series(
path: impl AsRef<Path>,
options: &PropagationOptions,
) -> Result<ConductionSeries> {
let path = path.as_ref();
let report = run_analysis(path, &options.analysis)?;
Ok(conduction_series_from_spikes(path, &report.spikes, options))
}
pub fn pdm_detect(path: impl AsRef<Path>, analysis: &AnalysisOptions) -> Result<SpikeTrain> {
Ok(run_analysis(path, analysis)?.spikes)
}
pub fn write_propagation_csv(report: &PropagationReport, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let mut w =
String::from("channel,row,col,first_spike_ms,delay_ms,velocity_mm_per_s,color_index\n");
for c in &report.cells {
w.push_str(&format!(
"{},{},{},{},{},{},{}\n",
c.channel + 1,
c.row,
c.col,
opt_f64(c.first_spike_ms),
opt_f64(c.delay_ms),
opt_f64(c.velocity_mm_per_s),
c.color_index
));
}
std::fs::write(path, w)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })?;
if let Some(grid) = &report.oversample {
let op = path.with_file_name(
path.file_stem()
.and_then(|s| s.to_str())
.map(|s| format!("{s}_oversample.csv"))
.unwrap_or_else(|| "propagation_oversample.csv".into()),
);
write_oversample_csv(grid, &op)?;
}
Ok(())
}
pub fn write_oversample_csv(grid: &OversampleGrid, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let mut w = String::from("row,col,delay_ms,color_index\n");
for r in 0..grid.rows {
for c in 0..grid.cols {
let i = r * grid.cols + c;
let d = grid.delays_ms[i];
w.push_str(&format!(
"{},{},{},{}\n",
r,
c,
if d.is_finite() { format!("{d:.6}") } else { String::new() },
grid.color_index[i]
));
}
}
std::fs::write(path, w)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
pub fn write_propagation_html(report: &PropagationReport, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let cols = report.cells.iter().map(|c| c.col).max().map(|c| c + 1).unwrap_or(8);
let max_d = report.cells.iter().filter_map(|c| c.delay_ms).fold(1e-6_f64, f64::max);
let mean_vel = {
let vs: Vec<f64> = report
.cells
.iter()
.filter_map(|c| c.velocity_mm_per_s)
.filter(|v| v.is_finite())
.collect();
if vs.is_empty() {
0.0
} else {
vs.iter().sum::<f64>() / vs.len() as f64
}
};
let cells_json = serde_json::to_string(
&report
.cells
.iter()
.map(|c| {
serde_json::json!({
"ch": c.channel + 1,
"row": c.row,
"col": c.col,
"delay": c.delay_ms,
"vel": c.velocity_mm_per_s,
"t": c.delay_ms.map(|d| (d / max_d).clamp(0.0, 1.0)).unwrap_or(0.0),
})
})
.collect::<Vec<_>>(),
)
.unwrap_or_else(|_| "[]".into());
let html = format!(
r#"<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Propagation delay</title>
<style>
body{{font-family:system-ui;margin:1.25rem;background:#fafafa}}
.grid{{display:grid;gap:3px;max-width:480px}}
.cell{{aspect-ratio:1;border-radius:3px;cursor:pointer}}
#detail{{margin-top:1rem;padding:.75rem;background:#fff;border:1px solid #ddd;border-radius:6px}}
</style></head><body>
<h1>Propagation delay map</h1>
<p>{src} · ref ch{ref_ch} @ {ref_t:.3} ms · mean velocity {vel:.2} mm/s</p>
<div class="grid" id="g" style="grid-template-columns:repeat({cols},1fr)"></div>
<div id="detail">Click a cell for details</div>
<script>
const cells = {cells};
const g = document.getElementById('g');
const detail = document.getElementById('detail');
cells.forEach(c => {{
const d = document.createElement('div');
d.className = 'cell';
const t = c.t;
d.style.background = `rgb(${{Math.round(255*t)}},80,${{Math.round(255*(1-t))}})`;
d.title = 'Ch' + c.ch;
d.onclick = () => {{
detail.textContent = `Ch ${{c.ch}} · delay ${{c.delay != null ? c.delay.toFixed(3)+' ms' : 'n/a'}} · velocity ${{c.vel != null ? c.vel.toFixed(2)+' mm/s' : 'n/a'}}`;
}};
g.appendChild(d);
}});
</script></body></html>"#,
src = report.path.display(),
ref_ch = report.reference_channel + 1,
ref_t = report.reference_time_ms,
vel = mean_vel,
cols = cols,
cells = cells_json
);
std::fs::write(path, html)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
pub fn write_conduction_html(series: &ConductionSeries, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let frames_json = serde_json::to_string(
&series
.frames
.iter()
.map(|f| {
let max_d =
f.report.cells.iter().filter_map(|c| c.delay_ms).fold(1e-6_f64, f64::max);
serde_json::json!({
"bin": f.bin_index,
"start": f.start_ms,
"end": f.end_ms,
"ref_ch": f.report.reference_channel + 1,
"ref_t": f.report.reference_time_ms,
"cells": f.report.cells.iter().map(|c| serde_json::json!({
"ch": c.channel + 1,
"row": c.row,
"col": c.col,
"delay": c.delay_ms,
"t": c.delay_ms.map(|d| (d / max_d).clamp(0.0, 1.0)).unwrap_or(0.0),
})).collect::<Vec<_>>(),
})
})
.collect::<Vec<_>>(),
)
.unwrap_or_else(|_| "[]".into());
let cols = series
.frames
.first()
.and_then(|f| f.report.cells.iter().map(|c| c.col).max())
.map(|c| c + 1)
.unwrap_or(8);
let html = format!(
r#"<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Conduction series</title>
<style>
body{{font-family:system-ui;margin:1.25rem}}
.grid{{display:grid;gap:3px;max-width:480px}}
.cell{{aspect-ratio:1;border-radius:3px}}
input[type=range]{{width:min(480px,100%)}}
</style></head><body>
<h1>Conduction series</h1>
<p>{src} · {n} frames</p>
<label>Frame <span id="lab">0</span></label><br>
<input type="range" id="slider" min="0" max="{max}" value="0">
<p id="meta"></p>
<div class="grid" id="g" style="grid-template-columns:repeat({cols},1fr)"></div>
<script>
const frames = {frames};
const g = document.getElementById('g');
const slider = document.getElementById('slider');
const lab = document.getElementById('lab');
const meta = document.getElementById('meta');
function render(i) {{
const f = frames[i];
lab.textContent = i;
meta.textContent = `bin ${{f.bin}} · ${{f.start.toFixed(1)}}–${{f.end.toFixed(1)}} ms · ref ch${{f.ref_ch}} @ ${{f.ref_t.toFixed(3)}} ms`;
g.innerHTML = '';
f.cells.forEach(c => {{
const d = document.createElement('div');
d.className = 'cell';
d.style.background = `rgb(${{Math.round(255*c.t)}},80,${{Math.round(255*(1-c.t))}})`;
d.title = 'Ch' + c.ch + (c.delay != null ? (' ' + c.delay.toFixed(2) + ' ms') : '');
g.appendChild(d);
}});
}}
slider.oninput = () => render(+slider.value);
render(0);
</script></body></html>"#,
src = series.path.display(),
n = series.frames.len(),
max = series.frames.len().saturating_sub(1),
cols = cols,
frames = frames_json
);
std::fs::write(path, html)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
fn apply_average_bins(
cells: &[PropagationCell],
kind: AverageBinKind,
options: &PropagationOptions,
) -> Vec<PropagationCell> {
match kind {
AverageBinKind::None => cells.to_vec(),
AverageBinKind::Bin16 => average_fixed_groups(cells, 4, options),
AverageBinKind::Bin32 => average_fixed_groups(cells, 2, options),
AverageBinKind::Presto => average_presto_wells(cells, options),
}
}
fn mean_opt(vals: &[f64]) -> Option<f64> {
if vals.is_empty() {
None
} else {
Some(vals.iter().sum::<f64>() / vals.len() as f64)
}
}
fn velocity_from_delay(options: &PropagationOptions, delay: Option<f64>) -> Option<f64> {
delay.map(|d| {
if d.abs() < 1e-6 {
0.0
} else {
(options.electrode_pitch_um / 1000.0) / (d / 1000.0)
}
})
}
fn average_fixed_groups(
cells: &[PropagationCell],
group: usize,
options: &PropagationOptions,
) -> Vec<PropagationCell> {
let mut out = Vec::new();
let n = options.grid_rows * options.grid_cols;
let bins = n.div_ceil(group);
for b in 0..bins {
let slice = &cells[(b * group).min(cells.len())..((b + 1) * group).min(cells.len())];
let delays: Vec<f64> = slice.iter().filter_map(|c| c.delay_ms).collect();
let firsts: Vec<f64> = slice.iter().filter_map(|c| c.first_spike_ms).collect();
let delay = mean_opt(&delays);
out.push(PropagationCell {
channel: b,
row: b / options.grid_cols.max(1),
col: b % options.grid_cols.max(1),
first_spike_ms: mean_opt(&firsts),
delay_ms: delay,
velocity_mm_per_s: velocity_from_delay(options, delay),
color_index: 0,
});
}
out
}
fn average_presto_wells(
cells: &[PropagationCell],
options: &PropagationOptions,
) -> Vec<PropagationCell> {
let plate = options.well_plate;
let n_wells = plate.well_count();
let cols = plate.plate_cols().max(1);
let mut buckets: Vec<(Vec<f64>, Vec<f64>)> =
(0..n_wells).map(|_| (Vec::new(), Vec::new())).collect();
for c in cells {
let w = plate.well_of_channel(c.channel).min(n_wells.saturating_sub(1));
if let Some(d) = c.delay_ms {
buckets[w].0.push(d);
}
if let Some(t) = c.first_spike_ms {
buckets[w].1.push(t);
}
}
buckets
.into_iter()
.enumerate()
.map(|(w, (delays, firsts))| {
let delay = mean_opt(&delays);
PropagationCell {
channel: w,
row: w / cols,
col: w % cols,
first_spike_ms: mean_opt(&firsts),
delay_ms: delay,
velocity_mm_per_s: velocity_from_delay(options, delay),
color_index: 0,
}
})
.collect()
}
fn grid_pos(channel: usize, rows: usize, cols: usize) -> (usize, usize) {
let idx = channel % (rows * cols);
(idx / cols, idx % cols)
}
fn opt_f64(v: Option<f64>) -> String {
v.map(|x| format!("{x:.6}")).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::analysis::spike::{Spike, SpikeTrain};
#[test]
fn delay_increases_with_time() {
let mut train = SpikeTrain::default();
train.push(Spike { channel: 0, within_trace_time_ms: 10.0, ..Default::default() });
train.push(Spike { channel: 1, within_trace_time_ms: 20.0, ..Default::default() });
let report = propagation_from_spikes(
"mem.modat",
&train,
&PropagationOptions { reference_channel: Some(0), ..Default::default() },
);
let c1 = report.cells.iter().find(|c| c.channel == 1).unwrap();
assert!((c1.delay_ms.unwrap() - 10.0).abs() < 1e-9);
}
#[test]
fn conduction_bins_split() {
let mut train = SpikeTrain::default();
for (ch, t) in [(0, 10.0), (1, 20.0), (0, 100.0), (1, 110.0)] {
train.push(Spike { channel: ch, within_trace_time_ms: t, ..Default::default() });
}
let series = conduction_series_from_spikes(
"mem.modat",
&train,
&PropagationOptions {
reference_channel: Some(0),
conduction_bins: 2,
..Default::default()
},
);
assert_eq!(series.frames.len(), 2);
}
}