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
//! analysis log directory I/O (`log file names).

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

use serde::{Deserialize, Serialize};

use crate::analysis::{
    compute_burst_result_table, import_spike_csv, AnalysisOptions, AnalysisReport,
    BurstResultTable, ResultTableOptions, SingleChannelBurst, SpikeTrain,
};
use crate::error::{Med64Error, Result};
use crate::export::{write_result_table_csv, write_single_burst_csv, write_spike_timestamps_csv};
use crate::project::{load_project, save_project, AnalysisProject};

/// Files written under a burst-analysis log folder.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalysisLogManifest {
    pub version: u32,
    pub source_path: PathBuf,
    pub files: Vec<String>,
}

/// Restored contents of a log directory.
#[derive(Debug, Clone)]
pub struct AnalysisLogRestore {
    pub dir: PathBuf,
    pub spikes: SpikeTrain,
    pub bursts: BurstDataFilePublic,
    pub config: Option<AnalysisProject>,
    pub results: Option<BurstResultTable>,
}

/// Save a burst analysis-compatible log directory:
/// `spike_time_stamp.csv`, `single_ch_burst.csv`, `burst.json`, `results.csv`, `config.json`.
pub fn save_analysis_log_dir(
    report: &AnalysisReport,
    options: &AnalysisOptions,
    dir: impl AsRef<Path>,
) -> Result<AnalysisLogManifest> {
    let dir = dir.as_ref();
    std::fs::create_dir_all(dir)
        .map_err(|source| Med64Error::WriteIo { path: dir.to_path_buf(), source })?;

    let spike_path = dir.join("spike_time_stamp.csv");
    write_spike_timestamps_csv(report, &spike_path)?;

    let single_path = dir.join("single_ch_burst.csv");
    write_single_burst_csv(report, &single_path)?;

    let burst_path = dir.join("burst.json");
    save_burst_data_json(report, &burst_path)?;

    let results_path = dir.join("results.csv");
    write_result_table_csv(report, &results_path)?;

    let config_path = dir.join("config.json");
    let project = AnalysisProject::from_report(report, options);
    save_project(&project, &config_path)?;

    // Spike thresholds (units mV) for log reload.
    let thr_path = dir.join("spike_thresholds.csv");
    {
        let mut w = String::from("channel,plus_mv,minus_mv,enabled\n");
        let n = report.header.num_channel_slots().max(1);
        for ch in 0..n {
            let plus = options.plus_thresholds_mv.as_ref().and_then(|v| v.get(ch)).copied();
            let minus = options.minus_thresholds_mv.as_ref().and_then(|v| v.get(ch)).copied();
            w.push_str(&format!(
                "{},{},{},1\n",
                ch + 1,
                plus.map(|v| format!("{v}")).unwrap_or_default(),
                minus.map(|v| format!("{v}")).unwrap_or_default(),
            ));
        }
        std::fs::write(&thr_path, w)
            .map_err(|source| Med64Error::WriteIo { path: thr_path.clone(), source })?;
    }

    let info_path = dir.join("information.txt");
    {
        let body = format!(
            "source={}\nspikes={}\nsingle_bursts={}\nmulti_bursts={}\nduration_ms={:.3}\n",
            report.path.display(),
            report.spikes.len(),
            report.single_bursts.len(),
            report.multi_bursts.len(),
            report.header.real_trace_duration_ms,
        );
        std::fs::write(&info_path, body)
            .map_err(|source| Med64Error::WriteIo { path: info_path.clone(), source })?;
    }

    let summary_path = dir.join("summary.txt");
    {
        let table = compute_burst_result_table(report, &ResultTableOptions::default());
        let mut body = String::from("Analysis summary\n");
        for row in &table.rows {
            body.push_str(&format!(
                "{}={}\n",
                row.map_label,
                row.value.map(|v| format!("{v:.6}")).unwrap_or_else(|| "NaN".into())
            ));
        }
        std::fs::write(&summary_path, body)
            .map_err(|source| Med64Error::WriteIo { path: summary_path.clone(), source })?;
    }

    // Average spike waveforms as `wave_data`.
    let wave_path = dir.join("wave_data.csv");
    {
        let avgs = crate::analysis::average_spike_waveforms(&report.spikes, true);
        crate::export::write_average_waveforms_csv(&avgs, &wave_path)?;
    }

    // Also dump the 13-row table as JSON for tooling.
    let table = compute_burst_result_table(report, &ResultTableOptions::default());
    let table_path = dir.join("results.json");
    let json = serde_json::to_string_pretty(&table)
        .map_err(|e| Med64Error::InvalidWrite { message: e.to_string() })?;
    std::fs::write(&table_path, json)
        .map_err(|source| Med64Error::WriteIo { path: table_path.clone(), source })?;

    Ok(AnalysisLogManifest {
        version: 1,
        source_path: report.path.clone(),
        files: vec![
            "spike_time_stamp.csv".into(),
            "single_ch_burst.csv".into(),
            "burst.json".into(),
            "results.csv".into(),
            "results.json".into(),
            "config.json".into(),
            "spike_thresholds.csv".into(),
            "information.txt".into(),
            "summary.txt".into(),
            "wave_data.csv".into(),
        ],
    })
}

