Skip to main content

grib/grid/
helpers.rs

1#[cfg(feature = "gridpoints-proj")]
2use proj::Proj;
3
4#[allow(unused_imports)]
5use crate::GribError;
6#[cfg(not(feature = "gridpoints-proj"))]
7use crate::projection::Project;
8use crate::{GridPointIndexIterator, def::grib2::table::ScanningMode};
9
10pub(crate) fn evenly_spaced_longitudes(
11    start_microdegree: u32,
12    end_microdegree: u32,
13    div: usize,
14    angle_units: f64,
15    scanning_mode: ScanningMode,
16) -> Vec<f64> {
17    let is_consistent =
18        !((end_microdegree > start_microdegree) ^ scanning_mode.scans_positively_for_i());
19
20    let (start, end) = (start_microdegree as f64, end_microdegree as f64);
21    let (start, end) = if is_consistent {
22        (start, end)
23    } else if start_microdegree > end_microdegree {
24        (start, end + 360_000_000_f64)
25    } else {
26        (start + 360_000_000_f64, end)
27    };
28
29    let lons = evenly_spaced_degrees(start, end, div, angle_units);
30
31    if is_consistent {
32        lons
33    } else {
34        lons.into_iter()
35            .map(|x| if x < 360.0 { x } else { x - 360.0 })
36            .collect()
37    }
38}
39
40pub(crate) fn evenly_spaced_degrees(
41    start_microdegree: f64,
42    end_microdegree: f64,
43    div: usize,
44    angle_units: f64,
45) -> Vec<f64> {
46    let delta = (end_microdegree - start_microdegree) / div as f64;
47    (0..=div)
48        .map(move |x| (start_microdegree + x as f64 * delta) * angle_units)
49        .collect()
50}
51
52/// An iterator over latitudes and longitudes of grid points of a regular grid.
53#[derive(Clone)]
54pub struct RegularGridIterator {
55    lat: Vec<f64>,
56    lon: Vec<f64>,
57    ij: GridPointIndexIterator,
58}
59
60impl RegularGridIterator {
61    pub(crate) fn new(lat: Vec<f64>, lon: Vec<f64>, ij: GridPointIndexIterator) -> Self {
62        Self { lat, lon, ij }
63    }
64}
65
66impl Iterator for RegularGridIterator {
67    type Item = (f64, f64);
68
69    fn next(&mut self) -> Option<Self::Item> {
70        let (i, j) = self.ij.next()?;
71        Some((self.lat[j], self.lon[i]))
72    }
73
74    fn size_hint(&self) -> (usize, Option<usize>) {
75        self.ij.size_hint()
76    }
77}
78
79#[derive(Clone)]
80#[cfg(feature = "gridpoints-proj")]
81pub struct ProjectionLatLonIterator {
82    xy: std::vec::IntoIter<(f64, f64)>,
83}
84
85#[cfg(feature = "gridpoints-proj")]
86impl Iterator for ProjectionLatLonIterator {
87    type Item = (f64, f64);
88
89    fn next(&mut self) -> Option<Self::Item> {
90        self.xy
91            .next()
92            .map(|(lon, lat)| (lat.to_degrees(), lon.to_degrees()))
93    }
94
95    fn size_hint(&self) -> (usize, Option<usize>) {
96        self.xy.size_hint()
97    }
98}
99
100#[cfg(feature = "gridpoints-proj")]
101pub(crate) fn latlons_from_projection_with_first_point_and_delta(
102    proj_def: &str,
103    first_point_latlon_in_degrees: (f64, f64),
104    delta_in_meters: (f64, f64),
105    indices: GridPointIndexIterator,
106) -> Result<ProjectionLatLonIterator, GribError> {
107    let projection = Proj::new(proj_def)?;
108    let (first_point_lat, first_point_lon) = first_point_latlon_in_degrees;
109    let (first_corner_x, first_corner_y) = projection.project(
110        (first_point_lon.to_radians(), first_point_lat.to_radians()),
111        false,
112    )?;
113
114    let (dx, dy) = delta_in_meters;
115    let mut xy = indices
116        .map(|(i, j)| {
117            (
118                first_corner_x + dx * i as f64,
119                first_corner_y + dy * j as f64,
120            )
121        })
122        .collect::<Vec<_>>();
123
124    projection.project_array(&mut xy, true)?;
125
126    Ok(ProjectionLatLonIterator { xy: xy.into_iter() })
127}
128
129#[cfg(not(feature = "gridpoints-proj"))]
130pub(crate) fn latlons_from_projection_with_first_point_and_delta<P: Project>(
131    projection: &P,
132    first_point_latlon_in_degrees: (f64, f64),
133    delta_in_meters: (f64, f64),
134    indices: GridPointIndexIterator,
135) -> Result<std::vec::IntoIter<(f64, f64)>, GribError> {
136    let (first_point_lat, first_point_lon) = first_point_latlon_in_degrees;
137    let (first_corner_x, first_corner_y) = projection.project(
138        &(first_point_lon.to_radians(), first_point_lat.to_radians()),
139        false,
140    )?;
141
142    let (dx, dy) = delta_in_meters;
143    let latlons = indices
144        .map(|(i, j)| {
145            projection
146                .project(
147                    &(
148                        first_corner_x + dx * i as f64,
149                        first_corner_y + dy * j as f64,
150                    ),
151                    true,
152                )
153                .map(|(lon, lat)| (lat.to_degrees(), lon.to_degrees()))
154        })
155        .collect::<Result<Vec<_>, _>>()?;
156    Ok(latlons.into_iter())
157}
158
159#[cfg(feature = "gridpoints-proj")]
160pub(crate) fn latlons_from_projection_with_first_point_and_last_point(
161    proj_def: &str,
162    first_point_latlon_in_degrees: (f64, f64),
163    last_point_latlon_in_degrees: (f64, f64),
164    (ni, nj): (usize, usize),
165    indices: GridPointIndexIterator,
166) -> Result<std::vec::IntoIter<(f64, f64)>, GribError> {
167    let projection = Proj::new(proj_def)?;
168    let (first_point_lat, first_point_lon) = first_point_latlon_in_degrees;
169    let (first_corner_x, first_corner_y) = projection.project(
170        (first_point_lon.to_radians(), first_point_lat.to_radians()),
171        false,
172    )?;
173    let (last_point_lat, last_point_lon) = last_point_latlon_in_degrees;
174    let (last_corner_x, last_corner_y) = projection.project(
175        (last_point_lon.to_radians(), last_point_lat.to_radians()),
176        false,
177    )?;
178
179    let dx = (last_corner_x - first_corner_x) / (ni - 1) as f64;
180    let dy = (last_corner_y - first_corner_y) / (nj - 1) as f64;
181    let mut xy = indices
182        .map(|(i, j)| {
183            (
184                first_corner_x + dx * i as f64,
185                first_corner_y + dy * j as f64,
186            )
187        })
188        .collect::<Vec<_>>();
189
190    let lonlat = projection.project_array(&mut xy, true)?;
191    let latlon = lonlat
192        .iter_mut()
193        .map(|(lon, lat)| (lat.to_degrees(), lon.to_degrees()))
194        .collect::<Vec<_>>();
195
196    Ok(latlon.into_iter())
197}
198
199pub(crate) fn normalize_latlon((lat, lon): (f64, f64)) -> (f64, f64) {
200    let lon = (lon + 540.) % 360. - 180.;
201    (lat, lon)
202}
203
204#[cfg(feature = "gridpoints-proj")]
205impl From<proj::ProjCreateError> for GribError {
206    fn from(e: proj::ProjCreateError) -> Self {
207        Self::Unknown(e.to_string())
208    }
209}
210
211#[cfg(feature = "gridpoints-proj")]
212impl From<proj::ProjError> for GribError {
213    fn from(e: proj::ProjError) -> Self {
214        Self::Unknown(e.to_string())
215    }
216}
217
218#[cfg(test)]
219pub(crate) mod test_helpers {
220    macro_rules! assert_almost_eq {
221        ($a1:expr, $a2:expr, $d:expr $(,)?) => {
222            if $a1 - $a2 > $d {
223                panic!(
224                    "assertion a1 - a2 <= delta failed\n a1 - a2: {} - {}\n   delta: {}",
225                    $a1, $a2, $d
226                );
227            } else if $a2 - $a1 > $d {
228                panic!(
229                    "assertion a2 - a1 <= delta failed\n a2 - a1: {} - {}\n   delta: {}",
230                    $a2, $a1, $d
231                );
232            }
233        };
234    }
235    pub(crate) use assert_almost_eq;
236
237    macro_rules! test_assert_almost_eq_do_not_panic {
238        ($((
239            $name:ident,
240            $a1:expr,
241            $a2:expr,
242            $d:expr $(,)?
243        )),* $(,)?) => ($(
244            #[test]
245            fn $name() {
246                assert_almost_eq!($a1, $a2, $d)
247            }
248        )*);
249    }
250
251    test_assert_almost_eq_do_not_panic! {
252        (assert_almost_eq_does_not_panic_for_positive_lt_positive, 1.01, 1.02, 0.1),
253        (assert_almost_eq_does_not_panic_for_positive_gt_positive, 1.02, 1.01, 0.1),
254        (assert_almost_eq_does_not_panic_for_negative_lt_negative, -1.02, -1.01, 0.1),
255        (assert_almost_eq_does_not_panic_for_negative_gt_negative, -1.01, -1.02, 0.1),
256        (assert_almost_eq_does_not_panic_for_positive_negative, 0.01, -0.01, 0.1),
257        (assert_almost_eq_does_not_panic_for_negative_positive, -0.01, 0.01, 0.1),
258    }
259
260    macro_rules! test_assert_almost_eq_panic {
261        ($((
262            $name:ident,
263            $a1:expr,
264            $a2:expr,
265            $d:expr,
266            $message:expr $(,)?
267        )),* $(,)?) => ($(
268            #[test]
269            #[should_panic(expected = $message)]
270            fn $name() {
271                assert_almost_eq!($a1, $a2, $d)
272            }
273        )*);
274    }
275
276    test_assert_almost_eq_panic! {
277        (
278            assert_almost_eq_panics_for_positive_lt_positive, 1.01, 1.02, 0.001,
279            " a2 - a1: 1.02 - 1.01\n   delta: 0.001",
280        ),
281        (
282            assert_almost_eq_panics_for_positive_gt_positive, 1.02, 1.01, 0.001,
283            " a1 - a2: 1.02 - 1.01\n   delta: 0.001",
284        ),
285        (
286            assert_almost_eq_panics_for_negative_lt_negative, -1.02, -1.01, 0.001,
287            " a2 - a1: -1.01 - -1.02\n   delta: 0.001",
288        ),
289        (
290            assert_almost_eq_panics_for_negative_gt_negative, -1.01, -1.02, 0.001,
291            " a1 - a2: -1.01 - -1.02\n   delta: 0.001",
292        ),
293        (
294            assert_almost_eq_panics_for_positive_negative, 0.01, -0.01, 0.001,
295            " a1 - a2: 0.01 - -0.01\n   delta: 0.001",
296        ),
297        (
298            assert_almost_eq_panics_for_negative_positive, -0.01, 0.01, 0.001,
299            " a2 - a1: 0.01 - -0.01\n   delta: 0.001",
300        ),
301        (
302            assert_almost_eq_panic_message_containing_trailing_zeros, -0.0100, 0.0100, 0.0010,
303            " a2 - a1: 0.01 - -0.01\n   delta: 0.001",
304        ),
305    }
306
307    #[allow(dead_code)]
308    pub(crate) fn assert_coord_almost_eq((x1, y1): (f64, f64), (x2, y2): (f64, f64), delta: f64) {
309        assert_almost_eq!(x1, x2, delta);
310        assert_almost_eq!(y1, y2, delta);
311    }
312}
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317
318    macro_rules! test_lat_lon_grid_iter {
319        ($(($name:ident, $scanning_mode:expr, $expected:expr $(,)?)),* $(,)?) => ($(
320            #[test]
321            fn $name() {
322                let lat = (0..3).into_iter().map(|i| i as f64).collect::<Vec<_>>();
323                let lon = (10..12).into_iter().map(|i| i as f64).collect::<Vec<_>>();
324                let scanning_mode = ScanningMode($scanning_mode);
325                let ij = GridPointIndexIterator::new((lon.len(), lat.len()), scanning_mode).unwrap();
326                let actual = RegularGridIterator::new(lat, lon, ij).collect::<Vec<_>>();
327                assert_eq!(actual, $expected);
328            }
329        )*);
330    }
331
332    test_lat_lon_grid_iter! {
333        (
334            lat_lon_grid_iter_with_scanning_mode_0b00000000,
335            0b00000000,
336            vec![
337                (0., 10.),
338                (0., 11.),
339                (1., 10.),
340                (1., 11.),
341                (2., 10.),
342                (2., 11.),
343            ],
344        ),
345        (
346            lat_lon_grid_iter_with_scanning_mode_0b00100000,
347            0b00100000,
348            vec![
349                (0., 10.),
350                (1., 10.),
351                (2., 10.),
352                (0., 11.),
353                (1., 11.),
354                (2., 11.),
355            ],
356        ),
357        (
358            lat_lon_grid_iter_with_scanning_mode_0b00010000,
359            0b00010000,
360            vec![
361                (0., 10.),
362                (0., 11.),
363                (1., 11.),
364                (1., 10.),
365                (2., 10.),
366                (2., 11.),
367            ],
368        ),
369        (
370            lat_lon_grid_iter_with_scanning_mode_0b00110000,
371            0b00110000,
372            vec![
373                (0., 10.),
374                (1., 10.),
375                (2., 10.),
376                (2., 11.),
377                (1., 11.),
378                (0., 11.),
379            ],
380        ),
381    }
382
383    #[test]
384    fn lat_lon_grid_iterator_size_hint() {
385        let lat = (0..3).map(|i| i as f64).collect::<Vec<_>>();
386        let lon = (10..12).map(|i| i as f64).collect::<Vec<_>>();
387        let scanning_mode = ScanningMode(0b00000000);
388        let ij = GridPointIndexIterator::new((lon.len(), lat.len()), scanning_mode).unwrap();
389        let mut iter = RegularGridIterator::new(lat, lon, ij);
390
391        assert_eq!(iter.size_hint(), (6, Some(6)));
392        let _ = iter.next();
393        assert_eq!(iter.size_hint(), (5, Some(5)));
394    }
395
396    #[test]
397    fn latlon_normalization() {
398        assert_eq!(normalize_latlon((90., -180.)), (90., -180.));
399        assert_eq!(normalize_latlon((90., 0.)), (90., 0.));
400        assert_eq!(normalize_latlon((90., 179.)), (90., 179.));
401        assert_eq!(normalize_latlon((90., 180.)), (90., -180.));
402        assert_eq!(normalize_latlon((90., 360.)), (90., 0.));
403        assert_eq!(normalize_latlon((90., 540.)), (90., -180.));
404    }
405}