use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::analysis::{run_analysis, AnalysisReport};
use crate::error::{Med64Error, Result};
use crate::toolkit::spike_detector::{
analysis_options_from, compute_threshold_table, SpikeDetectorOptions, SpikePolarity,
};
pub const WELLS_8: usize = 8;
pub const CH_PER_WELL_8: usize = 8;
#[derive(Debug, Clone)]
pub struct SpikeWellFreqOptions {
pub spike: SpikeDetectorOptions,
}
impl Default for SpikeWellFreqOptions {
fn default() -> Self {
Self {
spike: SpikeDetectorOptions {
polarity: SpikePolarity::MinusOnly,
..SpikeDetectorOptions::toolkit_default()
},
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WellFreqRow {
pub well: usize,
pub well_label: String,
pub channels: usize,
pub spike_count: usize,
pub rate_hz: f64,
#[serde(default)]
pub serr_hz: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpikeWellFreqReport {
pub path: PathBuf,
pub wells: Vec<WellFreqRow>,
pub spike_count: usize,
}
pub fn well_label_ah(well: usize) -> String {
format!("{}", (b'A' + well as u8) as char)
}
pub fn well_of_channel_8(channel: usize) -> Option<usize> {
if channel >= 64 {
None
} else {
Some(channel / CH_PER_WELL_8)
}
}
pub fn run_spike_well_freq(
path: impl AsRef<Path>,
options: &SpikeWellFreqOptions,
) -> Result<SpikeWellFreqReport> {
let path = path.as_ref();
let thresholds = compute_threshold_table(path, &options.spike)?;
let analysis = run_analysis(path, &analysis_options_from(&options.spike, &thresholds))?;
Ok(spike_well_freq_from_analysis(&analysis))
}
pub fn spike_well_freq_from_analysis(analysis: &AnalysisReport) -> SpikeWellFreqReport {
let duration_s = (analysis
.spikes
.spikes
.iter()
.map(|s| s.within_trace_time_ms)
.fold(analysis.header.real_trace_duration_ms, f64::max)
/ 1000.0)
.max(1e-9);
let mut counts = [0usize; WELLS_8];
let mut per_ch = vec![0usize; 64];
for sp in &analysis.spikes.spikes {
if sp.channel < per_ch.len() {
per_ch[sp.channel] += 1;
}
if let Some(w) = well_of_channel_8(sp.channel) {
counts[w] += 1;
}
}
let wells = (0..WELLS_8)
.map(|w| {
let ch_rates: Vec<f64> = (0..CH_PER_WELL_8)
.map(|i| per_ch[w * CH_PER_WELL_8 + i] as f64 / duration_s)
.collect();
let mean = counts[w] as f64 / (CH_PER_WELL_8 as f64 * duration_s);
let var = if ch_rates.len() < 2 {
0.0
} else {
ch_rates.iter().map(|r| (r - mean).powi(2)).sum::<f64>()
/ (ch_rates.len() - 1) as f64
};
let serr = (var.sqrt()) / (ch_rates.len() as f64).sqrt();
WellFreqRow {
well: w,
well_label: well_label_ah(w),
channels: CH_PER_WELL_8,
spike_count: counts[w],
rate_hz: mean,
serr_hz: serr,
}
})
.collect();
SpikeWellFreqReport { path: analysis.path.clone(), wells, spike_count: analysis.spikes.len() }
}
pub fn write_spike_well_freq_csv(
report: &SpikeWellFreqReport,
path: impl AsRef<Path>,
) -> Result<()> {
let path = path.as_ref();
let mut out = String::from("well,label,channels,spike_count,rate_hz,serr_hz\n");
for w in &report.wells {
out.push_str(&format!(
"{},{},{},{},{:.6},{:.6}\n",
w.well + 1,
w.well_label,
w.channels,
w.spike_count,
w.rate_hz,
w.serr_hz
));
}
std::fs::write(path, out)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
pub fn write_spike_well_freq_package(
report: &SpikeWellFreqReport,
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 csv = dir.join("well_frequency.csv");
write_spike_well_freq_csv(report, &csv)?;
Ok(vec![csv])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn labels_a_through_h() {
assert_eq!(well_label_ah(0), "A");
assert_eq!(well_label_ah(7), "H");
assert_eq!(well_of_channel_8(15), Some(1));
}
}