use serde::{Deserialize, Serialize};
use crate::analysis::spike::SpikeTrain;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum MultiBurstMethod {
#[default]
RateThreshold,
NetworkBurst,
Spikes,
ActiveChannels,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiChannelBurst {
pub trace: u32,
pub start_ms: f64,
pub end_ms: f64,
pub peak_rate_hz: f64,
pub num_spikes: usize,
pub peak_series: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsdrPoint {
pub time_ms: f64,
pub rate_hz: f64,
pub smoothed_hz: f64,
pub spike_count: usize,
pub active_channels: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsdrTrace {
pub points: Vec<AsdrPoint>,
pub threshold_hz: f64,
pub lower_threshold: f64,
pub method: MultiBurstMethod,
pub bursts: Vec<MultiChannelBurst>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AutoThresholdBase {
Mean,
MedianMad,
PopulationSd,
}
#[derive(Debug, Clone)]
pub struct MultiChannelBurstOptions {
pub bin_width_ms: f64,
pub smoothing_bins: usize,
pub auto_threshold_percent: f64,
pub auto_threshold_percent_low: f64,
pub auto_threshold_base: AutoThresholdBase,
pub manual_upper: Option<f64>,
pub manual_lower: Option<f64>,
pub method: MultiBurstMethod,
pub min_bursting_channels: usize,
}
impl Default for MultiChannelBurstOptions {
fn default() -> Self {
Self {
bin_width_ms: 50.0,
smoothing_bins: 5,
auto_threshold_percent: 200.0,
auto_threshold_percent_low: 100.0,
auto_threshold_base: AutoThresholdBase::Mean,
manual_upper: None,
manual_lower: None,
method: MultiBurstMethod::RateThreshold,
min_bursting_channels: 1,
}
}
}
pub fn detect_multi_channel_bursts(
train: &SpikeTrain,
trace_duration_ms: f64,
options: &MultiChannelBurstOptions,
) -> Vec<MultiChannelBurst> {
compute_asdr(train, trace_duration_ms, options).bursts
}
pub fn compute_asdr(
train: &SpikeTrain,
trace_duration_ms: f64,
options: &MultiChannelBurstOptions,
) -> AsdrTrace {
if train.is_empty() || trace_duration_ms <= 0.0 || options.bin_width_ms <= 0.0 {
return AsdrTrace {
points: Vec::new(),
threshold_hz: 0.0,
lower_threshold: 0.0,
method: options.method,
bursts: Vec::new(),
};
}
let bin_count = (trace_duration_ms / options.bin_width_ms).ceil() as usize;
let bin_count = bin_count.max(1);
let mut spike_counts = vec![0usize; bin_count];
let mut channel_sets: Vec<std::collections::BTreeSet<usize>> =
vec![std::collections::BTreeSet::new(); bin_count];
let gate =
matches!(options.method, MultiBurstMethod::NetworkBurst | MultiBurstMethod::ActiveChannels)
&& options.min_bursting_channels > 1;
let mut per_bin_channel: Vec<std::collections::BTreeMap<usize, usize>> =
vec![std::collections::BTreeMap::new(); bin_count];
for spike in &train.spikes {
let idx = (spike.within_trace_time_ms / options.bin_width_ms) as usize;
if idx < bin_count {
spike_counts[idx] += 1;
*per_bin_channel[idx].entry(spike.channel).or_insert(0) += 1;
}
}
for (idx, counts) in per_bin_channel.iter().enumerate() {
for (&channel, &n) in counts {
if !gate || n >= options.min_bursting_channels {
channel_sets[idx].insert(channel);
}
}
}
let active: Vec<usize> = channel_sets.iter().map(|s| s.len()).collect();
let series: Vec<f64> = (0..bin_count)
.map(|i| match options.method {
MultiBurstMethod::RateThreshold => {
let scale = 1000.0 / options.bin_width_ms;
round_half_up_3(spike_counts[i] as f64 * scale)
}
MultiBurstMethod::NetworkBurst => spike_counts[i] as f64 * active[i] as f64,
MultiBurstMethod::Spikes => spike_counts[i] as f64,
MultiBurstMethod::ActiveChannels => active[i] as f64,
})
.collect();
let w = options.smoothing_bins;
let smoothed = calc_moving_average(&series, w);
let (upper, lower) = thresholds(&series, options);
let points: Vec<AsdrPoint> = (0..bin_count)
.map(|i| AsdrPoint {
time_ms: i as f64 * options.bin_width_ms,
rate_hz: series[i],
smoothed_hz: if smoothed[i].is_nan() { series[i] } else { smoothed[i] },
spike_count: spike_counts[i],
active_channels: active[i],
})
.collect();
let bursts = detect_rate_bursts(
&series,
&smoothed,
&spike_counts,
upper,
lower,
w,
options.bin_width_ms,
train.spikes.first().map(|s| s.trace).unwrap_or(0),
);
AsdrTrace {
points,
threshold_hz: upper,
lower_threshold: lower,
method: options.method,
bursts,
}
}
fn round_half_up_3(v: f64) -> f64 {
(v * 1000.0).round() / 1000.0
}
pub fn calc_moving_average(values: &[f64], window: usize) -> Vec<f64> {
if window == 0 {
return values.to_vec();
}
let n = values.len();
let mut out = vec![f64::NAN; n];
if n <= 2 * window {
return out;
}
for i in window..(n - window) {
let start = i - window;
let end = i + window + 1;
let slice = &values[start..end];
out[i] = slice.iter().sum::<f64>() / slice.len() as f64;
}
out
}
fn thresholds(raw: &[f64], options: &MultiChannelBurstOptions) -> (f64, f64) {
if let (Some(u), Some(l)) = (options.manual_upper, options.manual_lower) {
return (u, l);
}
if let Some(u) = options.manual_upper {
return (u, options.manual_lower.unwrap_or(u * 0.5));
}
let base = match options.auto_threshold_base {
AutoThresholdBase::Mean => {
if raw.is_empty() {
0.0
} else {
raw.iter().sum::<f64>() / raw.len() as f64
}
}
AutoThresholdBase::MedianMad => {
let mut sorted = raw.to_vec();
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
median_sorted(&sorted) / 0.6744999885559082
}
AutoThresholdBase::PopulationSd => population_sd(raw),
};
let upper = base * options.auto_threshold_percent / 100.0;
let lower = base * options.auto_threshold_percent_low / 100.0;
(upper, lower)
}
fn median_sorted(sorted: &[f64]) -> f64 {
if sorted.is_empty() {
return f64::NAN;
}
let n = sorted.len();
if n % 2 == 0 {
(sorted[n / 2 - 1] + sorted[n / 2]) / 2.0
} else {
sorted[n / 2]
}
}
fn population_sd(values: &[f64]) -> f64 {
if values.is_empty() {
return 0.0;
}
let mean = values.iter().sum::<f64>() / values.len() as f64;
let var = values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / values.len() as f64;
var.sqrt()
}
fn detect_rate_bursts(
raw: &[f64],
smoothed: &[f64],
spike_counts: &[usize],
upper: f64,
lower: f64,
margin: usize,
bin_ms: f64,
trace: u32,
) -> Vec<MultiChannelBurst> {
let n = raw.len();
if n == 0 {
return Vec::new();
}
let start = margin.min(n);
let end = n.saturating_sub(margin).max(start);
let mut bursts = Vec::new();
let mut in_burst = false;
let mut burst_start = 0usize;
for i in start..end {
let v = if smoothed[i].is_finite() {
smoothed[i]
} else {
continue;
};
if !in_burst {
if v >= upper {
in_burst = true;
burst_start = i;
}
} else if v < lower {
push_burst(&mut bursts, raw, spike_counts, burst_start, i, bin_ms, trace);
in_burst = false;
}
}
if in_burst {
push_burst(&mut bursts, raw, spike_counts, burst_start, end, bin_ms, trace);
}
bursts
}
fn push_burst(
out: &mut Vec<MultiChannelBurst>,
raw: &[f64],
spike_counts: &[usize],
start: usize,
end: usize,
bin_ms: f64,
trace: u32,
) {
if end <= start {
return;
}
let mut peak = f64::NEG_INFINITY;
let mut spikes = 0usize;
for i in start..end {
peak = peak.max(raw[i]);
spikes += spike_counts[i];
}
out.push(MultiChannelBurst {
trace,
start_ms: start as f64 * bin_ms,
end_ms: end as f64 * bin_ms,
peak_rate_hz: peak,
num_spikes: spikes,
peak_series: peak,
});
}
#[cfg(test)]
mod tests {
use super::*;
use crate::analysis::spike::{Spike, SpikeTrain};
#[test]
fn finds_rate_burst() {
let mut train = SpikeTrain::default();
for t in (0..200).map(|i| i as f64 * 5.0) {
train.push(Spike {
channel: (t as usize) % 8,
within_trace_time_ms: t,
within_session_time_ms: t,
peak_mv: 1.0,
..Default::default()
});
}
let bursts = detect_multi_channel_bursts(
&train,
1000.0,
&MultiChannelBurstOptions {
auto_threshold_percent: 50.0,
auto_threshold_percent_low: 25.0,
smoothing_bins: 2,
..Default::default()
},
);
assert!(!bursts.is_empty());
}
#[test]
fn moving_average_has_nan_margins() {
let v = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
let s = calc_moving_average(&v, 2);
assert!(s[0].is_nan() && s[1].is_nan());
assert!(s[8].is_nan() && s[9].is_nan());
assert!((s[2] - 3.0).abs() < 1e-9); }
#[test]
fn product_method_uses_count_times_channels() {
let mut train = SpikeTrain::default();
for ch in 0..4usize {
for k in 0..10 {
train.push(Spike {
channel: ch,
within_trace_time_ms: k as f64 * 10.0,
within_session_time_ms: k as f64 * 10.0,
peak_mv: 1.0,
..Default::default()
});
}
}
let asdr = compute_asdr(
&train,
100.0,
&MultiChannelBurstOptions {
method: MultiBurstMethod::NetworkBurst,
smoothing_bins: 0,
auto_threshold_percent: 10.0,
auto_threshold_percent_low: 5.0,
..Default::default()
},
);
assert!(asdr.points.iter().any(|p| p.rate_hz > 0.0));
assert!(asdr.points.iter().any(|p| p.active_channels >= 1));
}
#[test]
fn min_bursting_channels_actually_gates() {
let mut train = SpikeTrain::default();
for k in 0..10 {
train.push(Spike {
channel: 0,
within_trace_time_ms: k as f64 * 2.0,
within_session_time_ms: k as f64 * 2.0,
peak_mv: 1.0,
..Default::default()
});
}
for ch in 1..4 {
train.push(Spike {
channel: ch,
within_trace_time_ms: 5.0,
within_session_time_ms: 5.0,
peak_mv: 1.0,
..Default::default()
});
}
let active = |min_ch: usize, method: MultiBurstMethod| {
compute_asdr(
&train,
100.0,
&MultiChannelBurstOptions {
method,
bin_width_ms: 50.0,
smoothing_bins: 0,
min_bursting_channels: min_ch,
..Default::default()
},
)
.points[0]
.active_channels
};
assert_eq!(active(1, MultiBurstMethod::NetworkBurst), 4, "ungated");
assert_eq!(
active(3, MultiBurstMethod::NetworkBurst),
1,
"gate at 3 must drop the three single-spike channels"
);
assert_eq!(
active(11, MultiBurstMethod::NetworkBurst),
0,
"a gate above every channel count leaves nothing active"
);
assert_eq!(active(3, MultiBurstMethod::ActiveChannels), 1, "ActiveChannels gates too");
assert_eq!(
active(3, MultiBurstMethod::RateThreshold),
4,
"RateThreshold must ignore the gate"
);
}
}