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,
};
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>,
pub well_limit: Option<usize>,
pub alpha_well_labels: bool,
pub plate: crate::layout::WellPlate,
pub export_raw_csv: bool,
pub export_raw_bin: bool,
pub poincare_max_isi_ms: Option<f64>,
pub poincare_enabled: bool,
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 })
}
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);
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)
}
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 })
}
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 })
}
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 })
}
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('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
}