netcdf-reader 0.4.0

Pure-Rust NetCDF-3 classic and NetCDF-4 (HDF5-backed) file reader
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
//! CF axis identification.
//!
//! Determines the role of each coordinate variable (T, X, Y, Z) based on:
//! - The `axis` attribute (most explicit)
//! - The `standard_name` attribute (e.g., "latitude", "longitude", "time")
//! - The `units` attribute (e.g., "degrees_north", "degrees_east")
//! - The `positive` attribute for vertical axes
//!
//! Priority follows CF Conventions Table 1: axis > standard_name > units > positive.

use crate::types::{NcDimension, NcGroup, NcVariable};

/// The axis role of a coordinate variable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CfAxisType {
    /// Time axis.
    T,
    /// Longitude / easting axis.
    X,
    /// Latitude / northing axis.
    Y,
    /// Vertical axis.
    Z,
    /// Cannot be determined.
    Unknown,
}

/// A discovered CF axis backed by a NetCDF coordinate variable.
#[derive(Debug, Clone, Copy)]
pub struct CfCoordinateAxis<'a> {
    /// The coordinate variable carrying the CF axis metadata.
    pub variable: &'a NcVariable,
    /// The dimension represented by the coordinate variable.
    pub dimension: &'a NcDimension,
    /// The inferred CF axis type.
    pub axis_type: CfAxisType,
}

/// Identify the CF axis type of a variable.
///
/// Checks attributes in CF priority order:
/// 1. `axis` attribute ("X", "Y", "Z", "T")
/// 2. `standard_name` attribute
/// 3. `units` attribute
/// 4. `positive` attribute (vertical indicator)
pub fn identify_axis(var: &NcVariable) -> CfAxisType {
    // 1. Explicit axis attribute (highest priority)
    if let Some(attr) = var.attribute("axis") {
        if let Some(val) = attr.value.as_string() {
            match val.trim().to_uppercase().as_str() {
                "X" => return CfAxisType::X,
                "Y" => return CfAxisType::Y,
                "Z" => return CfAxisType::Z,
                "T" => return CfAxisType::T,
                _ => {}
            }
        }
    }

    // 2. standard_name attribute
    if let Some(attr) = var.attribute("standard_name") {
        if let Some(val) = attr.value.as_string() {
            match val.trim() {
                "latitude" => return CfAxisType::Y,
                "longitude" => return CfAxisType::X,
                "time" => return CfAxisType::T,
                "altitude"
                | "height"
                | "depth"
                | "air_pressure"
                | "atmosphere_hybrid_sigma_pressure_coordinate"
                | "atmosphere_ln_pressure_coordinate"
                | "atmosphere_sigma_coordinate"
                | "ocean_sigma_coordinate"
                | "ocean_s_coordinate"
                | "ocean_double_sigma_coordinate" => return CfAxisType::Z,
                "projection_x_coordinate" | "grid_longitude" => return CfAxisType::X,
                "projection_y_coordinate" | "grid_latitude" => return CfAxisType::Y,
                _ => {}
            }
        }
    }

    // 3. units attribute
    if let Some(attr) = var.attribute("units") {
        if let Some(val) = attr.value.as_string() {
            let lower = val.trim().to_lowercase();
            // Latitude units
            if matches!(
                lower.as_str(),
                "degrees_north"
                    | "degree_north"
                    | "degree_n"
                    | "degrees_n"
                    | "degreen"
                    | "degreesn"
            ) {
                return CfAxisType::Y;
            }
            // Longitude units
            if matches!(
                lower.as_str(),
                "degrees_east" | "degree_east" | "degree_e" | "degrees_e" | "degreee" | "degreese"
            ) {
                return CfAxisType::X;
            }
            // Time units (contains "since")
            if lower.contains(" since ") {
                return CfAxisType::T;
            }
            // Pressure units (common vertical)
            if matches!(
                lower.as_str(),
                "pa" | "hpa" | "mbar" | "millibar" | "bar" | "atm"
            ) {
                return CfAxisType::Z;
            }
        }
    }

    // 4. positive attribute (vertical axis indicator)
    if let Some(attr) = var.attribute("positive") {
        if let Some(val) = attr.value.as_string() {
            let lower = val.trim().to_lowercase();
            if lower == "up" || lower == "down" {
                return CfAxisType::Z;
            }
        }
    }

    CfAxisType::Unknown
}

