med64 0.0.2

Headless MED64 electrophysiology toolkit: .modat I/O, spike/burst analysis, assays, spike-rate maps, and CSV/HTML/SVG/HDF5 export
Documentation
use std::fs;
use std::path::{Path, PathBuf};

use serde::Serialize;

use crate::diagnostics::{analyze, DiagnosticOptions, Diagnostics};
use crate::error::{Med64Error, Result};
use crate::header::Med64Header;
use crate::recording::Recording;

/// Chart generation options.
#[derive(Debug, Clone)]
pub struct ChartOptions {
    pub block_index: usize,
    /// Time window in milliseconds from block start.
    pub duration_ms: f64,
    pub channels: Option<Vec<usize>>,
    /// Max points per channel after decimation.
    pub max_points: usize,
    pub diagnostic_blocks: Option<usize>,
}

impl Default for ChartOptions {
    fn default() -> Self {
        Self {
            block_index: 0,
            duration_ms: 500.0,
            channels: None,
            max_points: 2000,
            diagnostic_blocks: Some(10),
        }
    }
}

impl ChartOptions {
    pub fn block_index(mut self, index: usize) -> Self {
        self.block_index = index;
        self
    }

    pub fn duration_ms(mut self, ms: f64) -> Self {
        self.duration_ms = ms;
        self
    }

    pub fn channels(mut self, channels: &[usize]) -> Self {
        self.channels = Some(channels.to_vec());
        self
    }
}

/// Waveform series ready for plotting.
#[derive(Debug, Clone, Serialize)]
pub struct WaveformSeries {
    pub channel: usize,
    pub label: String,
    pub times_ms: Vec<f64>,
    pub millivolts: Vec<f64>,
}

#[derive(Debug, Clone, Serialize)]
struct ChartPayload {
    title: String,
    source: String,
    header: PayloadHeader,
    diagnostics: PayloadDiagnostics,
    waveforms: Vec<WaveformSeries>,
    channel_rms: Vec<PayloadRms>,
}

#[derive(Debug, Clone, Serialize)]
struct PayloadHeader {
    sample_rate_hz: f64,
    interval_ms: f64,
    block_index: usize,
    window_ms: f64,
}

#[derive(Debug, Clone, Serialize)]
struct PayloadDiagnostics {
    warnings: Vec<String>,
    blocks_scanned: usize,
}

#[derive(Debug, Clone, Serialize)]
struct PayloadRms {
    channel: usize,
    rms_mv: f64,
    peak_to_peak_mv: f64,
}

/// Build waveform series from a recording window.
pub fn extract_waveforms(
    recording: &mut Recording,
    header: &Med64Header,
    options: &ChartOptions,
) -> Result<Vec<WaveformSeries>> {
    recording.seek_block(options.block_index)?;
    let block = recording.read_block()?.ok_or_else(|| Med64Error::InvalidBlock {
        path: recording.path().to_path_buf(),
        block_index: options.block_index,
        message: "block not found".into(),
    })?;

    let interval = header.interval_ms();
    let base_ms = block.block_offset_ms + block.trace_offset_ms;
    let max_points = block.samples.len().min((options.duration_ms / interval).ceil() as usize);

    let channel_filter: Vec<usize> =
        options.channels.clone().unwrap_or_else(|| block.channel_indices.clone());

    let mut series = Vec::new();
    for &channel in &channel_filter {
        let col = block.channel_indices.iter().position(|&c| c == channel).ok_or_else(|| {
            Med64Error::InvalidWrite { message: format!("channel {channel} not in block") }
        })?;

        let mut times_ms = Vec::with_capacity(max_points);
        let mut millivolts = Vec::with_capacity(max_points);
        for point_idx in 0..max_points {
            let t = base_ms + point_idx as f64 * interval;
            if t - base_ms > options.duration_ms {
                break;
            }
            let counts = block.samples[point_idx][col];
            times_ms.push(t);
            millivolts.push(header.counts_to_millivolts(counts));
        }

        decimate_series(&mut times_ms, &mut millivolts, options.max_points);
        series.push(WaveformSeries {
            channel,
            label: format!("Ch {channel}"),
            times_ms,
            millivolts,
        });
    }
    Ok(series)
}

