Skip to main content

lib_jsl_file_io/
netcdf.rs

1//! NetCDF-3 files, classic and 64-bit offset (SciPy's `io.netcdf_file`).
2//!
3//! A NetCDF-3 file is big-endian: the magic `CDF` and a version byte (1 classic, 2 with 64-bit
4//! offsets), the number of records, then lists of dimensions (one may be unlimited, the record
5//! dimension), global attributes and variables (name, dimensions, attributes, type, size and the
6//! offset of the data). Fixed-size variables are stored one after another; variables along the
7//! record dimension are interleaved record by record. Types are bytes, characters, 16- and
8//! 32-bit integers and 32- and 64-bit floats.
9//!
10//! See the book entry [Scientific data files](https://jwkunz.github.io/lib_jsl/book/foundations/scientific-files.html#netcdf-3).
11
12use lib_jsl_core::ErrorsJSL;
13use std::path::Path;
14
15/// Values of one NetCDF type, in C order.
16#[derive(Clone, Debug, PartialEq)]
17#[non_exhaustive]
18pub enum NcValue {
19    Byte(Vec<i8>),
20    Char(String),
21    Short(Vec<i16>),
22    Int(Vec<i32>),
23    Float(Vec<f32>),
24    Double(Vec<f64>),
25}
26
27impl NcValue {
28    fn type_code(&self) -> u32 {
29        match self {
30            NcValue::Byte(_) => 1,
31            NcValue::Char(_) => 2,
32            NcValue::Short(_) => 3,
33            NcValue::Int(_) => 4,
34            NcValue::Float(_) => 5,
35            NcValue::Double(_) => 6,
36        }
37    }
38
39    /// The number of elements (bytes, for characters).
40    pub fn len(&self) -> usize {
41        match self {
42            NcValue::Byte(v) => v.len(),
43            NcValue::Char(s) => s.len(),
44            NcValue::Short(v) => v.len(),
45            NcValue::Int(v) => v.len(),
46            NcValue::Float(v) => v.len(),
47            NcValue::Double(v) => v.len(),
48        }
49    }
50
51    pub fn is_empty(&self) -> bool {
52        self.len() == 0
53    }
54
55    /// The values as `f64` (characters as their byte values).
56    pub fn to_f64(&self) -> Vec<f64> {
57        match self {
58            NcValue::Byte(v) => v.iter().map(|&x| x as f64).collect(),
59            NcValue::Char(s) => s.bytes().map(|b| b as f64).collect(),
60            NcValue::Short(v) => v.iter().map(|&x| x as f64).collect(),
61            NcValue::Int(v) => v.iter().map(|&x| x as f64).collect(),
62            NcValue::Float(v) => v.iter().map(|&x| x as f64).collect(),
63            NcValue::Double(v) => v.clone(),
64        }
65    }
66
67    fn encode(&self) -> Vec<u8> {
68        match self {
69            NcValue::Byte(v) => v.iter().map(|&x| x as u8).collect(),
70            NcValue::Char(s) => s.as_bytes().to_vec(),
71            NcValue::Short(v) => v.iter().flat_map(|x| x.to_be_bytes()).collect(),
72            NcValue::Int(v) => v.iter().flat_map(|x| x.to_be_bytes()).collect(),
73            NcValue::Float(v) => v.iter().flat_map(|x| x.to_be_bytes()).collect(),
74            NcValue::Double(v) => v.iter().flat_map(|x| x.to_be_bytes()).collect(),
75        }
76    }
77
78    fn element_size(code: u32) -> Option<usize> {
79        Some(match code {
80            1 | 2 => 1,
81            3 => 2,
82            4 | 5 => 4,
83            6 => 8,
84            _ => return None,
85        })
86    }
87
88    fn decode(code: u32, b: &[u8]) -> Result<NcValue, ErrorsJSL> {
89        Ok(match code {
90            1 => NcValue::Byte(b.iter().map(|&x| x as i8).collect()),
91            2 => NcValue::Char(String::from_utf8_lossy(b).into_owned()),
92            3 => NcValue::Short(b.chunks_exact(2).map(|c| i16::from_be_bytes([c[0], c[1]])).collect()),
93            4 => NcValue::Int(b.chunks_exact(4).map(|c| i32::from_be_bytes(c.try_into().expect("4 bytes"))).collect()),
94            5 => NcValue::Float(b.chunks_exact(4).map(|c| f32::from_be_bytes(c.try_into().expect("4 bytes"))).collect()),
95            6 => NcValue::Double(b.chunks_exact(8).map(|c| f64::from_be_bytes(c.try_into().expect("8 bytes"))).collect()),
96            _ => return Err(bad("NetCDF: unknown type")),
97        })
98    }
99
100    fn empty_like(code: u32) -> NcValue {
101        NcValue::decode(code, &[]).expect("valid code")
102    }
103
104    fn append(&mut self, other: NcValue) {
105        match (self, other) {
106            (NcValue::Byte(a), NcValue::Byte(b)) => a.extend(b),
107            (NcValue::Char(a), NcValue::Char(b)) => a.push_str(&b),
108            (NcValue::Short(a), NcValue::Short(b)) => a.extend(b),
109            (NcValue::Int(a), NcValue::Int(b)) => a.extend(b),
110            (NcValue::Float(a), NcValue::Float(b)) => a.extend(b),
111            (NcValue::Double(a), NcValue::Double(b)) => a.extend(b),
112            _ => unreachable!("record slabs share their variable's type"),
113        }
114    }
115}
116
117/// A variable: its dimensions (indices into the file's dimension list), attributes and data in
118/// C order (the record dimension, if any, first).
119#[derive(Clone, Debug, PartialEq)]
120#[non_exhaustive]
121pub struct NcVariable {
122    pub name: String,
123    pub dims: Vec<usize>,
124    pub attributes: Vec<(String, NcValue)>,
125    pub data: NcValue,
126}
127
128impl NcVariable {
129    pub fn new(name: &str, dims: Vec<usize>, data: NcValue) -> Self {
130        NcVariable { name: name.to_string(), dims, attributes: Vec::new(), data }
131    }
132
133    pub fn with_attribute(mut self, name: &str, value: NcValue) -> Self {
134        self.attributes.push((name.to_string(), value));
135        self
136    }
137}
138
139/// The contents of a NetCDF-3 file.
140#[derive(Clone, Debug, PartialEq, Default)]
141#[non_exhaustive]
142pub struct NetCdf {
143    /// Dimension names and lengths; `None` for the unlimited (record) dimension.
144    pub dimensions: Vec<(String, Option<usize>)>,
145    pub attributes: Vec<(String, NcValue)>,
146    pub variables: Vec<NcVariable>,
147    /// The number of records along the unlimited dimension.
148    pub numrecs: usize,
149    /// 1 for the classic format, 2 for 64-bit offsets.
150    pub version: u8,
151}
152
153impl NetCdf {
154    pub fn new() -> Self {
155        NetCdf { version: 1, ..Default::default() }
156    }
157
158    pub fn with_dimension(mut self, name: &str, length: Option<usize>) -> Self {
159        self.dimensions.push((name.to_string(), length));
160        self
161    }
162
163    pub fn with_attribute(mut self, name: &str, value: NcValue) -> Self {
164        self.attributes.push((name.to_string(), value));
165        self
166    }
167
168    /// Adds a variable; along the unlimited dimension the number of records follows its data.
169    pub fn with_variable(mut self, v: NcVariable) -> Self {
170        self.variables.push(v);
171        self
172    }
173
174    /// The variable with this name.
175    pub fn variable(&self, name: &str) -> Option<&NcVariable> {
176        self.variables.iter().find(|v| v.name == name)
177    }
178
179    /// The lengths of a variable's dimensions (the record dimension as `numrecs`).
180    pub fn shape(&self, v: &NcVariable) -> Vec<usize> {
181        v.dims.iter().map(|&d| self.dimensions[d].1.unwrap_or(self.numrecs)).collect()
182    }
183}
184
185fn bad(msg: &'static str) -> ErrorsJSL {
186    ErrorsJSL::InvalidInputRange(msg)
187}
188
189struct Cursor<'a> {
190    b: &'a [u8],
191    pos: usize,
192}
193
194impl Cursor<'_> {
195    fn take(&mut self, n: usize) -> Result<&[u8], ErrorsJSL> {
196        let s = self.b.get(self.pos..self.pos + n).ok_or(bad("NetCDF: truncated header"))?;
197        self.pos += n;
198        Ok(s)
199    }
200    fn u32(&mut self) -> Result<u32, ErrorsJSL> {
201        Ok(u32::from_be_bytes(self.take(4)?.try_into().expect("4 bytes")))
202    }
203    fn u64(&mut self) -> Result<u64, ErrorsJSL> {
204        Ok(u64::from_be_bytes(self.take(8)?.try_into().expect("8 bytes")))
205    }
206    fn name(&mut self) -> Result<String, ErrorsJSL> {
207        let n = self.u32()? as usize;
208        let s = String::from_utf8_lossy(self.take(n)?).into_owned();
209        self.take((4 - n % 4) % 4)?;
210        Ok(s)
211    }
212    fn attributes(&mut self) -> Result<Vec<(String, NcValue)>, ErrorsJSL> {
213        let tag = self.u32()?;
214        let n = self.u32()? as usize;
215        if tag == 0 {
216            return Ok(Vec::new());
217        }
218        if tag != 0x0C {
219            return Err(bad("NetCDF: expected an attribute list"));
220        }
221        let mut out = Vec::with_capacity(n);
222        for _ in 0..n {
223            let name = self.name()?;
224            let ty = self.u32()?;
225            let count = self.u32()? as usize;
226            let size = NcValue::element_size(ty).ok_or(bad("NetCDF: unknown attribute type"))? * count;
227            let v = NcValue::decode(ty, self.take(size)?)?;
228            self.take((4 - size % 4) % 4)?;
229            out.push((name, v));
230        }
231        Ok(out)
232    }
233}
234
235// ANCHOR: netcdf_decode
236/// Parses a NetCDF-3 file (SciPy's `netcdf_file(..., "r")`), classic or 64-bit offset.
237pub fn netcdf_decode(bytes: &[u8]) -> Result<NetCdf, ErrorsJSL> {
238    let mut c = Cursor { b: bytes, pos: 0 };
239    let magic = c.take(4)?;
240    if &magic[..3] != b"CDF" || !matches!(magic[3], 1 | 2) {
241        return Err(bad("NetCDF: not a NetCDF-3 file (NetCDF-4 files are HDF5)"));
242    }
243    let version = magic[3];
244    let numrecs_raw = c.u32()?;
245    let tag = c.u32()?;
246    let ndims = c.u32()? as usize;
247    if tag != 0 && tag != 0x0A {
248        return Err(bad("NetCDF: expected a dimension list"));
249    }
250    let mut dimensions = Vec::with_capacity(ndims);
251    for _ in 0..ndims {
252        let name = c.name()?;
253        let len = c.u32()? as usize;
254        dimensions.push((name, if len == 0 { None } else { Some(len) }));
255    }
256    let attributes = c.attributes()?;
257    let tag = c.u32()?;
258    let nvars = c.u32()? as usize;
259    if tag != 0 && tag != 0x0B {
260        return Err(bad("NetCDF: expected a variable list"));
261    }
262    struct Raw {
263        name: String,
264        dims: Vec<usize>,
265        attributes: Vec<(String, NcValue)>,
266        ty: u32,
267        vsize: usize,
268        begin: usize,
269    }
270    let mut raws = Vec::with_capacity(nvars);
271    for _ in 0..nvars {
272        let name = c.name()?;
273        let nd = c.u32()? as usize;
274        let dims: Vec<usize> = (0..nd).map(|_| c.u32().map(|d| d as usize)).collect::<Result<_, _>>()?;
275        if dims.iter().any(|&d| d >= dimensions.len()) {
276            return Err(bad("NetCDF: a variable refers to an unknown dimension"));
277        }
278        let attributes = c.attributes()?;
279        let ty = c.u32()?;
280        let vsize = c.u32()? as usize;
281        let begin = if version == 1 { c.u32()? as usize } else { c.u64()? as usize };
282        raws.push(Raw { name, dims, attributes, ty, vsize, begin });
283    }
284    let is_record = |r: &Raw| r.dims.first().is_some_and(|&d| dimensions[d].1.is_none());
285    let rec_vars: Vec<usize> = (0..raws.len()).filter(|&i| is_record(&raws[i])).collect();
286    // The stride between records: the sum of the record variables' sizes, unpadded when there
287    // is only one record variable.
288    let recsize: usize = rec_vars.iter().map(|&i| raws[i].vsize).sum();
289    let numrecs = if numrecs_raw == u32::MAX {
290        // Streaming: infer the count from the file length.
291        match rec_vars.first() {
292            Some(&i) if recsize > 0 => (bytes.len().saturating_sub(raws[i].begin)) / recsize,
293            _ => 0,
294        }
295    } else {
296        numrecs_raw as usize
297    };
298    let mut variables = Vec::with_capacity(raws.len());
299    for r in &raws {
300        let size = NcValue::element_size(r.ty).ok_or(bad("NetCDF: unknown variable type"))?;
301        let per: usize = r.dims.iter().filter(|&&d| dimensions[d].1.is_some()).map(|&d| dimensions[d].1.expect("fixed")).product();
302        let nbytes = per * size;
303        let data = if is_record(r) {
304            let mut v = NcValue::empty_like(r.ty);
305            for k in 0..numrecs {
306                let at = r.begin + k * recsize;
307                let slab = bytes.get(at..at + nbytes).ok_or(bad("NetCDF: truncated record data"))?;
308                v.append(NcValue::decode(r.ty, slab)?);
309            }
310            v
311        } else {
312            NcValue::decode(r.ty, bytes.get(r.begin..r.begin + nbytes).ok_or(bad("NetCDF: truncated data"))?)?
313        };
314        variables.push(NcVariable { name: r.name.clone(), dims: r.dims.clone(), attributes: r.attributes.clone(), data });
315    }
316    Ok(NetCdf { dimensions, attributes, variables, numrecs, version })
317}
318// ANCHOR_END: netcdf_decode
319
320fn put_name(out: &mut Vec<u8>, s: &str) {
321    out.extend((s.len() as u32).to_be_bytes());
322    out.extend(s.as_bytes());
323    out.resize(out.len().next_multiple_of(4), 0);
324}
325
326fn put_attributes(out: &mut Vec<u8>, atts: &[(String, NcValue)]) {
327    if atts.is_empty() {
328        out.extend([0u8; 8]);
329        return;
330    }
331    out.extend(0x0Cu32.to_be_bytes());
332    out.extend((atts.len() as u32).to_be_bytes());
333    for (name, v) in atts {
334        put_name(out, name);
335        out.extend(v.type_code().to_be_bytes());
336        out.extend((v.len() as u32).to_be_bytes());
337        out.extend(v.encode());
338        out.resize(out.len().next_multiple_of(4), 0);
339    }
340}
341
342// ANCHOR: netcdf_encode
343/// Writes a NetCDF-3 file (SciPy's `netcdf_file(..., "w")`) in the declared version: the header,
344/// then the fixed-size variables, then the records. The number of records is taken from the
345/// record variables' data, which must agree.
346pub fn netcdf_encode(nc: &NetCdf) -> Result<Vec<u8>, ErrorsJSL> {
347    let version = if nc.version == 2 { 2 } else { 1 };
348    if nc.dimensions.iter().filter(|d| d.1.is_none()).count() > 1 {
349        return Err(bad("NetCDF: at most one unlimited dimension"));
350    }
351    let fixed = |v: &NcVariable| -> usize { v.dims.iter().filter_map(|&d| nc.dimensions[d].1).product() };
352    let is_rec = |v: &NcVariable| v.dims.first().is_some_and(|&d| nc.dimensions[d].1.is_none());
353    for v in &nc.variables {
354        if v.dims.iter().any(|&d| d >= nc.dimensions.len()) || v.dims.iter().skip(1).any(|&d| nc.dimensions[d].1.is_none()) {
355            return Err(bad("NetCDF: the unlimited dimension may only be a variable's first"));
356        }
357    }
358    // The number of records.
359    let mut numrecs = None;
360    for v in nc.variables.iter().filter(|v| is_rec(v)) {
361        let per = fixed(v);
362        if per == 0 || v.data.len() % per != 0 {
363            return Err(bad("NetCDF: record variable data is not a whole number of records"));
364        }
365        let n = v.data.len() / per;
366        if numrecs.is_some_and(|m| m != n) {
367            return Err(bad("NetCDF: record variables have different numbers of records"));
368        }
369        numrecs = Some(n);
370    }
371    let numrecs = numrecs.unwrap_or(0);
372    for v in nc.variables.iter().filter(|v| !is_rec(v)) {
373        if v.data.len() != fixed(v) {
374            return Err(bad("NetCDF: a variable's data does not match its dimensions"));
375        }
376    }
377    let size_of = |v: &NcVariable| NcValue::element_size(v.data.type_code()).expect("valid type") * fixed(v);
378    let rec_count = nc.variables.iter().filter(|v| is_rec(v)).count();
379    let vsize = |v: &NcVariable| if is_rec(v) && rec_count == 1 { size_of(v) } else { size_of(v).next_multiple_of(4) };
380    // The header, first with placeholder offsets to learn its length.
381    let header = |begins: &[usize]| -> Vec<u8> {
382        let mut out = Vec::new();
383        out.extend(b"CDF");
384        out.push(version);
385        out.extend((numrecs as u32).to_be_bytes());
386        if nc.dimensions.is_empty() {
387            out.extend([0u8; 8]);
388        } else {
389            out.extend(0x0Au32.to_be_bytes());
390            out.extend((nc.dimensions.len() as u32).to_be_bytes());
391            for (name, len) in &nc.dimensions {
392                put_name(&mut out, name);
393                out.extend((len.unwrap_or(0) as u32).to_be_bytes());
394            }
395        }
396        put_attributes(&mut out, &nc.attributes);
397        if nc.variables.is_empty() {
398            out.extend([0u8; 8]);
399        } else {
400            out.extend(0x0Bu32.to_be_bytes());
401            out.extend((nc.variables.len() as u32).to_be_bytes());
402            for (k, v) in nc.variables.iter().enumerate() {
403                put_name(&mut out, &v.name);
404                out.extend((v.dims.len() as u32).to_be_bytes());
405                for &d in &v.dims {
406                    out.extend((d as u32).to_be_bytes());
407                }
408                put_attributes(&mut out, &v.attributes);
409                out.extend(v.data.type_code().to_be_bytes());
410                out.extend((vsize(v) as u32).to_be_bytes());
411                if version == 1 {
412                    out.extend((begins[k] as u32).to_be_bytes());
413                } else {
414                    out.extend((begins[k] as u64).to_be_bytes());
415                }
416            }
417        }
418        out
419    };
420    let hlen = header(&vec![0; nc.variables.len()]).len();
421    let mut begins = vec![0usize; nc.variables.len()];
422    let mut at = hlen;
423    for (k, v) in nc.variables.iter().enumerate().filter(|(_, v)| !is_rec(v)) {
424        begins[k] = at;
425        at += vsize(v);
426    }
427    let rec_start = at;
428    let mut off = rec_start;
429    for (k, v) in nc.variables.iter().enumerate().filter(|(_, v)| is_rec(v)) {
430        begins[k] = off;
431        off += vsize(v);
432    }
433    let recsize: usize = nc.variables.iter().filter(|v| is_rec(v)).map(vsize).sum();
434    if version == 1 && rec_start + recsize * numrecs > u32::MAX as usize {
435        return Err(bad("NetCDF: too large for the classic format; use version 2"));
436    }
437    let mut out = header(&begins);
438    for v in nc.variables.iter().filter(|v| !is_rec(v)) {
439        let mut b = v.data.encode();
440        b.resize(vsize(v), 0);
441        out.extend(b);
442    }
443    let encoded: Vec<(usize, Vec<u8>, usize)> = nc.variables.iter().filter(|v| is_rec(v)).map(|v| (size_of(v), v.data.encode(), vsize(v))).collect();
444    for r in 0..numrecs {
445        for (size, bytes, vs) in &encoded {
446            let mut slab = bytes[r * size..(r + 1) * size].to_vec();
447            slab.resize(*vs, 0);
448            out.extend(slab);
449        }
450    }
451    Ok(out)
452}
453// ANCHOR_END: netcdf_encode
454
455/// Reads a NetCDF-3 file.
456pub fn read_netcdf_file(path: impl AsRef<Path>) -> Result<NetCdf, ErrorsJSL> {
457    netcdf_decode(&std::fs::read(path).map_err(|_| ErrorsJSL::RuntimeError("could not read the NetCDF file"))?)
458}
459
460/// Writes a NetCDF-3 file.
461pub fn write_netcdf_file(path: impl AsRef<Path>, nc: &NetCdf) -> Result<(), ErrorsJSL> {
462    std::fs::write(path, netcdf_encode(nc)?).map_err(|_| ErrorsJSL::RuntimeError("could not write the NetCDF file"))
463}
464
465#[cfg(test)]
466mod tests {
467    use super::*;
468
469    #[test]
470    fn round_trip_with_records() {
471        for version in [1u8, 2] {
472            let mut nc = NetCdf::new()
473                .with_dimension("time", None)
474                .with_dimension("x", Some(3))
475                .with_attribute("title", NcValue::Char("test".into()))
476                .with_variable(NcVariable::new("x", vec![1], NcValue::Double(vec![0.5, 1.5, 2.5])).with_attribute("units", NcValue::Char("m".into())))
477                .with_variable(NcVariable::new("temp", vec![0, 1], NcValue::Float(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0])))
478                .with_variable(NcVariable::new("flag", vec![0], NcValue::Short(vec![7, -8])))
479                .with_variable(NcVariable::new("b", vec![1], NcValue::Byte(vec![1, -2, 3])));
480            nc.version = version;
481            let bytes = netcdf_encode(&nc).unwrap();
482            let back = netcdf_decode(&bytes).unwrap();
483            assert_eq!(back.numrecs, 2);
484            assert_eq!(back.variables, nc.variables);
485            assert_eq!(back.attributes, nc.attributes);
486            assert_eq!(back.shape(back.variable("temp").unwrap()), vec![2, 3]);
487        }
488    }
489}