med64 0.0.2

Headless MED64 electrophysiology toolkit: .modat I/O, spike/burst analysis, assays, spike-rate maps, and CSV/HTML/SVG/HDF5 export
Documentation
//! spike detector settings + export prefs.

use std::path::Path;

use crate::analysis::{LowPassKind, ThresholdMethod};
use crate::error::{Med64Error, Result};
use crate::toolkit::spike_detector::{SpikeDetectorOptions, SpikePolarity, ThresholdCalcRange};

#[derive(Debug, Clone)]
pub struct SpikeDetectorPrefs {
    pub comboduration: String,
    pub combohpf: String,
    pub combolpf: String,
    pub combomethod: String,
    pub choice_file_format: String,
    /// Last path; wire key `textfile1=` in `conf_spikedetector.properties`.
    pub last_path: String,
}

impl Default for SpikeDetectorPrefs {
    fn default() -> Self {
        Self {
            comboduration: "last".into(),
            combohpf: "Butterworth highpass".into(),
            combolpf: "None".into(),
            combomethod: "median (- threshold only)".into(),
            choice_file_format: "HDF5 (.h5)".into(),
            last_path: String::new(),
        }
    }
}

impl SpikeDetectorPrefs {
    pub fn apply_to(&self, options: &mut SpikeDetectorOptions) {
        options.calc_range = ThresholdCalcRange::parse(&self.comboduration, 10.0);
        options.highpass_hz = map_hp(&self.combohpf);
        options.lowpass_hz = map_lp(&self.combolpf);
        if self.combolpf.to_ascii_lowercase().contains("butterworth") {
            options.lowpass_kind = LowPassKind::Butterworth;
        } else if self.combolpf.to_ascii_lowercase().contains("bessel") {
            options.lowpass_kind = LowPassKind::Bessel;
        }
        apply_method(&self.combomethod, options);
        let fmt = self.choice_file_format.to_ascii_lowercase();
        options.export.hdf5 = fmt.contains("hdf5") || fmt.contains(".h5");
    }
}

fn map_hp(combo: &str) -> Option<f64> {
    let s = combo.to_ascii_lowercase();
    if s.contains("none") {
        None
    } else if s.contains("highpass") || s.contains("butterworth") {
        Some(100.0)
    } else {
        Some(100.0)
    }
}

fn map_lp(combo: &str) -> Option<f64> {
    let s = combo.to_ascii_lowercase();
    if s.contains("none") || s.is_empty() {
        None
    } else if s.contains("lowpass") || s.contains("butterworth") {
        Some(2000.0)
    } else {
        None
    }
}

fn apply_method(combo: &str, options: &mut SpikeDetectorOptions) {
    let s = combo.to_ascii_lowercase();
    if s.contains("standard") || s.contains("sd") || s.contains("stdev") {
        options.threshold_method = ThresholdMethod::StandardDeviation;
    } else if s.contains("fixed") {
        options.threshold_method = ThresholdMethod::Fixed;
    } else {
        options.threshold_method = ThresholdMethod::Median;
    }
    if s.contains("+") && s.contains("-") && (s.contains("both") || s.contains("+/-")) {
        options.polarity = SpikePolarity::Both;
    } else if s.contains("+") && !s.contains("-") {
        options.polarity = SpikePolarity::PlusOnly;
    } else if s.contains("-") {
        options.polarity = SpikePolarity::MinusOnly;
    }
}

pub fn load_spike_detector_prefs(path: impl AsRef<Path>) -> Result<SpikeDetectorPrefs> {
    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 prefs = SpikeDetectorPrefs::default();
    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;
        };
        match k.trim() {
            "comboduration" => prefs.comboduration = v.trim().to_string(),
            "combohpf" => prefs.combohpf = v.trim().to_string(),
            "combolpf" => prefs.combolpf = v.trim().to_string(),
            "combomethod" => prefs.combomethod = v.trim().to_string(),
            "choiceFileFormat" => prefs.choice_file_format = v.trim().to_string(),
            // Wire key in spike detector .properties files.
            "textfile1" => prefs.last_path = v.trim().to_string(),
            _ => {}
        }
    }
    Ok(prefs)
}

/// Merge setting + export property files (later keys win).
pub fn load_spike_detector_prefs_pair(
    settings: impl AsRef<Path>,
    export: Option<&Path>,
) -> Result<SpikeDetectorPrefs> {
    let mut prefs = load_spike_detector_prefs(settings)?;
    if let Some(export) = export {
        let exp = load_spike_detector_prefs(export)?;
        if !exp.choice_file_format.is_empty() {
            prefs.choice_file_format = exp.choice_file_format;
        }
    }
    Ok(prefs)
}

pub fn write_spike_detector_prefs(
    prefs: &SpikeDetectorPrefs,
    path: impl AsRef<Path>,
) -> Result<()> {
    let path = path.as_ref();
    let body = format!(
        "# med64 spike detector prefs\n\
         comboduration={}\n\
         combohpf={}\n\
         combolpf={}\n\
         combomethod={}\n\
         choiceFileFormat={}\n\
         textfile1={}\n", // wire key
        prefs.comboduration,
        prefs.combohpf,
        prefs.combolpf,
        prefs.combomethod,
        prefs.choice_file_format,
        prefs.last_path,
    );
    std::fs::write(path, body)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// Thin wrapper: `conf_propagationspikedetector_Threshold.properties` → threshold loader.
pub fn load_propagation_spike_detector_threshold(
    path: impl AsRef<Path>,
) -> Result<SpikeDetectorOptions> {
    crate::toolkit::spike_detector::load_threshold_properties(path)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn spike_detector_prefs_roundtrip() {
        let dir = std::env::temp_dir().join(format!("med64-sdpref-{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let path = dir.join("conf_spikedetectorsetting.properties");
        let prefs = SpikeDetectorPrefs {
            comboduration: "last".into(),
            combohpf: "Butterworth highpass".into(),
            combolpf: "None".into(),
            combomethod: "median (- threshold only)".into(),
            choice_file_format: "HDF5 (.h5)".into(),
            last_path: "/tmp/spikes".into(),
        };
        write_spike_detector_prefs(&prefs, &path).unwrap();
        let loaded = load_spike_detector_prefs(&path).unwrap();
        assert_eq!(loaded.last_path, "/tmp/spikes");
        let mut opts = SpikeDetectorOptions::toolkit_default();
        loaded.apply_to(&mut opts);
        assert!(opts.highpass_hz.is_some());
        assert!(opts.lowpass_hz.is_none());
        assert!(matches!(opts.polarity, SpikePolarity::MinusOnly));
        assert!(opts.export.hdf5);
        // Path-only conf_spikedetector.properties (wire key textfile1=)
        let path_only = dir.join("conf_spikedetector.properties");
        std::fs::write(&path_only, "textfile1=/data/mea\n").unwrap();
        let path_prefs = load_spike_detector_prefs(&path_only).unwrap();
        assert_eq!(path_prefs.last_path, "/data/mea");
        let _ = std::fs::remove_dir_all(dir);
    }
}