use serde::{Deserialize, Serialize};
use crate::analysis::{run_analysis, AnalysisOptions, Spike, SpikeTrain};
use crate::error::Result;
use crate::recording::Recording;
use crate::toolkit::peth::{
peri_event_histogram, stim_events_from_recording, PethOptions, PethReport,
};
use crate::toolkit::propagation::{propagation_from_spikes, PropagationOptions, PropagationReport};
use crate::toolkit::spectrum::load_channel_mv;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PaceSource {
Synthetic,
StimMarkers,
ElectrodeArtifact,
}
impl PaceSource {
pub fn parse(s: &str) -> Option<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"synthetic" | "interval" | "synth" => Some(Self::Synthetic),
"markers" | "stim" | "block" => Some(Self::StimMarkers),
"artifact" | "electrode" | "f1" => Some(Self::ElectrodeArtifact),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum PaceRhythmMode {
#[default]
Paced,
Spontaneous,
}
impl PaceRhythmMode {
pub fn parse(s: &str) -> Option<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"paced" | "pace" => Some(Self::Paced),
"spontaneous" | "spont" | "s" => Some(Self::Spontaneous),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaceWindow {
pub start_ms: f64,
pub end_ms: f64,
pub mode: PaceRhythmMode,
}
#[derive(Debug, Clone)]
pub struct PacingOptions {
pub analysis: AnalysisOptions,
pub source: PaceSource,
pub pace_interval_ms: f64,
pub electrode_pitch_um: f64,
pub peth_pre_ms: f64,
pub peth_post_ms: f64,
pub peth_bin_ms: f64,
pub stim_channel_a: usize,
pub stim_channel_b: usize,
pub artifact_mv: f64,
pub artifact_refractory_ms: f64,
pub peak1_from_ms: f64,
pub peak1_to_ms: f64,
pub peak2_from_ms: f64,
pub peak2_to_ms: f64,
pub range_start_ms: Option<f64>,
pub range_end_ms: Option<f64>,
pub mark_spontaneous: bool,
pub ranges: Vec<PaceWindow>,
}
impl Default for PacingOptions {
fn default() -> Self {
Self {
analysis: AnalysisOptions { max_blocks: Some(20), ..AnalysisOptions::default() },
source: PaceSource::StimMarkers,
pace_interval_ms: 500.0,
electrode_pitch_um: 150.0,
peth_pre_ms: 20.0,
peth_post_ms: 100.0,
peth_bin_ms: 2.0,
stim_channel_a: 40, stim_channel_b: 41,
artifact_mv: 5.0,
artifact_refractory_ms: 50.0,
peak1_from_ms: 0.0,
peak1_to_ms: 100.0,
peak2_from_ms: 100.0,
peak2_to_ms: 300.0,
range_start_ms: None,
range_end_ms: None,
mark_spontaneous: false,
ranges: Vec::new(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChChartBeat {
pub channel: usize,
pub beat_index: usize,
pub timestamp1_ms: f64,
pub timestamp2_ms: Option<f64>,
pub fpd_ms: Option<f64>,
pub isi_ms: Option<f64>,
pub amp_plus_mv: f64,
pub amp_minus_mv: f64,
pub amp_pp_mv: f64,
pub r: f64,
pub paced: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PacingReport {
pub path: PathBuf,
pub pace_times_ms: Vec<f64>,
pub capture_ratio: f64,
pub mean_latency_ms: f64,
pub propagation: PropagationReport,
pub peth: PethReport,
#[serde(default)]
pub source: String,
#[serde(default)]
pub fpd_ms: Vec<f64>,
#[serde(default)]
pub fpd2_ms: Vec<f64>,
#[serde(default)]
pub isi_ms: Vec<f64>,
#[serde(default)]
pub stim_channels: Vec<usize>,
#[serde(default)]
pub spontaneous_spike_count: usize,
#[serde(default)]
pub ranges: Vec<PaceWindow>,
#[serde(default)]
pub chchart: Vec<ChChartBeat>,
#[serde(default)]
pub captured: Vec<bool>,
}
pub fn analyze_pacing(path: impl AsRef<Path>, options: &PacingOptions) -> Result<PacingReport> {
let path = path.as_ref();
let pace_times = resolve_pace_times(path, options)?;
let report = run_analysis(path, &options.analysis)?;
Ok(pacing_from_spikes_with_paces(path, &report.spikes, &pace_times, options))
}
pub fn resolve_pace_times(path: &Path, options: &PacingOptions) -> Result<Vec<f64>> {
match options.source {
PaceSource::Synthetic => {
let rec = Recording::open(path)?;
let header = rec.header().clone();
let duration_ms = if let Some(n) = options.analysis.max_blocks {
n as f64 * header.num_data_points_per_block() as f64 * header.interval_ms()
} else {
header.real_trace_duration_ms
};
Ok(synthetic_paces(duration_ms, options.pace_interval_ms))
}
PaceSource::StimMarkers => {
let mut events = stim_events_from_recording(path, options.analysis.max_blocks)?;
if events.is_empty() {
let rec = Recording::open(path)?;
let dur = rec.header().real_trace_duration_ms;
events = synthetic_paces(dur, options.pace_interval_ms);
}
Ok(events)
}
PaceSource::ElectrodeArtifact => detect_artifact_paces(path, options),
}
}
fn synthetic_paces(duration_ms: f64, interval_ms: f64) -> Vec<f64> {
let mut pace_times = Vec::new();
let mut t = 0.0;
while t < duration_ms.max(1.0) {
pace_times.push(t);
t += interval_ms.max(1.0);
}
if pace_times.is_empty() {
pace_times.push(0.0);
}
pace_times
}
fn detect_artifact_paces(path: &Path, options: &PacingOptions) -> Result<Vec<f64>> {
let channels = [options.stim_channel_a, options.stim_channel_b];
let mut events = Vec::new();
for &ch in &channels {
let (header, samples) = load_channel_mv(path, ch, options.analysis.max_blocks)?;
let interval = header.interval_ms();
let refractory = ((options.artifact_refractory_ms / interval).round() as isize).max(1);
let mut last = -refractory;
for i in 1..samples.len() {
let dv = (samples[i] - samples[i - 1]).abs();
if dv >= options.artifact_mv && i as isize >= last + refractory {
events.push(i as f64 * interval);
last = i as isize;
}
}
}
events.sort_by(|a, b| a.partial_cmp(b).unwrap());
let mut dedup = Vec::new();
for t in events {
if dedup
.last()
.map(|p: &f64| (t - p).abs() >= options.artifact_refractory_ms * 0.5)
.unwrap_or(true)
{
dedup.push(t);
}
}
if dedup.is_empty() {
let mut opts = options.clone();
opts.source = PaceSource::StimMarkers;
return resolve_pace_times(path, &opts);
}
Ok(dedup)
}
pub fn pacing_from_spikes(
path: impl AsRef<Path>,
train: &SpikeTrain,
duration_ms: f64,
options: &PacingOptions,
) -> PacingReport {
let paces = synthetic_paces(duration_ms, options.pace_interval_ms);
pacing_from_spikes_with_paces(path.as_ref(), train, &paces, options)
}
fn effective_windows(options: &PacingOptions) -> Vec<PaceWindow> {
if !options.ranges.is_empty() {
return options.ranges.iter().take(3).cloned().collect();
}
let lo = options.range_start_ms.unwrap_or(0.0);
let hi = options.range_end_ms.unwrap_or(f64::MAX);
vec![PaceWindow { start_ms: lo, end_ms: hi, mode: PaceRhythmMode::Paced }]
}
fn spikes_in_window<'a>(train: &'a SpikeTrain, window: &PaceWindow) -> Vec<&'a Spike> {
train
.spikes
.iter()
.filter(|s| {
s.within_session_time_ms >= window.start_ms && s.within_session_time_ms <= window.end_ms
})
.collect()
}
fn find_peak_lag<'a>(
spikes: &[&'a Spike],
pace: f64,
from_ms: f64,
to_ms: f64,
) -> Option<(f64, &'a Spike)> {
let mut best: Option<(f64, &Spike)> = None;
for &spike in spikes {
let lag = spike.within_session_time_ms - pace;
if lag >= from_ms && lag <= to_ms {
best = Some(match best {
Some((prev, _)) if lag < prev => (lag, spike),
Some(prev) => prev,
None => (lag, spike),
});
}
}
best
}
fn amp_plus_minus(spike: &Spike) -> (f64, f64) {
let amp = spike.peak_mv;
match spike.direction {
crate::analysis::SpikeDirection::Plus => (amp.max(0.0), 0.0),
crate::analysis::SpikeDirection::Minus => (0.0, amp.min(0.0)),
}
}
fn build_chchart(
train: &SpikeTrain,
pace_times: &[f64],
options: &PacingOptions,
windows: &[PaceWindow],
) -> Vec<ChChartBeat> {
let mut out = Vec::new();
let by_ch = train.by_channel();
for (&channel, ch_spikes) in &by_ch {
let mut beat_index = 0usize;
let mut last_t1: Option<f64> = None;
for window in windows {
let in_win: Vec<&Spike> = ch_spikes
.iter()
.copied()
.filter(|s| {
s.within_session_time_ms >= window.start_ms
&& s.within_session_time_ms <= window.end_ms
})
.collect();
if in_win.is_empty() {
continue;
}
match window.mode {
PaceRhythmMode::Paced => {
for &pace in pace_times {
if pace < window.start_ms || pace > window.end_ms {
continue;
}
let p1 = find_peak_lag(
&in_win,
pace,
options.peak1_from_ms,
options.peak1_to_ms,
);
let Some((lag1, spike1)) = p1 else {
continue;
};
let t1 = pace + lag1;
let p2 = find_peak_lag(
&in_win,
pace,
options.peak2_from_ms,
options.peak2_to_ms,
);
let (t2, spike2) = match p2 {
Some((lag2, s2)) => (Some(pace + lag2), Some(s2)),
None => (None, None),
};
let (amp_plus, amp_minus) = amp_plus_minus(spike1);
let (ap2, am2) = spike2.map(amp_plus_minus).unwrap_or((0.0, 0.0));
let amp_plus = if amp_plus.abs() > 0.0 { amp_plus } else { ap2 };
let amp_minus = if amp_minus.abs() > 0.0 { amp_minus } else { am2 };
let fpd = t2.map(|t| t - t1);
let amp_pp = amp_plus.abs() + amp_minus.abs();
let r = match fpd {
Some(f) if f.abs() > 1e-9 => amp_pp / f,
_ => 0.0,
};
let isi = last_t1.map(|prev| t1 - prev);
last_t1 = Some(t1);
out.push(ChChartBeat {
channel,
beat_index,
timestamp1_ms: t1,
timestamp2_ms: t2,
fpd_ms: fpd,
isi_ms: isi,
amp_plus_mv: amp_plus,
amp_minus_mv: amp_minus,
amp_pp_mv: amp_pp,
r,
paced: true,
});
beat_index += 1;
}
}
PaceRhythmMode::Spontaneous => {
let mut spikes_sorted = in_win;
spikes_sorted.sort_by(|a, b| {
a.within_session_time_ms.partial_cmp(&b.within_session_time_ms).unwrap()
});
for (si, &spike1) in spikes_sorted.iter().enumerate() {
let t1 = spike1.within_session_time_ms;
let t2 = spikes_sorted[si + 1..]
.iter()
.find(|s| {
let lag = s.within_session_time_ms - t1;
lag >= options.peak2_from_ms && lag <= options.peak2_to_ms
})
.map(|s| s.within_session_time_ms);
let (amp_plus, amp_minus) = amp_plus_minus(spike1);
let fpd = t2.map(|t| t - t1);
let amp_pp = amp_plus.abs() + amp_minus.abs();
let r = match fpd {
Some(f) if f.abs() > 1e-9 => amp_pp / f,
_ => 0.0,
};
let isi = last_t1.map(|prev| t1 - prev);
last_t1 = Some(t1);
out.push(ChChartBeat {
channel,
beat_index,
timestamp1_ms: t1,
timestamp2_ms: t2,
fpd_ms: fpd,
isi_ms: isi,
amp_plus_mv: amp_plus,
amp_minus_mv: amp_minus,
amp_pp_mv: amp_pp,
r,
paced: false,
});
beat_index += 1;
}
}
}
}
}
out
}
pub fn pacing_from_spikes_with_paces(
path: &Path,
train: &SpikeTrain,
pace_times: &[f64],
options: &PacingOptions,
) -> PacingReport {
let windows = effective_windows(options);
let mut captured_n = 0usize;
let mut latency_sum = 0.0;
let mut fpd_ms = Vec::new();
let mut fpd2_ms = Vec::new();
let mut captured_flags = Vec::with_capacity(pace_times.len());
for &pace in pace_times {
let in_paced_window = windows
.iter()
.any(|w| w.mode == PaceRhythmMode::Paced && pace >= w.start_ms && pace <= w.end_ms);
if !options.ranges.is_empty() && !in_paced_window {
let in_any = windows.iter().any(|w| pace >= w.start_ms && pace <= w.end_ms);
if !in_any {
captured_flags.push(false);
fpd_ms.push(f64::NAN);
fpd2_ms.push(f64::NAN);
continue;
}
}
let window_spikes: Vec<&Spike> = if options.ranges.is_empty() {
train.spikes.iter().collect()
} else {
windows
.iter()
.filter(|w| pace >= w.start_ms && pace <= w.end_ms)
.flat_map(|w| spikes_in_window(train, w))
.collect()
};
let best1 = find_peak_lag(&window_spikes, pace, options.peak1_from_ms, options.peak1_to_ms)
.map(|(lag, _)| lag);
let best2 = find_peak_lag(&window_spikes, pace, options.peak2_from_ms, options.peak2_to_ms)
.map(|(lag, _)| lag);
let got = best1.is_some();
captured_flags.push(got);
if let Some(lag) = best1 {
if in_paced_window || options.ranges.is_empty() {
captured_n += 1;
latency_sum += lag;
}
fpd_ms.push(lag);
} else {
fpd_ms.push(f64::NAN);
}
if let Some(lag) = best2 {
fpd2_ms.push(lag);
} else {
fpd2_ms.push(f64::NAN);
}
}
let paced_n = pace_times
.iter()
.filter(|&&p| {
windows
.iter()
.any(|w| w.mode == PaceRhythmMode::Paced && p >= w.start_ms && p <= w.end_ms)
})
.count()
.max(1);
let capture_ratio = captured_n as f64 / paced_n as f64;
let mean_latency = if captured_n > 0 { latency_sum / captured_n as f64 } else { 0.0 };
let mut isi_ms = Vec::new();
for w in pace_times.windows(2) {
isi_ms.push(w[1] - w[0]);
}
let spontaneous_spike_count = if options.mark_spontaneous
|| windows.iter().any(|w| w.mode == PaceRhythmMode::Spontaneous)
{
let mut count = 0usize;
for window in &windows {
if window.mode == PaceRhythmMode::Spontaneous {
count += spikes_in_window(train, window).len();
} else if options.mark_spontaneous {
count += spikes_in_window(train, window)
.into_iter()
.filter(|s| {
!pace_times.iter().any(|&p| {
let lag = s.within_session_time_ms - p;
lag >= options.peak1_from_ms && lag <= options.peak2_to_ms
})
})
.count();
}
}
count
} else {
0
};
let chchart = build_chchart(train, pace_times, options, &windows);
let prop = propagation_from_spikes(
path,
train,
&PropagationOptions {
electrode_pitch_um: options.electrode_pitch_um,
analysis: options.analysis.clone(),
..PropagationOptions::default()
},
);
let peth = peri_event_histogram(
train,
pace_times,
&PethOptions {
pre_ms: options.peth_pre_ms,
post_ms: options.peth_post_ms,
bin_ms: options.peth_bin_ms,
..Default::default()
},
);
PacingReport {
path: path.to_path_buf(),
pace_times_ms: pace_times.to_vec(),
capture_ratio,
mean_latency_ms: mean_latency,
propagation: prop,
peth,
source: format!("{:?}", options.source),
fpd_ms,
fpd2_ms,
isi_ms,
stim_channels: vec![options.stim_channel_a, options.stim_channel_b],
spontaneous_spike_count,
ranges: windows,
chchart,
captured: captured_flags,
}
}
pub fn write_pacing_package(
report: &PacingReport,
out_dir: impl AsRef<Path>,
) -> Result<Vec<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 paces = dir.join("pace_times.csv");
{
let mut w = String::from("pace_index,time_ms,fpd_ms,fpd2_ms,captured\n");
for (i, t) in report.pace_times_ms.iter().enumerate() {
let fpd = report
.fpd_ms
.get(i)
.copied()
.filter(|v| v.is_finite())
.map(|v| format!("{v:.6}"))
.unwrap_or_default();
let fpd2 = report
.fpd2_ms
.get(i)
.copied()
.filter(|v| v.is_finite())
.map(|v| format!("{v:.6}"))
.unwrap_or_default();
let cap = report.captured.get(i).copied().unwrap_or(false);
w.push_str(&format!("{i},{t:.6},{fpd},{fpd2},{}\n", cap as u8));
}
std::fs::write(&paces, w)
.map_err(|source| crate::error::Med64Error::WriteIo { path: paces.clone(), source })?;
outs.push(paces);
}
let chchart = dir.join("chchart_metrics.csv");
{
let mut w = String::from(
"channel,beat_index,timestamp1_ms,timestamp2_ms,fpd_ms,isi_ms,amp_plus_mv,amp_minus_mv,amp_pp_mv,r,paced\n",
);
for b in &report.chchart {
w.push_str(&format!(
"{},{},{:.6},{},{},{},{:.6},{:.6},{:.6},{:.6},{}\n",
b.channel + 1,
b.beat_index,
b.timestamp1_ms,
opt_f64(b.timestamp2_ms),
opt_f64(b.fpd_ms),
opt_f64(b.isi_ms),
b.amp_plus_mv,
b.amp_minus_mv,
b.amp_pp_mv,
b.r,
b.paced as u8,
));
}
std::fs::write(&chchart, w).map_err(|source| crate::error::Med64Error::WriteIo {
path: chchart.clone(),
source,
})?;
outs.push(chchart);
}
let fpd_by_ch = dir.join("fpd_by_channel.tsv");
{
let mut by_ch: std::collections::BTreeMap<usize, (Vec<f64>, Vec<f64>)> =
std::collections::BTreeMap::new();
for b in &report.chchart {
let e = by_ch.entry(b.channel).or_default();
if let Some(fpd) = b.fpd_ms {
e.0.push(fpd);
}
if let Some(isi) = b.isi_ms {
e.1.push(isi);
}
}
let mut w = String::from("Ch\tFPD_\tISI_\n");
for (ch, (fpds, isis)) in by_ch {
let mean_fpd =
if fpds.is_empty() { 0.0 } else { fpds.iter().sum::<f64>() / fpds.len() as f64 };
let mean_isi =
if isis.is_empty() { 0.0 } else { isis.iter().sum::<f64>() / isis.len() as f64 };
w.push_str(&format!("{}\t{:.6}\t{:.6}\n", ch + 1, mean_fpd, mean_isi));
}
std::fs::write(&fpd_by_ch, w).map_err(|source| crate::error::Med64Error::WriteIo {
path: fpd_by_ch.clone(),
source,
})?;
outs.push(fpd_by_ch);
}
let summary = dir.join("pacing_summary.txt");
{
let body = format!(
"source: {}\npaces: {}\ncapture_ratio: {:.6}\nmean_latency_ms: {:.6}\nmean_isi_ms: {:.6}\nspontaneous_spike_count: {}\nranges: {}\nchchart_beats: {}\n",
report.source,
report.pace_times_ms.len(),
report.capture_ratio,
report.mean_latency_ms,
if report.isi_ms.is_empty() {
0.0
} else {
report.isi_ms.iter().sum::<f64>() / report.isi_ms.len() as f64
},
report.spontaneous_spike_count,
report.ranges.len(),
report.chchart.len(),
);
std::fs::write(&summary, body).map_err(|source| crate::error::Med64Error::WriteIo {
path: summary.clone(),
source,
})?;
outs.push(summary);
}
let ch_html = dir.join("pacing_chchart.html");
write_pacing_chchart_html(report, &ch_html)?;
outs.push(ch_html);
let delay_html = dir.join("pacing_delay_map.html");
write_pacing_delay_map_html(report, &delay_html)?;
outs.push(delay_html);
Ok(outs)
}
pub fn write_pacing_chchart_html(report: &PacingReport, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let mut by_ch: std::collections::BTreeMap<usize, Vec<&ChChartBeat>> =
std::collections::BTreeMap::new();
for b in &report.chchart {
by_ch.entry(b.channel).or_default().push(b);
}
let mut panels = String::new();
for ch in 0..64 {
let beats = by_ch.get(&ch).map(|v| v.as_slice()).unwrap_or(&[]);
let mut pts = String::new();
for (i, b) in beats.iter().enumerate() {
let y = b.fpd_ms.unwrap_or(b.timestamp1_ms);
let px =
if beats.len() <= 1 { 40.0 } else { i as f64 / (beats.len() - 1) as f64 * 80.0 };
let py = 40.0 - (y / 100.0).clamp(0.0, 1.0) * 36.0;
pts.push_str(&format!("{px:.1},{py:.1} "));
}
panels.push_str(&format!(
r##"<div class="ch"><div class="lab">Ch {}</div>
<svg viewBox="0 0 80 48" width="100%" height="48"><polyline fill="none" stroke="#0ea5e9" stroke-width="1.2" points="{pts}"/></svg></div>"##,
ch + 1
));
}
let html = format!(
r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>Pacing ChChart 64</title>
<style>body{{font-family:system-ui;margin:1rem}}.g{{display:grid;grid-template-columns:repeat(8,1fr);gap:4px;max-width:960px}}
.ch{{border:1px solid #e2e8f0;padding:2px}}.lab{{font-size:.65rem;color:#64748b}}</style></head>
<body><h1>Pacing 64-channel beat chart</h1>
<p>{} · {} paces · capture {:.1}%</p>
<div class="g">{panels}</div></body></html>"#,
report.path.display(),
report.pace_times_ms.len(),
report.capture_ratio * 100.0
);
std::fs::write(path, html)
.map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })
}
pub fn write_pacing_delay_map_html(report: &PacingReport, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let mut lat = vec![f64::NAN; 64];
for b in &report.chchart {
if let Some(fpd) = b.fpd_ms {
let slot = &mut lat[b.channel.min(63)];
if slot.is_nan() {
*slot = fpd;
} else {
*slot = (*slot + fpd) * 0.5;
}
}
}
for cell in &report.propagation.cells {
if cell.channel < 64 {
if let Some(d) = cell.delay_ms {
if d.is_finite() {
lat[cell.channel] = d;
}
}
}
}
let finite: Vec<f64> = lat.iter().copied().filter(|v| v.is_finite()).collect();
let lo = finite.iter().copied().fold(f64::INFINITY, f64::min);
let hi = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
let mut cells = String::new();
for (i, &v) in lat.iter().enumerate() {
let (bg, label) = if v.is_finite() {
let t = if hi > lo { ((v - lo) / (hi - lo)).clamp(0.0, 1.0) } else { 0.5 };
let r = (255.0 * t) as u8;
let b = (255.0 * (1.0 - t)) as u8;
(format!("rgb({r},80,{b})"), format!("{v:.1}"))
} else {
("#e2e8f0".into(), "—".into())
};
cells.push_str(&format!(
r#"<div class="c" style="background:{bg}" title="Ch {}">{label}</div>"#,
i + 1
));
}
let html = format!(
r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>Pacing delay map</title>
<style>body{{font-family:system-ui;margin:1rem}}.g{{display:grid;grid-template-columns:repeat(8,1fr);gap:3px;max-width:420px}}
.c{{aspect-ratio:1;display:flex;align-items:center;justify-content:center;font-size:.65rem;color:#111}}</style></head>
<body><h1>Pacing delay map</h1>
<p>mean latency {:.2} ms · range [{lo:.1}, {hi:.1}]</p>
<div class="g">{cells}</div></body></html>"#,
report.mean_latency_ms
);
std::fs::write(path, html)
.map_err(|source| crate::error::Med64Error::WriteIo { path: path.to_path_buf(), source })
}
fn opt_f64(v: Option<f64>) -> String {
v.map(|x| format!("{x:.6}")).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::analysis::spike::{Spike, SpikeTrain};
#[test]
fn captures_paced_spikes() {
let mut train = SpikeTrain::default();
for t in [5.0, 505.0, 1005.0] {
train.push(Spike {
within_session_time_ms: t,
within_trace_time_ms: t,
channel: 0,
..Default::default()
});
}
let report = pacing_from_spikes(
"mem.modat",
&train,
1500.0,
&PacingOptions {
source: PaceSource::Synthetic,
pace_interval_ms: 500.0,
peth_post_ms: 50.0,
peak1_to_ms: 50.0,
..Default::default()
},
);
assert!(report.capture_ratio > 0.9);
assert!(report.mean_latency_ms > 0.0);
assert_eq!(report.fpd_ms.len(), 3);
assert!(!report.chchart.is_empty());
}
}