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
//! Generate small 384-channel well-plate `.modat` / `.modax` fixtures.

use std::path::Path;

use crate::block::Med64DataBlock;
use crate::error::Result;
use crate::formats::{write_modax_wrapper_with_meta, ModaxWrapperMeta};
use crate::header::{HeaderBuilder, Med64Header};
use crate::writer::ModatWriter;

/// Options for [`write_synthetic_well384`] / [`write_synthetic_well384_modax`].
#[derive(Debug, Clone)]
pub struct SyntheticWell384Options {
    /// Logical channel indices marked active in the 384-byte extended map.
    pub active_channels: Vec<usize>,
    /// Number of data blocks written (one trace when `blocks_per_trace` equals this).
    pub num_blocks: u32,
    /// Samples per block (derived from `trace_duration_ms` / `blocks_per_trace` at 20 kHz).
    pub points_per_block: u32,
}

impl Default for SyntheticWell384Options {
    fn default() -> Self {
        // Spread 24 electrodes across the 384-well map (every 16th slot).
        let active_channels = (0..384).step_by(16).collect();
        Self { active_channels, num_blocks: 2, points_per_block: 500 }
    }
}

/// Write a minimal PRESTO-format `.modat` with synthetic spike-like waveforms.
pub fn write_synthetic_well384(
    path: impl AsRef<Path>,
    options: &SyntheticWell384Options,
) -> Result<()> {
    let path = path.as_ref();
    let header = build_presto_header(path, options);
    let mut writer = ModatWriter::create(path, header.clone())?;

    for block_idx in 0..options.num_blocks {
        let block = synthetic_block(&header, options, block_idx);
        writer.write_block(&block)?;
    }
    writer.finish()?;
    Ok(())
}

/// Write a 384-ch `.modax` fixture: synthetic `.modat` payload + XML preamble.
///
/// The binary body matches [`write_synthetic_well384`]; the XML wrapper uses
/// [`ModaxWrapperMeta::presto384`] plus sampling / active-channel tags.
pub fn write_synthetic_well384_modax(
    path: impl AsRef<Path>,
    options: &SyntheticWell384Options,
) -> Result<()> {
    let path = path.as_ref();
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("synthetic_well384");
    let modat_path = parent.join(format!(".{stem}.modat.tmp"));
    write_synthetic_well384(&modat_path, options)?;
    let result = write_modax_wrapper_with_meta(
        &modat_path,
        path,
        512,
        ModaxWrapperMeta::presto384_with_channels(&options.active_channels, 20_000.0),
    );
    let _ = std::fs::remove_file(&modat_path);
    result
}

fn build_presto_header(path: &Path, options: &SyntheticWell384Options) -> Med64Header {
    let mut ext = vec![0u8; 384];
    for &ch in &options.active_channels {
        if ch < ext.len() {
            ext[ch] = 1;
        }
    }

    let blocks_per_trace = options.num_blocks.max(1);
    let trace_duration_ms =
        options.points_per_block as f64 * blocks_per_trace as f64 * 1000.0 / 20_000.0;

    let mut header = HeaderBuilder::new()
        .path(path)
        .number_of_traces(1)
        .blocks_per_trace(blocks_per_trace)
        .sampling_frequency_hz(20_000.0)
        .trace_duration_ms(trace_duration_ms)
        .build();

    header.data_format_version = 6;
    header.active_channels = [0u8; 64];
    header.extended_active_channels = Some(ext);
    header.number_of_real_data_blocks = options.num_blocks;
    header
}

fn synthetic_block(
    header: &Med64Header,
    options: &SyntheticWell384Options,
    block_idx: u32,
) -> Med64DataBlock {
    let active = header.active_channel_indices();
    let n_points = options.points_per_block as usize;
    let mut samples = vec![vec![0i16; active.len()]; n_points];

    // Positive spikes on the first active channel, negative on the fifth (if present).
    if let Some(&ch0) = active.first() {
        if let Some(col) = active.iter().position(|&ch| ch == ch0) {
            inject_spike_train(&mut samples, col, &[100, 300], SYNTH_SPIKE_AMPLITUDE);
        }
    }
    if active.len() > 4 {
        let ch_neg = active[4];
        if let Some(col) = active.iter().position(|&ch| ch == ch_neg) {
            inject_spike_train(&mut samples, col, &[200, 400], SYNTH_NEG_SPIKE_AMPLITUDE);
        }
    }

    let payload_len = n_points as u32 * active.len() as u32 * 2;
    let block_offset_ms = block_idx as f64 * header.ms_per_block() as f64;

    Med64DataBlock {
        trace_number: 0,
        block_number: block_idx,
        trace_offset_ms: 0.0,
        block_offset_ms,
        number_of_data_points: options.points_per_block,
        first_block: u8::from(block_idx == 0),
        last_block: u8::from(block_idx + 1 == options.num_blocks),
        stimulation_loop_number: 0,
        stimulation_step_number: 0,
        size_of_data_block: payload_len,
        channel_indices: active.clone(),
        samples,
    }
}