/// Load a previously saved log directory.
pub fn load_analysis_log_dir(dir: impl AsRef<Path>) -> Result<AnalysisLogRestore> {
    let dir = dir.as_ref();
    let spike_path = dir.join("spike_time_stamp.csv");
    let spikes = if spike_path.exists() {
        import_spike_csv(&spike_path)?.spikes
    } else {
        SpikeTrain::default()
    };

    let burst_path = dir.join("burst.json");
    let bursts = if burst_path.exists() {
        load_burst_data_json(&burst_path)?
    } else {
        BurstDataFilePublic { single_channel: Vec::new(), multi_channel: Vec::new() }
    };

    let config_path = dir.join("config.json");
    let config = if config_path.exists() { Some(load_project(&config_path)?) } else { None };

    let results = {
        let json_path = dir.join("results.json");
        if json_path.exists() {
            let text = std::fs::read_to_string(&json_path)
                .map_err(|source| Med64Error::Io { path: json_path.clone(), source })?;
            Some(serde_json::from_str(&text).map_err(|e| Med64Error::InvalidMoflo {
                path: json_path,
                message: e.to_string(),
            })?)
        } else {
            None
        }
    };

    Ok(AnalysisLogRestore { dir: dir.to_path_buf(), spikes, bursts, config, results })
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct BurstDataFile {
    pub single_channel: Vec<SingleChannelBurst>,
    pub multi_channel: Vec<crate::analysis::MultiChannelBurst>,
}

fn save_burst_data_json(report: &AnalysisReport, path: &Path) -> Result<()> {
    let data = BurstDataFile {
        single_channel: report.single_bursts.clone(),
        multi_channel: report.multi_bursts.clone(),
    };
    let json = serde_json::to_string_pretty(&data)
        .map_err(|e| Med64Error::InvalidWrite { message: e.to_string() })?;
    std::fs::write(path, json)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// Load `burst.json` written by [`save_analysis_log_dir`].
pub fn load_burst_data_json(path: impl AsRef<Path>) -> Result<BurstDataFilePublic> {
    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 data: BurstDataFile = serde_json::from_str(&text).map_err(|e| {
        Med64Error::InvalidMoflo { path: path.to_path_buf(), message: e.to_string() }
    })?;
    Ok(BurstDataFilePublic {
        single_channel: data.single_channel,
        multi_channel: data.multi_channel,
    })
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BurstDataFilePublic {
    pub single_channel: Vec<SingleChannelBurst>,
    pub multi_channel: Vec<crate::analysis::MultiChannelBurst>,
}