Skip to main content

lib_jsl_file_io/
matlab4.rs

1//! MATLAB level-4 `.mat` files (SciPy's `io.loadmat` and `io.savemat` with `format='4'`).
2//!
3//! A level-4 file has no file header: it is a sequence of variables, each a 20-byte header of five
4//! 32-bit integers (`MOPT`, rows, columns, a complex flag and the name length), the NUL-terminated
5//! name, and the column-major data (the real part, then the imaginary part when the flag is set).
6//! `MOPT = 1000 M + 100 O + 10 P + T` packs the byte order `M` (0 little-endian IEEE, 1
7//! big-endian IEEE), a reserved digit `O = 0`, the data type `P` (double, single, int32, int16,
8//! uint16 or uint8) and the matrix type `T` (full, text or sparse). A sparse matrix is stored as
9//! an `(nnz + 1) × 3` array of 1-based row, column and value, with the matrix dimensions in its
10//! last row (a fourth column holds the imaginary parts of a complex one).
11//!
12//! Variables are returned as [`MatValue`], the same type the level-5 reader produces. Reading
13//! accepts both IEEE byte orders; VAX and Cray files are refused. Writing produces little-endian
14//! files.
15//!
16//! See the book entry [Scientific data files](https://jwkunz.github.io/lib_jsl/book/foundations/scientific-files.html#matlab-level-4-files).
17
18use crate::matlab::{MatClass, MatValue};
19use lib_jsl_core::ErrorsJSL;
20use std::path::Path;
21
22fn bad(msg: &'static str) -> ErrorsJSL {
23    ErrorsJSL::InvalidInputRange(msg)
24}
25
26/// The version of a MAT-file, as told by its first bytes.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum MatVersion {
30    /// Level 4: no file header.
31    V4,
32    /// Level 5 (also the 7.x files that are not HDF5).
33    V5,
34    /// Version 7.3: an HDF5 file, not supported.
35    V73,
36}
37
38/// Whether `v` is a valid `MOPT` of a level-4 variable header.
39fn valid_mopt(v: i32) -> bool {
40    (0..=5000).contains(&v) && (v / 100) % 10 == 0 && (v / 10) % 10 <= 5 && v % 10 <= 2
41}
42
43/// Tells the version of a MAT-file (SciPy's `get_matfile_version`): a level-5 file starts with a
44/// 128-byte text header ending in a version and an endian indicator; otherwise the first four
45/// bytes are tried as the `MOPT` of a level-4 variable in each byte order.
46pub fn mat_version(bytes: &[u8]) -> Result<MatVersion, ErrorsJSL> {
47    if bytes.len() >= 128 && (&bytes[126..128] == b"IM" || &bytes[126..128] == b"MI") {
48        let version = if &bytes[126..128] == b"IM" { u16::from_le_bytes([bytes[124], bytes[125]]) } else { u16::from_be_bytes([bytes[124], bytes[125]]) };
49        return match version {
50            0x0100 => Ok(MatVersion::V5),
51            0x0200 => Ok(MatVersion::V73),
52            _ => Err(bad("MAT-file: unknown version")),
53        };
54    }
55    if bytes.len() >= 4 {
56        let b = [bytes[0], bytes[1], bytes[2], bytes[3]];
57        if valid_mopt(i32::from_le_bytes(b)) || valid_mopt(i32::from_be_bytes(b)) {
58            return Ok(MatVersion::V4);
59        }
60    }
61    Err(bad("MAT-file: neither a level-4 nor a level-5 file"))
62}
63
64/// The data types of a level-4 variable.
65const P_DOUBLE: i32 = 0;
66const P_SINGLE: i32 = 1;
67const P_INT32: i32 = 2;
68const P_INT16: i32 = 3;
69const P_UINT16: i32 = 4;
70const P_UINT8: i32 = 5;
71
72fn p_size(p: i32) -> usize {
73    match p {
74        P_DOUBLE => 8,
75        P_SINGLE | P_INT32 => 4,
76        P_INT16 | P_UINT16 => 2,
77        _ => 1,
78    }
79}
80
81fn p_class(p: i32) -> MatClass {
82    match p {
83        P_DOUBLE => MatClass::Double,
84        P_SINGLE => MatClass::Single,
85        P_INT32 => MatClass::Int32,
86        P_INT16 => MatClass::Int16,
87        P_UINT16 => MatClass::Uint16,
88        _ => MatClass::Uint8,
89    }
90}
91
92struct Cursor<'a> {
93    b: &'a [u8],
94    pos: usize,
95    big: bool,
96}
97
98impl Cursor<'_> {
99    fn take(&mut self, n: usize) -> Result<&[u8], ErrorsJSL> {
100        let end = self.pos.checked_add(n).filter(|&e| e <= self.b.len()).ok_or_else(|| bad("MAT-file (level 4): truncated variable"))?;
101        let s = &self.b[self.pos..end];
102        self.pos = end;
103        Ok(s)
104    }
105
106    fn int(&mut self) -> Result<i32, ErrorsJSL> {
107        let s: [u8; 4] = self.take(4)?.try_into().expect("4 bytes");
108        Ok(if self.big { i32::from_be_bytes(s) } else { i32::from_le_bytes(s) })
109    }
110
111    /// `count` values of data type `p`, as `f64`.
112    fn values(&mut self, p: i32, count: usize) -> Result<Vec<f64>, ErrorsJSL> {
113        let width = p_size(p);
114        let bytes = count.checked_mul(width).ok_or_else(|| bad("MAT-file (level 4): dimensions overflow"))?;
115        let big = self.big;
116        let raw = self.take(bytes)?;
117        Ok(raw
118            .chunks_exact(width)
119            .map(|c| match p {
120                P_DOUBLE => {
121                    let a: [u8; 8] = c.try_into().expect("8 bytes");
122                    if big { f64::from_be_bytes(a) } else { f64::from_le_bytes(a) }
123                }
124                P_SINGLE => {
125                    let a: [u8; 4] = c.try_into().expect("4 bytes");
126                    (if big { f32::from_be_bytes(a) } else { f32::from_le_bytes(a) }) as f64
127                }
128                P_INT32 => {
129                    let a: [u8; 4] = c.try_into().expect("4 bytes");
130                    (if big { i32::from_be_bytes(a) } else { i32::from_le_bytes(a) }) as f64
131                }
132                P_INT16 => {
133                    let a: [u8; 2] = c.try_into().expect("2 bytes");
134                    (if big { i16::from_be_bytes(a) } else { i16::from_le_bytes(a) }) as f64
135                }
136                P_UINT16 => {
137                    let a: [u8; 2] = c.try_into().expect("2 bytes");
138                    (if big { u16::from_be_bytes(a) } else { u16::from_le_bytes(a) }) as f64
139                }
140                _ => c[0] as f64,
141            })
142            .collect())
143    }
144}
145
146// ANCHOR: loadmat4
147/// Parses a level-4 MAT-file (SciPy's `loadmat`): the variables in file order, as `(name, value)`
148/// pairs. Numeric matrices keep their stored type, text becomes a character array, and a sparse
149/// matrix a compressed-sparse-column [`MatValue::Sparse`].
150pub fn mat4_decode(bytes: &[u8]) -> Result<Vec<(String, MatValue)>, ErrorsJSL> {
151    if bytes.len() < 4 {
152        return Err(bad("MAT-file (level 4): shorter than one header"));
153    }
154    let first: [u8; 4] = bytes[..4].try_into().expect("4 bytes");
155    let big = if valid_mopt(i32::from_le_bytes(first)) {
156        false
157    } else if valid_mopt(i32::from_be_bytes(first)) {
158        true
159    } else {
160        return Err(bad("MAT-file (level 4): the first header is not valid in either byte order"));
161    };
162    let mut c = Cursor { b: bytes, pos: 0, big };
163    let mut out = Vec::new();
164    while c.pos < bytes.len() {
165        let mopt = c.int()?;
166        let (rows, cols, imagf, namlen) = (c.int()?, c.int()?, c.int()?, c.int()?);
167        if !valid_mopt(mopt) {
168            return Err(bad("MAT-file (level 4): invalid MOPT in a variable header"));
169        }
170        let (m, rest) = (mopt / 1000, mopt % 1000);
171        if m > 1 {
172            return Err(bad("MAT-file (level 4): VAX and Cray byte orders are not supported"));
173        }
174        let (p, t) = ((rest / 10) % 10, rest % 10);
175        if rows < 0 || cols < 0 || !(0..=1).contains(&imagf) || !(1..=1024).contains(&namlen) {
176            return Err(bad("MAT-file (level 4): invalid dimensions or name length"));
177        }
178        let name_bytes = c.take(namlen as usize)?;
179        let name: String = name_bytes.iter().take_while(|&&b| b != 0).map(|&b| b as char).collect();
180        let (rows, cols) = (rows as usize, cols as usize);
181        let count = rows.checked_mul(cols).ok_or_else(|| bad("MAT-file (level 4): dimensions overflow"))?;
182        let real = c.values(p, count)?;
183        let imag = if imagf == 1 && t != 2 { Some(c.values(p, count)?) } else { None };
184        let value = match t {
185            0 => MatValue::Numeric { class: p_class(p), dims: vec![rows, cols], real, imag },
186            1 => MatValue::Char { dims: vec![rows, cols], chars: real.iter().map(|&v| char::from_u32(v as u32).unwrap_or('\u{fffd}')).collect() },
187            _ => sparse_from_triplets(rows, cols, &real)?,
188        };
189        out.push((name, value));
190    }
191    Ok(out)
192}
193// ANCHOR_END: loadmat4
194
195/// The `(nnz + 1) × 3` (or 4) array of a stored sparse matrix, column-major with `rows` rows, as a
196/// compressed-sparse-column matrix.
197fn sparse_from_triplets(rows: usize, cols: usize, data: &[f64]) -> Result<MatValue, ErrorsJSL> {
198    if rows < 1 || !(cols == 3 || cols == 4) {
199        return Err(bad("MAT-file (level 4): a sparse matrix is stored with 3 or 4 columns and at least one row"));
200    }
201    let nnz = rows - 1;
202    let at = |i: usize, j: usize| data[i + j * rows];
203    let (nrows, ncols) = (at(nnz, 0), at(nnz, 1));
204    if nrows < 0.0 || ncols < 0.0 || nrows.fract() != 0.0 || ncols.fract() != 0.0 || nrows > u32::MAX as f64 || ncols > u32::MAX as f64 {
205        return Err(bad("MAT-file (level 4): invalid sparse dimensions"));
206    }
207    let (nrows, ncols) = (nrows as usize, ncols as usize);
208    let mut entries: Vec<(usize, usize, f64, f64)> = Vec::with_capacity(nnz);
209    for k in 0..nnz {
210        let (i, j) = (at(k, 0), at(k, 1));
211        if i < 1.0 || j < 1.0 || i > nrows as f64 || j > ncols as f64 || i.fract() != 0.0 || j.fract() != 0.0 {
212            return Err(bad("MAT-file (level 4): a sparse index lies outside the matrix"));
213        }
214        entries.push((j as usize - 1, i as usize - 1, at(k, 2), if cols == 4 { at(k, 3) } else { 0.0 }));
215    }
216    entries.sort_by_key(|e| (e.0, e.1));
217    let mut col_ptr = vec![0usize; ncols + 1];
218    for e in &entries {
219        col_ptr[e.0 + 1] += 1;
220    }
221    for j in 0..ncols {
222        col_ptr[j + 1] += col_ptr[j];
223    }
224    Ok(MatValue::Sparse {
225        nrows,
226        ncols,
227        row_indices: entries.iter().map(|e| e.1).collect(),
228        col_ptr,
229        real: entries.iter().map(|e| e.2).collect(),
230        imag: if cols == 4 { Some(entries.iter().map(|e| e.3).collect()) } else { None },
231        logical: false,
232    })
233}
234
235/// Reads a MAT-file of either level 4 or level 5, by [`mat_version`].
236pub fn mat_decode_any(bytes: &[u8]) -> Result<Vec<(String, MatValue)>, ErrorsJSL> {
237    match mat_version(bytes)? {
238        MatVersion::V4 => mat4_decode(bytes),
239        MatVersion::V5 => crate::matlab::mat_decode(bytes),
240        MatVersion::V73 => crate::hdf5::mat73_decode(bytes),
241    }
242}
243
244#[allow(clippy::too_many_arguments)]
245fn put_header(out: &mut Vec<u8>, name: &str, p: i32, t: i32, rows: usize, cols: usize, imagf: bool, big: bool) -> Result<(), ErrorsJSL> {
246    if name.is_empty() || !name.is_ascii() || name.contains('\0') {
247        return Err(bad("MAT-file (level 4): variable names must be non-empty ASCII"));
248    }
249    if rows > i32::MAX as usize || cols > i32::MAX as usize {
250        return Err(bad("MAT-file (level 4): dimension above 2³¹ − 1"));
251    }
252    let word = |out: &mut Vec<u8>, v: i32| out.extend(if big { v.to_be_bytes() } else { v.to_le_bytes() });
253    word(out, i32::from(big) * 1000 + p * 10 + t);
254    word(out, rows as i32);
255    word(out, cols as i32);
256    word(out, imagf as i32);
257    word(out, name.len() as i32 + 1);
258    out.extend(name.as_bytes());
259    out.push(0);
260    Ok(())
261}
262
263fn put_values(out: &mut Vec<u8>, p: i32, values: &[f64], big: bool) {
264    macro_rules! put {
265        ($x:expr) => {
266            out.extend(if big { $x.to_be_bytes().to_vec() } else { $x.to_le_bytes().to_vec() })
267        };
268    }
269    for &v in values {
270        match p {
271            P_DOUBLE => put!(v),
272            P_SINGLE => put!(v as f32),
273            P_INT32 => put!(v as i32),
274            P_INT16 => put!(v as i16),
275            P_UINT16 => put!(v as u16),
276            _ => out.push(v as u8),
277        }
278    }
279}
280
281// ANCHOR: savemat4
282/// Writes a level-4 MAT-file (SciPy's `savemat` with `format='4'`), little-endian (see
283/// [`mat4_encode_big_endian`] for the other byte order). Level 4 holds
284/// two-dimensional arrays of doubles, singles, 32- and 16-bit integers and bytes, text, and sparse
285/// matrices: other classes, logical arrays, cells, structures and arrays of more than two
286/// dimensions are refused.
287pub fn mat4_encode(variables: &[(String, MatValue)]) -> Result<Vec<u8>, ErrorsJSL> {
288    mat4_encode_with(variables, false)
289}
290
291/// As [`mat4_encode`], big-endian (`MOPT` digit 1): the byte order of MATLAB on 68000 and SPARC
292/// machines, read by every level-4 reader.
293pub fn mat4_encode_big_endian(variables: &[(String, MatValue)]) -> Result<Vec<u8>, ErrorsJSL> {
294    mat4_encode_with(variables, true)
295}
296
297fn mat4_encode_with(variables: &[(String, MatValue)], big: bool) -> Result<Vec<u8>, ErrorsJSL> {
298    let mut out = Vec::new();
299    for (name, v) in variables {
300        match v {
301            MatValue::Numeric { class, dims, real, imag } => {
302                let p = match class {
303                    MatClass::Double => P_DOUBLE,
304                    MatClass::Single => P_SINGLE,
305                    MatClass::Int32 => P_INT32,
306                    MatClass::Int16 => P_INT16,
307                    MatClass::Uint16 => P_UINT16,
308                    MatClass::Uint8 => P_UINT8,
309                    _ => return Err(bad("MAT-file (level 4): this numeric class cannot be stored")),
310                };
311                if dims.len() != 2 || dims[0] * dims[1] != real.len() || imag.as_ref().is_some_and(|i| i.len() != real.len()) {
312                    return Err(bad("MAT-file (level 4): arrays must be two-dimensional and match their dimensions"));
313                }
314                put_header(&mut out, name, p, 0, dims[0], dims[1], imag.is_some(), big)?;
315                put_values(&mut out, p, real, big);
316                if let Some(im) = imag {
317                    put_values(&mut out, p, im, big);
318                }
319            }
320            MatValue::Char { dims, chars } => {
321                if dims.len() != 2 || dims[0] * dims[1] != chars.len() || chars.iter().any(|&c| c as u32 > 255) {
322                    return Err(bad("MAT-file (level 4): text must be a two-dimensional array of Latin-1 characters"));
323                }
324                put_header(&mut out, name, P_UINT8, 1, dims[0], dims[1], false, big)?;
325                out.extend(chars.iter().map(|&c| c as u32 as u8));
326            }
327            MatValue::Sparse { nrows, ncols, row_indices, col_ptr, real, imag, logical } => {
328                if *logical || col_ptr.len() != ncols + 1 || row_indices.len() != real.len() || imag.as_ref().is_some_and(|i| i.len() != real.len()) {
329                    return Err(bad("MAT-file (level 4): invalid or logical sparse matrix"));
330                }
331                let nnz = real.len();
332                let width = if imag.is_some() { 4 } else { 3 };
333                let mut ijv = vec![0.0; (nnz + 1) * width];
334                let rows = nnz + 1;
335                let mut k = 0;
336                for j in 0..*ncols {
337                    for q in col_ptr[j]..col_ptr[j + 1] {
338                        ijv[k] = (row_indices[q] + 1) as f64;
339                        ijv[k + rows] = (j + 1) as f64;
340                        ijv[k + 2 * rows] = real[q];
341                        if let Some(im) = imag {
342                            ijv[k + 3 * rows] = im[q];
343                        }
344                        k += 1;
345                    }
346                }
347                ijv[nnz] = *nrows as f64;
348                ijv[nnz + rows] = *ncols as f64;
349                put_header(&mut out, name, P_DOUBLE, 2, rows, width, false, big)?;
350                put_values(&mut out, P_DOUBLE, &ijv, big);
351            }
352            _ => return Err(bad("MAT-file (level 4): logical arrays, cells and structures cannot be stored")),
353        }
354    }
355    Ok(out)
356}
357// ANCHOR_END: savemat4
358
359/// Reads a level-4 MAT-file.
360pub fn read_mat4_file(path: impl AsRef<Path>) -> Result<Vec<(String, MatValue)>, ErrorsJSL> {
361    mat4_decode(&std::fs::read(path).map_err(|_| ErrorsJSL::RuntimeError("could not read the MAT-file"))?)
362}
363
364/// Writes a level-4 MAT-file.
365pub fn write_mat4_file(path: impl AsRef<Path>, variables: &[(String, MatValue)]) -> Result<(), ErrorsJSL> {
366    std::fs::write(path, mat4_encode(variables)?).map_err(|_| ErrorsJSL::RuntimeError("could not write the MAT-file"))
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    fn sample() -> Vec<(String, MatValue)> {
374        vec![
375            ("a".into(), MatValue::from_rows(&[vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.5]])),
376            ("z".into(), MatValue::Numeric { class: MatClass::Double, dims: vec![1, 2], real: vec![1.0, -2.0], imag: Some(vec![0.5, 3.0]) }),
377            ("i16".into(), MatValue::Numeric { class: MatClass::Int16, dims: vec![2, 1], real: vec![-7.0, 300.0], imag: None }),
378            ("u8".into(), MatValue::Numeric { class: MatClass::Uint8, dims: vec![1, 3], real: vec![0.0, 128.0, 255.0], imag: None }),
379            ("f32".into(), MatValue::Numeric { class: MatClass::Single, dims: vec![1, 2], real: vec![0.5, -1.25], imag: None }),
380            ("s".into(), MatValue::from_text("héllo")),
381            ("sp".into(), MatValue::Sparse { nrows: 3, ncols: 2, row_indices: vec![0, 2, 1], col_ptr: vec![0, 2, 3], real: vec![1.0, 2.0, 3.0], imag: None, logical: false }),
382            ("spz".into(), MatValue::Sparse { nrows: 2, ncols: 2, row_indices: vec![1, 0], col_ptr: vec![0, 1, 2], real: vec![1.0, 2.0], imag: Some(vec![-1.0, 0.5]), logical: false }),
383            ("e".into(), MatValue::Numeric { class: MatClass::Double, dims: vec![0, 0], real: vec![], imag: None }),
384        ]
385    }
386
387    #[test]
388    fn big_endian_writing_round_trips() {
389        let vars = vec![
390            ("a".to_string(), MatValue::from_rows(&[vec![1.0, 2.5], vec![-3.0, 4.0]])),
391            ("n".to_string(), MatValue::Numeric { class: MatClass::Int16, dims: vec![1, 3], real: vec![1.0, -2.0, 300.0], imag: None }),
392            ("z".to_string(), MatValue::Numeric { class: MatClass::Double, dims: vec![1, 2], real: vec![1.0, 2.0], imag: Some(vec![-1.0, 0.5]) }),
393            ("t".to_string(), MatValue::from_text("hi")),
394        ];
395        let big = mat4_encode_big_endian(&vars).unwrap();
396        let little = mat4_encode(&vars).unwrap();
397        assert_eq!(big.len(), little.len());
398        assert_eq!(&big[..4], &1000i32.to_be_bytes());
399        assert_eq!(mat4_decode(&big).unwrap(), mat4_decode(&little).unwrap());
400        assert_eq!(mat_version(&big).unwrap(), MatVersion::V4);
401    }
402
403    #[test]
404    fn round_trip() {
405        let vars = sample();
406        let bytes = mat4_encode(&vars).unwrap();
407        assert_eq!(mat_version(&bytes).unwrap(), MatVersion::V4);
408        assert_eq!(mat4_decode(&bytes).unwrap(), vars);
409        assert_eq!(mat_decode_any(&bytes).unwrap(), vars);
410    }
411
412    #[test]
413    fn reads_big_endian() {
414        // `x = [1 2]` as a big-endian double matrix: MOPT = 1000.
415        let mut b = Vec::new();
416        for v in [1000i32, 1, 2, 0, 2] {
417            b.extend(v.to_be_bytes());
418        }
419        b.extend(b"x\0");
420        for v in [1.0f64, 2.0] {
421            b.extend(v.to_be_bytes());
422        }
423        assert_eq!(mat_version(&b).unwrap(), MatVersion::V4);
424        assert_eq!(mat4_decode(&b).unwrap(), vec![("x".to_string(), MatValue::from_slice(&[1.0, 2.0]))]);
425    }
426
427    #[test]
428    fn version_detection_and_refusals() {
429        let v5 = crate::matlab::mat_encode(&sample()[..1], false).unwrap();
430        assert_eq!(mat_version(&v5).unwrap(), MatVersion::V5);
431        assert!(mat_decode_any(&v5).is_ok());
432        assert!(mat_version(&[0xff; 8]).is_err());
433        assert!(mat4_encode(&[("l".into(), MatValue::Logical { dims: vec![1, 1], data: vec![true] })]).is_err());
434        assert!(mat4_encode(&[("n".into(), MatValue::Numeric { class: MatClass::Int64, dims: vec![1, 1], real: vec![1.0], imag: None })]).is_err());
435        assert!(mat4_encode(&[("t".into(), MatValue::Numeric { class: MatClass::Double, dims: vec![1, 1, 2], real: vec![1.0, 2.0], imag: None })]).is_err());
436        assert!(mat4_encode(&[("".into(), MatValue::from_slice(&[1.0]))]).is_err());
437    }
438
439    #[test]
440    fn truncated_and_corrupt_files_are_errors() {
441        let bytes = mat4_encode(&sample()).unwrap();
442        for cut in [3usize, 10, 19, 25, bytes.len() - 1] {
443            assert!(mat4_decode(&bytes[..cut]).is_err(), "cut at {cut}");
444        }
445        // A sparse matrix whose row index lies beyond its dimensions: [[99, 1, 5], [3, 2, 0]].
446        let mut bad_sparse = Vec::new();
447        for v in [2i32, 2, 3, 0, 3] {
448            bad_sparse.extend(v.to_le_bytes());
449        }
450        bad_sparse.extend(b"s\0");
451        for v in [99.0f64, 3.0, 1.0, 2.0, 5.0, 0.0] {
452            bad_sparse.extend(v.to_le_bytes());
453        }
454        assert!(mat4_decode(&bad_sparse).is_err());
455        // Random bytes never panic.
456        let mut state = 99u64;
457        for _ in 0..200 {
458            let junk: Vec<u8> = (0..64).map(|_| { state = state.wrapping_mul(6364136223846793005).wrapping_add(1); (state >> 56) as u8 }).collect();
459            let _ = mat4_decode(&junk);
460        }
461    }
462}