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
//! Electrode layout profiles and extended-format readers (PRESTO 384-ch, Basic4x4, QuadII).

use std::fs::File;
use std::io::Read;
use std::path::Path;

use crate::error::{Med64Error, Result};
use crate::header::{Med64Header, FILE_HEADER_BYTES, NUM_CHANNELS};

/// Hardware / software layout profile for channel mapping and export.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RecordingLayout {
    /// Standard 64-channel MED64 `.modat`.
    Med64Standard,
    /// PRESTO high-density plate (384 channels).
    Presto384,
    /// Basic4x4 16-electrode array mapped into 64-channel space.
    Basic4x4,
    /// QuadII / Allegro 4-well layout.
    QuadII,
}

impl RecordingLayout {
    pub fn num_channels(self) -> usize {
        match self {
            Self::Med64Standard | Self::Basic4x4 | Self::QuadII => NUM_CHANNELS,
            Self::Presto384 => 384,
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            Self::Med64Standard => "MED64 64-ch",
            Self::Presto384 => "PRESTO 384-ch",
            Self::Basic4x4 => "Basic4x4 16-el",
            Self::QuadII => "QuadII 4-well",
        }
    }
}

/// PRESTO-style well plates (`channellist`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WellPlate {
    Wells6,
    Wells24,
    Wells48,
    Wells96,
}

impl WellPlate {
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim() {
            "6" | "6well" => Some(Self::Wells6),
            "24" | "24well" => Some(Self::Wells24),
            "48" | "48well" => Some(Self::Wells48),
            "96" | "96well" => Some(Self::Wells96),
            _ => None,
        }
    }

    pub fn well_count(self) -> usize {
        match self {
            Self::Wells6 => 6,
            Self::Wells24 => 24,
            Self::Wells48 => 48,
            Self::Wells96 => 96,
        }
    }

    /// Electrodes per well on a 384-channel PRESTO plate.
    pub fn electrodes_per_well(self) -> usize {
        384 / self.well_count()
    }

    pub fn plate_cols(self) -> usize {
        match self {
            Self::Wells6 => 3,
            Self::Wells24 => 6,
            Self::Wells48 => 8,
            Self::Wells96 => 12,
        }
    }

    pub fn well_of_channel(self, channel: usize) -> usize {
        channel / self.electrodes_per_well()
    }

    pub fn electrode_in_well(self, channel: usize) -> usize {
        channel % self.electrodes_per_well()
    }

    pub fn label(self, channel: usize) -> String {
        format!("W{:02}E{}", self.well_of_channel(channel) + 1, self.electrode_in_well(channel) + 1)
    }

    /// welltype24-style ID (A1…D6 for 24-well).
    pub fn alpha_well_label(self, well: usize) -> String {
        let cols = self.plate_cols();
        let row = well / cols;
        let col = well % cols;
        let letter = (b'A' + row as u8) as char;
        format!("{letter}{}", col + 1)
    }
}

/// Detect layout from header metadata and optional file magic.
pub fn detect_layout(header: &Med64Header, path: &Path) -> RecordingLayout {
    if header.extended_active_channels.is_some() || header.num_channel_slots() > NUM_CHANNELS {
        return RecordingLayout::Presto384;
    }

    if let Ok(magic) = read_tail_magic(path) {
        if magic.contains("PRESTO") {
            return RecordingLayout::Presto384;
        }
    }

    match header.data_format_version {
        4 => RecordingLayout::Basic4x4,
        5 if header.num_active_channels() > NUM_CHANNELS => RecordingLayout::Presto384,
        5 => RecordingLayout::QuadII,
        6 => RecordingLayout::Presto384,
        _ => RecordingLayout::Med64Standard,
    }
}

fn read_tail_magic(path: &Path) -> Result<String> {
    let mut file =
        File::open(path).map_err(|source| Med64Error::Io { path: path.to_path_buf(), source })?;
    let mut buf = [0u8; 16];
    file.read_exact(&mut buf).ok();
    Ok(String::from_utf8_lossy(&buf).into_owned())
}

/// Map logical channel index to well/electrode label for export.
pub fn channel_label(layout: RecordingLayout, channel: usize) -> String {
    match layout {
        RecordingLayout::Med64Standard => format!("Ch{}", channel + 1),
        RecordingLayout::Presto384 => {
            let well = channel / 4 + 1;
            let elec = channel % 4 + 1;
            format!("W{well:02}E{elec}")
        }
        RecordingLayout::Basic4x4 => {
            if channel < 16 {
                let row = channel / 4 + 1;
                let col = channel % 4 + 1;
                format!("E{row}{col}")
            } else {
                format!("Ch{}", channel + 1)
            }
        }
        RecordingLayout::QuadII => {
            let well = channel / 16 + 1;
            let elec = channel % 16 + 1;
            format!("W{well}E{elec}")
        }
    }
}

/// Channels used for spike/burst analysis given layout profile.
pub fn analysis_channels(layout: RecordingLayout, header: &Med64Header) -> Vec<usize> {
    match layout {
        RecordingLayout::Basic4x4 => header
            .active_channel_indices_for(NUM_CHANNELS)
            .into_iter()
            .filter(|&ch| ch < 16)
            .collect(),
        RecordingLayout::QuadII => header
            .active_channel_indices_for(NUM_CHANNELS)
            .into_iter()
            .filter(|&ch| ch < 64)
            .collect(),
        RecordingLayout::Presto384 => header.active_channel_indices_for(384),
        RecordingLayout::Med64Standard => header.active_channel_indices(),
    }
}

/// Open a recording with layout detection.
pub fn open_with_layout(path: impl AsRef<Path>) -> Result<(Med64Header, RecordingLayout)> {
    let path = path.as_ref();
    let mut file =
        File::open(path).map_err(|source| Med64Error::Io { path: path.to_path_buf(), source })?;
    let header = Med64Header::read_from(path, &mut file)?;
    let layout = detect_layout(&header, path);
    Ok((header, layout))
}

/// PRESTO files may embed a magic token after the standard 123-byte header region.
#[allow(dead_code)]
pub fn is_presto_file(path: &Path) -> bool {
    open_with_layout(path).map(|(_, layout)| layout == RecordingLayout::Presto384).unwrap_or(false)
}

/// Bytes required for active-channel map (standard vs PRESTO).
#[allow(dead_code)]
pub fn active_channel_map_bytes(layout: RecordingLayout) -> usize {
    layout.num_channels()
}

/// Extended header size hint for non-standard layouts (from `Med64FileReader`).
#[allow(dead_code)]
pub fn extended_header_bytes(layout: RecordingLayout) -> usize {
    match layout {
        RecordingLayout::Presto384 => FILE_HEADER_BYTES + 384,
        _ => FILE_HEADER_BYTES,
    }
}

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

    #[test]
    fn standard_layout_for_sample_data1() {
        let rec = Recording::open(crate::fixture_paths::sample_data1()).unwrap();
        let layout = detect_layout(rec.header(), rec.path());
        assert_eq!(layout, RecordingLayout::Med64Standard);
    }

    #[test]
    fn presto_labels() {
        assert_eq!(channel_label(RecordingLayout::Presto384, 0), "W01E1");
        assert_eq!(channel_label(RecordingLayout::Presto384, 5), "W02E2");
    }
}