use serde::{Deserialize, Serialize};
use crate::analysis::{run_analysis, AnalysisOptions};
use crate::error::{Med64Error, Result};
use crate::export::write_filtered_raw_csv;
use crate::export_waveform::{
write_filtered_i16_binary, write_filtered_waveforms, FilteredExportOptions,
};
use crate::toolkit::spectrum::load_channel_mv;
use crate::toolkit::voltage_chart::write_filtered_f64_binary;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone)]
pub struct WaveletOptions {
pub channel: usize,
pub max_blocks: Option<usize>,
pub f_min_hz: f64,
pub f_max_hz: f64,
pub n_per_octave: usize,
pub sigma: f64,
pub skip_samples: usize,
pub max_time_points: usize,
}
impl Default for WaveletOptions {
fn default() -> Self {
Self {
channel: 0,
max_blocks: Some(5),
f_min_hz: 10.0,
f_max_hz: 200.0,
n_per_octave: 4,
sigma: 6.0,
skip_samples: 4,
max_time_points: 256,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WaveletBand {
pub frequency_hz: f64,
pub power: Vec<f64>,
pub times_ms: Vec<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WaveletReport {
pub path: std::path::PathBuf,
pub channel: usize,
pub bands: Vec<WaveletBand>,
#[serde(default)]
pub max_blocks: Option<usize>,
}
#[derive(Debug, Clone)]
pub struct WaveletExportOptions {
pub filterexport: bool,
pub rawdataexport: bool,
pub binary_shorts: bool,
pub binary_doubles: bool,
pub ascii_csv: bool,
pub mobius_modat: bool,
pub hdf5: bool,
pub name: String,
}
impl Default for WaveletExportOptions {
fn default() -> Self {
Self {
filterexport: false,
rawdataexport: false,
binary_shorts: false,
binary_doubles: false,
ascii_csv: false,
mobius_modat: false,
hdf5: false,
name: "wavelet".into(),
}
}
}
pub fn continuous_wavelet(
path: impl AsRef<Path>,
options: &WaveletOptions,
) -> Result<WaveletReport> {
let path = path.as_ref();
let (header, samples) = load_channel_mv(path, options.channel, options.max_blocks)?;
let fs = header.sampling_frequency_hz;
let freqs = log_spaced_freqs(options.f_min_hz, options.f_max_hz, options.n_per_octave);
let step = options.skip_samples.max(1);
let times: Vec<usize> =
(0..samples.len()).step_by(step).take(options.max_time_points).collect();
let times_ms: Vec<f64> = times.iter().map(|&i| i as f64 * 1000.0 / fs).collect();
let mut bands = Vec::new();
for &freq in &freqs {
let scale = options.sigma / (2.0 * std::f64::consts::PI * freq);
let mut power = Vec::with_capacity(times.len());
for &t in × {
let (re, im) = morlet_coeff(&samples, t, fs, scale, options.sigma);
power.push(re * re + im * im);
}
bands.push(WaveletBand { frequency_hz: freq, power, times_ms: times_ms.clone() });
}
Ok(WaveletReport {
path: path.to_path_buf(),
channel: options.channel,
bands,
max_blocks: options.max_blocks,
})
}
pub fn write_wavelet_create_image(
report: &WaveletReport,
out_dir: impl AsRef<Path>,
) -> Result<Vec<std::path::PathBuf>> {
let dir = out_dir.as_ref();
std::fs::create_dir_all(dir)
.map_err(|source| crate::error::Med64Error::WriteIo { path: dir.to_path_buf(), source })?;
let mut outs = Vec::new();
let bands_csv = dir.join("bands.csv");
{
let mut w = String::from("frequency_hz,mean_power,max_power\n");
for b in &report.bands {
let mean = if b.power.is_empty() {
0.0
} else {
b.power.iter().sum::<f64>() / b.power.len() as f64
};
let maxp = b.power.iter().copied().fold(0.0_f64, f64::max);
w.push_str(&format!("{:.6},{:.8},{:.8}\n", b.frequency_hz, mean, maxp));
}
std::fs::write(&bands_csv, w).map_err(|source| crate::error::Med64Error::WriteIo {
path: bands_csv.clone(),
source,
})?;
}
outs.push(bands_csv);
let summary = dir.join("wavelet_summary.txt");
{
let n_t = report.bands.first().map(|b| b.power.len()).unwrap_or(0);
let text = format!(
"path: {}\nchannel: {}\nbands: {}\ntime_points: {}\nf_min_hz: {:.3}\nf_max_hz: {:.3}\n",
report.path.display(),
report.channel + 1,
report.bands.len(),
n_t,
report.bands.first().map(|b| b.frequency_hz).unwrap_or(0.0),
report.bands.last().map(|b| b.frequency_hz).unwrap_or(0.0),
);
std::fs::write(&summary, text).map_err(|source| crate::error::Med64Error::WriteIo {
path: summary.clone(),
source,
})?;
}
outs.push(summary);
let global_max =
report.bands.iter().flat_map(|b| b.power.iter().copied()).fold(1e-12_f64, f64::max);
let n_bands = report.bands.len().max(1);
let n_t = report.bands.first().map(|b| b.power.len()).unwrap_or(1).max(1);
let mut cells = String::new();
for (bi, band) in report.bands.iter().enumerate() {
for (ti, &p) in band.power.iter().enumerate() {
let t = (p / global_max).clamp(0.0, 1.0);
let r = (20.0 + 220.0 * t) as u8;
let g = (30.0 + 100.0 * (1.0 - t)) as u8;
let b = (80.0 + 140.0 * (1.0 - t)) as u8;
cells.push_str(&format!(
"<div class=\"c\" style=\"grid-row:{};grid-column:{};background:rgb({r},{g},{b})\" title=\"{:.1} Hz · p={:.4}\"></div>",
n_bands - bi,
ti + 1,
band.frequency_hz,
p
));
}
}
let freq_labels: String = report
.bands
.iter()
.enumerate()
.map(|(i, b)| {
format!(
"<div style=\"grid-row:{};grid-column:1\">{:.0}</div>",
n_bands - i,
b.frequency_hz
)
})
.collect();
let scalogram = dir.join("scalogram.html");
let html = format!(
r#"<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Wavelet scalogram</title>
<style>
body{{font-family:system-ui;margin:1rem;background:#fafafa}}
.wrap{{display:grid;grid-template-columns:3rem 1fr;gap:4px;align-items:stretch;max-width:960px}}
.freqs{{display:grid;grid-template-rows:repeat({nb},1fr);font-size:.65rem;color:#64748b;text-align:right;padding-right:4px}}
.heat{{display:grid;grid-template-columns:repeat({nt},1fr);grid-template-rows:repeat({nb},1fr);gap:1px;background:#e2e8f0;min-height:280px}}
.c{{min-height:4px}}
</style></head><body>
<h1>Wavelet scalogram</h1>
<p>{} · ch{} · {nb} bands × {nt} time</p>
<div class="wrap">
<div class="freqs">{freq}</div>
<div class="heat">{cells}</div>
</div>
</body></html>"#,
report.path.display(),
report.channel + 1,
nb = n_bands,
nt = n_t,
freq = freq_labels,
cells = cells
);
std::fs::write(&scalogram, html)
.map_err(|source| crate::error::Med64Error::WriteIo { path: scalogram.clone(), source })?;
outs.push(scalogram);
let prefer = dir.join("wavelet_prefer.html");
{
let display = serde_json::json!({
"channel": report.channel + 1,
"bands": report.bands.len(),
"times": report.bands.first().map(|b| b.times_ms.len()).unwrap_or(0),
});
let html = format!(
r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>Wavelet Prefer</title>
<style>body{{font-family:system-ui;margin:1rem}}pre{{background:#f8fafc;padding:1rem}}</style></head>
<body><h1>Wavelet Prefer</h1>
<label>Preview scale <input id="scale" type="range" min="50" max="200" value="100"></label>
<pre>{opts}</pre>
<div id="preview">scalogram display options</div>
<script>document.getElementById('scale').oninput=e=>{{document.getElementById('preview').style.transform=`scale(${{e.target.value/100}})`;}};</script>
</body></html>"#,
opts = serde_json::to_string_pretty(&display).unwrap_or_else(|_| "{}".into()),
);
std::fs::write(&prefer, html)
.map_err(|source| crate::error::Med64Error::WriteIo { path: prefer.clone(), source })?;
outs.push(prefer);
}
Ok(outs)
}
fn needs_waveforms(options: &WaveletExportOptions) -> bool {
options.filterexport
|| options.rawdataexport
|| options.binary_shorts
|| options.binary_doubles
|| options.ascii_csv
|| options.mobius_modat
|| options.hdf5
}
pub fn write_wavelet_package(
report: &WaveletReport,
out_dir: impl AsRef<Path>,
options: &WaveletExportOptions,
) -> Result<Vec<PathBuf>> {
let mut outs = write_wavelet_create_image(report, &out_dir)?;
let dir = out_dir.as_ref();
if needs_waveforms(options) {
let analysis_opts = AnalysisOptions {
max_blocks: report.max_blocks.or(Some(40)),
retain_filtered: true,
..AnalysisOptions::reference()
};
let analysis = run_analysis(&report.path, &analysis_opts)?;
if options.filterexport {
let p = dir.join("filterexport.csv");
write_filtered_raw_csv(&analysis, &p)?;
outs.push(p);
}
if options.rawdataexport {
let p = dir.join("rawdataexport.csv");
write_filtered_raw_csv(&analysis, &p)?;
outs.push(p);
let raw_bin = dir.join(format!("{}_raw.i16.bin", options.name));
write_raw_i16_export(&report.path, analysis_opts.max_blocks, &raw_bin)?;
outs.push(raw_bin);
}
if options.binary_shorts {
let p = dir.join(format!("{}_filtered.i16.bin", options.name));
write_filtered_i16_binary(&analysis, &p)?;
outs.push(p);
}
if options.binary_doubles {
let p = dir.join(format!("{}_filtered.f64.bin", options.name));
write_filtered_f64_binary(&analysis, &p)?;
outs.push(p);
}
if options.ascii_csv || options.mobius_modat {
let filt = write_filtered_waveforms(
&analysis,
dir,
&options.name,
&FilteredExportOptions {
write_i16: false,
write_f32: false,
write_csv: options.ascii_csv,
write_modat: options.mobius_modat,
points_per_block: 0,
},
)?;
outs.extend(filt.paths);
}
if options.hdf5 {
let p = dir.join(format!("{}.h5", options.name));
#[cfg(feature = "hdf5")]
{
use crate::export::{write_spike_hdf5, SpikeHdf5Options};
write_spike_hdf5(&analysis, &p, &SpikeHdf5Options::default())?;
outs.push(p);
}
#[cfg(not(feature = "hdf5"))]
{
let _ = p;
let _ = &analysis;
}
}
}
Ok(outs)
}
fn write_raw_i16_export(
path: &Path,
max_blocks: Option<usize>,
out: impl AsRef<Path>,
) -> Result<()> {
use crate::recording::Recording;
let out = out.as_ref();
let mut rec = Recording::open(path)?;
let mut bytes = Vec::new();
for (bi, block) in rec.blocks().enumerate() {
if max_blocks.is_some_and(|m| bi >= m) {
break;
}
let block = block?;
for row in &block.samples {
for &s in row {
bytes.extend_from_slice(&s.to_le_bytes());
}
}
}
std::fs::write(out, bytes)
.map_err(|source| Med64Error::WriteIo { path: out.to_path_buf(), source })
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscreteWaveletReport {
pub path: std::path::PathBuf,
pub channel: usize,
pub levels: usize,
pub approx: Vec<f64>,
pub details: Vec<Vec<f64>>,
}
pub fn discrete_wavelet(
path: impl AsRef<Path>,
channel: usize,
levels: usize,
max_blocks: Option<usize>,
) -> Result<DiscreteWaveletReport> {
let path = path.as_ref();
let (_header, samples) = load_channel_mv(path, channel, max_blocks)?;
let (approx, details) = haar_dwt(&samples, levels.max(1));
Ok(DiscreteWaveletReport {
path: path.to_path_buf(),
channel,
levels: details.len(),
approx,
details,
})
}
fn haar_dwt(samples: &[f64], levels: usize) -> (Vec<f64>, Vec<Vec<f64>>) {
let mut approx = samples.to_vec();
if approx.len() % 2 == 1 {
approx.push(*approx.last().unwrap_or(&0.0));
}
let mut details = Vec::new();
for _ in 0..levels {
if approx.len() < 2 {
break;
}
let mut next = Vec::with_capacity(approx.len() / 2);
let mut detail = Vec::with_capacity(approx.len() / 2);
for pair in approx.chunks_exact(2) {
next.push((pair[0] + pair[1]) * std::f64::consts::FRAC_1_SQRT_2);
detail.push((pair[0] - pair[1]) * std::f64::consts::FRAC_1_SQRT_2);
}
details.push(detail);
approx = next;
if approx.len() % 2 == 1 {
approx.push(*approx.last().unwrap_or(&0.0));
}
}
(approx, details)
}
fn log_spaced_freqs(f_min: f64, f_max: f64, n_per_octave: usize) -> Vec<f64> {
if f_min <= 0.0 || f_max <= f_min {
return vec![f_min.max(1.0)];
}
let octaves = (f_max / f_min).log2();
let n = (octaves * n_per_octave as f64).ceil().max(1.0) as usize;
(0..=n)
.map(|i| f_min * 2.0_f64.powf(i as f64 / n_per_octave as f64))
.filter(|&f| f <= f_max * 1.001)
.collect()
}
fn morlet_coeff(samples: &[f64], center: usize, fs: f64, scale: f64, sigma: f64) -> (f64, f64) {
let half = (scale * sigma * 3.0 * fs).ceil() as isize;
let mut re = 0.0;
let mut im = 0.0;
let mut norm = 0.0;
for dt in -half..=half {
let idx = center as isize + dt;
if idx < 0 || idx as usize >= samples.len() {
continue;
}
let t = dt as f64 / fs;
let env = (-0.5 * (t / scale).powi(2)).exp();
let omega = sigma * t / scale;
let w_re = env * omega.cos();
let w_im = env * omega.sin();
let x = samples[idx as usize];
re += x * w_re;
im += x * w_im;
norm += env;
}
if norm > 0.0 {
(re / norm, im / norm)
} else {
(0.0, 0.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn freqs_are_log_spaced() {
let f = log_spaced_freqs(10.0, 160.0, 2);
assert!(f.first().copied().unwrap() <= 10.1);
assert!(f.last().copied().unwrap() >= 80.0);
assert!(f.len() >= 4);
}
#[test]
fn haar_splits_constant_to_approx() {
let (a, d) = haar_dwt(&[2.0, 2.0, 2.0, 2.0], 1);
assert_eq!(d.len(), 1);
assert!(d[0].iter().all(|v| v.abs() < 1e-12));
assert!(a
.iter()
.all(|v| (v - 2.0 * std::f64::consts::SQRT_2).abs() < 1e-9 || (v - 2.0).abs() < 1.0));
}
#[test]
fn wavelet_create_image_package() {
let report = continuous_wavelet(
crate::fixture_paths::sample_data1(),
&WaveletOptions {
max_blocks: Some(2),
max_time_points: 32,
n_per_octave: 2,
..Default::default()
},
)
.unwrap();
let dir = std::env::temp_dir().join("med64_wavelet_create_image_test");
let _ = std::fs::remove_dir_all(&dir);
let outs = write_wavelet_create_image(&report, &dir).unwrap();
assert!(outs.iter().any(|p| p.ends_with("scalogram.html")));
assert!(outs.iter().any(|p| p.ends_with("bands.csv")));
assert!(dir.join("wavelet_summary.txt").is_file());
}
}