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 crate::block::Med64DataBlock;
use crate::error::Result;
use crate::header::Med64Header;
use crate::reader::Med64Reader;

/// A single multichannel sample exposed for streaming/export.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Sample {
    pub block_index: usize,
    pub point_index: usize,
    pub channel: usize,
    pub time_ms: f64,
    pub counts: i16,
    pub millivolts: f64,
}

/// A batch of samples produced by chunked pipeline iteration.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct SampleBatch {
    pub samples: Vec<Sample>,
}

impl SampleBatch {
    pub fn len(&self) -> usize {
        self.samples.len()
    }

    pub fn is_empty(&self) -> bool {
        self.samples.is_empty()
    }
}

/// Lazy iterator over data blocks.
pub struct BlockStream<'a> {
    pub(crate) reader: &'a mut Med64Reader,
    pub(crate) header: &'a Med64Header,
    pub(crate) channels: Option<&'a [usize]>,
    pub(crate) next_index: usize,
    pub(crate) total: usize,
}

impl BlockStream<'_> {
    pub fn len(&self) -> usize {
        self.total.saturating_sub(self.next_index)
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl Iterator for BlockStream<'_> {
    type Item = Result<Med64DataBlock>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.next_index >= self.total {
            return None;
        }
        let index = self.next_index;
        self.next_index += 1;
        Some(self.reader.next_block(self.header, self.channels).and_then(|block| {
            block.ok_or_else(|| crate::error::Med64Error::InvalidBlock {
                path: self.header.path.clone(),
                block_index: index,
                message: "unexpected EOF".into(),
            })
        }))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let rem = self.len();
        (rem, Some(rem))
    }
}

/// Flat iterator over all samples in block order.
pub struct SampleStream<'a> {
    blocks: BlockStream<'a>,
    header: Med64Header,
    current_block: Option<Med64DataBlock>,
    block_index: usize,
    point_index: usize,
    channel_col: usize,
}

impl<'a> SampleStream<'a> {
    pub(crate) fn new(blocks: BlockStream<'a>, header: Med64Header) -> Self {
        Self { blocks, header, current_block: None, block_index: 0, point_index: 0, channel_col: 0 }
    }
}

impl Iterator for SampleStream<'_> {
    type Item = Result<Sample>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if self.current_block.is_none() {
                match self.blocks.next()? {
                    Ok(block) => {
                        self.current_block = Some(block);
                        self.point_index = 0;
                        self.channel_col = 0;
                    }
                    Err(err) => return Some(Err(err)),
                }
            }

            let block = self.current_block.as_ref().expect("block loaded");
            if self.point_index >= block.samples.len() {
                self.current_block = None;
                self.block_index += 1;
                continue;
            }

            if self.channel_col >= block.channel_indices.len() {
                self.channel_col = 0;
                self.point_index += 1;
                continue;
            }

            let channel = block.channel_indices[self.channel_col];
            let counts = block.samples[self.point_index][self.channel_col];
            let interval = self.header.interval_ms();
            let time_ms =
                block.block_offset_ms + block.trace_offset_ms + self.point_index as f64 * interval;
            let sample = Sample {
                block_index: self.block_index,
                point_index: self.point_index,
                channel,
                time_ms,
                counts,
                millivolts: self.header.counts_to_millivolts(counts),
            };
            self.channel_col += 1;
            return Some(Ok(sample));
        }
    }
}

/// Collect samples into fixed-size batches (useful for ML / IPC / vectorized ops).
pub struct SampleChunks<'a> {
    inner: SampleStream<'a>,
    chunk_size: usize,
    buffer: SampleBatch,
}

impl<'a> SampleChunks<'a> {
    pub fn new(inner: SampleStream<'a>, chunk_size: usize) -> Self {
        Self { inner, chunk_size: chunk_size.max(1), buffer: SampleBatch::default() }
    }
}

impl Iterator for SampleChunks<'_> {
    type Item = Result<SampleBatch>;

    fn next(&mut self) -> Option<Self::Item> {
        self.buffer.samples.clear();
        while self.buffer.samples.len() < self.chunk_size {
            match self.inner.next()? {
                Ok(sample) => self.buffer.samples.push(sample),
                Err(err) => return Some(Err(err)),
            }
        }
        Some(Ok(self.buffer.clone()))
    }
}

/// Iterator adapter that maps each block through a fallible function.
#[allow(dead_code)]
pub struct MapBlocks<'a, F> {
    inner: BlockStream<'a>,
    f: F,
}

impl<'a, F, T> MapBlocks<'a, F>
where
    F: FnMut(Med64DataBlock) -> Result<T>,
{
    #[allow(dead_code)]
    pub fn new(inner: BlockStream<'a>, f: F) -> Self {
        Self { inner, f }
    }
}

impl<F, T> Iterator for MapBlocks<'_, F>
where
    F: FnMut(Med64DataBlock) -> Result<T>,
{
    type Item = Result<T>;

    fn next(&mut self) -> Option<Self::Item> {
        Some(self.inner.next()?.and_then(&mut self.f))
    }
}

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

    #[test]
    fn sample_stream_count_matches_block_grid() {
        let path = &crate::fixture_paths::sample_data1();
        let mut rec = Recording::open(path).unwrap();
        let header = rec.header().clone();
        let n_blocks = header.number_of_real_data_blocks as usize;
        let n_pts = header.num_data_points_per_block() as usize;
        let n_ch = header.num_active_channels();
        let count = rec.samples().filter_map(Result::ok).count();
        assert_eq!(count, n_blocks * n_pts * n_ch);
    }
}