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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use std::io::{Read, Write};
use std::path::{Path, PathBuf};

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};

use crate::error::{Med64Error, Result};

/// Fixed-size file header for standard MED64 `.modat` recordings.
pub const FILE_HEADER_BYTES: usize = 123;
pub const NUM_CHANNELS: usize = 64;

/// Metadata parsed from the first 123 bytes of a `.modat` file.
///
/// Layout matches `jp.med64.med64spikeanalysis.utils.Med64FileReader` (little-endian).
#[derive(Debug, Clone, PartialEq)]
pub struct Med64Header {
    pub path: PathBuf,
    pub number_of_traces: u32,
    pub blocks_per_trace: u32,
    pub data_format_version: u8,
    pub sampling_frequency_hz: f64,
    pub trace_duration_ms: f64,
    pub daq_voltage_range: f64,
    pub conversion_factor: f64,
    pub active_channels: [u8; NUM_CHANNELS],
    pub start_year: i16,
    pub start_month: u8,
    pub start_day: u8,
    /// Milliseconds since local midnight for recording start.
    pub start_time_ms: u32,
    pub start_timezone_minutes: i16,
    pub number_of_real_data_blocks: u32,
    pub real_trace_duration_ms: f64,
    /// PRESTO / extended formats: optional 384-byte active-channel map after standard header.
    pub extended_active_channels: Option<Vec<u8>>,
}

impl Med64Header {
    pub(crate) fn read_from<R: std::io::Read>(path: &Path, reader: &mut R) -> Result<Self> {
        let mut buf = [0u8; FILE_HEADER_BYTES];
        reader
            .read_exact(&mut buf)
            .map_err(|source| Med64Error::Io { path: path.to_path_buf(), source })?;

        let mut cursor = std::io::Cursor::new(buf);

        let number_of_traces =
            cursor.read_u32::<LittleEndian>().map_err(|_| Med64Error::InvalidHeader {
                path: path.to_path_buf(),
                message: "failed to read number_of_traces".into(),
            })?;
        let blocks_per_trace =
            cursor.read_u32::<LittleEndian>().map_err(|_| Med64Error::InvalidHeader {
                path: path.to_path_buf(),
                message: "failed to read blocks_per_trace".into(),
            })?;
        let data_format_version = cursor.read_u8().map_err(|_| Med64Error::InvalidHeader {
            path: path.to_path_buf(),
            message: "failed to read data_format_version".into(),
        })?;
        let sampling_frequency_hz =
            cursor.read_f64::<LittleEndian>().map_err(|_| Med64Error::InvalidHeader {
                path: path.to_path_buf(),
                message: "failed to read sampling_frequency".into(),
            })?;
        let trace_duration_ms =
            cursor.read_f64::<LittleEndian>().map_err(|_| Med64Error::InvalidHeader {
                path: path.to_path_buf(),
                message: "failed to read trace_duration".into(),
            })?;
        let daq_voltage_range =
            cursor.read_f64::<LittleEndian>().map_err(|_| Med64Error::InvalidHeader {
                path: path.to_path_buf(),
                message: "failed to read daq_voltage_range".into(),
            })?;
        let conversion_factor =
            cursor.read_f64::<LittleEndian>().map_err(|_| Med64Error::InvalidHeader {
                path: path.to_path_buf(),
                message: "failed to read conversion_factor".into(),
            })?;

        let mut active_channels = [0u8; NUM_CHANNELS];
        cursor
            .read_exact(&mut active_channels)
            .map_err(|source| Med64Error::Io { path: path.to_path_buf(), source })?;

        let start_year =
            cursor.read_i16::<LittleEndian>().map_err(|_| Med64Error::InvalidHeader {
                path: path.to_path_buf(),
                message: "failed to read start_year".into(),
            })?;
        let start_month = cursor.read_u8().map_err(|_| Med64Error::InvalidHeader {
            path: path.to_path_buf(),
            message: "failed to read start_month".into(),
        })?;
        let start_day = cursor.read_u8().map_err(|_| Med64Error::InvalidHeader {
            path: path.to_path_buf(),
            message: "failed to read start_day".into(),
        })?;
        let start_time_ms =
            cursor.read_u32::<LittleEndian>().map_err(|_| Med64Error::InvalidHeader {
                path: path.to_path_buf(),
                message: "failed to read start_time_ms".into(),
            })?;
        let start_timezone_minutes =
            cursor.read_i16::<LittleEndian>().map_err(|_| Med64Error::InvalidHeader {
                path: path.to_path_buf(),
                message: "failed to read start_timezone".into(),
            })?;

        // Reserved / undocumented trailing field in the official reader.
        let _reserved = cursor.read_i64::<LittleEndian>().ok();

        let mut extended_active_channels = None;
        if data_format_version == 6 {
            let mut extra = vec![0u8; 384];
            if reader.read_exact(&mut extra).is_ok() {
                extended_active_channels = Some(extra);
            }
        }

        Ok(Self {
            path: path.to_path_buf(),
            number_of_traces,
            blocks_per_trace,
            data_format_version,
            sampling_frequency_hz,
            trace_duration_ms,
            daq_voltage_range,
            conversion_factor,
            active_channels,
            start_year,
            start_month,
            start_day,
            start_time_ms,
            start_timezone_minutes,
            number_of_real_data_blocks: 0,
            real_trace_duration_ms: 0.0,
            extended_active_channels,
        })
    }

