use std::path::{Path, PathBuf};
use crate::analysis::AnalysisReport;
use crate::error::{Med64Error, Result};
use crate::toolkit::fbo::write_filtered_mobius_modat;
#[derive(Debug, Clone)]
pub struct FilteredExportOptions {
pub write_i16: bool,
pub write_f32: bool,
pub write_csv: bool,
pub write_modat: bool,
pub points_per_block: usize,
}
impl Default for FilteredExportOptions {
fn default() -> Self {
Self {
write_i16: true,
write_f32: true,
write_csv: true,
write_modat: true,
points_per_block: 0,
}
}
}
#[derive(Debug, Clone)]
pub struct FilteredExportReport {
pub paths: Vec<PathBuf>,
}
pub fn write_filtered_waveforms(
report: &AnalysisReport,
dir: impl AsRef<Path>,
stem: &str,
options: &FilteredExportOptions,
) -> Result<FilteredExportReport> {
let dir = dir.as_ref();
std::fs::create_dir_all(dir)
.map_err(|source| Med64Error::WriteIo { path: dir.to_path_buf(), source })?;
if report.filtered_by_channel.is_empty() {
return Err(Med64Error::InvalidWrite {
message: "no filtered traces; set AnalysisOptions.retain_filtered".into(),
});
}
let mut paths = Vec::new();
if options.write_i16 {
let p = dir.join(format!("{stem}_filtered.i16.bin"));
write_filtered_i16_binary(report, &p)?;
paths.push(p);
}
if options.write_f32 {
let p = dir.join(format!("{stem}_filtered.f32.bin"));
write_filtered_f32_binary(report, &p)?;
paths.push(p);
}
if options.write_csv {
let p = dir.join(format!("{stem}_filtered.csv"));
write_filtered_interleaved_csv(report, &p)?;
paths.push(p);
}
if options.write_modat {
let p = dir.join(format!("{stem}_filtered.modat"));
write_filtered_mobius_modat(report, &p, options.points_per_block)?;
paths.push(p);
}
Ok(FilteredExportReport { paths })
}
fn ordered_channels(report: &AnalysisReport) -> Vec<usize> {
let mut chs: Vec<usize> = report.filtered_by_channel.keys().copied().collect();
chs.sort_unstable();
chs
}
fn n_samples(report: &AnalysisReport) -> usize {
report.filtered_by_channel.values().map(|v| v.len()).max().unwrap_or(0)
}
pub fn write_filtered_i16_binary(report: &AnalysisReport, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let channels = ordered_channels(report);
let n = n_samples(report);
let mut bytes = Vec::with_capacity(n * channels.len() * 2);
for i in 0..n {
for &ch in &channels {
let mv = report.filtered_by_channel[&ch].get(i).copied().unwrap_or(0.0);
bytes.extend_from_slice(&report.header.millivolts_to_counts(mv).to_le_bytes());
}
}
std::fs::write(path, bytes)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
pub fn write_filtered_f32_binary(report: &AnalysisReport, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let channels = ordered_channels(report);
let n = n_samples(report);
let mut bytes = Vec::with_capacity(n * channels.len() * 4);
for i in 0..n {
for &ch in &channels {
let mv = report.filtered_by_channel[&ch].get(i).copied().unwrap_or(0.0);
bytes.extend_from_slice(&(mv as f32).to_le_bytes());
}
}
std::fs::write(path, bytes)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
pub fn write_filtered_interleaved_csv(
report: &AnalysisReport,
path: impl AsRef<Path>,
) -> Result<()> {
let path = path.as_ref();
let channels = ordered_channels(report);
let n = n_samples(report);
let interval = report.header.interval_ms();
let mut out = String::from("time_ms");
for &ch in &channels {
out.push_str(&format!(",ch{}", ch + 1));
}
out.push('\n');
for i in 0..n {
out.push_str(&format!("{:.6}", i as f64 * interval));
for &ch in &channels {
let mv = report.filtered_by_channel[&ch].get(i).copied().unwrap_or(0.0);
out.push_str(&format!(",{mv:.8}"));
}
out.push('\n');
}
std::fs::write(path, out)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}