fn inject_spike_train(samples: &mut [Vec<i16>], col: usize, peaks: &[usize], amplitude: i16) {
    for &peak in peaks {
        if peak >= samples.len() {
            continue;
        }
        for (offset, scale) in [(-2, 0.25), (-1, 0.6), (0, 1.0), (1, 0.6), (2, 0.25)] {
            let idx = peak as isize + offset;
            if idx >= 0 && (idx as usize) < samples.len() {
                let value = (f64::from(amplitude) * scale).round() as i16;
                samples[idx as usize][col] = samples[idx as usize][col].saturating_add(value);
            }
        }
    }
}

/// Peak ADC counts for synthetic spikes (~1.5 mV after conversion).
const SYNTH_SPIKE_AMPLITUDE: i16 = 10_000;
const SYNTH_NEG_SPIKE_AMPLITUDE: i16 = -9_000;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::{analysis_channels, detect_layout, RecordingLayout};
    use crate::reader::Med64Reader;

    use crate::analysis::{run_analysis, AnalysisOptions, ThresholdMethod};

    #[test]
    fn synthetic_presto384_detects_spikes() {
        let dir = std::env::temp_dir().join(format!("med64-presto-detect-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("detect.modat");
        write_synthetic_well384(&path, &SyntheticWell384Options::default()).unwrap();

        let report = run_analysis(
            &path,
            &AnalysisOptions {
                max_blocks: Some(2),
                highpass_hz: Some(100.0),
                lowpass_hz: Some(2_000.0),
                threshold_method: ThresholdMethod::Fixed,
                plus_thresholds_mv: Some(vec![0.5; 384]),
                minus_thresholds_mv: Some(vec![-0.5; 384]),
                ..Default::default()
            },
        )
        .unwrap();
        assert!(!report.spikes.is_empty(), "synthetic PRESTO should yield detectable spikes");

        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn round_trip_synthetic_presto384() {
        let dir = std::env::temp_dir().join(format!("med64-presto-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("synthetic_presto384.modat");

        write_synthetic_well384(&path, &SyntheticWell384Options::default()).unwrap();

        let mut reader = Med64Reader::open(&path).unwrap();
        let header = reader.read_header().unwrap();
        assert_eq!(header.data_format_version, 6);
        assert_eq!(header.num_channel_slots(), 384);
        assert_eq!(header.num_active_channels(), 24);
        assert_eq!(detect_layout(&header, &path), RecordingLayout::Presto384);
        assert_eq!(analysis_channels(RecordingLayout::Presto384, &header).len(), 24);

        let block0 = reader.next_block(&header, None).unwrap().unwrap();
        assert_eq!(block0.number_of_data_points, 500);
        assert_eq!(block0.samples[0].len(), 24);
        assert_ne!(block0.samples[100][0], 0, "expected synthetic spike on channel 0");

        let block1 = reader.next_block(&header, None).unwrap().unwrap();
        assert_eq!(block1.block_number, 1);
        assert!(reader.next_block(&header, None).unwrap().is_none());

        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn synthetic_well384_modax_opens_and_analyzes() {
        let dir = std::env::temp_dir().join(format!("med64-modax-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("synthetic_well384.modax");
        write_synthetic_well384_modax(&path, &SyntheticWell384Options::default()).unwrap();

        let raw = std::fs::read(&path).unwrap();
        let head = String::from_utf8_lossy(&raw[..raw.len().min(512)]);
        assert!(head.contains("NumberChannels>384"));
        assert!(head.contains("SamplingFrequency"));
        assert!(head.contains("ActiveChannels"));

        let rec = crate::formats::open_recording_any(&path).unwrap();
        assert_eq!(rec.header().num_channel_slots(), 384);
        assert_eq!(detect_layout(rec.header(), &path), RecordingLayout::Presto384);

        let mut last_blocks = 0usize;
        let report = crate::analysis::run_analysis_with_progress(
            &path,
            &AnalysisOptions {
                max_blocks: Some(2),
                highpass_hz: Some(100.0),
                lowpass_hz: Some(2_000.0),
                threshold_method: ThresholdMethod::Fixed,
                plus_thresholds_mv: Some(vec![0.5; 384]),
                minus_thresholds_mv: Some(vec![-0.5; 384]),
                ..Default::default()
            },
            |p| {
                if p.stage == crate::analysis::AnalysisStage::ReadingBlocks {
                    last_blocks = p.blocks_done;
                }
            },
        )
        .unwrap();
        assert!(last_blocks >= 1);
        assert!(!report.spikes.is_empty());
        let _ = std::fs::remove_dir_all(dir);
    }
}