use serde::{Deserialize, Serialize};
use crate::analysis::spike::{Spike, SpikeTrain};
use crate::analysis::waveform_avg::{average_spike_waveforms, AverageWaveform};
use crate::error::{Med64Error, Result};
use crate::header::Med64Header;
use std::path::Path;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpikeScatterPoint {
pub channel: usize,
pub peak_mv: f64,
pub duration_ms: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RasterTimeHistogram {
pub bin_ms: f64,
pub edges: Vec<f64>,
pub counts: Vec<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpikePostHocReport {
pub scatter: Vec<SpikeScatterPoint>,
pub mean_waveforms: Vec<AverageWaveform>,
pub raster_histogram: RasterTimeHistogram,
}
pub fn spike_posthoc(train: &SpikeTrain, raster_bin_ms: f64) -> SpikePostHocReport {
let scatter = train
.spikes
.iter()
.map(|s| SpikeScatterPoint {
channel: s.channel,
peak_mv: s.peak_mv.abs(),
duration_ms: s.duration_ms,
})
.collect();
SpikePostHocReport {
scatter,
mean_waveforms: average_spike_waveforms(train, false),
raster_histogram: raster_time_histogram(train, raster_bin_ms.max(1.0)),
}
}
pub fn raster_time_histogram(train: &SpikeTrain, bin_ms: f64) -> RasterTimeHistogram {
let max_t = train.spikes.iter().map(|s| s.within_trace_time_ms).fold(0.0_f64, f64::max);
let n = ((max_t / bin_ms).ceil() as usize).max(1);
let mut counts = vec![0u64; n];
for s in &train.spikes {
let idx = (s.within_trace_time_ms / bin_ms).floor() as usize;
if idx < counts.len() {
counts[idx] += 1;
}
}
RasterTimeHistogram { bin_ms, edges: (0..=n).map(|i| i as f64 * bin_ms).collect(), counts }
}
pub fn write_scatter_csv(points: &[SpikeScatterPoint], path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let mut w = String::from("channel,peak_mv,duration_ms\n");
for p in points {
w.push_str(&format!("{},{:.6},{:.6}\n", p.channel + 1, p.peak_mv, p.duration_ms));
}
std::fs::write(path, w)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
pub fn write_raster_histogram_csv(
hist: &RasterTimeHistogram,
path: impl AsRef<Path>,
) -> Result<()> {
let path = path.as_ref();
let mut w = String::from("bin_start_ms,count\n");
for (i, &c) in hist.counts.iter().enumerate() {
w.push_str(&format!("{:.3},{c}\n", hist.edges[i]));
}
std::fs::write(path, w)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
#[cfg(feature = "hdf5")]
pub fn import_spike_timestamps_hdf5(
path: impl AsRef<Path>,
header: Med64Header,
) -> Result<(Med64Header, SpikeTrain)> {
use hdf5::File;
let path = path.as_ref();
let file = File::open(path).map_err(|err| Med64Error::InvalidHeader {
path: path.to_path_buf(),
message: format!("HDF5 open failed: {err}"),
})?;
let mut train = SpikeTrain::default();
if let Ok(spikes) = file.group("med64/spikes") {
let channels: Vec<i32> = spikes
.dataset("channel")
.and_then(|d| d.read_1d::<i32>())
.map(|a| a.to_vec())
.unwrap_or_default();
let times: Vec<f64> = spikes
.dataset("within_trace_time_ms")
.and_then(|d| d.read_1d::<f64>())
.map(|a| a.to_vec())
.unwrap_or_default();
for (ch, t) in channels.into_iter().zip(times) {
train.push(Spike {
channel: ch.max(0) as usize,
within_trace_time_ms: t,
within_session_time_ms: t,
..Default::default()
});
}
}
if train.is_empty() {
if let Ok(names) = file.member_names() {
for name in names {
if !name.contains("timestamp") {
continue;
}
let Ok(ds) = file.dataset(&name) else {
continue;
};
let Ok(arr) = ds.read_1d::<f32>() else {
continue;
};
let channel = name
.trim_start_matches("ch")
.split('-')
.next()
.and_then(|s| s.parse::<usize>().ok())
.unwrap_or(1)
.saturating_sub(1);
for t in arr.iter() {
train.push(Spike {
channel,
within_trace_time_ms: f64::from(*t),
within_session_time_ms: f64::from(*t),
..Default::default()
});
}
}
}
}
Ok((header, train))
}
#[cfg(not(feature = "hdf5"))]
pub fn import_spike_timestamps_hdf5(
path: impl AsRef<Path>,
_header: Med64Header,
) -> Result<(Med64Header, SpikeTrain)> {
Err(Med64Error::InvalidHeader {
path: path.as_ref().to_path_buf(),
message: "HDF5 import requires the `hdf5` feature".into(),
})
}