use std::path::Path;
use crate::analysis::filter::FilterAlgorithm;
use crate::analysis::spike::{calc_thresholds, ThresholdOptions};
use crate::error::{Med64Error, Result};
use crate::recording::Recording;
use super::types::{ChannelThresholdRow, SpikeDetectorOptions, ThresholdCalcRange};
pub fn compute_threshold_table(
path: impl AsRef<Path>,
options: &SpikeDetectorOptions,
) -> Result<Vec<ChannelThresholdRow>> {
let path = path.as_ref();
let mut rec = Recording::open(path)?;
let header = rec.header().clone();
let n_ch = header.num_channel_slots();
let sample_rate = header.sampling_frequency_hz;
let interval = 1000.0 / sample_rate;
let hp = options.highpass_hz.unwrap_or(100.0);
let lp = options.lowpass_hz.unwrap_or(5000.0);
let mut filters: Vec<crate::analysis::filter::BandpassFilter> = (0..n_ch)
.map(|_| {
crate::analysis::filter::BandpassFilter::with_algorithm(
1.0 / sample_rate,
hp,
lp,
options.lowpass_kind,
FilterAlgorithm::SecondPole,
)
})
.collect();
let mut by_ch: Vec<Vec<f64>> = vec![Vec::new(); n_ch];
for (bi, block) in rec.blocks().enumerate() {
if options.max_blocks.is_some_and(|m| bi >= m) {
break;
}
let block = block?;
for (col, &ch) in block.channel_indices.iter().enumerate() {
if ch >= n_ch {
continue;
}
let mut mv: Vec<f64> =
block.samples.iter().map(|row| header.counts_to_millivolts(row[col])).collect();
filters[ch].reset();
filters[ch].filter_block(&mut mv);
for v in &mut mv {
*v = (*v as f32) as f64;
}
by_ch[ch].extend(mv);
}
}
let thr_opts = ThresholdOptions {
method: options.threshold_method,
magnification_percent: options.threshold_percent,
..ThresholdOptions::default()
};
let mut rows = Vec::with_capacity(n_ch);
for ch in 0..n_ch {
let enabled = options.channel_on.as_ref().and_then(|v| v.get(ch).copied()).unwrap_or(true);
let samples = slice_calc_range(&by_ch[ch], &options.calc_range, interval);
let auto = calc_thresholds(samples, &thr_opts, None);
let plus_fixed =
options.plus_thresholds_mv.as_ref().and_then(|v| v.get(ch).copied()).flatten();
let minus_fixed =
options.minus_thresholds_mv.as_ref().and_then(|v| v.get(ch).copied()).flatten();
let cluster_k = options.cluster_k.unwrap_or(0);
rows.push(ChannelThresholdRow {
channel: ch,
enabled,
plus_mv: Some(plus_fixed.unwrap_or(auto.plus_mv)),
minus_mv: Some(minus_fixed.unwrap_or(auto.minus_mv)),
cluster_k,
});
}
Ok(rows)
}
fn slice_calc_range<'a>(
samples: &'a [f64],
range: &ThresholdCalcRange,
interval_ms: f64,
) -> &'a [f64] {
if samples.is_empty() {
return samples;
}
match range {
ThresholdCalcRange::All => samples,
ThresholdCalcRange::FirstSeconds(sec) => {
let n = ((*sec * 1000.0 / interval_ms).ceil() as usize).min(samples.len());
&samples[..n]
}
ThresholdCalcRange::LastSeconds(sec) => {
let n = ((*sec * 1000.0 / interval_ms).ceil() as usize).min(samples.len());
&samples[samples.len() - n..]
}
}
}
pub fn load_threshold_properties(path: impl AsRef<Path>) -> Result<SpikeDetectorOptions> {
let path = path.as_ref();
let text = std::fs::read_to_string(path)
.map_err(|source| Med64Error::Io { path: path.to_path_buf(), source })?;
let mut opts = SpikeDetectorOptions::toolkit_default();
let mut on = vec![true; 64];
let mut plus: Vec<Option<f64>> = vec![None; 64];
let mut minus: Vec<Option<f64>> = vec![None; 64];
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some((k, v)) = line.split_once('=') else {
continue;
};
let k = k.trim();
let v = v.trim();
if let Some(rest) = k.strip_prefix("ch") {
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
let Ok(ch1) = digits.parse::<usize>() else {
continue;
};
let ch = ch1.saturating_sub(1);
if ch >= 64 {
continue;
}
let suffix = &rest[digits.len()..];
match suffix {
"onoff" => on[ch] = v.eq_ignore_ascii_case("true"),
"plusthreshold" => {
plus[ch] = if v.eq_ignore_ascii_case("none") { None } else { v.parse().ok() };
}
"minusthreshold" => {
minus[ch] = if v.eq_ignore_ascii_case("none") { None } else { v.parse().ok() };
}
"cluster" => {
if !v.eq_ignore_ascii_case("off") {
if let Ok(k) = v.parse::<usize>() {
opts.cluster_k = Some(k.max(1));
}
}
}
_ => {}
}
}
}
opts.channel_on = Some(on);
opts.plus_thresholds_mv = Some(plus);
opts.minus_thresholds_mv = Some(minus);
Ok(opts)
}
pub fn write_threshold_properties(
rows: &[ChannelThresholdRow],
path: impl AsRef<Path>,
) -> Result<()> {
let path = path.as_ref();
let mut out = String::from("# med64 Spike Detector thresholds\n");
for row in rows {
let ch = row.channel + 1;
out.push_str(&format!("ch{ch}onoff={}\n", if row.enabled { "True" } else { "False" }));
match row.plus_mv {
Some(v) => out.push_str(&format!("ch{ch}plusthreshold={v}\n")),
None => out.push_str(&format!("ch{ch}plusthreshold=None\n")),
}
match row.minus_mv {
Some(v) => out.push_str(&format!("ch{ch}minusthreshold={v}\n")),
None => out.push_str(&format!("ch{ch}minusthreshold=None\n")),
}
out.push_str(&format!(
"ch{ch}cluster={}\n",
if row.cluster_k == 0 { "Off".into() } else { row.cluster_k.to_string() }
));
}
std::fs::write(path, out)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
pub fn write_settings_table_csv(
rows: &[ChannelThresholdRow],
path: impl AsRef<Path>,
) -> Result<()> {
let path = path.as_ref();
let mut out = String::from("channelNo,onoff,plusthresh,minusthresh,cluster\n");
for row in rows {
out.push_str(&format!(
"{},{},{},{},{}\n",
row.channel + 1,
if row.enabled { "On" } else { "Off" },
row.plus_mv.map(|v| format!("{v}")).unwrap_or_else(|| "None".into()),
row.minus_mv.map(|v| format!("{v}")).unwrap_or_else(|| "None".into()),
if row.cluster_k == 0 { "Off".into() } else { row.cluster_k.to_string() }
));
}
std::fs::write(path, out)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
pub fn load_settings_table_csv(path: impl AsRef<Path>) -> Result<Vec<ChannelThresholdRow>> {
let path = path.as_ref();
let text = std::fs::read_to_string(path)
.map_err(|source| Med64Error::Io { path: path.to_path_buf(), source })?;
let mut rows = Vec::new();
for (li, line) in text.lines().enumerate() {
let line = line.trim();
if line.is_empty() || li == 0 && line.to_ascii_lowercase().contains("channel") {
continue;
}
let parts: Vec<&str> = line.split(',').map(|s| s.trim()).collect();
if parts.len() < 5 {
continue;
}
let channel = parts[0]
.parse::<usize>()
.map_err(|_| Med64Error::InvalidWrite {
message: format!("bad channelNo in {}", path.display()),
})?
.saturating_sub(1);
let enabled = !matches!(parts[1].to_ascii_lowercase().as_str(), "off" | "false" | "0");
let parse_opt = |s: &str| -> Option<f64> {
if s.eq_ignore_ascii_case("none") || s.is_empty() {
None
} else {
s.parse().ok()
}
};
let cluster_k =
if parts[4].eq_ignore_ascii_case("off") { 0 } else { parts[4].parse().unwrap_or(0) };
rows.push(ChannelThresholdRow {
channel,
enabled,
plus_mv: parse_opt(parts[2]),
minus_mv: parse_opt(parts[3]),
cluster_k,
});
}
Ok(rows)
}
pub fn apply_to_all_on_off(rows: &mut [ChannelThresholdRow], enabled: bool) {
for r in rows {
r.enabled = enabled;
}
}
pub fn apply_to_all_plus_thresh(rows: &mut [ChannelThresholdRow], plus_mv: Option<f64>) {
for r in rows {
r.plus_mv = plus_mv;
}
}
pub fn apply_to_all_minus_thresh(rows: &mut [ChannelThresholdRow], minus_mv: Option<f64>) {
for r in rows {
r.minus_mv = minus_mv;
}
}
pub fn apply_to_all_cluster(rows: &mut [ChannelThresholdRow], cluster_k: usize) {
for r in rows {
r.cluster_k = cluster_k;
}
}