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
use std::io::Write;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::analysis::AnalysisReport;
use crate::error::{Med64Error, Result};

use super::csv::{
    write_asdr_csv, write_intra_burst_csv, write_multi_burst_csv, write_raster_csv,
    write_single_burst_csv,
};
use super::draw::{write_line_bmp, write_line_png, write_raster_bmp, write_raster_png};
use super::util::{create_writer, io};

/// `AsdrChartKind` for ImageExportService chart rendering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum AsdrChartKind {
    #[default]
    Line,
    Column,
}

/// Burst Detector batch-export package using [`crate::BatchExportPrefs`] naming.
pub fn write_burst_batch_package(
    report: &AnalysisReport,
    out_dir: impl AsRef<Path>,
    prefs: &crate::toolkit::batch_export_prefs::BatchExportPrefs,
    basename: &str,
) -> Result<Vec<PathBuf>> {
    write_burst_batch_package_with_chart(report, out_dir, prefs, basename, AsdrChartKind::Line)
}

pub fn write_burst_batch_package_with_chart(
    report: &AnalysisReport,
    out_dir: impl AsRef<Path>,
    prefs: &crate::toolkit::batch_export_prefs::BatchExportPrefs,
    basename: &str,
    chart_kind: AsdrChartKind,
) -> Result<Vec<PathBuf>> {
    use crate::toolkit::batch_export_prefs::{write_batch_export_prefs, ChartImageType};

    if prefs.is_not_target_selected() {
        return Err(Med64Error::InvalidWrite {
            message: "no batch export target selected (all export_* false)".into(),
        });
    }
    let dir = out_dir.as_ref();
    std::fs::create_dir_all(dir)
        .map_err(|source| Med64Error::WriteIo { path: dir.to_path_buf(), source })?;
    let mut outputs = Vec::new();
    let mut manifest_files = Vec::new();

    if prefs.export_chart {
        let path = dir.join(prefs.filename(basename, &prefs.chart_suffix));
        write_asdr_csv(report, &path)?;
        outputs.push(path.clone());
        manifest_files.push(path.file_name().unwrap().to_string_lossy().into_owned());

        let asdr_series: Vec<(f64, f64)> =
            report.asdr.points.iter().map(|p| (p.time_ms, p.smoothed_hz)).collect();
        let chart_img = dir.join(prefs.image_filename(basename, &prefs.chart_suffix));
        match (prefs.chart_image_type, chart_kind) {
            (ChartImageType::Png, AsdrChartKind::Line) => {
                write_line_png(&asdr_series, &chart_img, 800, 480)?;
            }
            (ChartImageType::Bmp, AsdrChartKind::Line) => {
                write_line_bmp(&asdr_series, &chart_img, 800, 480)?;
            }
            (ChartImageType::Png, AsdrChartKind::Column) => {
                write_bar_png(&asdr_series, &chart_img, 800, 480)?;
            }
            (ChartImageType::Bmp, AsdrChartKind::Column) => {
                write_bar_bmp(&asdr_series, &chart_img, 800, 480)?;
            }
        }
        outputs.push(chart_img.clone());
        manifest_files.push(chart_img.file_name().unwrap().to_string_lossy().into_owned());
    }
    if prefs.export_burst {
        let path = dir.join(prefs.filename(basename, &prefs.burst_suffix));
        write_multi_burst_csv(report, &path)?;
        outputs.push(path);
    }
    if prefs.export_summary_values {
        let path = dir.join(prefs.filename(basename, &prefs.summary_values_suffix));
        {
            let mut w = create_writer(&path)?;
            writeln!(
                w,
                "metric,value\nspikes,{}\nsingle_channel_bursts,{}\nmulti_channel_bursts,{}\nasdr_bins,{}\nasdr_upper_hz,{:.6}\nasdr_lower_hz,{:.6}\nduration_ms,{:.3}",
                report.spikes.len(),
                report.single_bursts.len(),
                report.multi_bursts.len(),
                report.asdr.points.len(),
                report.asdr.threshold_hz,
                report.asdr.lower_threshold,
                report.header.real_trace_duration_ms
            )
            .map_err(io(&path))?;
        }
        outputs.push(path);
    }
    if prefs.export_individual_values {
        let path = dir.join(prefs.filename(basename, &prefs.individual_values_suffix));
        write_single_burst_csv(report, &path)?;
        outputs.push(path);
    }
    if prefs.export_details {
        let path = dir.join(prefs.filename(basename, &prefs.details_suffix));
        let intra_empty = report.multi_bursts.is_empty()
            || report.spikes.spikes.iter().all(|s| {
                !report.multi_bursts.iter().any(|b| {
                    s.within_trace_time_ms >= b.start_ms && s.within_trace_time_ms < b.end_ms
                })
            });
        if intra_empty {
            write_multi_burst_csv(report, &path)?;
        } else {
            write_intra_burst_csv(report, &path)?;
        }
        outputs.push(path);
    }
    if prefs.export_spike_events {
        let path = dir.join(prefs.filename(basename, &prefs.spike_events_suffix));
        write_raster_csv(report, &path)?;
        outputs.push(path.clone());
        manifest_files.push(path.file_name().unwrap().to_string_lossy().into_owned());
        let img = dir.join(prefs.image_filename(basename, &prefs.spike_events_suffix));
        match prefs.chart_image_type {
            ChartImageType::Png => write_raster_png(report, &img, 800, 480)?,
            ChartImageType::Bmp => write_raster_bmp(report, &img, 800, 480)?,
        }
        outputs.push(img.clone());
        manifest_files.push(img.file_name().unwrap().to_string_lossy().into_owned());
    }

    let prefs_path = dir.join("batch_export_prefs.properties");
    write_batch_export_prefs(prefs, &prefs_path)?;
    outputs.push(prefs_path);

    let manifest = dir.join("image_export_manifest.json");
    let body = serde_json::json!({
        "basename": basename,
        "chart_kind": match chart_kind {
            AsdrChartKind::Line => "line",
            AsdrChartKind::Column => "column",
        },
        "chart_image_type": match prefs.chart_image_type {
            ChartImageType::Png => "png",
            ChartImageType::Bmp => "bmp",
        },
        "files": outputs.iter().filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).collect::<Vec<_>>(),
    });
    std::fs::write(&manifest, serde_json::to_string_pretty(&body).unwrap_or_else(|_| "{}".into()))
        .map_err(|source| Med64Error::WriteIo { path: manifest.clone(), source })?;
    outputs.push(manifest);

    Ok(outputs)
}

fn write_bar_png(series: &[(f64, f64)], path: &Path, w: u32, h: u32) -> Result<()> {
    // Approximate columns as a stepped line for ImageExportService Column kind.
    let mut stepped = Vec::new();
    for window in series.windows(2) {
        stepped.push(window[0]);
        stepped.push((window[1].0, window[0].1));
    }
    if let Some(last) = series.last() {
        stepped.push(*last);
    }
    write_line_png(&stepped, path, w, h)
}

fn write_bar_bmp(series: &[(f64, f64)], path: &Path, w: u32, h: u32) -> Result<()> {
    let mut stepped = Vec::new();
    for window in series.windows(2) {
        stepped.push(window[0]);
        stepped.push((window[1].0, window[0].1));
    }
    if let Some(last) = series.last() {
        stepped.push(*last);
    }
    write_line_bmp(&stepped, path, w, h)
}