use std::io::Write;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::analysis::spike::SpikeTrain;
use crate::error::{Med64Error, Result};
use crate::toolkit::connectivity::{spike_connectivity, ConnectivityEdge, ConnectivityOptions};
#[derive(Debug, Clone)]
pub struct ConnectionMapOptions {
pub connectivity: ConnectivityOptions,
pub grid_cols: usize,
pub grid_rows: usize,
pub min_weight: f64,
pub write_matrix: bool,
pub write_edge_list: bool,
pub write_html: bool,
}
impl Default for ConnectionMapOptions {
fn default() -> Self {
Self {
connectivity: ConnectivityOptions::default(),
grid_cols: 8,
grid_rows: 8,
min_weight: 0.0,
write_matrix: true,
write_edge_list: true,
write_html: true,
}
}
}
pub type ConnectivityExportOptions = ConnectionMapOptions;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionMapReport {
pub n_channels: usize,
pub grid_cols: usize,
pub grid_rows: usize,
pub coincidence: Vec<Vec<f64>>,
pub peak_lag_ms: Vec<Vec<f64>>,
pub edges: Vec<ConnectivityEdge>,
}
pub fn connection_map(train: &SpikeTrain, options: &ConnectionMapOptions) -> ConnectionMapReport {
let n = options.grid_rows * options.grid_cols;
let report = spike_connectivity(train, &options.connectivity);
let mut coincidence = vec![vec![0.0; n]; n];
let mut peak_lag_ms = vec![vec![0.0; n]; n];
let edges: Vec<ConnectivityEdge> =
report.edges.into_iter().filter(|e| e.coincidence_index >= options.min_weight).collect();
for edge in &edges {
if edge.channel_a < n && edge.channel_b < n {
coincidence[edge.channel_a][edge.channel_b] = edge.coincidence_index;
coincidence[edge.channel_b][edge.channel_a] = edge.coincidence_index;
peak_lag_ms[edge.channel_a][edge.channel_b] = edge.peak_lag_ms;
peak_lag_ms[edge.channel_b][edge.channel_a] = -edge.peak_lag_ms;
}
}
ConnectionMapReport {
n_channels: n,
grid_cols: options.grid_cols,
grid_rows: options.grid_rows,
coincidence,
peak_lag_ms,
edges,
}
}
pub fn write_connection_map_package(
report: &ConnectionMapReport,
options: &ConnectionMapOptions,
out_dir: impl AsRef<Path>,
) -> Result<Vec<PathBuf>> {
let dir = out_dir.as_ref();
std::fs::create_dir_all(dir)
.map_err(|source| Med64Error::WriteIo { path: dir.to_path_buf(), source })?;
let mut outs = Vec::new();
if options.write_edge_list {
let p = dir.join("connection_map_edges.csv");
write_connection_map_csv(report, &p)?;
outs.push(p);
}
if options.write_matrix {
let p = dir.join("connection_map_matrix.csv");
write_connection_map_matrix_csv(report, &p)?;
outs.push(p);
}
if options.write_html {
let p = write_connection_map_html(report, dir.join("connection_map.html"))?;
outs.push(p);
}
Ok(outs)
}
pub fn write_connection_map_csv(
report: &ConnectionMapReport,
path: impl AsRef<Path>,
) -> Result<()> {
let path = path.as_ref();
let mut w = std::io::BufWriter::new(
std::fs::File::create(path)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })?,
);
writeln!(w, "channel_a,channel_b,peak_lag_ms,peak_count,coincidence_index")
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })?;
for e in &report.edges {
writeln!(
w,
"{},{},{:.4},{},{:.6}",
e.channel_a + 1,
e.channel_b + 1,
e.peak_lag_ms,
e.peak_count,
e.coincidence_index
)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })?;
}
Ok(())
}
pub fn write_connection_map_matrix_csv(
report: &ConnectionMapReport,
path: impl AsRef<Path>,
) -> Result<()> {
let path = path.as_ref();
let mut w = std::io::BufWriter::new(
std::fs::File::create(path)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })?,
);
write!(w, "ch").map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })?;
for j in 0..report.n_channels {
write!(w, ",{}", j + 1)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })?;
}
writeln!(w).map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })?;
for (i, row) in report.coincidence.iter().enumerate() {
write!(w, "{}", i + 1)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })?;
for v in row {
write!(w, ",{:.6}", v)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })?;
}
writeln!(w).map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })?;
}
Ok(())
}
pub fn write_connection_map_html(
report: &ConnectionMapReport,
path: impl AsRef<Path>,
) -> Result<PathBuf> {
let path = path.as_ref().to_path_buf();
let max_c = report.coincidence.iter().flatten().cloned().fold(0.0_f64, f64::max).max(1e-9);
let mut cells = String::new();
for i in 0..report.n_channels {
for j in 0..report.n_channels {
let c = report.coincidence[i][j];
let lag = report.peak_lag_ms[i][j];
let t = (c / max_c).clamp(0.0, 1.0);
let r = (20.0 + 200.0 * t) as u8;
let g = (30.0 + 80.0 * (1.0 - t)) as u8;
let b = (60.0 + 120.0 * (1.0 - t)) as u8;
cells.push_str(&format!(
"<div class=\"cell\" title=\"Ch{}→Ch{} coinc={:.2} lag={:.1}ms\" style=\"background:rgb({r},{g},{b})\"></div>",
i + 1,
j + 1,
c,
lag
));
}
}
let html = format!(
r#"<!DOCTYPE html><html><head><meta charset="utf-8"/><title>Connection Map</title>
<style>
body{{font-family:system-ui,sans-serif;margin:1.5rem;background:#0f1419;color:#e7ecf3}}
h1{{font-weight:600;font-size:1.25rem}}
.grid{{display:grid;grid-template-columns:repeat({cols},1fr);gap:1px;max-width:720px;background:#1a222c;padding:1px}}
.cell{{aspect-ratio:1;min-width:6px}}
.meta{{opacity:.75;font-size:.9rem;margin-bottom:1rem}}
</style></head><body>
<h1>Connection Map</h1>
<p class="meta">{n} channels · {edges} pairs · max coincidence {max:.2}</p>
<div class="grid">{cells}</div>
</body></html>"#,
cols = report.n_channels,
n = report.n_channels,
edges = report.edges.len(),
max = max_c,
cells = cells
);
std::fs::write(&path, html)
.map_err(|source| Med64Error::WriteIo { path: path.clone(), source })?;
Ok(path)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::analysis::spike::{Spike, SpikeTrain};
#[test]
fn matrix_symmetric_for_pair() {
let mut train = SpikeTrain::default();
for t in [10.0, 20.0, 30.0, 40.0, 50.0] {
train.push(Spike { channel: 0, within_trace_time_ms: t, ..Default::default() });
train.push(Spike { channel: 1, within_trace_time_ms: t + 2.0, ..Default::default() });
}
let map = connection_map(
&train,
&ConnectionMapOptions { grid_cols: 2, grid_rows: 1, ..Default::default() },
);
assert!(map.coincidence[0][1] > 0.0);
assert!((map.coincidence[0][1] - map.coincidence[1][0]).abs() < 1e-9);
}
}