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
//! Power spectrum analysis prefs (`conf_powerspectrumanalysis.properties`).

use std::path::Path;

use crate::error::{Med64Error, Result};
use crate::toolkit::beta_prefs::first_selected_channel;
use crate::toolkit::spectrum::{HumNoiseRemoval, SpectrumOptions};

#[derive(Debug, Clone)]
pub struct SpectrumPrefs {
    pub channel_sele: String,
    pub combohumremoval: String,
    pub groupnorma: String,
    pub text_channel_sele: String,
    pub textfile: String,
}

impl Default for SpectrumPrefs {
    fn default() -> Self {
        Self {
            channel_sele: String::new(),
            combohumremoval: "None".into(),
            groupnorma: "radionormaon".into(),
            text_channel_sele: "1".into(),
            textfile: String::new(),
        }
    }
}

impl SpectrumPrefs {
    pub fn apply_to(&self, options: &mut SpectrumOptions) {
        if let Some(ch) = first_selected_channel(&self.channel_sele, &self.text_channel_sele) {
            options.channel = ch;
        }
        options.hum = parse_hum(&self.combohumremoval);
    }
}

fn parse_hum(s: &str) -> HumNoiseRemoval {
    let t = s.trim().to_ascii_lowercase();
    if t.contains("50") {
        HumNoiseRemoval::FiftyHz
    } else if t.contains("60") {
        HumNoiseRemoval::SixtyHz
    } else {
        HumNoiseRemoval::None
    }
}

pub fn load_spectrum_prefs(path: impl AsRef<Path>) -> Result<SpectrumPrefs> {
    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 = SpectrumPrefs::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() {
            "ChannelSele" => prefs.channel_sele = v.trim().to_string(),
            "combohumremoval" => prefs.combohumremoval = v.trim().to_string(),
            "groupnorma" => prefs.groupnorma = v.trim().to_string(),
            "textChannelSele" => prefs.text_channel_sele = v.trim().to_string(),
            "textfile" => prefs.textfile = v.trim().to_string(),
            _ => {}
        }
    }
    Ok(prefs)
}

pub fn write_spectrum_prefs(prefs: &SpectrumPrefs, path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    let body = format!(
        "# med64 power spectrum prefs\n\
         ChannelSele={}\n\
         combohumremoval={}\n\
         groupnorma={}\n\
         textChannelSele={}\n\
         textfile={}\n",
        prefs.channel_sele,
        prefs.combohumremoval,
        prefs.groupnorma,
        prefs.text_channel_sele,
        prefs.textfile,
    );
    std::fs::write(path, body)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

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

    #[test]
    fn spectrum_prefs_roundtrip() {
        let dir = std::env::temp_dir().join(format!("med64-psapref-{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let path = dir.join("conf_powerspectrumanalysis.properties");
        let prefs = SpectrumPrefs {
            channel_sele: "0,0,1,".into(),
            combohumremoval: "60".into(),
            groupnorma: "radionormaon".into(),
            text_channel_sele: "3".into(),
            textfile: "/tmp".into(),
        };
        write_spectrum_prefs(&prefs, &path).unwrap();
        let loaded = load_spectrum_prefs(&path).unwrap();
        let mut opts = SpectrumOptions::default();
        loaded.apply_to(&mut opts);
        assert_eq!(opts.channel, 2);
        assert_eq!(opts.hum, HumNoiseRemoval::SixtyHz);
        let _ = std::fs::remove_dir_all(dir);
    }
}