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
//! Connectivity preference property files.

use std::path::{Path, PathBuf};

use crate::error::{Med64Error, Result};
use crate::toolkit::connectivity_package::ConnectivityPackageOptions;
use crate::toolkit::pdm_detector::PdmTimestampMode;

/// Keys from connectivity export / pref properties files.
#[derive(Debug, Clone)]
pub struct ConnectivityPrefs {
    /// `ineach` | `inone` | `radioall`
    pub export_mode: String,
    pub combo_speed: String,
    pub combo_trace: String,
    pub text_window: f64,
    pub text_trace_start: f64,
    pub text_trace_end: f64,
    pub node_color: String,
    pub bg_color: String,
    pub line_color: String,
    pub gap_bin_ms: f64,
}

impl Default for ConnectivityPrefs {
    fn default() -> Self {
        Self {
            export_mode: "inone".into(),
            combo_speed: "1".into(),
            combo_trace: "all".into(),
            text_window: 5.0,
            text_trace_start: 0.0,
            text_trace_end: 0.0,
            node_color: "chartlineblue".into(),
            bg_color: "#ffffff".into(),
            line_color: "chartlinered".into(),
            gap_bin_ms: 1.0,
        }
    }
}

impl ConnectivityPrefs {
    pub fn apply_to(&self, opts: &mut ConnectivityPackageOptions) {
        opts.gap_bin_ms = self.gap_bin_ms;
        opts.timestamps.mode = match self.export_mode.to_ascii_lowercase().as_str() {
            "ineach" | "each" => PdmTimestampMode::Each,
            "radioall" | "all" => PdmTimestampMode::All,
            _ => PdmTimestampMode::All,
        };
        if self.text_window > 0.0 {
            opts.connection_map.connectivity.max_lag_ms = self.text_window;
        }
    }
}

pub fn write_connectivity_properties(
    prefs: &ConnectivityPrefs,
    path: impl AsRef<Path>,
) -> Result<()> {
    let path = path.as_ref();
    let body = format!(
        "# med64 connectivity prefs\n\
         ineach={}\n\
         inone={}\n\
         radioall={}\n\
         comboitemsCSV={}\n\
         combospeed={}\n\
         combotrace={}\n\
         textwindow={}\n\
         texttracetimestart={}\n\
         texttracetimend={}\n\
         textnode={}\n\
         textline={}\n\
         textbg={}\n\
         gap_bin_ms={}\n",
        prefs.export_mode.eq_ignore_ascii_case("ineach"),
        prefs.export_mode.eq_ignore_ascii_case("inone"),
        prefs.export_mode.eq_ignore_ascii_case("radioall")
            || prefs.export_mode.eq_ignore_ascii_case("all"),
        prefs.export_mode,
        prefs.combo_speed,
        prefs.combo_trace,
        prefs.text_window,
        prefs.text_trace_start,
        prefs.text_trace_end,
        prefs.node_color,
        prefs.line_color,
        prefs.bg_color,
        prefs.gap_bin_ms,
    );
    std::fs::write(path, body)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

pub fn load_connectivity_properties(path: impl AsRef<Path>) -> Result<ConnectivityPrefs> {
    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 = ConnectivityPrefs::default();
    let mut ineach = false;
    let mut inone = false;
    let mut radioall = false;
    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();
        match k {
            "ineach" => ineach = v.eq_ignore_ascii_case("true"),
            "inone" => inone = v.eq_ignore_ascii_case("true"),
            "radioall" => radioall = v.eq_ignore_ascii_case("true"),
            "comboitemsCSV" => prefs.export_mode = v.to_string(),
            "combospeed" => prefs.combo_speed = v.to_string(),
            "combotrace" => prefs.combo_trace = v.to_string(),
            "textwindow" => prefs.text_window = v.parse().unwrap_or(prefs.text_window),
            "texttracetimestart" => {
                prefs.text_trace_start = v.parse().unwrap_or(prefs.text_trace_start)
            }
            "texttracetimend" | "texttracetimesend" => {
                prefs.text_trace_end = v.parse().unwrap_or(prefs.text_trace_end)
            }
            "textnode" => prefs.node_color = v.to_string(),
            "textline" => prefs.line_color = v.to_string(),
            "textbg" => prefs.bg_color = v.to_string(),
            "gap_bin_ms" => prefs.gap_bin_ms = v.parse().unwrap_or(prefs.gap_bin_ms),
            _ => {}
        }
    }
    if ineach {
        prefs.export_mode = "ineach".into();
    } else if radioall {
        prefs.export_mode = "radioall".into();
    } else if inone {
        prefs.export_mode = "inone".into();
    }
    Ok(prefs)
}

pub fn default_connectivity_prefs_path(dir: impl AsRef<Path>) -> PathBuf {
    dir.as_ref().join("conf_connectivity_pref.properties")
}

/// Load prefs from `dir/conf_connectivity_pref.properties`.
pub fn load_default_connectivity_prefs(dir: impl AsRef<Path>) -> Result<ConnectivityPrefs> {
    load_connectivity_properties(default_connectivity_prefs_path(dir))
}

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

    #[test]
    fn roundtrip_prefs() {
        let dir = std::env::temp_dir().join(format!("med64-cpref-{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let path = default_connectivity_prefs_path(&dir);
        let prefs = ConnectivityPrefs {
            export_mode: "ineach".into(),
            gap_bin_ms: 2.5,
            text_window: 10.0,
            ..Default::default()
        };
        write_connectivity_properties(&prefs, &path).unwrap();
        let loaded = load_default_connectivity_prefs(&dir).unwrap();
        assert_eq!(loaded.export_mode, "ineach");
        assert!((loaded.gap_bin_ms - 2.5).abs() < 1e-9);
        let mut opts = ConnectivityPackageOptions::default();
        loaded.apply_to(&mut opts);
        assert!(matches!(opts.timestamps.mode, PdmTimestampMode::Each));
        let _ = std::fs::remove_dir_all(dir);
    }
}