Skip to main content

grib/def/grib2/
template5.rs

1use grib_template_derive::{Dump, TryFromSlice, WriteToBuffer};
2
3use super::table5;
4
5/// Data representation template 5.0 - Grid point data - simple packing.
6#[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
7pub struct Template5_0 {
8    pub simple: param_set::SimplePacking,
9    pub orig_field_type: table5::OriginalFieldValueType,
10}
11
12/// Data representation template 5.1 - Matrix value at grid point - simple
13/// packing.
14#[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
15pub struct Template5_1 {
16    pub simple: param_set::SimplePacking,
17    pub orig_field_type: table5::OriginalFieldValueType,
18    /// 0, no matrix bit maps present; 1-matrix bit maps present.
19    pub matrix_bitmap_present: u8,
20    /// Number of data values encoded in Section 7.
21    pub num_encoded_vals: u32,
22    /// NR - first dimension (rows) of each matrix.
23    pub num_dim_1: u16,
24    /// NC - second dimension (columns) of each matrix.
25    pub num_dim_2: u16,
26    /// First dimension coordinate value definition (Code table 5.2).
27    pub dim_1_coord_def: table5::MatrixCoordinateValueFuncDefinition,
28    /// NC1 - number of coefficients or values used to specify first dimension
29    /// coordinate function.
30    pub num_dim_1_coeffs: u8,
31    /// Second dimension coordinate value definition (Code table 5.2).
32    pub dim_2_coord_def: table5::MatrixCoordinateValueFuncDefinition,
33    /// NC2 - number of coefficients or values used to specify second dimension
34    /// coordinate function.
35    pub num_dim_2_coeffs: u8,
36    /// First dimension physical significance (Code table 5.3).
37    pub dim_1_significance: table5::MatrixCoordinateParam,
38    /// Second dimension physical significance (Code table 5.3).
39    pub dim_2_significance: table5::MatrixCoordinateParam,
40    /// Coefficients to define first dimension coordinate values in functional
41    /// form, or the explicit coordinate values (IEEE 32-bit floating-point
42    /// value).
43    #[grib_template(len = "num_dim_1_coeffs")]
44    pub dim_1_coeffs: Vec<f32>,
45    /// Coefficients to define second dimension coordinate values in functional
46    /// form, or the explicit coordinate values (IEEE 32-bit floating-point
47    /// value).
48    #[grib_template(len = "num_dim_2_coeffs")]
49    pub dim_2_coeffs: Vec<f32>,
50}
51
52/// Data representation template 5.2 - Grid point data - complex packing.
53#[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
54pub struct Template5_2 {
55    pub simple: param_set::SimplePacking,
56    pub orig_field_type: table5::OriginalFieldValueType,
57    pub complex: param_set::ComplexPacking,
58}
59
60/// Data representation template 5.3 - Grid point data - complex packing and
61/// spatial differencing.
62#[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
63pub struct Template5_3 {
64    pub simple: param_set::SimplePacking,
65    pub orig_field_type: table5::OriginalFieldValueType,
66    pub complex: param_set::ComplexPacking,
67    pub spatial_diff_order: table5::SpatialDifferencingOrder,
68    /// Number of octets required in the data section to specify extra
69    /// descriptors needed for spatial differencing (octets 6-ww in data
70    /// template 7.3).
71    pub num_extra_desc_octets: u8,
72}
73
74/// Data representation template 5.4 - Grid point data - IEEE floating point
75/// data.
76#[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
77pub struct Template5_4 {
78    pub precision: table5::FloatPrecision,
79}
80
81/// Data representation template 5.40 - Grid point data - JPEG 2000 code stream
82/// format.
83#[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
84pub struct Template5_40 {
85    pub simple: param_set::SimplePacking,
86    pub orig_field_type: table5::OriginalFieldValueType,
87    pub compression_type: table5::CompressionType,
88    /// Target compression ratio, M:1 (with respect to the bit-depth specified
89    /// in octet 20), when octet 22 indicates lossy compression. Otherwise, set
90    /// to missing (see Note 3).
91    pub compression_ratio: u8,
92}
93
94/// Data representation template 5.41 - Grid point data - Portable Network
95/// Graphics (PNG).
96#[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
97pub struct Template5_41 {
98    pub simple: param_set::SimplePacking,
99    pub orig_field_type: table5::OriginalFieldValueType,
100}
101
102/// Data representation template 5.42 - Grid point data - CCSDS recommended
103/// lossless compression.
104#[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
105pub struct Template5_42 {
106    pub simple: param_set::SimplePacking,
107    pub orig_field_type: table5::OriginalFieldValueType,
108    /// CCSDS compression options mask (see Note 3).
109    pub mask: u8,
110    /// Block size.
111    pub block_size: u8,
112    /// Reference sample interval.
113    pub ref_sample_interval: u16,
114}
115
116/// Data representation template 5.50 - Spectral data - simple packing.
117#[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
118pub struct Template5_50 {
119    pub simple: param_set::SimplePacking,
120    /// Real part of (0.0) coefficient (IEEE 32-bit floating-point value).
121    pub real_part_zero: f32,
122}
123
124/// Data representation template 5.51 - Spherical harmonics data - complex
125/// packing.
126#[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
127pub struct Template5_51 {
128    pub simple: param_set::SimplePacking,
129    /// P - Laplacian scaling factor (expressed in 10-6 units).
130    pub p: i32,
131    /// JS - pentagonal resolution parameter of the unpacked subset (see Note
132    /// 1).
133    pub js: u16,
134    /// KS - pentagonal resolution parameter of the unpacked subset (see Note
135    /// 1).
136    pub ks: u16,
137    /// MS - pentagonal resolution parameter of the unpacked subset (see Note
138    /// 1).
139    pub ms: u16,
140    /// TS - total number of values in the unpacked subset (see Note 1).
141    pub ts: u32,
142    /// Precision of the unpacked subset (see Code table 5.7).
143    pub precision: table5::FloatPrecision,
144}
145
146/// Data representation template 5.53 - Spectral data for limited area models -
147/// complex packing.
148#[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
149pub struct Template5_53 {
150    pub simple: param_set::SimplePacking,
151    pub bi_fourier_subtrunc_type: table5::BiFourierSubtruncationType,
152    pub bi_fourier_pack_mode: table5::BiFourierPackMode,
153    /// P - Laplacian scaling factor (expressed in 10-6 units).
154    pub p: i32,
155    /// NS - bi-Fourier resolution parameter of the unpacked subset (see Note
156    /// 1).
157    pub ns: u16,
158    /// MS - bi-Fourier resolution parameter of the unpacked subset (see Note
159    /// 1).
160    pub ms: u16,
161    /// TS - total number of values in the unpacked subset (see Note 1).
162    pub ts: u32,
163    /// Precision of the unpacked subset (see Code table 5.7).
164    pub precision: table5::FloatPrecision,
165}
166
167/// Data representation template 5.61 - Grid point data - simple packing with
168/// logarithm pre-processing.
169#[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
170pub struct Template5_61 {
171    pub simple: param_set::SimplePacking,
172    /// Pre-processing parameter (B) (IEEE 32-bit floating-point value).
173    pub preprocess_param: f32,
174}
175
176/// Data representation template 5.200 - Run length packing with level values.
177#[derive(Debug, PartialEq, Eq, Clone, TryFromSlice, WriteToBuffer, Dump)]
178pub struct Template5_200 {
179    /// Number of bits used for each packed value in the run length packing with
180    /// level value.
181    pub num_bits: u8,
182    /// MV - maximum value within the levels that are used in the packing.
183    pub max_val: u16,
184    /// MVL - maximum value of level (predefined).
185    pub max_level: u16,
186    /// Decimal scale factor of representative value of each level.
187    pub dec: u8,
188    /// List of MVL scaled representative values of each level from lv=1 to MVL.
189    #[grib_template(len = "max_level")]
190    pub level_vals: Vec<u16>,
191}
192
193/// Data representation template 5.50002 - Second order packing.
194///
195/// This local template is defined by Météo-France.
196///
197/// # Examples
198///
199/// ```
200/// use std::io::Read;
201///
202/// use grib::{
203///     TryFromSlice,
204///     def::grib2::{
205///         table,
206///         template::{Template5_50002, Template5_50002Optional, param_set},
207///     },
208/// };
209///
210/// fn main() -> Result<(), Box<dyn std::error::Error>> {
211///     let mut buf = Vec::new();
212///
213///     let f = std::fs::File::open("testdata/constant-polyn0025.grib2")?;
214///     let mut f = std::io::BufReader::new(f);
215///     f.read_to_end(&mut buf)?;
216///
217///     let mut pos = 0x9a;
218///     let actual = Template5_50002::try_from_slice(&buf, &mut pos)?;
219///     let expected = Template5_50002 {
220///         simple: param_set::SimplePacking {
221///             ref_val: -0.46913582,
222///             exp: -13,
223///             dec: 0,
224///             num_bits: 24,
225///         },
226///         first_order_values_width: 23,
227///         num_groups: 379,
228///         second_order_packed_values_width: 264145,
229///         widths_width: 5,
230///         widths_len: 14,
231///         ordering_flags: table::OrderingFlags(0b00000000),
232///         spd_order: 2,
233///         optional: Some(Template5_50002Optional {
234///             num_spd_width_bits: 24,
235///         }),
236///     };
237///     assert_eq!(actual, expected);
238///
239///     Ok(())
240/// }
241/// ```
242#[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
243pub struct Template5_50002 {
244    pub simple: param_set::SimplePacking,
245    /// Width of first order values.
246    pub first_order_values_width: u8,
247    /// Number of groups.
248    pub num_groups: u32,
249    /// Number of second order packed values.
250    pub second_order_packed_values_width: u32,
251    /// Width of widths.
252    pub widths_width: u8,
253    /// Width of lengths.
254    pub widths_len: u8,
255    pub ordering_flags: table5::OrderingFlags,
256    /// Order of spatial differencing.
257    pub spd_order: u8,
258    pub optional: Option<Template5_50002Optional>,
259}
260
261#[derive(Debug, PartialEq, Eq, Clone, TryFromSlice, WriteToBuffer, Dump)]
262pub struct Template5_50002Optional {
263    /// Width of spatial differencing.
264    pub num_spd_width_bits: u8,
265}
266
267pub(crate) mod param_set {
268    use grib_template_derive::{Dump, TryFromSlice, WriteToBuffer};
269
270    use super::super::table5;
271
272    #[derive(Debug, PartialEq, Clone, TryFromSlice, WriteToBuffer, Dump)]
273    pub struct SimplePacking {
274        /// Reference value (R) (IEEE 32-bit floating-point value).
275        pub ref_val: f32,
276        /// Binary scale factor (E).
277        pub exp: i16,
278        /// Decimal scale factor (D).
279        pub dec: i16,
280        /// Number of bits used for each packed value for simple packing, or for
281        /// each group reference value for complex packing or spatial
282        /// differencing.
283        pub num_bits: u8,
284    }
285
286    impl SimplePacking {
287        pub(crate) fn zero_bit_reference_value(&self) -> f32 {
288            // Apply decimal scaling as wgrib2's internal decoder does with
289            // `-g2clib 0` (see unpk_grib's `nbits == 0` branch):
290            // https://github.com/NOAA-EMC/wgrib2/blob/develop/src/unpk.c
291            // ecCodes instead returns the reference value directly when
292            // `bits_per_value == 0` (see `DataSimplePacking::unpack`):
293            // https://github.com/ecmwf/eccodes/blob/develop/src/eccodes/accessor/DataSimplePacking.cc
294            // The distinction from g2clib emulation is documented here:
295            // https://www.cpc.ncep.noaa.gov/products/wesley/wgrib2/g2clib.html
296            self.ref_val * 10_f32.powi(-i32::from(self.dec))
297        }
298    }
299
300    #[derive(Debug, PartialEq, Eq, Clone, TryFromSlice, WriteToBuffer, Dump)]
301    pub struct ComplexPacking {
302        pub group_splitting_method: table5::GroupSplittingMethod,
303        pub missing_value_management: table5::ComplexPackingMissingValueManagement,
304        /// Primary missing value substitute.
305        pub primary_missing_value: u32,
306        /// Secondary missing value substitute.
307        pub secondary_missing_value: u32,
308        /// NG - number of groups of data values into which field is split.
309        pub num_groups: u32,
310        /// Reference for group widths (see Note 12).
311        pub group_width_ref: u8,
312        /// Number of bits used for the group widths (after the reference value
313        /// in octet 36 has been removed).
314        pub num_group_width_bits: u8,
315        /// Reference for group lengths (see Note 13).
316        pub group_len_ref: u32,
317        /// Length increment for the group lengths (see Note 14).
318        pub group_len_inc: u8,
319        /// True length of last group.
320        pub group_len_last: u32,
321        /// Number of bits used for the scaled group lengths (after subtraction
322        /// of the reference value given in octets 38-41 and division by
323        /// the length increment given in octet 42).
324        pub num_group_len_bits: u8,
325    }
326}