1#[cfg(feature = "gridpoints-proj")]
2use super::OsgeoProj;
3use super::{Ellipsoid, Project, helpers::t};
4
5const HALF_PI: f64 = std::f64::consts::FRAC_PI_2;
6const FORTH_PI: f64 = std::f64::consts::FRAC_PI_4;
7const EPS10: f64 = 1e-10;
8const TOL: f64 = 1e-8;
9
10#[derive(Debug, PartialEq, Clone)]
12pub struct Params {
13 pub ellipsoid: Ellipsoid,
15 pub lat_ts: f64,
17 pub lat_0: f64,
19 pub lon_0: f64,
21 pub k_0: f64,
23}
24
25#[cfg(feature = "gridpoints-proj")]
26impl OsgeoProj for Params {
27 fn proj_args(&self) -> String {
28 let Self {
29 ellipsoid: Ellipsoid { a, b, .. },
30 lat_ts,
31 lat_0,
32 lon_0,
33 k_0,
34 } = self;
35 format!(
36 "+a={a} +b={b} +proj=stere +lat_ts={lat_ts} +lat_0={lat_0} +lon_0={lon_0} +k_0={k_0}"
37 )
38 }
39}
40
41pub struct Projection {
43 lam0: f64,
44 a: f64,
45 e: f64,
46 e_sq: f64,
47 phi0: f64,
48 akm1: f64,
49 mode: ProjectionMode,
50}
51
52impl Projection {
53 pub fn new(p: &Params) -> Result<Self, &'static str> {
54 let Params {
55 ellipsoid: Ellipsoid { a, e, e_sq, .. },
56 lat_ts,
57 lat_0,
58 lon_0,
59 k_0,
60 } = p;
61 let phi0 = lat_0.to_radians();
62 let lam0 = lon_0.to_radians();
63 let phi_ts = lat_ts.to_radians().abs();
64
65 let absφ0 = phi0.abs();
66 let mode = if (absφ0 - HALF_PI).abs() < EPS10 {
67 ProjectionMode::Pole {
68 is_north_pole: phi0.is_sign_positive(),
69 }
70 } else {
71 ProjectionMode::NonPole {
72 is_equator: absφ0 <= EPS10,
73 x: ConformalLatitude::default(),
74 }
75 };
76
77 let (mode, akm1) = if *e_sq == 0. {
78 match mode {
79 ProjectionMode::NonPole { is_equator, .. } => {
80 let mode = if is_equator {
81 mode
82 } else {
83 ProjectionMode::NonPole {
84 is_equator,
85 x: ConformalLatitude::from(phi0),
86 }
87 };
88 let akm1 = 2. * k_0;
89 (mode, akm1)
90 }
91 ProjectionMode::Pole { .. } => {
92 let akm1 = if (phi_ts - HALF_PI).abs() < EPS10 {
93 2. * k_0
94 } else {
95 phi_ts.cos() / (FORTH_PI - 0.5 * phi_ts).tan()
96 };
97 (mode, akm1)
98 }
99 }
100 } else {
101 match mode {
102 ProjectionMode::NonPole { is_equator, .. } => {
103 let (sinφ0, cosφ0) = phi0.sin_cos();
104 let x = 2. * psi(phi0, sinφ0, *e).atan() - HALF_PI;
106 let t = sinφ0 * e;
107 let akm1 = 2. * k_0 * cosφ0 / (1. - t * t).sqrt();
108 let mode = ProjectionMode::NonPole {
109 is_equator,
110 x: ConformalLatitude::from(x),
111 };
112 (mode, akm1)
113 }
114 ProjectionMode::Pole { .. } => {
115 let akm1 = if (phi_ts - HALF_PI).abs() < EPS10 {
116 2. * k_0 / ((1. + e).powf(1. + e) * (1. - e).powf(1. - e)).sqrt()
117 } else {
118 let (sinφts, cosφts) = phi_ts.sin_cos();
119 let akm1 = cosφts / t(cosφts, sinφts, *e);
120 let t = sinφts * e;
121 akm1 / (1. - t * t).sqrt()
122 };
123 (mode, akm1)
124 }
125 }
126 };
127
128 let context = Self {
129 lam0,
130 a: *a,
131 e: *e,
132 e_sq: *e_sq,
133 phi0,
134 akm1,
135 mode,
136 };
137 Ok(context)
138 }
139
140 fn ellipsoidal_forward(&self, (lambda, phi): &(f64, f64)) -> Result<(f64, f64), &'static str> {
141 let (sinλ, cosλ) = lambda.sin_cos();
142 let (sinφ, cosφ) = phi.sin_cos();
143
144 let (x, y) = match &self.mode {
145 ProjectionMode::NonPole {
146 is_equator,
147 x: ConformalLatitude { sinφ0, cosφ0 },
148 } => {
149 let x = 2. * psi(*phi, sinφ, self.e).atan() - HALF_PI;
150 let (sinx, cosx) = x.sin_cos();
151
152 if *is_equator {
153 if 1. + cosx * cosλ == 0.0 {
154 (0., f64::INFINITY)
155 } else {
156 let a = self.akm1 / (1. + cosx * cosλ);
157 let x = a * cosx;
158 let y = a * sinx;
159 (x, y)
160 }
161 } else {
162 let denom = cosφ0 * (1. + sinφ0 * sinx + cosφ0 * cosx * cosλ);
163 if denom == 0. {
164 return Err(Self::ERR_TRANSFORMATION_OUTSIDE_DOMAIN);
165 }
166 let a = self.akm1 / denom;
167 let x = a * cosx;
168 let y = a * (cosφ0 * sinx - sinφ0 * cosx * cosλ);
169 (x, y)
170 }
171 }
172 ProjectionMode::Pole { is_north_pole } => {
173 let (phi, cosλ, sinφ) = if *is_north_pole {
174 (*phi, cosλ, sinφ)
175 } else {
176 (-phi, -cosλ, -sinφ)
177 };
178 let x = if (phi - HALF_PI).abs() < 1e-15 {
179 0.
180 } else {
181 self.akm1 * t(cosφ, sinφ, self.e)
182 };
183 let y = -x * cosλ;
184 (x, y)
185 }
186 };
187
188 let x = x * sinλ;
189 Ok((x, y))
190 }
191
192 const ERR_TRANSFORMATION_OUTSIDE_DOMAIN: &str =
193 "Coordinate transformation outside projection domain";
194
195 fn spheroidal_forward(&self, (lambda, phi): &(f64, f64)) -> Result<(f64, f64), &'static str> {
196 let (sinλ, cosλ) = lambda.sin_cos();
197 let (sinφ, cosφ) = phi.sin_cos();
198
199 let (x, y) = match &self.mode {
200 ProjectionMode::NonPole {
201 is_equator,
202 x: ConformalLatitude { sinφ0, cosφ0 },
203 } => {
204 let y = if *is_equator {
205 1. + cosφ * cosλ
206 } else {
207 1. + sinφ0 * sinφ + cosφ0 * cosφ * cosλ
208 };
209
210 if y <= EPS10 {
211 return Err(Self::ERR_TRANSFORMATION_OUTSIDE_DOMAIN);
212 }
213
214 let c = self.akm1 / y;
215 let x = c * cosφ * sinλ;
216 let y = c * if *is_equator {
217 sinφ
218 } else {
219 cosφ0 * sinφ - sinφ0 * cosφ * cosλ
220 };
221 (x, y)
222 }
223 ProjectionMode::Pole { is_north_pole } => {
224 let (cosλ, phi) = if *is_north_pole {
225 (-cosλ, -phi)
226 } else {
227 (cosλ, *phi)
228 };
229
230 if (phi - HALF_PI).abs() < TOL {
231 return Err(Self::ERR_TRANSFORMATION_OUTSIDE_DOMAIN);
232 }
233
234 let c = self.akm1 * (FORTH_PI + 0.5 * phi).tan();
235 let x = c * sinλ;
236 let y = c * cosλ;
237 (x, y)
238 }
239 };
240
241 Ok((x, y))
242 }
243
244 fn ellipsoidal_inverse(&self, (x, y): &(f64, f64)) -> Result<(f64, f64), &'static str> {
245 const MAX_ITER: usize = 8;
246 const CONV: f64 = 1e-10;
247 let rho = x.hypot(*y);
248
249 let (x, y, tp, mut phi_l, half_pi, half_e) = match &self.mode {
250 ProjectionMode::NonPole {
251 x: ConformalLatitude { sinφ0, cosφ0 },
252 ..
253 } => {
254 let tp = 2. * (rho * cosφ0).atan2(self.akm1);
255 let (sinφ, cosφ) = tp.sin_cos();
256 let phi_l = if rho == 0. {
257 (cosφ * sinφ0).asin()
258 } else {
259 (cosφ * sinφ0 + (y * sinφ * cosφ0 / rho)).asin()
260 };
261
262 let tp = (0.5 * (HALF_PI + phi_l)).tan();
263 let x = x * sinφ;
264 let y = rho * cosφ0 * cosφ - y * sinφ0 * sinφ;
265 let half_pi = HALF_PI;
266 let half_e = 0.5 * self.e;
267 (x, y, tp, phi_l, half_pi, half_e)
268 }
269 ProjectionMode::Pole { is_north_pole } => {
270 let y = if *is_north_pole { -y } else { *y };
271 let tp = -rho / self.akm1;
272 let phi_l = HALF_PI - 2. * tp.atan();
273 let half_pi = -HALF_PI;
274 let half_e = -0.5 * self.e;
275 (*x, y, tp, phi_l, half_pi, half_e)
276 }
277 };
278
279 let mut count = MAX_ITER;
280 while count > 0 {
281 let sinφ = self.e * phi_l.sin();
282 let phi = 2. * (tp * ((1. + sinφ) / (1. - sinφ)).powf(half_e)).atan() - half_pi;
283 if (phi_l - phi).abs() < CONV {
284 let phi = if let ProjectionMode::Pole {
285 is_north_pole: false,
286 } = self.mode
287 {
288 -phi
289 } else {
290 phi
291 };
292 let lambda = if x == 0. && y == 0. { 0. } else { x.atan2(y) };
293 return Ok((lambda, phi));
294 }
295
296 phi_l = phi;
297 count -= 1;
298 }
299
300 Err(Self::ERR_TRANSFORMATION_OUTSIDE_DOMAIN)
301 }
302
303 fn spheroidal_inverse(&self, (x, y): &(f64, f64)) -> Result<(f64, f64), &'static str> {
304 let rho = x.hypot(*y);
305 let c = 2. * (rho / self.akm1).atan();
306 let (sinc, cosc) = c.sin_cos();
307
308 let (lambda, phi) = match &self.mode {
309 ProjectionMode::NonPole {
310 is_equator: true, ..
311 } => {
312 let phi = if rho.abs() <= EPS10 {
313 0.
314 } else {
315 (y * sinc / rho).asin()
316 };
317 let lambda = if cosc == 0. && *x == 0. {
318 0.
319 } else {
320 (x * sinc).atan2(cosc * rho)
321 };
322 (lambda, phi)
323 }
324 ProjectionMode::NonPole {
325 is_equator: false,
326 x: ConformalLatitude { sinφ0, cosφ0 },
327 } => {
328 let phi = if rho.abs() <= EPS10 {
329 self.phi0
330 } else {
331 (cosc * sinφ0 + y * sinc * cosφ0 / rho).asin()
332 };
333 let c = cosc - sinφ0 * phi.sin();
334 let lambda = if c == 0. && *x == 0. {
335 0.
336 } else {
337 (x * sinc * cosφ0).atan2(c * rho)
338 };
339 (lambda, phi)
340 }
341 ProjectionMode::Pole { is_north_pole } => {
342 let (y, cosc) = if *is_north_pole {
343 (-y, cosc)
344 } else {
345 (*y, -cosc)
346 };
347 let phi = if rho.abs() <= EPS10 {
348 self.phi0
349 } else {
350 cosc.asin()
351 };
352 let lambda = if *x == 0. && y == 0. { 0. } else { x.atan2(y) };
353 (lambda, phi)
354 }
355 };
356
357 Ok((lambda, phi))
358 }
359}
360
361impl Project for Projection {
362 fn forward(&self, xy: &(f64, f64)) -> Result<(f64, f64), &'static str> {
363 if self.e_sq == 0.0 {
364 self.spheroidal_forward(xy)
365 } else {
366 self.ellipsoidal_forward(xy)
367 }
368 }
369
370 fn inverse(&self, xy: &(f64, f64)) -> Result<(f64, f64), &'static str> {
371 if self.e_sq == 0.0 {
372 self.spheroidal_inverse(xy)
373 } else {
374 self.ellipsoidal_inverse(xy)
375 }
376 }
377
378 fn a(&self) -> &f64 {
379 &self.a
380 }
381
382 fn lam0(&self) -> &f64 {
383 &self.lam0
384 }
385}
386
387enum ProjectionMode {
388 NonPole {
389 is_equator: bool,
390 x: ConformalLatitude,
391 },
392 Pole {
393 is_north_pole: bool,
394 },
395}
396
397#[derive(Default)]
398struct ConformalLatitude {
399 sinφ0: f64,
400 cosφ0: f64,
401}
402
403impl From<f64> for ConformalLatitude {
404 fn from(value: f64) -> Self {
405 let (sinφ0, cosφ0) = value.sin_cos();
406 Self { sinφ0, cosφ0 }
407 }
408}
409
410fn psi(phit: f64, sinφ: f64, e: f64) -> f64 {
412 let sinφ = sinφ * e;
413 (0.5 * (HALF_PI + phit)).tan() * ((1. - sinφ) / (1. + sinφ)).powf(0.5 * e)
414}
415
416#[cfg(all(test, feature = "gridpoints-proj"))]
417mod tests {
418 use proj::Proj;
419
420 use super::*;
421
422 const FORWARD_TOLERANCE_METERS: f64 = 1e-7;
423 const INVERSE_TOLERANCE_RADIANS: f64 = 1e-12;
424
425 macro_rules! projection_comparison_tests {
426 ($(($name:ident, $params:expr, $coordinates:expr $(,)?)),* $(,)?) => ($(
427 #[test]
428 fn $name() -> Result<(), Box<dyn std::error::Error>> {
429 assert_agrees_with_proj($params, $coordinates)
430 }
431 )*);
432 }
433
434 projection_comparison_tests! {
435 (
436 agrees_with_proj_for_ellipsoidal_north_pole,
437 Params {
438 ellipsoid: Ellipsoid::from_a_and_b(6_378_137., 6_356_752.314_245),
439 lat_ts: 60.,
440 lat_0: 90.,
441 lon_0: -111.,
442 k_0: 1.,
443 },
444 [(20., -140.), (45., -100.), (70., 10.), (89., 170.)],
445 ),
446 (
447 agrees_with_proj_for_ellipsoidal_south_pole,
448 Params {
449 ellipsoid: Ellipsoid::from_a_and_b(6_378_137., 6_356_752.314_245),
450 lat_ts: -71.,
451 lat_0: -90.,
452 lon_0: 20.,
453 k_0: 1.,
454 },
455 [(-20., -160.), (-45., -30.), (-70., 80.), (-89., 170.)],
456 ),
457 (
458 agrees_with_proj_for_spherical_north_pole,
459 Params {
460 ellipsoid: Ellipsoid::from_a_and_b(6_371_229., 6_371_229.),
461 lat_ts: 60.,
462 lat_0: 90.,
463 lon_0: 140.,
464 k_0: 1.,
465 },
466 [(20., -170.), (45., -40.), (70., 100.), (89., 179.)],
467 ),
468 (
469 agrees_with_proj_for_spherical_equatorial,
470 Params {
471 ellipsoid: Ellipsoid::from_a_and_b(6_371_229., 6_371_229.),
472 lat_ts: 0.,
473 lat_0: 0.,
474 lon_0: 15.,
475 k_0: 0.9996,
476 },
477 [(-70., -20.), (-20., 0.), (25., 45.), (70., 100.)],
478 ),
479 (
480 agrees_with_proj_for_ellipsoidal_oblique,
481 Params {
482 ellipsoid: Ellipsoid::from_a_and_b(6_378_137., 6_356_752.314_245),
483 lat_ts: 40.,
484 lat_0: 40.,
485 lon_0: -100.,
486 k_0: 0.9996,
487 },
488 [(-20., -140.), (0., -100.), (45., -70.), (75., 20.)],
489 ),
490 }
491
492 fn assert_agrees_with_proj(
493 params: Params,
494 coordinates: [(f64, f64); 4],
495 ) -> Result<(), Box<dyn std::error::Error>> {
496 let proj = Proj::new(¶ms.proj_args())?;
497 let projection = Projection::new(¶ms)?;
498
499 for (lat, lon) in coordinates {
500 let lonlat = (lon.to_radians(), lat.to_radians());
501 let expected_xy = proj.project(lonlat, false)?;
502 let actual_xy = projection.project(&lonlat, false)?;
503 assert_coordinates_close(actual_xy, expected_xy, FORWARD_TOLERANCE_METERS);
504
505 let expected_lonlat = proj.project(expected_xy, true)?;
506 let actual_lonlat = projection.project(&expected_xy, true)?;
507 assert_coordinates_close(actual_lonlat, expected_lonlat, INVERSE_TOLERANCE_RADIANS);
508 }
509
510 Ok(())
511 }
512
513 fn assert_coordinates_close(actual: (f64, f64), expected: (f64, f64), tolerance: f64) {
514 assert!(
515 (actual.0 - expected.0).abs() <= tolerance
516 && (actual.1 - expected.1).abs() <= tolerance,
517 "actual {actual:?} differs from expected {expected:?} by more than {tolerance}"
518 );
519 }
520}