/// Discover CF axes from coordinate variables in a group.
///
/// Only true coordinate variables are considered: one-dimensional variables
/// whose name matches their dimension name. Variables whose axis role cannot
/// be inferred are omitted.
pub fn discover_coordinate_axes(group: &NcGroup) -> Vec<CfCoordinateAxis<'_>> {
    group
        .coordinate_variables()
        .filter_map(discover_axis_for_coordinate_variable)
        .collect()
}

/// Discover CF axes used by a data variable from its coordinate variables.
///
/// The returned axes follow the variable's dimension order and are resolved
/// through the containing group.
pub fn discover_variable_axes<'a>(
    var: &NcVariable,
    group: &'a NcGroup,
) -> Vec<CfCoordinateAxis<'a>> {
    var.dimensions()
        .iter()
        .filter_map(|dim| group.coordinate_variable(&dim.name))
        .filter_map(discover_axis_for_coordinate_variable)
        .collect()
}

fn discover_axis_for_coordinate_variable(var: &NcVariable) -> Option<CfCoordinateAxis<'_>> {
    let dimension = var.coordinate_dimension()?;
    let axis_type = identify_axis(var);
    if axis_type == CfAxisType::Unknown {
        return None;
    }

    Some(CfCoordinateAxis {
        variable: var,
        dimension,
        axis_type,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{NcAttrValue, NcAttribute, NcDimension, NcType, NcVariable};

    fn make_var(attrs: Vec<NcAttribute>) -> NcVariable {
        NcVariable {
            name: "test".into(),
            dimensions: vec![],
            dtype: NcType::Float,
            attributes: attrs,
            data_offset: 0,
            _data_size: 0,
            is_record_var: false,
            record_size: 0,
        }
    }

    fn make_coordinate_var(
        name: &str,
        size: u64,
        dtype: NcType,
        attrs: Vec<NcAttribute>,
    ) -> NcVariable {
        NcVariable {
            name: name.into(),
            dimensions: vec![NcDimension {
                name: name.into(),
                size,
                is_unlimited: false,
            }],
            dtype,
            attributes: attrs,
            data_offset: 0,
            _data_size: 0,
            is_record_var: false,
            record_size: 0,
        }
    }

    fn attr(name: &str, value: &str) -> NcAttribute {
        NcAttribute {
            name: name.into(),
            value: NcAttrValue::Chars(value.into()),
        }
    }

    #[test]
    fn test_axis_attribute() {
        let var = make_var(vec![NcAttribute {
            name: "axis".into(),
            value: NcAttrValue::Chars("X".into()),
        }]);
        assert_eq!(identify_axis(&var), CfAxisType::X);
    }

    #[test]
    fn test_standard_name_latitude() {
        let var = make_var(vec![NcAttribute {
            name: "standard_name".into(),
            value: NcAttrValue::Chars("latitude".into()),
        }]);
        assert_eq!(identify_axis(&var), CfAxisType::Y);
    }

    #[test]
    fn test_standard_name_time() {
        let var = make_var(vec![NcAttribute {
            name: "standard_name".into(),
            value: NcAttrValue::Chars("time".into()),
        }]);
        assert_eq!(identify_axis(&var), CfAxisType::T);
    }

    #[test]
    fn test_units_degrees_north() {
        let var = make_var(vec![NcAttribute {
            name: "units".into(),
            value: NcAttrValue::Chars("degrees_north".into()),
        }]);
        assert_eq!(identify_axis(&var), CfAxisType::Y);
    }

    #[test]
    fn test_units_time_since() {
        let var = make_var(vec![NcAttribute {
            name: "units".into(),
            value: NcAttrValue::Chars("days since 1970-01-01".into()),
        }]);
        assert_eq!(identify_axis(&var), CfAxisType::T);
    }

    #[test]
    fn test_positive_up() {
        let var = make_var(vec![NcAttribute {
            name: "positive".into(),
            value: NcAttrValue::Chars("up".into()),
        }]);
        assert_eq!(identify_axis(&var), CfAxisType::Z);
    }

    #[test]
    fn test_unknown() {
        let var = make_var(vec![]);
        assert_eq!(identify_axis(&var), CfAxisType::Unknown);
    }

    #[test]
    fn test_axis_takes_precedence() {
        // axis="X" should win over standard_name="latitude"
        let var = make_var(vec![
            NcAttribute {
                name: "axis".into(),
                value: NcAttrValue::Chars("X".into()),
            },
            NcAttribute {
                name: "standard_name".into(),
                value: NcAttrValue::Chars("latitude".into()),
            },
        ]);
        assert_eq!(identify_axis(&var), CfAxisType::X);
    }

    #[test]
    fn test_discover_coordinate_axes_from_group() {
        let time = make_coordinate_var(
            "time",
            4,
            NcType::Double,
            vec![attr("units", "hours since 2000-01-01")],
        );
        let lat = make_coordinate_var(
            "lat",
            6,
            NcType::Double,
            vec![attr("units", "degrees_north")],
        );
        let lon = make_coordinate_var(
            "lon",
            12,
            NcType::Double,
            vec![attr("units", "degrees_east")],
        );
        let station = NcVariable {
            name: "station".into(),
            dimensions: vec![NcDimension {
                name: "obs".into(),
                size: 4,
                is_unlimited: false,
            }],
            dtype: NcType::Int,
            attributes: vec![attr("axis", "X")],
            data_offset: 0,
            _data_size: 0,
            is_record_var: false,
            record_size: 0,
        };
        let group = crate::types::NcGroup {
            name: "/".into(),
            dimensions: vec![
                time.dimensions()[0].clone(),
                lat.dimensions()[0].clone(),
                lon.dimensions()[0].clone(),
            ],
            variables: vec![time, lat, lon, station],
            attributes: vec![],
            groups: vec![],
        };

        let axes = discover_coordinate_axes(&group);
        let discovered: Vec<(&str, CfAxisType)> = axes
            .iter()
            .map(|axis| (axis.variable.name(), axis.axis_type))
            .collect();
        assert_eq!(
            discovered,
            vec![
                ("time", CfAxisType::T),
                ("lat", CfAxisType::Y),
                ("lon", CfAxisType::X)
            ]
        );
    }

    #[test]
    fn test_discover_variable_axes_follows_dimension_order() {
        let time = make_coordinate_var(
            "time",
            4,
            NcType::Double,
            vec![attr("units", "hours since 2000-01-01")],
        );
        let lat = make_coordinate_var(
            "lat",
            6,
            NcType::Double,
            vec![attr("units", "degrees_north")],
        );
        let lon = make_coordinate_var(
            "lon",
            12,
            NcType::Double,
            vec![attr("units", "degrees_east")],
        );
        let temperature = NcVariable {
            name: "temperature".into(),
            dimensions: vec![
                time.dimensions()[0].clone(),
                lat.dimensions()[0].clone(),
                lon.dimensions()[0].clone(),
            ],
            dtype: NcType::Float,
            attributes: vec![],
            data_offset: 0,
            _data_size: 0,
            is_record_var: false,
            record_size: 0,
        };
        let group = crate::types::NcGroup {
            name: "/".into(),
            dimensions: vec![
                time.dimensions()[0].clone(),
                lat.dimensions()[0].clone(),
                lon.dimensions()[0].clone(),
            ],
            variables: vec![lon, time, lat, temperature.clone()],
            attributes: vec![],
            groups: vec![],
        };

        let axes = discover_variable_axes(&temperature, &group);
        let discovered: Vec<(&str, CfAxisType)> = axes
            .iter()
            .map(|axis| (axis.dimension.name.as_str(), axis.axis_type))
            .collect();
        assert_eq!(
            discovered,
            vec![
                ("time", CfAxisType::T),
                ("lat", CfAxisType::Y),
                ("lon", CfAxisType::X)
            ]
        );
    }
}