    /// Duration of one data block in milliseconds.
    pub fn ms_per_block(&self) -> u32 {
        (self.trace_duration_ms / self.blocks_per_trace as f64).round() as u32
    }

    /// Sample count per channel in each data block.
    pub fn num_data_points_per_block(&self) -> u32 {
        let ms = self.ms_per_block() as f64;
        (ms * self.sampling_frequency_hz / 1000.0).round() as u32
    }

    /// Sample interval in milliseconds (1 / sampling rate, converted to ms).
    pub fn interval_ms(&self) -> f64 {
        1000.0 / self.sampling_frequency_hz
    }

    /// Number of logical channel slots for this file (64 standard, 384 PRESTO).
    pub fn num_channel_slots(&self) -> usize {
        if self.extended_active_channels.is_some() {
            384
        } else {
            NUM_CHANNELS
        }
    }

    pub(crate) fn header_bytes_on_disk(&self) -> u64 {
        let mut bytes = FILE_HEADER_BYTES as u64;
        if self.extended_active_channels.is_some() || self.data_format_version == 6 {
            bytes += 384;
        }
        bytes
    }

    /// Zero-based indices of channels marked active in the file header.
    pub fn active_channel_indices(&self) -> Vec<usize> {
        self.active_channel_indices_for(self.num_channel_slots())
    }

    /// Active channel indices up to `max_channels` using standard and extended maps.
    pub fn active_channel_indices_for(&self, max_channels: usize) -> Vec<usize> {
        if let Some(ref ext) = self.extended_active_channels {
            return ext
                .iter()
                .enumerate()
                .filter_map(|(idx, &flag)| (flag == 1 && idx < max_channels).then_some(idx))
                .collect();
        }
        self.active_channels
            .iter()
            .enumerate()
            .filter_map(|(idx, &flag)| (flag == 1 && idx < max_channels).then_some(idx))
            .collect()
    }

    pub fn num_active_channels(&self) -> usize {
        self.active_channel_indices().len()
    }

    /// Convert raw ADC counts to millivolts using the file conversion factor.
    pub fn counts_to_millivolts(&self, counts: i16) -> f64 {
        f64::from(counts) * self.conversion_factor
    }

    pub fn millivolts_to_counts(&self, mv: f64) -> i16 {
        if self.conversion_factor == 0.0 {
            return 0;
        }
        let v = (mv / self.conversion_factor).round();
        v.clamp(i16::MIN as f64, i16::MAX as f64) as i16
    }

    pub fn start_hour(&self) -> u32 {
        self.start_time_ms / 3_600_000
    }

    pub fn start_minute(&self) -> u32 {
        (self.start_time_ms % 3_600_000) / 60_000
    }

    pub fn start_second(&self) -> u32 {
        (self.start_time_ms % 60_000) / 1_000
    }

    pub fn start_millisecond(&self) -> u32 {
        self.start_time_ms % 1_000
    }

    /// Number of logical traces present in the file (ceil of blocks / blocks_per_trace).
    pub fn real_num_of_traces(&self) -> u32 {
        if self.blocks_per_trace == 0 {
            return 0;
        }
        (self.number_of_real_data_blocks as f64 / self.blocks_per_trace as f64).ceil() as u32
    }

    /// Recording start as Unix epoch milliseconds (matches official Calendar-based reader).
    pub fn start_date_time(&self) -> i64 {
        use chrono::{Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone};

        let date = NaiveDate::from_ymd_opt(
            self.start_year as i32,
            u32::from(self.start_month),
            u32::from(self.start_day),
        )
        .expect("invalid start date in header");
        let time = NaiveTime::from_hms_milli_opt(
            self.start_hour(),
            self.start_minute(),
            self.start_second(),
            self.start_millisecond(),
        )
        .expect("invalid start time in header");
        let naive = NaiveDateTime::new(date, time);
        Local
            .from_local_datetime(&naive)
            .single()
            .expect("ambiguous or invalid local datetime")
            .timestamp_millis()
    }

    /// Blocks spanning a duration in milliseconds.
    pub fn blocks_of_duration(&self, duration_ms: f64) -> u32 {
        let ms_per_block = self.ms_per_block() as f64;
        if ms_per_block <= 0.0 {
            return 0;
        }
        (duration_ms / ms_per_block).ceil() as u32
    }

    pub(crate) fn finalize_block_counts(&mut self, file_size: u64, block_size: u64) {
        if block_size == 0 {
            self.number_of_real_data_blocks = 0;
            self.real_trace_duration_ms = 0.0;
            return;
        }

        let payload_bytes = file_size.saturating_sub(self.header_bytes_on_disk());
        self.number_of_real_data_blocks = (payload_bytes / block_size) as u32;
        self.real_trace_duration_ms =
            self.ms_per_block() as f64 * self.number_of_real_data_blocks as f64;
    }

