Scientific data files: Matrix Market, MATLAB, IDL, HDF5, Harwell-Boeing, NetCDF, Fortran and ARFF
| Problem | Exchange matrices and labelled arrays with MATLAB, Fortran programs, climate and ocean models, sparse-matrix collections and machine-learning tools, in the formats scipy.io reads and writes |
| Devised by | Ronald Boisvert, Roldan Pozo and Karin Remington (1996), Matrix Market; Iain Duff, Roger Grimes and John Lewis (1989), the Harwell-Boeing collection; The MathWorks, the level-4 and level-5 MAT-files; Research Systems, the makers of IDL, the IDL save file, documented by Craig Markwardt and first read from Python by Thomas Robitaille (2010); Russ Rew and Glenn Davis at Unidata (1990), NetCDF; the University of Waikato (1999), ARFF for Weka |
| Accuracy | Values round-trip exactly; SciPy reads every file the library writes, and the library reads every file SciPy writes, including all 47 IDL files of SciPy’s test suite, value for value, and the datasets of h5py and netCDF4 files (table below) |
| Cost | ; compressed MAT-files add deflate’s cost |
| Read first | Data files: CSV and NumPy .npy |
| API | matrix_market (mm_decode, mm_encode, mm_info, MatrixMarket); matlab (mat_decode, mat_encode, mat_whos, MatValue); matlab4 (mat4_decode, mat4_encode, mat_version, mat_decode_any); idl (idl_decode, IdlSave, IdlValue); harwell_boeing (hb_decode, hb_encode); netcdf (netcdf_decode, netcdf_encode, NetCdf); fortran (fortran_records_decode, fortran_records_encode); arff (arff_decode, arff_encode); hdf5 (hdf5_decode, mat73_decode, netcdf4_decode, Hdf5File); each with read_*_file and, except for IDL, write_*_file |
Overview
scipy.io reads and writes the file formats that scientific computing has accumulated, and this entry brings them to the library:
- Matrix Market (
.mtx): text files for sparse and dense matrices, the format of the SuiteSparse Matrix Collection and the common currency of sparse linear algebra. - MATLAB MAT-files (levels 4 and 5,
.mat): binary files of named variables, the way MATLAB saves and loads data. - IDL save files (
.sav): the binary files of the Interactive Data Language, common in astronomy and solar physics. - HDF5 (
.h5) and the formats built on it: MATLAB v7.3 MAT-files and NetCDF-4, read-only. - Harwell-Boeing (
.hb,.rua): the older fixed-width Fortran format of the original Harwell-Boeing sparse matrix collection. - NetCDF-3 (
.nc): self-describing binary files of named, dimensioned variables with attributes. It is the standard for climate, ocean and atmospheric data. - Fortran unformatted sequential files: the raw binary records Fortran programs write.
- ARFF (
.arff): Weka’s text format for machine-learning data sets, with numeric and nominal attributes.
Where it is used
Scientific data often arrive in the format of the tool that produced them.
- MATLAB and Fortran codes.
.matfiles carry results between MATLAB and other languages; Fortran unformatted records carry output from legacy simulations. - Climate and ocean science. NetCDF-4 (built on HDF5) is the standard for gridded temperature, sea level and weather model data.
- Sparse matrices. Matrix Market and Harwell-Boeing files are the exchange formats of the sparse-matrix collections used to test solvers.
- Astronomy and remote sensing. IDL save files and HDF5 hold images and instrument data.
History
The Harwell-Boeing collection of sparse test matrices (Duff, Grimes and Lewis, 1989) fixed its storage format in 80-column Fortran records. Ronald Boisvert, Roldan Pozo and Karin Remington at NIST replaced it with the simpler Matrix Market format in 1996. The MathWorks introduced the level-5 MAT-file with MATLAB 5 (1999) and added compression in MATLAB 7. Version 7.3 files are HDF5, a different format altogether, designed by Mike Folk and colleagues at NCSA in the late 1990s and now kept by the HDF Group; NetCDF-4 (2008) is built on it too. The level-4 format is MATLAB 4’s: a bare sequence of matrices with no file header.
IDL’s SAVE command writes a record-based file whose layout was not publicly documented. Craig Markwardt reverse-engineered the Unofficial Format Specification, and Thomas Robitaille’s idlsave (2010), which became scipy.io.readsav, implements it.
NetCDF was designed at Unidata by Russ Rew and Glenn Davis (1990), after NASA’s Common Data Format. Its classic format is still the most widely shared. Fortran’s record markers date back to the earliest unformatted I/O. The University of Waikato defined ARFF for the Weka machine-learning workbench.
The idea
Matrix Market
A banner line declares the object, the format (coordinate for sparse triplets, array for dense column-major values), the field (real, integer, complex, pattern) and the symmetry (general, symmetric, skew-symmetric, hermitian). After comment lines and a size line come the entries, with 1-based indices. A symmetric file stores only the lower triangle. A reader rebuilds the rest by mirroring each off-diagonal entry, negating it for skew-symmetric matrices and conjugating it for Hermitian ones.
MATLAB level-5 files
A 128-byte header ends with a version and the characters IM, read as MI on a machine of the other byte order. Then come data elements: an 8-byte tag (type, byte count) and the data, padded to 8 bytes. Elements of at most 4 bytes pack tag and data into 8 bytes.
A variable is a miMATRIX element containing nested elements: the array flags (class, complex, logical), the dimensions, the name, and the data in column-major order. Each part is stored in whatever integer or floating type is smallest. Sparse matrices store their compressed-column arrays, cells and structures store nested miMATRIX elements, and miCOMPRESSED wraps one miMATRIX in a zlib stream.
MATLAB level-4 files
There is no file header. Each variable has a 20-byte header of five 32-bit integers, then its name and data. The first integer, MOPT, is four decimal digits: the byte order (0 for little-endian IEEE, 1 for big-endian; VAX and Cray orders also existed), a reserved zero, the data type (double, single, 32-bit, 16-bit and unsigned 16-bit integers, unsigned byte) and the matrix type (full, text, sparse). The next three are the row and column counts and a flag for complex data, and the last is the length of the name, with its terminating NUL. The data follow in column-major order, the real part and then the imaginary part.
A sparse matrix has no format of its own. It is stored as a full array with one row per non-zero entry and the columns row, column and value, both indices counted from 1. A last row holds the matrix dimensions. A complex sparse matrix has a fourth column, for the imaginary parts, and is recognised by it.
A reader must find the byte order without a header. A valid MOPT is at most 5000, so the first integer read in the wrong order is almost always too large or negative: a big-endian MOPT of 1000 reads as in a little-endian reader.
IDL save files
The file starts with SR and a two-byte format code, then a sequence of records. Each record has a type, the absolute offset of the next record, four unused bytes and a body, so a reader can skip the records it does not need. Everything is big-endian and padded to 32 bits, so that a byte or a 16-bit integer, as a scalar, occupies four bytes.
A VARIABLE record holds the name and a type descriptor: a type code (byte, integer, long, float, double, complex, string, structure, pointer, object and the unsigned and 64-bit integers), flags for array and structure, and the descriptors that the flags call for.
- An array descriptor gives the number of elements, the number of dimensions and the dimensions. IDL’s first dimension varies fastest, so NumPy’s shape is the dimensions reversed.
- A structure descriptor gives the structure’s name and its tags, each with a type and its own array or structure descriptor. A structure that has been written before in the same file is described by its name alone.
The data come after a start marker. A structure array is stored element by element, tag by tag.
A pointer is an index into the file’s heap: a HEAP_DATA record holds the value under that index, in the same layout as a variable. The reader collects the heap first and then replaces each pointer, in variables and inside structures, by its target, for any chain of pointers; index 0 is the null pointer. A file written with the /COMPRESS keyword has the same records, each body compressed separately with zlib.
HDF5, MATLAB v7.3 and NetCDF-4
An HDF5 file is a small file system. A superblock (found at offset 0, 512, 1024, … so that a user block can come first, as MATLAB’s 512-byte header does) gives the sizes of addresses and lengths and the address of the root group. Every object (a group or a dataset) has an object header, a list of messages: a dataspace (the shape), a datatype, a data layout, a filter pipeline, attributes and, for groups, links. Old-style groups keep their members in a B-tree of symbol-table nodes with the names in a local heap; new-style groups carry link messages. Groups of the newest format with more than eight links (and objects with more than eight attributes) switch to dense storage: the link or attribute messages live in a fractal heap (a growing address space of blocks, with objects found by a heap ID) and a version 2 B-tree of heap IDs indexes them by name. A dataset’s data are contiguous, compact (inside the header) or chunked: split into blocks that are indexed by offset, in the old format by a B-tree, in the newest by a single chunk, a fixed array, an extensible array or a version 2 B-tree, each block run through the filters, deflate and byte shuffle (which stores the first bytes of every element together, so that deflate sees runs of similar bytes). Variable-length strings and sequences live in a global heap, and an element holds only a reference to it.
MATLAB v7.3 writes each variable as one HDF5 object with an attribute MATLAB_class, and stores arrays transposed (HDF5 is row-major), so the dimensions are the dataset’s reversed. Complex numbers are compounds of real and imag, sparse matrices are groups with data, ir and jc, cells are datasets of references into a #refs# group, and structures are groups of fields. NetCDF-4 marks dimensions as dimension scales (datasets with CLASS = DIMENSION_SCALE) and gives each variable a DIMENSION_LIST attribute of references to them.
Harwell-Boeing
The header gives the number of 80-column lines in each section, the matrix type (RUA: real, unsymmetric, assembled), the dimensions, and Fortran edit descriptors such as (26I3) and (3E25.16) for the sections. The body is the 1-based compressed-sparse-column pointers, row indices and values, in those fixed-width fields.
NetCDF-3
The header lists:
- the dimensions, one of which may be unlimited (the record dimension);
- the global attributes;
- the variables, each with its dimensions, attributes, type, size and file offset.
Fixed-size variables follow one after another. Variables along the record dimension are interleaved: record 0 of every record variable, then record 1, and so on. That is what lets a file grow by appending records. Everything is big-endian and padded to 4 bytes. Version 2 widens the offsets to 64 bits.
Fortran records and ARFF
A Fortran unformatted sequential write frames each record with its byte count, before and after, so a reader can skip records in either direction. ARFF is plain text: @relation, one @attribute per column, then @data with comma-separated rows and ? for missing values.
Implementation
/// Parses a level-5 MAT-file (SciPy's `loadmat`): the variables in file order, as
/// `(name, value)` pairs. The header's endian indicator `IM` or `MI` gives the byte order.
pub fn mat_decode(bytes: &[u8]) -> Result<Vec<(String, MatValue)>, ErrorsJSL> {
if bytes.len() < 128 {
return Err(bad("MAT-file: shorter than the 128-byte header"));
}
let swap = match &bytes[126..128] {
b"IM" => false,
b"MI" => true,
_ => return Err(bad("MAT-file: not a level-5 MAT-file (v7.3 files are HDF5)")),
};
let mut r = Reader { b: bytes, pos: 128, swap };
let mut out = Vec::new();
while !r.done() {
let (ty, d) = r.element()?;
let (name, value) = match ty {
MI_MATRIX => parse_matrix(d, swap)?,
MI_COMPRESSED => {
let raw = zlib_decompress(d)?;
let mut inner = Reader { b: &raw, pos: 0, swap };
let (ty2, d2) = inner.element()?;
if ty2 != MI_MATRIX {
return Err(bad("MAT-file: a compressed element does not hold a matrix"));
}
parse_matrix(d2, swap)?
}
_ => continue,
};
out.push((name, value));
}
Ok(out)
}
/// Parses a level-4 MAT-file (SciPy's `loadmat`): the variables in file order, as `(name, value)`
/// pairs. Numeric matrices keep their stored type, text becomes a character array, and a sparse
/// matrix a compressed-sparse-column [`MatValue::Sparse`].
pub fn mat4_decode(bytes: &[u8]) -> Result<Vec<(String, MatValue)>, ErrorsJSL> {
if bytes.len() < 4 {
return Err(bad("MAT-file (level 4): shorter than one header"));
}
let first: [u8; 4] = bytes[..4].try_into().expect("4 bytes");
let big = if valid_mopt(i32::from_le_bytes(first)) {
false
} else if valid_mopt(i32::from_be_bytes(first)) {
true
} else {
return Err(bad("MAT-file (level 4): the first header is not valid in either byte order"));
};
let mut c = Cursor { b: bytes, pos: 0, big };
let mut out = Vec::new();
while c.pos < bytes.len() {
let mopt = c.int()?;
let (rows, cols, imagf, namlen) = (c.int()?, c.int()?, c.int()?, c.int()?);
if !valid_mopt(mopt) {
return Err(bad("MAT-file (level 4): invalid MOPT in a variable header"));
}
let (m, rest) = (mopt / 1000, mopt % 1000);
if m > 1 {
return Err(bad("MAT-file (level 4): VAX and Cray byte orders are not supported"));
}
let (p, t) = ((rest / 10) % 10, rest % 10);
if rows < 0 || cols < 0 || !(0..=1).contains(&imagf) || !(1..=1024).contains(&namlen) {
return Err(bad("MAT-file (level 4): invalid dimensions or name length"));
}
let name_bytes = c.take(namlen as usize)?;
let name: String = name_bytes.iter().take_while(|&&b| b != 0).map(|&b| b as char).collect();
let (rows, cols) = (rows as usize, cols as usize);
let count = rows.checked_mul(cols).ok_or_else(|| bad("MAT-file (level 4): dimensions overflow"))?;
let real = c.values(p, count)?;
let imag = if imagf == 1 && t != 2 { Some(c.values(p, count)?) } else { None };
let value = match t {
0 => MatValue::Numeric { class: p_class(p), dims: vec![rows, cols], real, imag },
1 => MatValue::Char { dims: vec![rows, cols], chars: real.iter().map(|&v| char::from_u32(v as u32).unwrap_or('\u{fffd}')).collect() },
_ => sparse_from_triplets(rows, cols, &real)?,
};
out.push((name, value));
}
Ok(out)
}
/// Writes a level-4 MAT-file (SciPy's `savemat` with `format='4'`), little-endian (see
/// [`mat4_encode_big_endian`] for the other byte order). Level 4 holds
/// two-dimensional arrays of doubles, singles, 32- and 16-bit integers and bytes, text, and sparse
/// matrices: other classes, logical arrays, cells, structures and arrays of more than two
/// dimensions are refused.
pub fn mat4_encode(variables: &[(String, MatValue)]) -> Result<Vec<u8>, ErrorsJSL> {
mat4_encode_with(variables, false)
}
/// As [`mat4_encode`], big-endian (`MOPT` digit 1): the byte order of MATLAB on 68000 and SPARC
/// machines, read by every level-4 reader.
pub fn mat4_encode_big_endian(variables: &[(String, MatValue)]) -> Result<Vec<u8>, ErrorsJSL> {
mat4_encode_with(variables, true)
}
fn mat4_encode_with(variables: &[(String, MatValue)], big: bool) -> Result<Vec<u8>, ErrorsJSL> {
let mut out = Vec::new();
for (name, v) in variables {
match v {
MatValue::Numeric { class, dims, real, imag } => {
let p = match class {
MatClass::Double => P_DOUBLE,
MatClass::Single => P_SINGLE,
MatClass::Int32 => P_INT32,
MatClass::Int16 => P_INT16,
MatClass::Uint16 => P_UINT16,
MatClass::Uint8 => P_UINT8,
_ => return Err(bad("MAT-file (level 4): this numeric class cannot be stored")),
};
if dims.len() != 2 || dims[0] * dims[1] != real.len() || imag.as_ref().is_some_and(|i| i.len() != real.len()) {
return Err(bad("MAT-file (level 4): arrays must be two-dimensional and match their dimensions"));
}
put_header(&mut out, name, p, 0, dims[0], dims[1], imag.is_some(), big)?;
put_values(&mut out, p, real, big);
if let Some(im) = imag {
put_values(&mut out, p, im, big);
}
}
MatValue::Char { dims, chars } => {
if dims.len() != 2 || dims[0] * dims[1] != chars.len() || chars.iter().any(|&c| c as u32 > 255) {
return Err(bad("MAT-file (level 4): text must be a two-dimensional array of Latin-1 characters"));
}
put_header(&mut out, name, P_UINT8, 1, dims[0], dims[1], false, big)?;
out.extend(chars.iter().map(|&c| c as u32 as u8));
}
MatValue::Sparse { nrows, ncols, row_indices, col_ptr, real, imag, logical } => {
if *logical || col_ptr.len() != ncols + 1 || row_indices.len() != real.len() || imag.as_ref().is_some_and(|i| i.len() != real.len()) {
return Err(bad("MAT-file (level 4): invalid or logical sparse matrix"));
}
let nnz = real.len();
let width = if imag.is_some() { 4 } else { 3 };
let mut ijv = vec![0.0; (nnz + 1) * width];
let rows = nnz + 1;
let mut k = 0;
for j in 0..*ncols {
for q in col_ptr[j]..col_ptr[j + 1] {
ijv[k] = (row_indices[q] + 1) as f64;
ijv[k + rows] = (j + 1) as f64;
ijv[k + 2 * rows] = real[q];
if let Some(im) = imag {
ijv[k + 3 * rows] = im[q];
}
k += 1;
}
}
ijv[nnz] = *nrows as f64;
ijv[nnz + rows] = *ncols as f64;
put_header(&mut out, name, P_DOUBLE, 2, rows, width, false, big)?;
put_values(&mut out, P_DOUBLE, &ijv, big);
}
_ => return Err(bad("MAT-file (level 4): logical arrays, cells and structures cannot be stored")),
}
}
Ok(out)
}
/// Parses an IDL save file (SciPy's `readsav`): the variables in file order, pointers replaced
/// by what they point to, and the descriptive records. A compressed file (format code `\0\x06`)
/// is expanded record by record. Record types the reader does not use, such as `COMPILED` and
/// `PROMOTE64`, are skipped by their next-record offsets, where SciPy refuses some of them.
pub fn idl_decode(bytes: &[u8]) -> Result<IdlSave, ErrorsJSL> {
if bytes.len() < 4 || &bytes[..2] != b"SR" {
return Err(bad("IDL save file: invalid signature"));
}
let compressed = match &bytes[2..4] {
[0, 4] => false,
[0, 6] => true,
_ => return Err(bad("IDL save file: invalid record format")),
};
// Split into records: (type, body).
let mut records: Vec<(i32, Vec<u8>)> = Vec::new();
let mut pos = 4usize;
loop {
let header = bytes.get(pos..pos + 16).ok_or_else(|| bad("IDL save file: truncated before the end marker"))?;
let rectype = i32::from_be_bytes(header[0..4].try_into().expect("4 bytes"));
let next = u32::from_be_bytes(header[4..8].try_into().expect("4 bytes")) as u64 + ((u32::from_be_bytes(header[8..12].try_into().expect("4 bytes")) as u64) << 32);
if rectype == END_MARKER {
break;
}
let next = usize::try_from(next).map_err(|_| bad("IDL save file: record offset too large"))?;
if next < pos + 16 || next > bytes.len() {
return Err(bad("IDL save file: a record's next-record offset is outside the file"));
}
let body = &bytes[pos + 16..next];
records.push((rectype, if compressed { zlib_decompress(body)? } else { body.to_vec() }));
pos = next;
}
let mut defs: HashMap<String, Rc<StructDesc>> = HashMap::new();
let mut info = IdlInfo::default();
let mut raw: Vec<(String, IdlValue)> = Vec::new();
let mut heap: HashMap<i32, IdlValue> = HashMap::new();
for (rectype, body) in &records {
let mut r = Rd { b: body, pos: 0, defs: &mut defs };
match rectype {
2 => {
let name = r.string()?;
let value = r.typed_value()?.unwrap_or(IdlValue::Null);
raw.push((name, value));
}
16 => {
let index = r.long()?;
r.skip(4)?;
heap.insert(index, r.typed_value()?.unwrap_or(IdlValue::Null));
}
10 => {
r.skip(4 * 256)?;
info.date = Some(r.string()?);
info.user = Some(r.string()?);
info.host = Some(r.string()?);
}
14 => {
info.format = Some(r.long()?);
info.arch = Some(r.string()?);
info.os = Some(r.string()?);
info.release = Some(r.string()?);
}
13 => {
info.author = Some(r.string()?);
info.title = Some(r.string()?);
info.idcode = Some(r.string()?);
}
19 => info.notice = Some(r.string()?),
20 => info.description = Some(r.string_data()?),
_ => {}
}
}
let variables = raw.iter().map(|(n, v)| Ok((n.clone(), resolve(v, &heap, 0)?))).collect::<Result<Vec<_>, ErrorsJSL>>()?;
Ok(IdlSave { variables, info })
}
/// Parses an HDF5 file held in memory. The signature is searched for at offsets 0, 512, 1024, ...
/// (a user block, as in MATLAB v7.3 files, comes first).
pub fn hdf5_decode(bytes: &[u8]) -> Result<Hdf5File, ErrorsJSL> {
const SIGNATURE: &[u8; 8] = b"\x89HDF\r\n\x1a\n";
let mut base = 0usize;
while bytes.get(base..base + 8) != Some(SIGNATURE) {
base = if base == 0 { 512 } else { base * 2 };
if base + 8 > bytes.len() {
return Err(bad("HDF5: signature not found"));
}
}
let version = *bytes.get(base + 8).ok_or_else(|| bad("HDF5: truncated superblock"))?;
let (offset_size, length_size, root_addr) = match version {
0 | 1 => {
let (o, l) = (bytes.get(base + 13).copied().unwrap_or(0) as usize, bytes.get(base + 14).copied().unwrap_or(0) as usize);
if !(o == 8 || o == 4) || !(l == 8 || l == 4) {
return Err(bad("HDF5: unsupported sizes of offsets and lengths"));
}
// After the fixed part (and, in version 1, the indexed storage K): the four addresses,
// then the root group's symbol table entry.
let start = base + 24 + if version == 1 { 4 } else { 0 };
let entry = start + 4 * o;
let r = Reader { b: bytes, base, offset_size: o, length_size: l };
let header = r.offset(entry - base + o)?;
(o, l, header)
}
2 | 3 => {
let (o, l) = (bytes.get(base + 9).copied().unwrap_or(0) as usize, bytes.get(base + 10).copied().unwrap_or(0) as usize);
if !(o == 8 || o == 4) || !(l == 8 || l == 4) {
return Err(bad("HDF5: unsupported sizes of offsets and lengths"));
}
let r = Reader { b: bytes, base, offset_size: o, length_size: l };
let root = r.offset(12 + 3 * o)?;
(o, l, root)
}
_ => return Err(bad("HDF5: unsupported superblock version")),
};
let r = Reader { b: bytes, base, offset_size, length_size };
let mut loader = Loader { r, objects: HashMap::new(), names: HashMap::new(), active: HashSet::new(), count: 0 };
let root = match loader.load(root_addr as usize)? {
H5Object::Group(g) => g,
H5Object::Dataset(_) => return Err(bad("HDF5: the root is not a group")),
};
Ok(Hdf5File { root, objects: loader.objects, names: loader.names })
}
/// Reads a MATLAB v7.3 MAT-file (an HDF5 file with a 512-byte user block): the variables in the
/// order the file lists them (alphabetical), as the values [`crate::mat_decode`] gives for level 5.
/// Numeric, logical and character arrays (empty ones too), complex arrays, sparse matrices, cell
/// arrays and structures (scalar and arrays) are read; function handles, objects and `table`s are
/// reported as errors. The order of a structure's fields is MATLAB's (the attribute
/// `MATLAB_fields`) when the file has it, and the file's (alphabetical) otherwise.
pub fn mat73_decode(bytes: &[u8]) -> Result<Vec<(String, MatValue)>, ErrorsJSL> {
let file = hdf5_decode(bytes)?;
let mut out = Vec::new();
for (name, o) in &file.root.members {
if name == "#refs#" || name == "#subsystem#" {
continue;
}
out.push((name.clone(), mat_convert(&file, o, 0)?));
}
Ok(out)
}
/// Reads the root group of a NetCDF-4 file into the [`NetCdf`] of the classic model: dimensions
/// (the file's dimension scales), global attributes and variables with their attributes. Types
/// NetCDF-3 lacks (64-bit and unsigned integers, enumerations) are widened to `f64`; subgroups and
/// user-defined types are not represented (variables in subgroups are listed under the path
/// `group/name`). An unlimited dimension has length `None`, and `numrecs` is its current length.
pub fn netcdf4_decode(bytes: &[u8]) -> Result<NetCdf, ErrorsJSL> {
let file = hdf5_decode(bytes)?;
const INTERNAL: [&str; 6] = ["CLASS", "NAME", "DIMENSION_LIST", "REFERENCE_LIST", "_Netcdf4Dimid", "_Netcdf4Coordinates"];
let mut nc = NetCdf::new();
nc.version = 4;
// Dimension scales, in file order, by the address of their headers.
let mut scale_names = HashSet::new();
for (name, o) in &file.root.members {
if let H5Object::Dataset(d) = o
&& attr_string(o, "CLASS").as_deref() == Some("DIMENSION_SCALE")
{
let placeholder = attr_string(o, "NAME").is_some_and(|n| n.starts_with("This is a netCDF dimension but not a netCDF variable"));
let length = d.data.shape.first().copied().unwrap_or(1);
let unlimited = d.max_shape.first() == Some(&None);
if unlimited {
nc.numrecs = nc.numrecs.max(length);
}
nc.dimensions.push((name.clone(), if unlimited { None } else { Some(length) }));
if placeholder {
scale_names.insert(name.clone());
}
}
}
for (name, a) in &file.root.attributes {
if !INTERNAL.contains(&name.as_str()) && name != "_NCProperties" {
nc.attributes.push((name.clone(), nc_value(a)?));
}
}
let mut flat: Vec<(String, &H5Object)> = Vec::new();
fn collect<'a>(g: &'a H5Group, prefix: &str, out: &mut Vec<(String, &'a H5Object)>) {
for (name, o) in &g.members {
match o {
H5Object::Dataset(_) => out.push((format!("{prefix}{name}"), o)),
H5Object::Group(sub) => collect(sub, &format!("{prefix}{name}/"), out),
}
}
}
collect(&file.root, "", &mut flat);
for (name, o) in &flat {
let H5Object::Dataset(d) = o else { continue };
if scale_names.contains(name) {
continue;
}
let dims: Vec<usize> = match o.attribute("DIMENSION_LIST") {
Some(list) => list
.values
.iter()
.map(|v| match v {
H5Value::Sequence(s) => match s.first() {
Some(H5Value::Reference(r)) => file.name_of(*r).and_then(|n| nc.dimensions.iter().position(|(dn, _)| dn == n)).ok_or_else(|| bad("NetCDF-4: a dimension list names an unknown dimension")),
_ => Err(bad("NetCDF-4: an empty dimension list entry")),
},
_ => Err(bad("NetCDF-4: a malformed dimension list")),
})
.collect::<Result<_, _>>()?,
None if attr_string(o, "CLASS").as_deref() == Some("DIMENSION_SCALE") => vec![nc.dimensions.iter().position(|(dn, _)| dn == name).unwrap_or(0)],
None => Vec::new(),
};
let mut var = NcVariable::new(name, dims, nc_value(&d.data)?);
for (an, a) in o.attributes() {
if !INTERNAL.contains(&an.as_str()) {
var.attributes.push((an.clone(), nc_value(a)?));
}
}
nc.variables.push(var);
}
Ok(nc)
}
/// Parses a NetCDF-3 file (SciPy's `netcdf_file(..., "r")`), classic or 64-bit offset.
pub fn netcdf_decode(bytes: &[u8]) -> Result<NetCdf, ErrorsJSL> {
let mut c = Cursor { b: bytes, pos: 0 };
let magic = c.take(4)?;
if &magic[..3] != b"CDF" || !matches!(magic[3], 1 | 2) {
return Err(bad("NetCDF: not a NetCDF-3 file (NetCDF-4 files are HDF5)"));
}
let version = magic[3];
let numrecs_raw = c.u32()?;
let tag = c.u32()?;
let ndims = c.u32()? as usize;
if tag != 0 && tag != 0x0A {
return Err(bad("NetCDF: expected a dimension list"));
}
let mut dimensions = Vec::with_capacity(ndims);
for _ in 0..ndims {
let name = c.name()?;
let len = c.u32()? as usize;
dimensions.push((name, if len == 0 { None } else { Some(len) }));
}
let attributes = c.attributes()?;
let tag = c.u32()?;
let nvars = c.u32()? as usize;
if tag != 0 && tag != 0x0B {
return Err(bad("NetCDF: expected a variable list"));
}
struct Raw {
name: String,
dims: Vec<usize>,
attributes: Vec<(String, NcValue)>,
ty: u32,
vsize: usize,
begin: usize,
}
let mut raws = Vec::with_capacity(nvars);
for _ in 0..nvars {
let name = c.name()?;
let nd = c.u32()? as usize;
let dims: Vec<usize> = (0..nd).map(|_| c.u32().map(|d| d as usize)).collect::<Result<_, _>>()?;
if dims.iter().any(|&d| d >= dimensions.len()) {
return Err(bad("NetCDF: a variable refers to an unknown dimension"));
}
let attributes = c.attributes()?;
let ty = c.u32()?;
let vsize = c.u32()? as usize;
let begin = if version == 1 { c.u32()? as usize } else { c.u64()? as usize };
raws.push(Raw { name, dims, attributes, ty, vsize, begin });
}
let is_record = |r: &Raw| r.dims.first().is_some_and(|&d| dimensions[d].1.is_none());
let rec_vars: Vec<usize> = (0..raws.len()).filter(|&i| is_record(&raws[i])).collect();
// The stride between records: the sum of the record variables' sizes, unpadded when there
// is only one record variable.
let recsize: usize = rec_vars.iter().map(|&i| raws[i].vsize).sum();
let numrecs = if numrecs_raw == u32::MAX {
// Streaming: infer the count from the file length.
match rec_vars.first() {
Some(&i) if recsize > 0 => (bytes.len().saturating_sub(raws[i].begin)) / recsize,
_ => 0,
}
} else {
numrecs_raw as usize
};
let mut variables = Vec::with_capacity(raws.len());
for r in &raws {
let size = NcValue::element_size(r.ty).ok_or(bad("NetCDF: unknown variable type"))?;
let per: usize = r.dims.iter().filter(|&&d| dimensions[d].1.is_some()).map(|&d| dimensions[d].1.expect("fixed")).product();
let nbytes = per * size;
let data = if is_record(r) {
let mut v = NcValue::empty_like(r.ty);
for k in 0..numrecs {
let at = r.begin + k * recsize;
let slab = bytes.get(at..at + nbytes).ok_or(bad("NetCDF: truncated record data"))?;
v.append(NcValue::decode(r.ty, slab)?);
}
v
} else {
NcValue::decode(r.ty, bytes.get(r.begin..r.begin + nbytes).ok_or(bad("NetCDF: truncated data"))?)?
};
variables.push(NcVariable { name: r.name.clone(), dims: r.dims.clone(), attributes: r.attributes.clone(), data });
}
Ok(NetCdf { dimensions, attributes, variables, numrecs, version })
}
/// Parses a Matrix Market file (SciPy's `mmread`). Symmetric, skew-symmetric and Hermitian
/// matrices are expanded to the full matrix: each stored off-diagonal entry `(i, j, v)` adds
/// `(j, i, v)`, `(j, i, −v)` or `(j, i, v̄)`.
pub fn mm_decode(text: &str) -> Result<MatrixMarket, ErrorsJSL> {
let ((format, field, symmetry), comment, size, mut tokens) = split(text)?;
let (nrows, ncols) = (size[0], size[1]);
if symmetry != MmSymmetry::General && nrows != ncols {
return Err(bad("Matrix Market: a symmetric matrix must be square"));
}
let mut next_f64 = |what: &'static str| -> Result<f64, ErrorsJSL> {
let t = tokens.next().ok_or(bad(what))?;
t.parse::<f64>().or_else(|_| t.replace(['d', 'D'], "e").parse::<f64>()).map_err(|_| bad("Matrix Market: a value is not a number"))
};
let value = |next: &mut dyn FnMut(&'static str) -> Result<f64, ErrorsJSL>| -> Result<C64, ErrorsJSL> {
Ok(match field {
MmField::Pattern => C64::new(1.0, 0.0),
MmField::Complex => {
let re = next("Matrix Market: missing value")?;
C64::new(re, next("Matrix Market: missing imaginary part")?)
}
_ => C64::new(next("Matrix Market: missing value")?, 0.0),
})
};
let (mut rows, mut cols, mut values) = (Vec::new(), Vec::new(), Vec::new());
let mut push = |i: usize, j: usize, v: C64| {
rows.push(i);
cols.push(j);
values.push(v);
if i != j {
let mirrored = match symmetry {
MmSymmetry::General => return,
MmSymmetry::Symmetric => v,
MmSymmetry::SkewSymmetric => -v,
MmSymmetry::Hermitian => v.conj(),
};
rows.push(j);
cols.push(i);
values.push(mirrored);
}
};
match format {
MmFormat::Coordinate => {
for _ in 0..size[2] {
let i = next_f64("Matrix Market: missing row index")?;
let j = next_f64("Matrix Market: missing column index")?;
if !(i >= 1.0 && j >= 1.0 && i <= nrows as f64 && j <= ncols as f64 && i.fract() == 0.0 && j.fract() == 0.0) {
return Err(bad("Matrix Market: an index is out of range"));
}
let v = value(&mut next_f64)?;
push(i as usize - 1, j as usize - 1, v);
}
}
MmFormat::Array => {
for j in 0..ncols {
let start = match symmetry {
MmSymmetry::General => 0,
MmSymmetry::SkewSymmetric => j + 1,
_ => j,
};
for i in start..nrows {
let v = value(&mut next_f64)?;
push(i, j, v);
}
if symmetry == MmSymmetry::SkewSymmetric {
push(j, j, C64::new(0.0, 0.0));
}
}
}
}
Ok(MatrixMarket { nrows, ncols, format, field, symmetry, rows, cols, values, comment })
}
- The readers take bytes or text, and the writers return them, so they work in memory.
read_*_fileandwrite_*_filewrap them for files. - Matrix Market and Harwell-Boeing matrices come back as triplets or compressed sparse columns, ready for the library’s sparse matrices.
- MATLAB numeric data are returned as
f64with their class recorded. Values of 64-bit integers beyond lose precision. Level-4 variables come back as the sameMatValueas level-5 ones, andmat_decode_anychooses the reader bymat_version.mat4_encode_big_endianwrites the other byte order. The writer of level 4 refuses what level 4 cannot hold: logical arrays, integers other than 32-bit, 16-bit, unsigned 16-bit and unsigned bytes, cells, structures and arrays of more than two dimensions. idl_decodereturns each variable as anIdlValue: numbers (asf64, with the IDL type recorded; 64-bit integers beyond lose precision), strings, structure arrays and, for arrays of pointers, the targets. Arrays have NumPy’s shape. Pointers are resolved, and a pointer cycle is an error. Variable names keep their case, andIdlSave::getignores it, as IDL does.- The IDL reader skips record types it does not use (
COMPILED,PROMOTE64,SYSTEM_VARIABLE,COMMON) by their next-record offsets, where SciPy fails on some of them. It stops with an error, never a panic, on truncated or damaged files. hdf5_decodereturns the tree of groups and datasets with their attributes; each dataset is anH5ArrayofH5Values in row-major order with its shape andH5Type. It reads superblock versions 0 to 3, object headers of versions 1 and 2, symbol-table and link-message groups, compact, contiguous and chunked storage (version 1 B-tree, and since 2.37 the chunk indexes of layout version 4, since 2.47 also extensible arrays and layout version 5), the deflate, shuffle, Fletcher-32 and LZF filters, datatypes committed to the file, array datatypes, fill values for chunks and datasets that were never written, integers and floats of any size and byte order, strings (fixed and variable length), enumerations, compounds, references and variable-length sequences.mat_decode_anynow reads v7.3 files, with the sameMatValues as the other levels, andnetcdf4_decodereturns the classicNetCdf(types NetCDF-3 lacks are widened tof64; variables in groups below the root are listed asgroup/name, and an unlimited dimension has lengthNone, withnumrecsits current length). A structure’s fields come in MATLAB’s order, from the attributeMATLAB_fields.- Not supported:
- HDF5 external and virtual datasets, the shared message heap, filtered fractal heaps, the SZIP, N-bit and scale-offset filters (and the third-party ones such as Blosc and bzip2) and writing; these give an error naming the feature, and datasets over 4 GiB are refused as too large to read into memory;
- MATLAB v7.3 function handles, objects and tables;
- complex and elemental Harwell-Boeing matrices;
- sparse ARFF rows;
- writing IDL
.savfiles (SciPy cannot either), and IDL system variables.
In practice
The files were written by SciPy 1.17.1 with book/generator/data/make_io_refs.py, read by the library, written again by the library, and read back by SciPy. IDL has no writer, so its row is the other kind of test: the library and readsav both read the 47 .sav files of SciPy’s test suite, and everything they return, flattened into a list of numbers, must agree bit for bit (book/generator/data/make_idl_refs.py):
Table 26.12. File exchange with `scipy.io` in both directions.
| Format | Contents | Library reads SciPy’s file | SciPy reads the library’s file |
|---|---|---|---|
| Matrix Market, coordinate real general | 30 × 20, 60 entries | yes | yes |
| Matrix Market, coordinate real symmetric | 12 × 12, lower triangle stored | yes | yes |
| Matrix Market, array real general | 4 × 5 dense | yes | yes |
| Matrix Market, coordinate complex general | 6 × 6 | yes | yes |
| Harwell-Boeing (RUA) | 30 × 20, 60 entries | yes | yes |
| MATLAB level 5 | 9 variables: double, complex, int16, logical, char, sparse, cell, struct, 3-D | yes | yes |
| MATLAB level 5, compressed | 9 variables: double, complex, int16, logical, char, sparse, cell, struct, 3-D | yes | yes |
| MATLAB level 4 | 7 variables: double, complex, int16, single, char, real and complex sparse | yes | yes |
| IDL save file | SciPy’s 47 test files: scalars of every type, arrays to 8-D, strings, structures, pointers, compressed | 47 of 47 identical to readsav | (SciPy has no writer) |
| HDF5 (h5py, netCDF4) | Numeric datasets: contiguous, chunked with deflate and shuffle (old and new chunk indexes), big-endian, scalar, nested groups, dense links, NetCDF-4 | 56 of 56 identical to h5py | (read-only) |
NumPy .npz (savez, savez_compressed, data descriptors, big-endian, Fortran order, half precision) | 5 archives, 20 members | 20 of 20 members identical to what numpy.load returns | yes (stored); yes (deflated); yes (ZIP64 records) |
| NetCDF-3 classic | unlimited dimension, 3 record and 1 fixed variable, attributes | yes | yes |
| Fortran unformatted, 4-byte markers | 3 records: int32, float64, float32 | yes | yes |
| ARFF | 5 attributes (nominal and numeric), missing values | yes | (SciPy has no writer) |
Every value survives both directions exactly: floating-point numbers are written in binary, or as text with enough digits to read back the same value. SciPy reads MATLAB logical arrays as uint8 whether the library or SciPy wrote them. For level 4 the agreement goes further than values: writing back the variables read from SciPy’s file gives SciPy’s bytes. The IDL test files cover every scalar type, arrays of one to eight dimensions, strings, structures with arrays and nested structures in one and three dimensions, an inherited structure, scalar and array pointers (including null and dangling ones), and a compressed file with several variables.
Strengths
- Pure Rust readers and writers, with no HDF5, NetCDF or MATLAB libraries.
- Symmetric Matrix Market and Harwell-Boeing files are expanded on reading, and symmetric matrices can be written in half the space.
- MAT-files of level 4 or 5, in either byte order, compressed or not, with nested cells and structures, and a reader for IDL save files that agrees with SciPy’s on all of SciPy’s test files.
Weaknesses
- Whole files are read into memory; there is no memory mapping or partial reading of large NetCDF variables.
- The HDF5 reader is read-only. It covers the layouts that MATLAB, h5py and netCDF4 write by default, dense links and attributes (2.37), the chunk indexes of layout version 4 (single chunk, implicit, fixed array, version 2 B-tree) and, since 2.47, extensible arrays (the index of datasets that can grow along one dimension, with their paged data blocks, checked on 131 500 one-element chunks and on files with the unlimited dimension first and last) and layout version 5, which HDF5 2.0 writes for chunks over 4 GiB (it is version 4 with wider dimension sizes). Chunks that were never written read as the dataset’s fill value. The MATLAB v7.3 mapping was checked on files with MATLAB’s layout written by h5py and on two files written by MATLAB itself (from the matio project’s test data: nested structures, structure arrays, cells, sparse and character arrays). NOAA’s ERSSTv5 NetCDF-4 file (ten million chunked, deflated values) and three NetCDF-3 files from xarray’s data repository give the same sums as netCDF4.
- No IDL
.savwriter, and no IDL files with system variables. - Level-4 writing is little-endian only, and level-4 reading refuses the VAX and Cray byte orders.
Exercises
- How many entries does the
arrayformat store for a symmetric matrix, and for a skew-symmetric one? - Why can a NetCDF file grow along the unlimited dimension without rewriting the variables already written?
- A MAT-file element of type
miDOUBLEholds 12 bytes. How many bytes does it occupy in the file? - Why does a Fortran unformatted record carry its length at both ends?
- A level-4 file starts with the bytes
00 00 03 e8. In which byte order is it written, and what is its first variable? - Why does a
BYTEarray of 5 elements occupy 12 bytes in an IDL save file, and a scalarINTfour?
Hints and answers
- , the lower triangle with the diagonal, and for skew-symmetric matrices, whose diagonal is zero.
- Records are stored after all fixed-size data, and each new record appends one slab of every record variable at the end of the file. Only the record count in the header changes.
- 8 bytes of tag plus 12 bytes of data padded to 16: 24 bytes.
- So that a program can
BACKSPACE: from the trailing marker it can find the start of the record it has just read. - Read as a little-endian integer the first four bytes give , which is negative (), so the file is big-endian: . That is (big-endian), , (double) and (a full matrix).
- Everything in the file is padded to 32 bits. A scalar
INTsits in the low half of a 32-bit word. A byte array stores its byte count as a 32-bit word and then its bytes, padded to a multiple of four: 4 + 8 = 12.
Further reading
- R. F. Boisvert, R. Pozo and K. A. Remington, The Matrix Market Exchange Formats: Initial Design, NIST report NISTIR 5935 (1996).
- I. S. Duff, R. G. Grimes and J. G. Lewis, “Sparse matrix test problems”, ACM Transactions on Mathematical Software 15 (1989) 1–14.
- The MathWorks, MAT-File Format, version 7 (2023).
- C. Markwardt, Unofficial Format Specification of the IDL SAVE File (cow.physics.wisc.edu/~craigm/idl/savefmt); T. P. Robitaille,
idlsave(2010), nowscipy.io.readsav. - The MathWorks, MATLAB 4 MAT-file Format (Application Program Interface Guide, level-4 section).
- R. Rew and G. Davis, “NetCDF: an interface for scientific data access”, IEEE Computer Graphics and Applications 10 (1990) 76–82; Unidata, The NetCDF Classic Format Specification.
- T. A. Davis and Y. Hu, “The University of Florida sparse matrix collection”, ACM Transactions on Mathematical Software 38 (2011) 1:1–1:25.