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 BeatOptions {
pub channel: usize,
pub max_blocks: Option<usize>,
pub plus_threshold_mv: f64,
pub minus_threshold_mv: f64,
pub refractory_ms: f64,
pub smoothing: bool,
}
impl Default for BeatOptions {
fn default() -> Self {
Self {
channel: 0,
max_blocks: Some(50),
plus_threshold_mv: 0.2,
minus_threshold_mv: -0.2,
refractory_ms: 200.0,
smoothing: false,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Beat {
pub depolarization_ms: f64,
pub repolarization_ms: Option<f64>,
pub fpd_ms: Option<f64>,
pub isi_ms: Option<f64>,
pub amplitude_mv: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BeatReport {
pub path: std::path::PathBuf,
pub channel: usize,
pub beats: Vec<Beat>,
pub mean_isi_ms: f64,
pub mean_fpd_ms: f64,
pub rate_bpm: f64,
#[serde(default)]
pub max_blocks: Option<usize>,
}
#[derive(Debug, Clone)]
pub struct BeatExportOptions {
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 timestamps: bool,
pub name: String,
}
impl Default for BeatExportOptions {
fn default() -> Self {
Self {
filterexport: false,
rawdataexport: false,
binary_shorts: false,
binary_doubles: false,
ascii_csv: false,
mobius_modat: false,
hdf5: false,
timestamps: true,
name: "beat".into(),
}
}
}
pub fn detect_beats(path: impl AsRef<Path>, options: &BeatOptions) -> Result<BeatReport> {
let path = path.as_ref();
let (header, samples) = load_channel_mv(path, options.channel, options.max_blocks)?;
let interval = header.interval_ms();
let refractory = (options.refractory_ms / interval).round().max(1.0) as usize;
let mut beats = Vec::new();
let mut i = 1usize;
let mut last_peak = -(refractory as isize);
while i + 1 < samples.len() {
let v = samples[i];
if v >= options.plus_threshold_mv
&& samples[i] >= samples[i - 1]
&& samples[i] >= samples[i + 1]
&& (i as isize) >= last_peak + refractory as isize
{
let depol = i as f64 * interval;
let mut repo = None;
let search_end = (i + refractory).min(samples.len());
for j in i + 1..search_end {
if samples[j] <= options.minus_threshold_mv
&& j + 1 < samples.len()
&& samples[j] <= samples[j - 1]
&& samples[j] <= samples[j + 1]
{
repo = Some(j as f64 * interval);
break;
}
}
let isi = beats.last().map(|b: &Beat| depol - b.depolarization_ms);
beats.push(Beat {
depolarization_ms: depol,
repolarization_ms: repo,
fpd_ms: repo.map(|r| r - depol),
isi_ms: isi,
amplitude_mv: v,
});
last_peak = i as isize;
i += refractory / 2;
continue;
}
i += 1;
}
let isis: Vec<f64> = beats.iter().filter_map(|b| b.isi_ms).collect();
let fpds: Vec<f64> = beats.iter().filter_map(|b| b.fpd_ms).collect();
let mean_isi = mean(&isis);
let mean_fpd = mean(&fpds);
let rate_bpm = if mean_isi > 0.0 { 60_000.0 / mean_isi } else { 0.0 };
Ok(BeatReport {
path: path.to_path_buf(),
channel: options.channel,
beats,
mean_isi_ms: mean_isi,
mean_fpd_ms: mean_fpd,
rate_bpm,
max_blocks: options.max_blocks,
})
}
fn mean(xs: &[f64]) -> f64 {
if xs.is_empty() {
0.0
} else {
xs.iter().sum::<f64>() / xs.len() as f64
}
}
pub fn write_beat_csv(report: &BeatReport, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let mut w =
String::from("index,depolarization_ms,repolarization_ms,fpd_ms,isi_ms,amplitude_mv\n");
for (i, b) in report.beats.iter().enumerate() {
w.push_str(&format!(
"{},{:.3},{},{},{},{:.6}\n",
i + 1,
b.depolarization_ms,
opt_f64(b.repolarization_ms),
opt_f64(b.fpd_ms),
opt_f64(b.isi_ms),
b.amplitude_mv
));
}
std::fs::write(path, w)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
pub fn write_beat_fpd_isi_csv(report: &BeatReport, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let mut w = String::from("beat,depolarization_ms,fpd_ms,isi_ms\n");
for (i, b) in report.beats.iter().enumerate() {
w.push_str(&format!(
"{},{:.3},{},{}\n",
i + 1,
b.depolarization_ms,
opt_f64(b.fpd_ms),
opt_f64(b.isi_ms)
));
}
std::fs::write(path, w)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
pub fn write_beat_html(report: &BeatReport, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let scatter: Vec<_> = report
.beats
.iter()
.filter_map(|b| match (b.fpd_ms, b.isi_ms) {
(Some(fpd), Some(isi)) => Some(serde_json::json!({"fpd": fpd, "isi": isi})),
_ => None,
})
.collect();
let timeline: Vec<_> = report
.beats
.iter()
.map(|b| {
serde_json::json!({
"t": b.depolarization_ms,
"fpd": b.fpd_ms,
"amp": b.amplitude_mv,
})
})
.collect();
let html = format!(
r##"<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Beat / FPD</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body{{font-family:system-ui,sans-serif;margin:1.25rem;background:#f8fafc;color:#0f172a}}
h1{{font-size:1.35rem;margin:0 0 .25rem}} .sub{{color:#64748b;margin-bottom:1rem}}
.stats{{display:flex;gap:1.5rem;flex-wrap:wrap;margin-bottom:1.25rem}}
.stat{{background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:.75rem 1rem;min-width:8rem}}
.stat b{{display:block;font-size:1.25rem}} .stat span{{font-size:.75rem;color:#64748b}}
section{{margin:1.25rem 0;padding:1rem;background:#fff;border:1px solid #e2e8f0;border-radius:8px}}
canvas{{max-width:100%}}
</style></head><body>
<h1>Beat / FPD detector</h1>
<div class="sub">{src} · ch{ch} · {n} beats</div>
<div class="stats">
<div class="stat"><b>{rate:.1}</b><span>Rate (BPM)</span></div>
<div class="stat"><b>{mfpd:.1}</b><span>Mean FPD (ms)</span></div>
<div class="stat"><b>{misi:.1}</b><span>Mean ISI (ms)</span></div>
</div>
<section><h2>FPD vs ISI</h2><canvas id="scatter" height="140"></canvas></section>
<section><h2>Beat timeline</h2><canvas id="tl" height="100"></canvas></section>
<script>
const scatter = {scatter_json};
const timeline = {timeline_json};
new Chart(document.getElementById('scatter'), {{
type: 'scatter',
data: {{ datasets: [{{
label: 'FPD vs ISI',
data: scatter.map(p => ({{x:p.isi, y:p.fpd}})),
pointRadius: 3,
backgroundColor: 'rgba(37,99,235,.55)'
}}] }},
options: {{
plugins: {{ legend: {{ display: false }} }},
scales: {{
x: {{ title: {{ display: true, text: 'ISI (ms)' }} }},
y: {{ title: {{ display: true, text: 'FPD (ms)' }} }}
}}
}}
}});
new Chart(document.getElementById('tl'), {{
type: 'scatter',
data: {{ datasets: [{{
label: 'amplitude',
data: timeline.map(p => ({{x:p.t, y:p.amp}})),
pointRadius: 2.5,
backgroundColor: 'rgba(220,38,38,.55)'
}}] }},
options: {{
plugins: {{ legend: {{ display: false }} }},
scales: {{
x: {{ title: {{ display: true, text: 'Time (ms)' }} }},
y: {{ title: {{ display: true, text: 'Amplitude (mV)' }} }}
}}
}}
}});
</script>
</body></html>"##,
src = report.path.display(),
ch = report.channel + 1,
n = report.beats.len(),
rate = report.rate_bpm,
mfpd = report.mean_fpd_ms,
misi = report.mean_isi_ms,
scatter_json = serde_json::to_string(&scatter).unwrap_or_else(|_| "[]".into()),
timeline_json = serde_json::to_string(&timeline).unwrap_or_else(|_| "[]".into()),
);
std::fs::write(path, html)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
fn needs_waveforms(options: &BeatExportOptions) -> bool {
options.filterexport
|| options.rawdataexport
|| options.binary_shorts
|| options.binary_doubles
|| options.ascii_csv
|| options.mobius_modat
|| options.hdf5
}
pub fn write_beat_package(
report: &BeatReport,
out_dir: impl AsRef<Path>,
options: &BeatExportOptions,
) -> Result<Vec<PathBuf>> {
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 outs = Vec::new();
let csv = dir.join("beats.csv");
write_beat_csv(report, &csv)?;
outs.push(csv);
let fpd = dir.join("beat_fpd_isi.csv");
write_beat_fpd_isi_csv(report, &fpd)?;
outs.push(fpd);
let html = dir.join("beat.html");
write_beat_html(report, &html)?;
outs.push(html);
let peakline = dir.join("peakline_fpd_isi.tsv");
{
let mut w = String::from("beat\tdepolarization_ms\tfpd_ms\tisi_ms\n");
for (i, b) in report.beats.iter().enumerate() {
w.push_str(&format!(
"{}\t{:.3}\t{}\t{}\n",
i + 1,
b.depolarization_ms,
opt_f64(b.fpd_ms),
opt_f64(b.isi_ms)
));
}
std::fs::write(&peakline, w)
.map_err(|source| Med64Error::WriteIo { path: peakline.clone(), source })?;
outs.push(peakline);
}
if options.timestamps {
let ts = dir.join(format!("{}_SpikeTimeStamp.csv", options.name));
let mut w = String::from("channel,time_ms\n");
for b in &report.beats {
w.push_str(&format!("{},{:.6}\n", report.channel + 1, b.depolarization_ms));
}
std::fs::write(&ts, w)
.map_err(|source| Med64Error::WriteIo { path: ts.clone(), source })?;
outs.push(ts);
}
if needs_waveforms(options) {
let mut analysis_opts = AnalysisOptions {
max_blocks: report.max_blocks.or(Some(50)),
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;
}
}
let _ = &mut analysis_opts;
}
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 })
}
fn opt_f64(v: Option<f64>) -> String {
v.map(|x| format!("{x:.3}")).unwrap_or_default()
}
#[cfg(test)]
mod tests {
#[test]
fn finds_synthetic_beats() {
let mut samples = vec![0.0_f64; 3000];
for peak in [500usize, 1500, 2500] {
samples[peak] = 1.0;
if peak + 80 < samples.len() {
samples[peak + 80] = -0.5;
}
}
let mut beats = 0;
let mut last = -1000isize;
for i in 1..samples.len() - 1 {
if samples[i] >= 0.2
&& samples[i] >= samples[i - 1]
&& samples[i] >= samples[i + 1]
&& i as isize >= last + 200
{
beats += 1;
last = i as isize;
}
}
assert_eq!(beats, 3);
}
}