Skip to main content

grib/
grid.rs

1#[cfg(feature = "gridpoints-proj")]
2use helpers::ProjectionLatLonIterator;
3use helpers::RegularGridIterator;
4
5pub use self::{gaussian::compute_gaussian_latitudes, rotation::Unrotate};
6use crate::{
7    GribError, GridDefinition, TryFromSlice,
8    def::grib2::{
9        table::ScanningMode,
10        template::{
11            Template3_0, Template3_1, Template3_10, Template3_20, Template3_30, Template3_40,
12            Template3_41, param_set::Grid,
13        },
14    },
15};
16
17#[derive(Debug, PartialEq)]
18#[non_exhaustive]
19pub enum GridDefinitionTemplateValues {
20    Template0(Template3_0),
21    Template1(Template3_1),
22    Template10(Template3_10),
23    Template20(Template3_20),
24    Template30(Template3_30),
25    Template40(Template3_40),
26    Template41(Template3_41),
27}
28
29impl GridShortName for GridDefinitionTemplateValues {
30    fn short_name(&self) -> &'static str {
31        match self {
32            Self::Template0(def) => def.lat_lon.short_name(),
33            Self::Template1(def) => def.short_name(),
34            Self::Template10(def) => def.short_name(),
35            Self::Template20(def) => def.short_name(),
36            Self::Template30(def) => def.short_name(),
37            Self::Template40(def) => def.gaussian.short_name(),
38            Self::Template41(def) => def.short_name(),
39        }
40    }
41}
42
43impl GridPointIndex for GridDefinitionTemplateValues {
44    fn grid_shape(&self) -> (usize, usize) {
45        match self {
46            Self::Template0(def) => def.lat_lon.grid_shape(),
47            Self::Template1(def) => def.grid_shape(),
48            Self::Template10(def) => def.grid_shape(),
49            Self::Template20(def) => def.grid_shape(),
50            Self::Template30(def) => def.grid_shape(),
51            Self::Template40(def) => def.gaussian.grid_shape(),
52            Self::Template41(def) => def.grid_shape(),
53        }
54    }
55
56    fn scanning_mode(&self) -> &ScanningMode {
57        match self {
58            Self::Template0(def) => def.lat_lon.scanning_mode(),
59            Self::Template1(def) => def.scanning_mode(),
60            Self::Template10(def) => def.scanning_mode(),
61            Self::Template20(def) => def.scanning_mode(),
62            Self::Template30(def) => def.scanning_mode(),
63            Self::Template40(def) => def.gaussian.scanning_mode(),
64            Self::Template41(def) => def.scanning_mode(),
65        }
66    }
67}
68
69impl LatLons for GridDefinitionTemplateValues {
70    type Iter<'a>
71        = GridPointLatLons
72    where
73        Self: 'a;
74
75    fn latlons_unchecked<'a>(&'a self) -> Result<Self::Iter<'a>, GribError> {
76        let iter = match self {
77            Self::Template0(def) => GridPointLatLons::from(def.lat_lon.latlons_unchecked()?),
78            Self::Template1(def) => GridPointLatLons::from(def.latlons_unchecked()?),
79            Self::Template10(def) => GridPointLatLons::from(def.latlons_unchecked()?),
80            Self::Template20(def) => GridPointLatLons::from(def.latlons_unchecked()?),
81            Self::Template30(def) => GridPointLatLons::from(def.latlons_unchecked()?),
82            Self::Template40(def) => GridPointLatLons::from(def.gaussian.latlons_unchecked()?),
83            Self::Template41(def) => GridPointLatLons::from(def.latlons_unchecked()?),
84        };
85        Ok(iter)
86    }
87}
88
89impl TryFrom<&GridDefinition> for GridDefinitionTemplateValues {
90    type Error = GribError;
91
92    fn try_from(value: &GridDefinition) -> Result<Self, Self::Error> {
93        // In the future, we should switch the implementation like this:
94        //
95        // ```
96        // let buf = &value.payload;
97        // let mut pos = 0;
98        // let payload = crate::def::grib2::Section3Payload::try_from_slice(buf, &mut pos)?;
99        // let template = match payload.template {
100        // ..
101        // }
102        // ```
103        //
104        // However, since the current implementation of the templates has many
105        // limitations, to prevent errors, the template reading process is
106        // implemented as follows.
107        let buf = &value.payload[9..];
108        let mut pos = 0;
109        let num = value.grid_tmpl_num();
110        let template = match num {
111            0 => {
112                GridDefinitionTemplateValues::Template0(Template3_0::try_from_slice(buf, &mut pos)?)
113            }
114            1 => {
115                GridDefinitionTemplateValues::Template1(Template3_1::try_from_slice(buf, &mut pos)?)
116            }
117            10 => GridDefinitionTemplateValues::Template10(Template3_10::try_from_slice(
118                buf, &mut pos,
119            )?),
120            20 => GridDefinitionTemplateValues::Template20(Template3_20::try_from_slice(
121                buf, &mut pos,
122            )?),
123            30 => GridDefinitionTemplateValues::Template30(Template3_30::try_from_slice(
124                buf, &mut pos,
125            )?),
126            40 => GridDefinitionTemplateValues::Template40(Template3_40::try_from_slice(
127                buf, &mut pos,
128            )?),
129            41 => GridDefinitionTemplateValues::Template41(Template3_41::try_from_slice(
130                buf, &mut pos,
131            )?),
132            _ => {
133                return Err(GribError::NotSupported(format!(
134                    "lat/lon computation support for the template {num} is dropped in this build"
135                )));
136            }
137        };
138        if buf.len() > pos {
139            return Err(GribError::NotSupported(
140                "template with list of number of points".to_owned(),
141            ));
142        }
143        Ok(template)
144    }
145}
146
147/// A functionality to return a short name of the grid system.
148pub trait GridShortName {
149    /// Returns the grid type.
150    ///
151    /// The grid types are denoted as short strings based on `gridType` used in
152    /// ecCodes.
153    ///
154    /// This is provided primarily for debugging and simple notation purposes.
155    /// It is better to use enum variants instead of the string notation to
156    /// determine the grid type.
157    fn short_name(&self) -> &'static str;
158}
159
160impl<T: GridShortName + ?Sized> GridShortName for &T {
161    fn short_name(&self) -> &'static str {
162        (*self).short_name()
163    }
164}
165
166/// A functionality to generate an iterator over latitude/longitude of grid
167/// points.
168///
169/// Coordinates are returned as `(latitude, longitude)` in degrees using
170/// double-precision (`f64`) values.
171pub trait LatLons {
172    type Iter<'a>: Iterator<Item = (f64, f64)>
173    where
174        Self: 'a;
175
176    /// Computes and returns an iterator over latitudes and longitudes of grid
177    /// points in degrees. Unlike the return values from [`LatLons::latlons`],
178    /// the longitude values from thie method do not necessarily fall within
179    /// the range `[-180°, 180°]`.
180    fn latlons_unchecked<'a>(&'a self) -> Result<Self::Iter<'a>, GribError>;
181
182    /// Computes and returns an iterator over latitudes and longitudes of grid
183    /// points in degrees. The returned longitude values are converted to fall
184    /// within the range `[-180°, 180°]`.
185    ///
186    /// The order of lat/lon data of grid points is the same as the order of the
187    /// grid point values, defined by the scanning mode
188    /// ([`ScanningMode`](`crate::def::grib2::table::ScanningMode`)) in the
189    /// data.
190    #[allow(clippy::type_complexity)]
191    fn latlons<'a>(
192        &'a self,
193    ) -> Result<std::iter::Map<Self::Iter<'a>, fn((f64, f64)) -> (f64, f64)>, GribError> {
194        let iter = self
195            .latlons_unchecked()?
196            .map(helpers::normalize_latlon as fn((f64, f64)) -> (f64, f64));
197        Ok(iter)
198    }
199}
200
201impl<T: LatLons + ?Sized> LatLons for &T {
202    type Iter<'a>
203        = <T as LatLons>::Iter<'a>
204    where
205        Self: 'a;
206
207    fn latlons_unchecked<'a>(&'a self) -> Result<Self::Iter<'a>, GribError> {
208        (*self).latlons_unchecked()
209    }
210}
211
212/// An iterator over latitudes and longitudes of grid points in a submessage.
213///
214/// This `struct` is created by the [`latlons`] method on [`LatLons`]
215/// implemented for [`SubMessage`]. See its documentation for more.
216///
217/// [`latlons`]: crate::context::SubMessage::latlons
218/// [`SubMessage`]: crate::context::SubMessage
219#[derive(Clone)]
220pub struct GridPointLatLons(LatLonsWrapper);
221
222impl Iterator for GridPointLatLons {
223    type Item = (f64, f64);
224
225    fn next(&mut self) -> Option<Self::Item> {
226        match self {
227            Self(LatLonsWrapper::SigR(iter)) => iter.next(),
228            Self(LatLonsWrapper::SigUR(iter)) => iter.next(),
229            Self(LatLonsWrapper::SigIf(iter)) => iter.next(),
230            #[cfg(feature = "gridpoints-proj")]
231            Self(LatLonsWrapper::SigP(iter)) => iter.next(),
232        }
233    }
234
235    fn size_hint(&self) -> (usize, Option<usize>) {
236        match self {
237            Self(LatLonsWrapper::SigR(iter)) => iter.size_hint(),
238            Self(LatLonsWrapper::SigUR(iter)) => iter.size_hint(),
239            Self(LatLonsWrapper::SigIf(iter)) => iter.size_hint(),
240            #[cfg(feature = "gridpoints-proj")]
241            Self(LatLonsWrapper::SigP(iter)) => iter.size_hint(),
242        }
243    }
244}
245
246impl From<RegularGridIterator> for GridPointLatLons {
247    fn from(value: RegularGridIterator) -> Self {
248        Self(LatLonsWrapper::SigR(value))
249    }
250}
251
252impl From<Unrotate<RegularGridIterator>> for GridPointLatLons {
253    fn from(value: Unrotate<RegularGridIterator>) -> Self {
254        Self(LatLonsWrapper::SigUR(value))
255    }
256}
257
258impl From<std::vec::IntoIter<(f64, f64)>> for GridPointLatLons {
259    fn from(value: std::vec::IntoIter<(f64, f64)>) -> Self {
260        Self(LatLonsWrapper::SigIf(value))
261    }
262}
263
264#[cfg(feature = "gridpoints-proj")]
265impl From<ProjectionLatLonIterator> for GridPointLatLons {
266    fn from(value: ProjectionLatLonIterator) -> Self {
267        Self(LatLonsWrapper::SigP(value))
268    }
269}
270
271#[derive(Clone)]
272enum LatLonsWrapper {
273    SigR(RegularGridIterator),
274    SigUR(Unrotate<RegularGridIterator>),
275    SigIf(std::vec::IntoIter<(f64, f64)>),
276    #[cfg(feature = "gridpoints-proj")]
277    SigP(ProjectionLatLonIterator),
278}
279
280/// A functionality to generate an iterator over 2D index `(i, j)` of grid
281/// points.
282///
283/// # Examples
284///
285/// ```
286/// use grib::{GridPointIndex, def::grib2::table::ScanningMode};
287///
288/// struct Grid {
289///     ni: u32,
290///     nj: u32,
291///     scanning_mode: ScanningMode,
292/// }
293///
294/// impl GridPointIndex for Grid {
295///     fn grid_shape(&self) -> (usize, usize) {
296///         (self.ni as usize, self.nj as usize)
297///     }
298///
299///     fn scanning_mode(&self) -> &ScanningMode {
300///         &self.scanning_mode
301///     }
302/// }
303///
304/// let grid_2x3 = Grid {
305///     ni: 2,
306///     nj: 3,
307///     scanning_mode: ScanningMode(0b01000000),
308/// };
309/// assert_eq!(grid_2x3.grid_shape(), (2, 3));
310///
311/// let mut iter = grid_2x3.ij().unwrap();
312/// assert_eq!(iter.next(), Some((0, 0)));
313/// assert_eq!(iter.next(), Some((1, 0)));
314/// assert_eq!(iter.next(), Some((0, 1)));
315/// assert_eq!(iter.next(), Some((1, 1)));
316/// assert_eq!(iter.next(), Some((0, 2)));
317/// assert_eq!(iter.next(), Some((1, 2)));
318/// assert_eq!(iter.next(), None);
319/// ```
320pub trait GridPointIndex {
321    /// Returns the shape of the grid, i.e. a tuple of the number of grids in
322    /// the i and j directions.
323    fn grid_shape(&self) -> (usize, usize);
324
325    /// Returns [`ScanningMode`] used for the iteration.
326    fn scanning_mode(&self) -> &ScanningMode;
327
328    /// Returns an iterator over 2D index `(i, j)` of grid points.
329    fn ij(&self) -> Result<GridPointIndexIterator, GribError> {
330        GridPointIndexIterator::new(self.grid_shape(), *self.scanning_mode())
331    }
332}
333
334impl<T: GridPointIndex + ?Sized> GridPointIndex for &T {
335    fn grid_shape(&self) -> (usize, usize) {
336        (*self).grid_shape()
337    }
338
339    fn scanning_mode(&self) -> &ScanningMode {
340        (*self).scanning_mode()
341    }
342}
343
344/// An iterator over 2D index `(i, j)` of grid points.
345///
346/// This `struct` is created by the [`GridPointIndex::ij`] method. See its
347/// documentation for more.
348#[derive(Clone)]
349pub struct GridPointIndexIterator {
350    major_len: usize,
351    minor_len: usize,
352    scanning_mode: ScanningMode,
353    major_pos: usize,
354    minor_pos: usize,
355    increments: bool,
356}
357
358impl GridPointIndexIterator {
359    pub(crate) fn new(
360        (i_len, j_len): (usize, usize),
361        scanning_mode: ScanningMode,
362    ) -> Result<Self, GribError> {
363        if scanning_mode.has_unsupported_flags() {
364            let ScanningMode(mode) = scanning_mode;
365            return Err(GribError::NotSupported(format!("scanning mode {mode}")));
366        }
367
368        let (major_len, minor_len) = if scanning_mode.is_consecutive_for_i() {
369            (j_len, i_len)
370        } else {
371            (i_len, j_len)
372        };
373
374        Ok(Self {
375            major_len,
376            minor_len,
377            scanning_mode,
378            minor_pos: 0,
379            major_pos: 0,
380            increments: true,
381        })
382    }
383}
384
385impl Iterator for GridPointIndexIterator {
386    type Item = (usize, usize);
387
388    fn next(&mut self) -> Option<Self::Item> {
389        if self.major_pos == self.major_len {
390            return None;
391        }
392
393        let minor = if self.increments {
394            self.minor_pos
395        } else {
396            self.minor_len - self.minor_pos - 1
397        };
398        let major = self.major_pos;
399
400        self.minor_pos += 1;
401        if self.minor_pos == self.minor_len {
402            self.major_pos += 1;
403            self.minor_pos = 0;
404            if self.scanning_mode.scans_alternating_rows() {
405                self.increments = !self.increments;
406            }
407        }
408
409        if self.scanning_mode.is_consecutive_for_i() {
410            Some((minor, major))
411        } else {
412            Some((major, minor))
413        }
414    }
415
416    fn size_hint(&self) -> (usize, Option<usize>) {
417        let len = (self.major_len - self.major_pos) * self.minor_len - self.minor_pos;
418        (len, Some(len))
419    }
420}
421
422pub(crate) trait AngleUnit {
423    fn angle_unit(&self) -> f64;
424}
425
426impl AngleUnit for Grid {
427    fn angle_unit(&self) -> f64 {
428        let basic_angle = self.initial_production_domain_basic_angle;
429        let sub_angle = self.basic_angle_subdivisions;
430        if basic_angle == 0 {
431            1e-6
432        } else {
433            basic_angle as f64 / sub_angle as f64
434        }
435    }
436}
437
438#[cfg(test)]
439mod tests {
440    use super::*;
441    use crate::def::grib2::{
442        table::EarthShapeType,
443        template::param_set::{EarthShape, ScaledValue},
444    };
445
446    #[test]
447    fn grid_definition_template_0() -> Result<(), Box<dyn std::error::Error>> {
448        let buf = crate::test_utils::decompress_to_vec(
449            crate::test_utils::data::grib2::JMA_TORNADO_NOWCAST,
450        )?;
451        let data =
452            GridDefinition::from_payload(buf[0x2a..0x6d].to_vec().into_boxed_slice()).unwrap();
453
454        let actual = GridDefinitionTemplateValues::try_from(&data).unwrap();
455        let expected = GridDefinitionTemplateValues::Template0(Template3_0 {
456            earth: EarthShape {
457                shape: EarthShapeType(4),
458                spherical_earth_radius: ScaledValue {
459                    scale_factor: 0xff,
460                    scaled_value: 0xffffffff,
461                },
462                major_axis: ScaledValue {
463                    scale_factor: 1,
464                    scaled_value: 63781370,
465                },
466                minor_axis: ScaledValue {
467                    scale_factor: 1,
468                    scaled_value: 63567523,
469                },
470            },
471            lat_lon: crate::def::grib2::template::param_set::LatLonGrid {
472                grid: crate::def::grib2::template::param_set::Grid {
473                    ni: 256,
474                    nj: 336,
475                    initial_production_domain_basic_angle: 0,
476                    basic_angle_subdivisions: 0xffffffff,
477                    first_point_lat: 47958333,
478                    first_point_lon: 118062500,
479                    resolution_and_component_flags:
480                        crate::def::grib2::table::ResolutionAndComponentFlags(0b00110000),
481                    last_point_lat: 20041667,
482                    last_point_lon: 149937500,
483                },
484                i_direction_inc: 125000,
485                j_direction_inc: 83333,
486                scanning_mode: crate::def::grib2::table::ScanningMode(0b00000000),
487            },
488        });
489        assert_eq!(actual, expected);
490        Ok(())
491    }
492}
493
494mod earth;
495mod flags;
496mod gaussian;
497mod helpers;
498mod lambert;
499mod latlon;
500mod mercator;
501mod polar_stereographic;
502mod rotation;