use serde::{Deserialize, Serialize};
use crate::analysis::spike::SpikeTrain;
#[derive(Debug, Clone)]
pub struct AutocorrOptions {
pub bin_ms: f64,
pub max_lag_ms: f64,
pub exclude_zero_lag: bool,
}
impl Default for AutocorrOptions {
fn default() -> Self {
Self { bin_ms: 1.0, max_lag_ms: 100.0, exclude_zero_lag: true }
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelAutocorr {
pub channel: usize,
pub lag_ms: Vec<f64>,
pub counts: Vec<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutocorrReport {
pub channels: Vec<ChannelAutocorr>,
pub lag_ms: Vec<f64>,
pub total_counts: Vec<u64>,
}
pub fn spike_autocorrelogram(train: &SpikeTrain, options: &AutocorrOptions) -> AutocorrReport {
let n_bins = ((2.0 * options.max_lag_ms) / options.bin_ms).ceil() as usize;
let n_bins = n_bins.max(1);
let lag_ms: Vec<f64> =
(0..n_bins).map(|i| -options.max_lag_ms + i as f64 * options.bin_ms).collect();
let center = (options.max_lag_ms / options.bin_ms).round() as isize;
let mut channels = Vec::new();
let mut total = vec![0u64; n_bins];
for (channel, spikes) in train.by_channel() {
if spikes.len() < 2 {
continue;
}
let times: Vec<f64> = spikes.iter().map(|s| s.within_trace_time_ms).collect();
let mut counts = vec![0u64; n_bins];
for (i, &ti) in times.iter().enumerate() {
for (j, &tj) in times.iter().enumerate() {
if i == j {
continue;
}
let lag = tj - ti;
if lag.abs() > options.max_lag_ms {
continue;
}
if options.exclude_zero_lag && lag.abs() < options.bin_ms * 0.5 {
continue;
}
let idx = center + (lag / options.bin_ms).round() as isize;
if idx >= 0 && (idx as usize) < n_bins {
counts[idx as usize] += 1;
}
}
}
for (t, c) in total.iter_mut().zip(&counts) {
*t += *c;
}
channels.push(ChannelAutocorr { channel, lag_ms: lag_ms.clone(), counts });
}
AutocorrReport { channels, lag_ms, total_counts: total }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::analysis::spike::{Spike, SpikeTrain};
#[test]
fn regular_train_peaks_at_isi() {
let mut train = SpikeTrain::default();
for k in 0..20 {
train.push(Spike {
channel: 0,
within_trace_time_ms: k as f64 * 10.0,
..Default::default()
});
}
let report = spike_autocorrelogram(
&train,
&AutocorrOptions { bin_ms: 1.0, max_lag_ms: 50.0, exclude_zero_lag: true },
);
assert_eq!(report.channels.len(), 1);
let ch = &report.channels[0];
let idx_pos = ch.lag_ms.iter().position(|&l| (l - 10.0).abs() < 0.6).unwrap();
let idx_zero = ch.lag_ms.iter().position(|&l| l.abs() < 0.6).unwrap();
assert!(ch.counts[idx_pos] > ch.counts[idx_zero]);
}
}