use serde::Serialize;
use crate::error::Result;
use crate::header::Med64Header;
use crate::recording::Recording;
#[derive(Debug, Clone, Serialize)]
pub struct WaveStackTrace {
pub path: std::path::PathBuf,
pub trace: u32,
pub label: String,
pub times_ms: Vec<f64>,
pub millivolts: Vec<f64>,
}
#[derive(Debug, Clone, Serialize)]
pub struct WaveStack {
pub channel: usize,
#[serde(skip)]
pub header: Med64Header,
pub traces: Vec<WaveStackTrace>,
}
pub fn load_wave_stack(
paths: &[impl AsRef<std::path::Path>],
channel: usize,
max_blocks: Option<usize>,
) -> Result<WaveStack> {
let mut traces = Vec::new();
let mut header = None;
for path in paths {
let path = path.as_ref();
let mut rec = Recording::open(path)?;
let h = rec.header().clone();
header.get_or_insert(h.clone());
let interval = h.interval_ms();
let mut times = Vec::new();
let mut mvs = Vec::new();
let mut t0 = 0.0;
for (bi, block) in rec.blocks().enumerate() {
if max_blocks.is_some_and(|m| bi >= m) {
break;
}
let block = block?;
let col = block.channel_indices.iter().position(|&c| c == channel).unwrap_or(0);
for (i, row) in block.samples.iter().enumerate() {
times.push(t0 + i as f64 * interval);
mvs.push(h.counts_to_millivolts(row[col]));
}
t0 += block.samples.len() as f64 * interval;
}
traces.push(WaveStackTrace {
path: path.to_path_buf(),
trace: 0,
label: path
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| "trace".into()),
times_ms: times,
millivolts: mvs,
});
}
Ok(WaveStack {
channel,
header: header.unwrap_or_else(|| Med64Header {
path: std::path::PathBuf::from("empty.modat"),
number_of_traces: 0,
blocks_per_trace: 0,
data_format_version: 0,
sampling_frequency_hz: 20_000.0,
trace_duration_ms: 0.0,
daq_voltage_range: 10.0,
conversion_factor: 0.001,
active_channels: [0; 64],
start_year: 2020,
start_month: 1,
start_day: 1,
start_time_ms: 0,
start_timezone_minutes: 0,
number_of_real_data_blocks: 0,
real_trace_duration_ms: 0.0,
extended_active_channels: None,
}),
traces,
})
}
pub fn write_wavestack_html(stack: &WaveStack, path: impl AsRef<std::path::Path>) -> Result<()> {
let path = path.as_ref();
let datasets: Vec<_> = stack
.traces
.iter()
.enumerate()
.map(|(i, t)| {
serde_json::json!({
"label": t.label,
"data": t.times_ms.iter().zip(&t.millivolts).map(|(x,y)| serde_json::json!({"x": x, "y": y})).collect::<Vec<_>>(),
"borderColor": format!("hsl({} 70% 45%)", i * 53 % 360),
"pointRadius": 0,
})
})
.collect();
let html = format!(
r#"<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Waveform stack ch{}</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script></head>
<body><h1>Waveform viewer — channel {}</h1>
<canvas id="c"></canvas>
<script>
new Chart(document.getElementById('c'), {{
type: 'line',
data: {{ datasets: {} }},
options: {{ responsive: true, scales: {{ x: {{ title: {{ display: true, text: 'Time (ms)' }} }} }} }}
}});
</script></body></html>"#,
stack.channel + 1,
stack.channel + 1,
serde_json::to_string(&datasets).unwrap_or("[]".into())
);
std::fs::write(path, html)
.map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })?;
Ok(())
}