    /// Write the 123-byte file header in MED64 little-endian layout.
    pub fn write_to<W: Write>(&self, writer: &mut W) -> Result<()> {
        writer
            .write_u32::<LittleEndian>(self.number_of_traces)
            .and_then(|_| writer.write_u32::<LittleEndian>(self.blocks_per_trace))
            .and_then(|_| writer.write_u8(self.data_format_version))
            .and_then(|_| writer.write_f64::<LittleEndian>(self.sampling_frequency_hz))
            .and_then(|_| writer.write_f64::<LittleEndian>(self.trace_duration_ms))
            .and_then(|_| writer.write_f64::<LittleEndian>(self.daq_voltage_range))
            .and_then(|_| writer.write_f64::<LittleEndian>(self.conversion_factor))
            .and_then(|_| writer.write_all(&self.active_channels))
            .and_then(|_| writer.write_i16::<LittleEndian>(self.start_year))
            .and_then(|_| writer.write_u8(self.start_month))
            .and_then(|_| writer.write_u8(self.start_day))
            .and_then(|_| writer.write_u32::<LittleEndian>(self.start_time_ms))
            .and_then(|_| writer.write_i16::<LittleEndian>(self.start_timezone_minutes))
            .and_then(|_| writer.write_i64::<LittleEndian>(0))
            .map_err(|source| Med64Error::WriteIo { path: self.path.clone(), source })?;
        if let Some(ref ext) = self.extended_active_channels {
            writer
                .write_all(ext)
                .map_err(|source| Med64Error::WriteIo { path: self.path.clone(), source })?;
        } else if self.data_format_version == 6 {
            writer
                .write_all(&[0u8; 384])
                .map_err(|source| Med64Error::WriteIo { path: self.path.clone(), source })?;
        }
        Ok(())
    }
}

/// Builder for constructing a new `.modat` file header.
#[derive(Debug, Clone)]
pub struct HeaderBuilder {
    inner: Med64Header,
}

impl HeaderBuilder {
    pub fn new() -> Self {
        let mut active = [0u8; NUM_CHANNELS];
        active.fill(1);
        Self {
            inner: Med64Header {
                path: PathBuf::new(),
                number_of_traces: 1,
                blocks_per_trace: 1,
                data_format_version: 1,
                sampling_frequency_hz: 20_000.0,
                trace_duration_ms: 100.0,
                daq_voltage_range: 50.0,
                conversion_factor: 0.000_152_592_547_379_985_96,
                active_channels: active,
                start_year: 2012,
                start_month: 1,
                start_day: 1,
                start_time_ms: 0,
                start_timezone_minutes: 0,
                number_of_real_data_blocks: 0,
                real_trace_duration_ms: 0.0,
                extended_active_channels: None,
            },
        }
    }

    pub fn path(mut self, path: impl AsRef<Path>) -> Self {
        self.inner.path = path.as_ref().to_path_buf();
        self
    }

    pub fn number_of_traces(mut self, value: u32) -> Self {
        self.inner.number_of_traces = value;
        self
    }

    pub fn blocks_per_trace(mut self, value: u32) -> Self {
        self.inner.blocks_per_trace = value;
        self
    }

    pub fn sampling_frequency_hz(mut self, value: f64) -> Self {
        self.inner.sampling_frequency_hz = value;
        self
    }

    pub fn trace_duration_ms(mut self, value: f64) -> Self {
        self.inner.trace_duration_ms = value;
        self
    }

    pub fn conversion_factor(mut self, value: f64) -> Self {
        self.inner.conversion_factor = value;
        self
    }

    pub fn active_channels(mut self, channels: &[usize]) -> Self {
        self.inner.active_channels = [0u8; NUM_CHANNELS];
        for &ch in channels {
            if ch < NUM_CHANNELS {
                self.inner.active_channels[ch] = 1;
            }
        }
        self
    }

    pub fn build(self) -> Med64Header {
        self.inner
    }
}

impl Default for HeaderBuilder {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn parses_sample_data1_header() {
        let bytes = std::fs::read(crate::fixture_paths::sample_data1()).unwrap();
        let mut header =
            Med64Header::read_from(Path::new("sample data1.modat"), &mut Cursor::new(&bytes))
                .unwrap();

        assert_eq!(header.number_of_traces, 140);
        assert_eq!(header.blocks_per_trace, 1);
        assert_eq!(header.sampling_frequency_hz, 20_000.0);
        assert_eq!(header.trace_duration_ms, 100.0);
        assert_eq!(header.num_active_channels(), 64);
        assert_eq!(header.num_data_points_per_block(), 2000);
        assert_eq!(header.start_year, 2012);
        assert_eq!(header.start_month, 7);
        assert_eq!(header.start_day, 4);

        header.finalize_block_counts(bytes.len() as u64, 256_039);
        assert_eq!(header.number_of_real_data_blocks, 140);
    }
}