Skip to main content

xue/
projection.rs

1//! Grid geometry a reader needs without the encoder: the Lambert conformal
2//! projection a `grid.projection` block declares, and the true latitudes of a
3//! `grid.gaussian` block (`docs/bundle.md`, "Regional Grids").
4//!
5//! The trigonometry runs through `f64`'s methods, the C library's
6//! `sin`/`cos`/`tan`/`pow`, which is what Python's `math` module calls too, so
7//! the two encoders land on the same doubles on one machine.
8
9/// A Lambert conformal conic projection on a sphere, as GRIB2 grid
10/// definition template 3.30 declares it and as GDAL reports it back
11/// (`Lambert Conic Conformal (2SP)` with a spherical datum). Snyder (1987)
12/// §15, spherical case; with two equal standard parallels the cone constant
13/// is `sin` of the parallel.
14#[derive(Debug, Clone, Copy, PartialEq)]
15pub struct LambertConformal {
16    /// Sphere radius in metres — 6371229 for every NCEP product.
17    pub radius: f64,
18    pub standard_parallel_1: f64,
19    pub standard_parallel_2: f64,
20    pub latitude_of_origin: f64,
21    pub central_meridian: f64,
22}
23
24impl LambertConformal {
25    pub fn cone_constant(&self) -> f64 {
26        let phi_1 = self.standard_parallel_1.to_radians();
27        let phi_2 = self.standard_parallel_2.to_radians();
28        if phi_1 == phi_2 {
29            return phi_1.sin();
30        }
31        (phi_1.cos() / phi_2.cos()).ln()
32            / ((std::f64::consts::PI / 4.0 + phi_2 / 2.0).tan()
33                / (std::f64::consts::PI / 4.0 + phi_1 / 2.0).tan())
34            .ln()
35    }
36
37    /// `R·F` — the radius of the parallel at latitude `φ` is
38    /// `scale / tan(π/4 + φ/2)^n`.
39    pub fn scale(&self) -> f64 {
40        let n = self.cone_constant();
41        let phi_1 = self.standard_parallel_1.to_radians();
42        self.radius * (phi_1.cos() * (std::f64::consts::PI / 4.0 + phi_1 / 2.0).tan().powf(n) / n)
43    }
44
45    /// Projected distance from the apex of the cone to the parallel at
46    /// `latitude` (degrees).
47    pub fn parallel_radius(&self, latitude: f64) -> f64 {
48        self.scale()
49            / (std::f64::consts::PI / 4.0 + latitude.to_radians() / 2.0)
50                .tan()
51                .powf(self.cone_constant())
52    }
53
54    pub fn origin_radius(&self) -> f64 {
55        self.parallel_radius(self.latitude_of_origin)
56    }
57
58    /// The angle, in radians, the meridian at `longitude` makes with the
59    /// central meridian on the cone.
60    pub fn meridian_angle(&self, longitude: f64) -> f64 {
61        self.cone_constant() * (longitude - self.central_meridian).to_radians()
62    }
63
64    /// Projected `(x, y)` in metres of one point.
65    pub fn forward(&self, longitude: f64, latitude: f64) -> (f64, f64) {
66        let rho = self.parallel_radius(latitude);
67        let theta = self.meridian_angle(longitude);
68        (rho * theta.sin(), self.origin_radius() - rho * theta.cos())
69    }
70
71    /// [`Self::forward`] for a longitude spelled any way a caller may spell
72    /// it. Without the wrap, 262.5 and -97.5 would open different angles on
73    /// the cone and one of them would land off a grid that holds the point.
74    pub fn forward_wrapped(&self, longitude: f64, latitude: f64) -> (f64, f64) {
75        let delta = (longitude - self.central_meridian + 180.0).rem_euclid(360.0) - 180.0;
76        self.forward(self.central_meridian + delta, latitude)
77    }
78
79    /// Longitude and latitude, in degrees, of one projected point.
80    pub fn inverse(&self, x: f64, y: f64) -> (f64, f64) {
81        let n = self.cone_constant();
82        let dy = self.origin_radius() - y;
83        let rho = (x * x + dy * dy).sqrt().copysign(n);
84        // Both arguments carry the cone's sign: on a southern cone (n < 0)
85        // the radius is negative, and the angle would land half a turn away.
86        let sign = 1.0_f64.copysign(n);
87        let theta = (sign * x).atan2(sign * dy);
88        let latitude = 2.0 * (self.scale() / rho).powf(1.0 / n).atan() - std::f64::consts::PI / 2.0;
89        (
90            self.central_meridian + (theta / n).to_degrees(),
91            latitude.to_degrees(),
92        )
93    }
94}
95
96/// The latitude in degrees of row `row` of the regular Gaussian grid with `n`
97/// latitudes per hemisphere, counted from the north: the `row`-th root of the
98/// Legendre polynomial of order `2n`.
99///
100/// Newton's method from `cos(π(row + 0.75) / (2n + 0.5))` on the three-term
101/// recurrence, stopping once a step is below `1e-15` or after 100 steps. The
102/// operation order is normative (`docs/zarr-profile.md`, "Coordinates"): a
103/// library root finder differs from this by up to 1.8e-12° near the poles,
104/// which would move the bytes of a store's `latitude` coordinate.
105pub fn gaussian_latitude(n: u32, row: u32) -> f64 {
106    let order = 2 * u64::from(n);
107    let degree = order as f64;
108    let mut x = (std::f64::consts::PI * (f64::from(row) + 0.75) / (degree + 0.5)).cos();
109    for _ in 0..100 {
110        let (mut previous, mut current) = (1.0_f64, x);
111        for k in 2..=order {
112            let k = k as f64;
113            let next = ((2.0 * k - 1.0) * x * current - (k - 1.0) * previous) / k;
114            previous = current;
115            current = next;
116        }
117        let derivative = degree * (x * current - previous) / (x * x - 1.0);
118        let step = current / derivative;
119        x -= step;
120        if step.abs() < 1e-15 {
121            break;
122        }
123    }
124    x.asin().to_degrees()
125}
126
127/// Every latitude of the Gaussian grid with `n` latitudes per hemisphere,
128/// north to south.
129pub fn gaussian_latitudes(n: u32) -> Vec<f64> {
130    (0..2 * n).map(|row| gaussian_latitude(n, row)).collect()
131}
132
133/// A `grid.gaussian` block: which rows of the full Gaussian grid a bundle's
134/// rows are, so a crop or a reduced-resolution tier keeps its true latitudes.
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub struct GaussianRows {
137    pub n: u32,
138    pub first_row: u32,
139    pub row_stride: u32,
140}
141
142impl GaussianRows {
143    /// The latitude of a bundle row; `None` past the Gaussian grid's last
144    /// row, which a validated block never reaches from a row on its grid.
145    pub fn latitude(&self, row: u32) -> Option<f64> {
146        let full = u64::from(self.first_row) + u64::from(row) * u64::from(self.row_stride);
147        (full < 2 * u64::from(self.n)).then(|| gaussian_latitude(self.n, full as u32))
148    }
149
150    /// Whether the bundle's `row` is the first or last row of the whole
151    /// Gaussian grid, past which only the polar cap lies.
152    pub(crate) fn reaches_pole(&self, row: u32, north: bool) -> bool {
153        let full = u64::from(self.first_row) + u64::from(row) * u64::from(self.row_stride);
154        if north {
155            full == 0
156        } else {
157            full == 2 * u64::from(self.n) - 1
158        }
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    const HRRR: LambertConformal = LambertConformal {
167        radius: 6371229.0,
168        standard_parallel_1: 38.5,
169        standard_parallel_2: 38.5,
170        latitude_of_origin: 38.5,
171        central_meridian: -97.5,
172    };
173
174    #[test]
175    fn lambert_forward_and_inverse_round_trip() {
176        for (longitude, latitude) in [
177            (-97.5, 38.5),
178            (-122.72, 21.14),
179            (-60.9, 47.84),
180            (-134.1, 52.6),
181            (-75.0, 30.0),
182        ] {
183            let (x, y) = HRRR.forward(longitude, latitude);
184            let (back_longitude, back_latitude) = HRRR.inverse(x, y);
185            assert!((back_longitude - longitude).abs() < 1e-9, "{longitude}");
186            assert!((back_latitude - latitude).abs() < 1e-9, "{latitude}");
187        }
188    }
189
190    #[test]
191    fn the_origin_projects_to_zero_and_the_cone_constant_is_the_parallels_sine() {
192        let (x, y) = HRRR.forward(-97.5, 38.5);
193        assert!(x.abs() < 1e-6 && y.abs() < 1e-6);
194        assert!((HRRR.cone_constant() - 38.5_f64.to_radians().sin()).abs() < 1e-15);
195        assert!(HRRR.origin_radius() > 0.0);
196    }
197
198    #[test]
199    fn a_southern_cone_and_two_parallels_round_trip() {
200        let south = LambertConformal {
201            standard_parallel_1: -30.0,
202            standard_parallel_2: -60.0,
203            latitude_of_origin: -45.0,
204            central_meridian: 140.0,
205            ..HRRR
206        };
207        assert!(south.cone_constant() < 0.0);
208        let (x, y) = south.forward(150.0, -40.0);
209        let (longitude, latitude) = south.inverse(x, y);
210        assert!((longitude - 150.0).abs() < 1e-9);
211        assert!((latitude + 40.0).abs() < 1e-9);
212    }
213
214    #[test]
215    fn a_wrapped_longitude_lands_on_the_same_point() {
216        let (x, y) = HRRR.forward_wrapped(262.5, 38.5);
217        assert!(x.abs() < 1e-6 && y.abs() < 1e-6);
218        let (x, y) = HRRR.forward_wrapped(-100.0 + 720.0, 40.0);
219        let (expected_x, expected_y) = HRRR.forward(-100.0, 40.0);
220        assert!((x - expected_x).abs() < 1e-6 && (y - expected_y).abs() < 1e-6);
221    }
222
223    /// One unit in the last place of `x` is up to 3.6e-12° of latitude next
224    /// to a pole at n = 768, and the C libraries behind the first guess and
225    /// the final `asin` differ across platforms, so the goldens are held to a
226    /// few of those. That the two encoders agree to the bit on one machine is
227    /// the parity tests' to say.
228    const GOLDEN_TOLERANCE: f64 = 1e-11;
229
230    fn assert_golden(n: u32, row: u32, expected: f64) {
231        let latitude = gaussian_latitude(n, row);
232        assert!(
233            (latitude - expected).abs() < GOLDEN_TOLERANCE,
234            "n={n} row={row}: {latitude}"
235        );
236    }
237
238    #[test]
239    fn gaussian_latitudes_match_the_goldens() {
240        assert_golden(95, 0, 89.27671287810583);
241        assert_golden(95, 1, 88.33975425118209);
242        assert_golden(95, 2, 87.3972623773714);
243        assert_golden(95, 94, 0.4724393175759951);
244        assert_golden(95, 95, -0.4724393175759951);
245        assert_golden(95, 187, -87.3972623773714);
246        assert_golden(95, 188, -88.33975425118209);
247        assert_golden(95, 189, -89.27671287810583);
248        assert_golden(768, 0, 89.91032453466268);
249        assert_golden(768, 1, 89.79415738840316);
250        assert_golden(768, 2, 89.67730421235662);
251        assert_golden(768, 767, 0.058574679619089555);
252        assert_golden(768, 768, -0.058574679619089506);
253        assert_golden(768, 1533, -89.67730421235662);
254        assert_golden(768, 1534, -89.79415738840316);
255        assert_golden(768, 1535, -89.91032453466268);
256    }
257
258    #[test]
259    fn gaussian_latitudes_run_north_to_south() {
260        let latitudes = gaussian_latitudes(95);
261        assert_eq!(latitudes.len(), 190);
262        assert!(latitudes.windows(2).all(|pair| pair[0] > pair[1]));
263    }
264
265    #[test]
266    fn gaussian_rows_follow_the_crop_and_the_stride() {
267        let rows = GaussianRows {
268            n: 95,
269            first_row: 4,
270            row_stride: 2,
271        };
272        assert_eq!(rows.latitude(3), Some(gaussian_latitude(95, 10)));
273        assert_eq!(rows.latitude(92), Some(gaussian_latitude(95, 188)));
274        assert_eq!(rows.latitude(93), None);
275        assert!(!rows.reaches_pole(0, true));
276        let whole = GaussianRows {
277            n: 95,
278            first_row: 0,
279            row_stride: 1,
280        };
281        assert!(whole.reaches_pole(0, true));
282        assert!(whole.reaches_pole(189, false));
283    }
284}