fn decimate_series(times: &mut Vec<f64>, values: &mut Vec<f64>, max_points: usize) {
    if times.len() <= max_points {
        return;
    }
    let step = (times.len() as f64 / max_points as f64).ceil() as usize;
    let mut t_out = Vec::with_capacity(max_points);
    let mut v_out = Vec::with_capacity(max_points);
    for i in (0..times.len()).step_by(step.max(1)) {
        t_out.push(times[i]);
        v_out.push(values[i]);
    }
    *times = t_out;
    *values = v_out;
}

/// Render a self-contained interactive HTML report (Chart.js).
pub fn render_html(
    recording: &mut Recording,
    diagnostics: &Diagnostics,
    waveforms: &[WaveformSeries],
    options: &ChartOptions,
) -> Result<String> {
    let header = recording.header();
    let payload = ChartPayload {
        title: format!(
            "MED64 — {}",
            recording.path().file_name().unwrap_or_default().to_string_lossy()
        ),
        source: recording.path().display().to_string(),
        header: PayloadHeader {
            sample_rate_hz: header.sampling_frequency_hz,
            interval_ms: header.interval_ms(),
            block_index: options.block_index,
            window_ms: options.duration_ms,
        },
        diagnostics: PayloadDiagnostics {
            warnings: diagnostics.warnings.clone(),
            blocks_scanned: diagnostics.blocks.len(),
        },
        waveforms: waveforms.to_vec(),
        channel_rms: diagnostics
            .channels
            .iter()
            .map(|ch| PayloadRms {
                channel: ch.channel,
                rms_mv: ch.rms_mv,
                peak_to_peak_mv: ch.peak_to_peak_mv,
            })
            .collect(),
    };

    let json = serde_json::to_string(&payload).map_err(|err| Med64Error::InvalidWrite {
        message: format!("failed to encode chart JSON: {err}"),
    })?;

    Ok(format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>{title}</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
  <style>
    :root {{ font-family: system-ui, sans-serif; color: #1a1a1a; background: #fafafa; }}
    body {{ margin: 0; padding: 1.5rem; max-width: 1400px; margin-inline: auto; }}
    h1 {{ font-size: 1.4rem; margin-bottom: 0.25rem; }}
    .meta {{ color: #555; font-size: 0.9rem; margin-bottom: 1rem; }}
    .grid {{ display: grid; gap: 1rem; grid-template-columns: 1fr; }}
    @media (min-width: 960px) {{ .grid {{ grid-template-columns: 2fr 1fr; }} }}
    .card {{ background: #fff; border: 1px solid #ddd; border-radius: 8px; padding: 1rem; box-shadow: 0 1px 3px rgba(0,0,0,.06); }}
    .card h2 {{ font-size: 1rem; margin: 0 0 0.75rem; }}
    canvas {{ max-height: 420px; }}
    table {{ width: 100%; border-collapse: collapse; font-size: 0.85rem; }}
    th, td {{ text-align: right; padding: 0.35rem 0.5rem; border-bottom: 1px solid #eee; }}
    th:first-child, td:first-child {{ text-align: left; }}
    .warn {{ color: #b45309; font-size: 0.85rem; }}
    ul {{ margin: 0; padding-left: 1.2rem; }}
  </style>
</head>
<body>
  <h1 id="title"></h1>
  <div class="meta" id="meta"></div>
  <div class="grid">
    <div class="card">
      <h2>Waveforms (mV)</h2>
      <canvas id="waveChart"></canvas>
    </div>
    <div class="card">
      <h2>Channel activity</h2>
      <canvas id="rmsChart"></canvas>
    </div>
  </div>
  <div class="card" style="margin-top:1rem">
    <h2>Diagnostics</h2>
    <div id="warn"></div>
    <table>
      <thead><tr><th>Ch</th><th>RMS mV</th><th>Peak-peak mV</th></tr></thead>
      <tbody id="stats"></tbody>
    </table>
  </div>
  <script>
    const DATA = {json};
    document.getElementById('title').textContent = DATA.title;
    document.getElementById('meta').textContent =
      `${{DATA.source}} · ${{DATA.header.sample_rate_hz}} Hz · block ${{DATA.header.block_index}} · ${{DATA.header.window_ms}} ms window`;

    const colors = ['#2563eb','#dc2626','#16a34a','#ca8a04','#9333ea','#0891b2','#ea580c','#4b5563'];
    const waveCtx = document.getElementById('waveChart');
    new Chart(waveCtx, {{
      type: 'line',
      data: {{
        datasets: DATA.waveforms.map((s, i) => ({{
          label: s.label,
          data: s.times_ms.map((t, j) => ({{ x: t, y: s.millivolts[j] }})),
          borderColor: colors[i % colors.length],
          borderWidth: 1,
          pointRadius: 0,
          tension: 0.1,
        }})),
      }},
      options: {{
        responsive: true,
        interaction: {{ mode: 'index', intersect: false }},
        scales: {{
          x: {{ type: 'linear', title: {{ display: true, text: 'Time (ms)' }} }},
          y: {{ title: {{ display: true, text: 'mV' }} }},
        }},
        plugins: {{ legend: {{ position: 'bottom' }} }},
      }},
    }});

    const rmsCtx = document.getElementById('rmsChart');
    new Chart(rmsCtx, {{
      type: 'bar',
      data: {{
        labels: DATA.channel_rms.map(r => 'Ch ' + r.channel),
        datasets: [{{
          label: 'RMS (mV)',
          data: DATA.channel_rms.map(r => r.rms_mv),
          backgroundColor: '#2563eb88',
        }}],
      }},
      options: {{
        responsive: true,
        scales: {{ y: {{ beginAtZero: true, title: {{ display: true, text: 'mV' }} }} }},
      }},
    }});

    const stats = document.getElementById('stats');
    DATA.channel_rms.forEach(r => {{
      const tr = document.createElement('tr');
      tr.innerHTML = `<td>Ch ${{r.channel}}</td><td>${{r.rms_mv.toFixed(4)}}</td><td>${{r.peak_to_peak_mv.toFixed(4)}}</td>`;
      stats.appendChild(tr);
    }});

    const warn = document.getElementById('warn');
    if (DATA.diagnostics.warnings.length) {{
      warn.innerHTML = '<ul class="warn">' + DATA.diagnostics.warnings.map(w => `<li>${{w}}</li>`).join('') + '</ul>';
    }}
  </script>
</body>
</html>"#,
        title = payload.title,
        json = json,
    ))
}

/// Analyze, chart, and write HTML report to disk.
pub fn write_html_report(
    path: impl AsRef<Path>,
    output: impl AsRef<Path>,
    options: &ChartOptions,
) -> Result<(Diagnostics, PathBuf)> {
    let path = path.as_ref();
    let output = output.as_ref().to_path_buf();

    let mut rec = Recording::open(path)?;
    if let Some(ch) = &options.channels {
        rec = rec.with_channels(ch);
    }

    let diag_opts = DiagnosticOptions {
        max_blocks: options.diagnostic_blocks,
        channels: options.channels.clone(),
    };
    let diagnostics = analyze(&mut rec, &diag_opts)?;

    let header = rec.header().clone();
    let waveforms = extract_waveforms(&mut rec, &header, options)?;
    let html = render_html(&mut rec, &diagnostics, &waveforms, options)?;

    fs::write(&output, html)
        .map_err(|source| Med64Error::WriteIo { path: output.clone(), source })?;
    Ok((diagnostics, output))
}

/// Convenience: diagnostics + HTML in one call.
pub fn chart_file(
    path: impl AsRef<Path>,
    output: impl AsRef<Path>,
    options: &ChartOptions,
) -> Result<(Diagnostics, PathBuf)> {
    write_html_report(path, output, options)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn renders_html_for_sample() {
        let out = std::env::temp_dir().join(format!("med64-chart-{}.html", std::process::id()));
        let (_diag, path) = chart_file(
            &crate::fixture_paths::sample_data1(),
            &out,
            &ChartOptions::default().channels(&[0, 1, 2]).duration_ms(100.0),
        )
        .unwrap();
        let html = fs::read_to_string(&path).unwrap();
        assert!(html.contains("waveChart"));
        assert!(html.contains("chart.js"));
        let _ = fs::remove_file(path);
    }
}