use serde::{Deserialize, Serialize};
use crate::analysis::spike::SpikeTrain;
#[derive(Debug, Clone)]
pub struct ConnectivityOptions {
pub max_lag_ms: f64,
pub bin_ms: f64,
pub min_spikes: usize,
}
impl Default for ConnectivityOptions {
fn default() -> Self {
Self { max_lag_ms: 50.0, bin_ms: 1.0, min_spikes: 5 }
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectivityEdge {
pub channel_a: usize,
pub channel_b: usize,
pub peak_lag_ms: f64,
pub peak_count: u64,
pub coincidence_index: f64,
pub histogram: Vec<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectivityReport {
pub edges: Vec<ConnectivityEdge>,
pub lag_edges_ms: Vec<f64>,
}
pub fn spike_connectivity(train: &SpikeTrain, options: &ConnectivityOptions) -> ConnectivityReport {
let n_bins = ((2.0 * options.max_lag_ms) / options.bin_ms).ceil() as usize;
let lag_edges: Vec<f64> =
(0..n_bins).map(|i| -options.max_lag_ms + i as f64 * options.bin_ms).collect();
let by_ch = train.by_channel();
let channels: Vec<usize> = by_ch
.iter()
.filter(|(_, spikes)| spikes.len() >= options.min_spikes)
.map(|(&ch, _)| ch)
.collect();
let mut edges = Vec::new();
for (i, &a) in channels.iter().enumerate() {
for &b in &channels[i + 1..] {
let sa = &by_ch[&a];
let sb = &by_ch[&b];
let mut hist = vec![0u64; n_bins.max(1)];
for spa in sa {
for spb in sb {
let lag = spb.within_trace_time_ms - spa.within_trace_time_ms;
if lag.abs() > options.max_lag_ms {
continue;
}
let idx = ((lag + options.max_lag_ms) / options.bin_ms).floor() as isize;
if idx >= 0 && (idx as usize) < hist.len() {
hist[idx as usize] += 1;
}
}
}
let (peak_i, &peak_count) =
hist.iter().enumerate().max_by_key(|(_, c)| *c).unwrap_or((0, &0));
let expected = hist.iter().sum::<u64>() as f64 / hist.len().max(1) as f64;
let coincidence = if expected > 0.0 { peak_count as f64 / expected } else { 0.0 };
edges.push(ConnectivityEdge {
channel_a: a,
channel_b: b,
peak_lag_ms: lag_edges.get(peak_i).copied().unwrap_or(0.0),
peak_count,
coincidence_index: coincidence,
histogram: hist,
});
}
}
edges.sort_by(|x, y| y.coincidence_index.partial_cmp(&x.coincidence_index).unwrap());
ConnectivityReport { edges, lag_edges_ms: lag_edges }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::analysis::spike::{Spike, SpikeTrain};
#[test]
fn finds_coincident_pair() {
let mut train = SpikeTrain::default();
for t in [10.0, 20.0, 30.0, 40.0, 50.0, 60.0] {
train.push(Spike { channel: 0, within_trace_time_ms: t, ..Default::default() });
train.push(Spike { channel: 1, within_trace_time_ms: t + 1.0, ..Default::default() });
}
let report = spike_connectivity(&train, &ConnectivityOptions::default());
assert!(!report.edges.is_empty());
assert!(report.edges[0].coincidence_index > 1.0);
}
}