-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy path_projections.py
More file actions
2362 lines (1967 loc) · 80.2 KB
/
_projections.py
File metadata and controls
2362 lines (1967 loc) · 80.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Numba JIT coordinate transforms for common projections.
Replaces pyproj for the most-used CRS pairs, giving ~30x speedup
via parallelised Numba kernels.
Supported fast paths
--------------------
- WGS84 (EPSG:4326) <-> Web Mercator (EPSG:3857)
- WGS84 / NAD83 <-> UTM zones (EPSG:326xx / 327xx / 269xx)
- WGS84 / NAD83 <-> Ellipsoidal Mercator (EPSG:3395)
- WGS84 / NAD83 <-> Lambert Conformal Conic (e.g. EPSG:2154)
- WGS84 / NAD83 <-> Albers Equal Area (e.g. EPSG:5070)
- WGS84 / NAD83 <-> Cylindrical Equal Area (e.g. EPSG:6933)
- WGS84 / NAD83 <-> Sinusoidal (e.g. MODIS)
- WGS84 / NAD83 <-> Lambert Azimuthal Equal Area (e.g. EPSG:3035)
- WGS84 / NAD83 <-> Polar Stereographic (e.g. EPSG:3031, 3413, 3996)
- WGS84 / NAD83 <-> Oblique Stereographic (e.g. EPSG:28992 RD New)
- WGS84 / NAD83 <-> Oblique Mercator Hotine (e.g. EPSG:3375 RSO)
All other CRS pairs fall back to pyproj.
"""
from __future__ import annotations
import math
import numpy as np
from numba import njit, prange
# ---------------------------------------------------------------------------
# WGS84 ellipsoid constants
# ---------------------------------------------------------------------------
_WGS84_A = 6378137.0 # semi-major axis (m)
_WGS84_F = 1.0 / 298.257223563 # flattening
_WGS84_B = _WGS84_A * (1.0 - _WGS84_F) # semi-minor axis
_WGS84_N = (_WGS84_A - _WGS84_B) / (_WGS84_A + _WGS84_B) # third flattening
_WGS84_E2 = 2.0 * _WGS84_F - _WGS84_F ** 2 # eccentricity squared
_WGS84_E = math.sqrt(_WGS84_E2) # eccentricity
# ---------------------------------------------------------------------------
# Web Mercator (EPSG:3857) -- spherical, trivial
# ---------------------------------------------------------------------------
@njit(nogil=True, cache=True)
def _merc_fwd_point(lon_deg, lat_deg):
"""(lon, lat) in degrees -> (x, y) in EPSG:3857 metres."""
x = _WGS84_A * math.radians(lon_deg)
phi = math.radians(lat_deg)
y = _WGS84_A * math.log(math.tan(math.pi / 4.0 + phi / 2.0))
return x, y
@njit(nogil=True, cache=True)
def _merc_inv_point(x, y):
"""(x, y) in EPSG:3857 metres -> (lon, lat) in degrees."""
lon = math.degrees(x / _WGS84_A)
lat = math.degrees(math.atan(math.sinh(y / _WGS84_A)))
return lon, lat
@njit(nogil=True, cache=True, parallel=True)
def merc_forward(lons, lats, out_x, out_y):
"""Batch WGS84 -> Web Mercator. Writes into pre-allocated arrays."""
for i in prange(lons.shape[0]):
out_x[i], out_y[i] = _merc_fwd_point(lons[i], lats[i])
@njit(nogil=True, cache=True, parallel=True)
def merc_inverse(xs, ys, out_lon, out_lat):
"""Batch Web Mercator -> WGS84. Writes into pre-allocated arrays."""
for i in prange(xs.shape[0]):
out_lon[i], out_lat[i] = _merc_inv_point(xs[i], ys[i])
# ---------------------------------------------------------------------------
# Datum shift: 7-parameter Helmert (Bursa-Wolf)
# ---------------------------------------------------------------------------
# Ellipsoid definitions: (a, f)
_ELLIPSOID_CLARKE1866 = (6378206.4, 1.0 / 294.9786982)
_ELLIPSOID_AIRY = (6377563.396, 1.0 / 299.3249646)
_ELLIPSOID_BESSEL = (6377397.155, 1.0 / 299.1528128)
_ELLIPSOID_INTL1924 = (6378388.0, 1.0 / 297.0)
_ELLIPSOID_ANS = (6378160.0, 1.0 / 298.25) # Australian National Spheroid
_ELLIPSOID_WGS84 = (_WGS84_A, _WGS84_F)
# 7-parameter Helmert: (dx, dy, dz, rx, ry, rz, ds, ellipsoid)
# dx/dy/dz: translation (metres)
# rx/ry/rz: rotation (arcseconds, position vector convention)
# ds: scale difference (ppm)
# ellipsoid: (a, f) of the source datum
# From EPSG dataset / NIMA TR 8350.2. Used as fallback when
# shift grids are not available.
_DATUM_PARAMS = {
# North America (3-param, no rotations published)
'NAD27': (-8.0, 160.0, 176.0, 0, 0, 0, 0, _ELLIPSOID_CLARKE1866),
'clarke66': (-8.0, 160.0, 176.0, 0, 0, 0, 0, _ELLIPSOID_CLARKE1866),
# UK -- OSGB36->ETRS89 (EPSG:1314, 7-param, position vector)
'OSGB36': (446.448, -125.157, 542.060, 0.1502, 0.2470, 0.8421, -20.4894, _ELLIPSOID_AIRY),
'airy': (446.448, -125.157, 542.060, 0.1502, 0.2470, 0.8421, -20.4894, _ELLIPSOID_AIRY),
# Germany -- DHDN->ETRS89 (EPSG:1776, 7-param)
'DHDN': (598.1, 73.7, 418.2, 0.202, 0.045, -2.455, 6.7, _ELLIPSOID_BESSEL),
'potsdam': (598.1, 73.7, 418.2, 0.202, 0.045, -2.455, 6.7, _ELLIPSOID_BESSEL),
# Austria -- MGI->ETRS89 (EPSG:1618, 7-param)
'MGI': (577.326, 90.129, 463.919, 5.1366, 1.4742, 5.2970, 2.4232, _ELLIPSOID_BESSEL),
'hermannskogel': (577.326, 90.129, 463.919, 5.1366, 1.4742, 5.2970, 2.4232, _ELLIPSOID_BESSEL),
# Europe -- ED50->WGS84 (EPSG:1133, 7-param, western Europe)
'ED50': (-87.0, -98.0, -121.0, 0, 0, 0.814, -0.38, _ELLIPSOID_INTL1924),
'intl': (-87.0, -98.0, -121.0, 0, 0, 0.814, -0.38, _ELLIPSOID_INTL1924),
# Belgium -- BD72->ETRS89 (EPSG:1609, 7-param)
'BD72': (-106.869, 52.2978, -103.724, 0.3366, -0.457, 1.8422, -1.2747, _ELLIPSOID_INTL1924),
# Switzerland -- CH1903->ETRS89 (EPSG:1753, 7-param)
'CH1903': (674.374, 15.056, 405.346, 0, 0, 0, 0, _ELLIPSOID_BESSEL),
# Portugal -- D73->ETRS89 (3-param)
'D73': (-239.749, 88.181, 30.488, 0, 0, 0, 0, _ELLIPSOID_INTL1924),
# Australia -- AGD66->GDA94 (3-param)
'AGD66': (-133.0, -48.0, 148.0, 0, 0, 0, 0, _ELLIPSOID_ANS),
'aust_SA': (-133.0, -48.0, 148.0, 0, 0, 0, 0, _ELLIPSOID_ANS),
# Japan -- Tokyo->WGS84 (3-param, grid not openly licensed)
'tokyo': (-146.414, 507.337, 680.507, 0, 0, 0, 0, _ELLIPSOID_BESSEL),
}
@njit(nogil=True, cache=True)
def _geodetic_to_ecef(lon_deg, lat_deg, a, f):
"""Geographic (deg) -> geocentric ECEF (metres)."""
lon = math.radians(lon_deg)
lat = math.radians(lat_deg)
e2 = 2.0 * f - f * f
slat = math.sin(lat)
clat = math.cos(lat)
N = a / math.sqrt(1.0 - e2 * slat * slat)
X = N * clat * math.cos(lon)
Y = N * clat * math.sin(lon)
Z = N * (1.0 - e2) * slat
return X, Y, Z
@njit(nogil=True, cache=True)
def _ecef_to_geodetic(X, Y, Z, a, f):
"""Geocentric ECEF (metres) -> geographic (deg). Iterative."""
e2 = 2.0 * f - f * f
lon = math.atan2(Y, X)
p = math.sqrt(X * X + Y * Y)
lat = math.atan2(Z, p * (1.0 - e2))
for _ in range(10):
slat = math.sin(lat)
N = a / math.sqrt(1.0 - e2 * slat * slat)
lat = math.atan2(Z + e2 * N * slat, p)
return math.degrees(lon), math.degrees(lat)
@njit(nogil=True, cache=True)
def _helmert7_fwd(lon_deg, lat_deg, dx, dy, dz, rx, ry, rz, ds,
a_src, f_src, a_tgt, f_tgt):
"""Datum shift: source -> target via 7-param Helmert (Bursa-Wolf).
rx/ry/rz in arcseconds (position vector convention), ds in ppm.
"""
X, Y, Z = _geodetic_to_ecef(lon_deg, lat_deg, a_src, f_src)
AS2RAD = math.pi / (180.0 * 3600.0)
rxr = rx * AS2RAD
ryr = ry * AS2RAD
rzr = rz * AS2RAD
sc = 1.0 + ds * 1e-6
X2 = dx + sc * (X - rzr * Y + ryr * Z)
Y2 = dy + sc * (rzr * X + Y - rxr * Z)
Z2 = dz + sc * (-ryr * X + rxr * Y + Z)
return _ecef_to_geodetic(X2, Y2, Z2, a_tgt, f_tgt)
@njit(nogil=True, cache=True)
def _helmert7_inv(lon_deg, lat_deg, dx, dy, dz, rx, ry, rz, ds,
a_src, f_src, a_tgt, f_tgt):
"""Inverse 7-param Helmert: target -> source (negate all params)."""
return _helmert7_fwd(lon_deg, lat_deg,
-dx, -dy, -dz, -rx, -ry, -rz, -ds,
a_tgt, f_tgt, a_src, f_src)
def _get_datum_params(crs):
"""Return (dx, dy, dz, rx, ry, rz, ds, a_src, f_src) for a non-WGS84 datum.
Returns None for WGS84/NAD83/GRS80 (no shift needed).
"""
try:
d = crs.to_dict()
except Exception:
return None
datum = d.get('datum', '')
ellps = d.get('ellps', '')
key = datum if datum in _DATUM_PARAMS else ellps
if key not in _DATUM_PARAMS:
return None
dx, dy, dz, rx, ry, rz, ds, (a_src, f_src) = _DATUM_PARAMS[key]
return dx, dy, dz, rx, ry, rz, ds, a_src, f_src
# ---------------------------------------------------------------------------
# Shared helpers (PROJ pj_tsfn, pj_sinhpsi2tanphi, authalic latitude)
# ---------------------------------------------------------------------------
@njit(nogil=True, cache=True)
def _norm_lon_rad(lon):
"""Normalize longitude to [-pi, pi]."""
while lon > math.pi:
lon -= 2.0 * math.pi
while lon < -math.pi:
lon += 2.0 * math.pi
return lon
@njit(nogil=True, cache=True)
def _pj_tsfn(phi, sinphi, e):
"""Isometric co-latitude: ts = exp(-psi).
Equivalent to tan(pi/4 - phi/2) / ((1-e*sinphi)/(1+e*sinphi))^(e/2).
"""
es = e * sinphi
return math.tan(math.pi / 4.0 - phi / 2.0) * math.pow(
(1.0 + es) / (1.0 - es), e / 2.0
)
@njit(nogil=True, cache=True)
def _pj_sinhpsi2tanphi(taup, e):
"""Newton iteration: recover tan(phi) from sinh(isometric lat).
Matches PROJ's pj_sinhpsi2tanphi -- 5 iterations, always converges.
"""
e2 = e * e
tau = taup
tau1 = math.sqrt(1.0 + tau * tau)
for _ in range(5):
tau1 = math.sqrt(1.0 + tau * tau)
sig = math.sinh(e * math.atanh(e * tau / tau1))
sig1 = math.sqrt(1.0 + sig * sig)
taupa = sig1 * tau - sig * tau1
dtau = ((taup - taupa) * (1.0 + (1.0 - e2) * tau * tau)
/ ((1.0 - e2) * tau1 * math.sqrt(1.0 + taupa * taupa)))
tau += dtau
if abs(dtau) < 1e-12:
break
return tau
@njit(nogil=True, cache=True)
def _authalic_q(sinphi, e):
"""Authalic latitude q-parameter: q(phi) for given sinphi and e."""
e2 = e * e
es = e * sinphi
return (1.0 - e2) * (sinphi / (1.0 - es * es) + math.atanh(es) / e)
def _authalic_apa(e):
"""Precompute 6 coefficients for the authalic latitude inverse series.
Returns array [APA0..APA5] used by _authalic_inv.
6 terms give sub-centimetre accuracy (vs ~4m with 3 terms).
Coefficients from Snyder (1987) / Karney (2011).
"""
e2 = e * e
e4 = e2 * e2
e6 = e4 * e2
e8 = e6 * e2
e10 = e8 * e2
e12 = e10 * e2
apa = np.empty(6, dtype=np.float64)
apa[0] = e2 / 3.0 + 31.0 * e4 / 180.0 + 59.0 * e6 / 560.0 + 17141.0 * e8 / 166320.0 + 28289.0 * e10 / 249480.0
apa[1] = 17.0 * e4 / 360.0 + 61.0 * e6 / 1260.0 + 10217.0 * e8 / 120960.0 + 319.0 * e10 / 3024.0
apa[2] = 383.0 * e6 / 45360.0 + 34729.0 * e8 / 1814400.0 + 192757.0 * e10 / 5765760.0
apa[3] = 6007.0 * e8 / 272160.0 + 36941.0 * e10 / 1270080.0
apa[4] = 33661.0 * e10 / 5765760.0
apa[5] = 0.0 # 12th order term negligible for Earth
return apa
@njit(nogil=True, cache=True)
def _authalic_inv(beta, apa):
"""Inverse authalic latitude: beta (authalic, rad) -> phi (geodetic, rad).
6-term Fourier series for sub-centimetre accuracy.
"""
t = 2.0 * beta
return (beta
+ apa[0] * math.sin(t)
+ apa[1] * math.sin(2.0 * t)
+ apa[2] * math.sin(3.0 * t)
+ apa[3] * math.sin(4.0 * t)
+ apa[4] * math.sin(5.0 * t))
# Precompute authalic coefficients for WGS84
_APA = _authalic_apa(_WGS84_E)
_QP = _authalic_q(1.0, _WGS84_E) # q at the pole
# ---------------------------------------------------------------------------
# Ellipsoidal Mercator (EPSG:3395)
# ---------------------------------------------------------------------------
@njit(nogil=True, cache=True)
def _emerc_fwd_point(lon_deg, lat_deg, k0, e):
"""(lon, lat) deg -> (x, y) metres, ellipsoidal Mercator."""
lam = math.radians(lon_deg)
phi = math.radians(lat_deg)
sinphi = math.sin(phi)
x = k0 * _WGS84_A * lam
y = k0 * _WGS84_A * (math.asinh(math.tan(phi)) - e * math.atanh(e * sinphi))
return x, y
@njit(nogil=True, cache=True)
def _emerc_inv_point(x, y, k0, e):
"""(x, y) metres -> (lon, lat) deg, ellipsoidal Mercator."""
lam = x / (k0 * _WGS84_A)
taup = math.sinh(y / (k0 * _WGS84_A))
tau = _pj_sinhpsi2tanphi(taup, e)
return math.degrees(lam), math.degrees(math.atan(tau))
@njit(nogil=True, cache=True, parallel=True)
def emerc_forward(lons, lats, out_x, out_y, k0, e):
for i in prange(lons.shape[0]):
out_x[i], out_y[i] = _emerc_fwd_point(lons[i], lats[i], k0, e)
@njit(nogil=True, cache=True, parallel=True)
def emerc_inverse(xs, ys, out_lon, out_lat, k0, e):
for i in prange(xs.shape[0]):
out_lon[i], out_lat[i] = _emerc_inv_point(xs[i], ys[i], k0, e)
# ---------------------------------------------------------------------------
# Lambert Conformal Conic (LCC)
# ---------------------------------------------------------------------------
def _lcc_params(crs):
"""Extract LCC projection parameters from a pyproj CRS.
Returns (lon0, lat0, n, c, rho0, k0) or None.
"""
try:
d = crs.to_dict()
except Exception:
return None
if d.get('proj') != 'lcc':
return None
if not _is_wgs84_compatible_ellipsoid(crs):
return None
units = d.get('units', 'm')
_UNIT_TO_METER = {'m': 1.0, 'us-ft': 0.3048006096012192, 'ft': 0.3048}
to_meter = _UNIT_TO_METER.get(units)
if to_meter is None:
return None
lat_1 = math.radians(d.get('lat_1', d.get('lat_0', 0.0)))
lat_2 = math.radians(d.get('lat_2', lat_1))
lat_0 = math.radians(d.get('lat_0', 0.0))
lon_0 = math.radians(d.get('lon_0', 0.0))
k0_param = d.get('k_0', d.get('k', 1.0))
e = _WGS84_E
a = _WGS84_A
sinphi1 = math.sin(lat_1)
cosphi1 = math.cos(lat_1)
sinphi2 = math.sin(lat_2)
m1 = cosphi1 / math.sqrt(1.0 - _WGS84_E2 * sinphi1 * sinphi1)
ts1 = math.tan(math.pi / 4.0 - lat_1 / 2.0) * math.pow(
(1.0 + e * sinphi1) / (1.0 - e * sinphi1), e / 2.0)
if abs(lat_1 - lat_2) > 1e-10:
m2 = cosphi2 = math.cos(lat_2)
cosphi2 /= math.sqrt(1.0 - _WGS84_E2 * sinphi2 * sinphi2)
ts2 = math.tan(math.pi / 4.0 - lat_2 / 2.0) * math.pow(
(1.0 + e * sinphi2) / (1.0 - e * sinphi2), e / 2.0)
n = math.log(m1 / cosphi2) / math.log(ts1 / ts2)
else:
n = sinphi1
c = m1 * math.pow(ts1, -n) / n
sinphi0 = math.sin(lat_0)
ts0 = math.tan(math.pi / 4.0 - lat_0 / 2.0) * math.pow(
(1.0 + e * sinphi0) / (1.0 - e * sinphi0), e / 2.0)
rho0 = a * k0_param * c * math.pow(ts0, n)
fe = d.get('x_0', 0.0) # always in metres in PROJ4 dict
fn = d.get('y_0', 0.0)
return lon_0, n, c, rho0, k0_param, fe, fn, to_meter
@njit(nogil=True, cache=True)
def _lcc_fwd_point(lon_deg, lat_deg, lon0, n, c, rho0, k0, e, a):
phi = math.radians(lat_deg)
lam = math.radians(lon_deg) - lon0
sinphi = math.sin(phi)
ts = math.tan(math.pi / 4.0 - phi / 2.0) * math.pow(
(1.0 + e * sinphi) / (1.0 - e * sinphi), e / 2.0)
rho = a * k0 * c * math.pow(ts, n)
lam_n = n * lam
x = rho * math.sin(lam_n)
y = rho0 - rho * math.cos(lam_n)
return x, y
@njit(nogil=True, cache=True)
def _lcc_inv_point(x, y, lon0, n, c, rho0, k0, e, a):
rho0_y = rho0 - y
if n < 0.0:
rho = -math.hypot(x, rho0_y)
lam_n = math.atan2(-x, -rho0_y)
else:
rho = math.hypot(x, rho0_y)
lam_n = math.atan2(x, rho0_y)
if abs(rho) < 1e-30:
return math.degrees(_norm_lon_rad(lon0 + lam_n / n)), 90.0 if n > 0 else -90.0
ts = math.pow(rho / (a * k0 * c), 1.0 / n)
# Recover phi from ts via Newton (pj_sinhpsi2tanphi)
phi_approx = math.pi / 2.0 - 2.0 * math.atan(ts)
taup = math.sinh(math.log(1.0 / ts)) # sinh(psi)
tau = _pj_sinhpsi2tanphi(taup, e)
phi = math.atan(tau)
lam = lam_n / n
return math.degrees(_norm_lon_rad(lam + lon0)), math.degrees(phi)
@njit(nogil=True, cache=True, parallel=True)
def lcc_forward(lons, lats, out_x, out_y,
lon0, n, c, rho0, k0, fe, fn, e, a):
for i in prange(lons.shape[0]):
x, y = _lcc_fwd_point(lons[i], lats[i], lon0, n, c, rho0, k0, e, a)
out_x[i] = x + fe
out_y[i] = y + fn
@njit(nogil=True, cache=True, parallel=True)
def lcc_inverse(xs, ys, out_lon, out_lat,
lon0, n, c, rho0, k0, fe, fn, e, a):
for i in prange(xs.shape[0]):
out_lon[i], out_lat[i] = _lcc_inv_point(
xs[i] - fe, ys[i] - fn, lon0, n, c, rho0, k0, e, a)
@njit(nogil=True, cache=True, parallel=True)
def lcc_inverse_2d(x_1d, y_1d, out_lon_2d, out_lat_2d,
lon0, n, c, rho0, k0, fe, fn, e, a, to_m):
"""2D LCC inverse from 1D coordinate arrays, with built-in unit conversion.
Avoids np.tile/np.repeat (saves ~550ms for 4096x4096) and fuses
the unit conversion into the inner loop.
"""
h = y_1d.shape[0]
w = x_1d.shape[0]
for i in prange(h):
y_m = y_1d[i] * to_m - fn
for j in range(w):
x_m = x_1d[j] * to_m - fe
out_lon_2d[i, j], out_lat_2d[i, j] = _lcc_inv_point(
x_m, y_m, lon0, n, c, rho0, k0, e, a)
@njit(nogil=True, cache=True, parallel=True)
def tmerc_inverse_2d(x_1d, y_1d, out_lon_2d, out_lat_2d,
lon0, k0, fe, fn, Qn, beta, cgb, to_m):
"""2D tmerc inverse from 1D coordinate arrays, with unit conversion."""
h = y_1d.shape[0]
w = x_1d.shape[0]
for i in prange(h):
y_m = y_1d[i] * to_m - fn
for j in range(w):
x_m = x_1d[j] * to_m - fe
out_lon_2d[i, j], out_lat_2d[i, j] = _tmerc_inv_point(
x_m, y_m, lon0, k0, Qn, beta, cgb)
# ---------------------------------------------------------------------------
# Albers Equal Area Conic (AEA)
# ---------------------------------------------------------------------------
def _aea_params(crs):
"""Extract AEA projection parameters from a pyproj CRS.
Returns (lon0, n, c, dd, rho0, fe, fn) or None.
"""
try:
d = crs.to_dict()
except Exception:
return None
if d.get('proj') != 'aea':
return None
lat_1 = math.radians(d.get('lat_1', 0.0))
lat_2 = math.radians(d.get('lat_2', lat_1))
lat_0 = math.radians(d.get('lat_0', 0.0))
lon_0 = math.radians(d.get('lon_0', 0.0))
e = _WGS84_E
e2 = _WGS84_E2
a = _WGS84_A
sinphi1 = math.sin(lat_1)
cosphi1 = math.cos(lat_1)
sinphi2 = math.sin(lat_2)
cosphi2 = math.cos(lat_2)
m1 = cosphi1 / math.sqrt(1.0 - e2 * sinphi1 * sinphi1)
m2 = cosphi2 / math.sqrt(1.0 - e2 * sinphi2 * sinphi2)
q1 = _authalic_q(sinphi1, e)
q2 = _authalic_q(sinphi2, e)
q0 = _authalic_q(math.sin(lat_0), e)
if abs(lat_1 - lat_2) > 1e-10:
n = (m1 * m1 - m2 * m2) / (q2 - q1)
else:
n = sinphi1
C = m1 * m1 + n * q1
rho0 = a * math.sqrt(C - n * q0) / n
fe = d.get('x_0', 0.0)
fn = d.get('y_0', 0.0)
return lon_0, n, C, rho0, fe, fn
@njit(nogil=True, cache=True)
def _aea_fwd_point(lon_deg, lat_deg, lon0, n, C, rho0, e, a):
phi = math.radians(lat_deg)
lam = math.radians(lon_deg) - lon0
q = _authalic_q(math.sin(phi), e)
val = C - n * q
if val < 0.0:
val = 0.0
rho = a * math.sqrt(val) / n
theta = n * lam
x = rho * math.sin(theta)
y = rho0 - rho * math.cos(theta)
return x, y
@njit(nogil=True, cache=True)
def _aea_inv_point(x, y, lon0, n, C, rho0, e, a, qp, apa):
rho0_y = rho0 - y
if n < 0.0:
rho = -math.hypot(x, rho0_y)
theta = math.atan2(-x, -rho0_y)
else:
rho = math.hypot(x, rho0_y)
theta = math.atan2(x, rho0_y)
q = (C - (rho * rho * n * n) / (a * a)) / n
# beta = asin(q / qp), clamped
ratio = q / qp
if ratio > 1.0:
ratio = 1.0
elif ratio < -1.0:
ratio = -1.0
beta = math.asin(ratio)
phi = _authalic_inv(beta, apa)
lam = theta / n
return math.degrees(_norm_lon_rad(lam + lon0)), math.degrees(phi)
@njit(nogil=True, cache=True, parallel=True)
def aea_forward(lons, lats, out_x, out_y,
lon0, n, C, rho0, fe, fn, e, a):
for i in prange(lons.shape[0]):
x, y = _aea_fwd_point(lons[i], lats[i], lon0, n, C, rho0, e, a)
out_x[i] = x + fe
out_y[i] = y + fn
@njit(nogil=True, cache=True, parallel=True)
def aea_inverse(xs, ys, out_lon, out_lat,
lon0, n, C, rho0, fe, fn, e, a, qp, apa):
for i in prange(xs.shape[0]):
out_lon[i], out_lat[i] = _aea_inv_point(
xs[i] - fe, ys[i] - fn, lon0, n, C, rho0, e, a, qp, apa)
# ---------------------------------------------------------------------------
# Cylindrical Equal Area (CEA)
# ---------------------------------------------------------------------------
def _cea_params(crs):
"""Extract CEA projection parameters from a pyproj CRS.
Returns (lon0, k0, fe, fn) or None.
"""
try:
d = crs.to_dict()
except Exception:
return None
if d.get('proj') != 'cea':
return None
lon_0 = math.radians(d.get('lon_0', 0.0))
lat_ts = math.radians(d.get('lat_ts', 0.0))
sinlts = math.sin(lat_ts)
coslts = math.cos(lat_ts)
# k0 = cos(lat_ts) / sqrt(1 - e² sin²(lat_ts))
k0 = coslts / math.sqrt(1.0 - _WGS84_E2 * sinlts * sinlts)
fe = d.get('x_0', 0.0)
fn = d.get('y_0', 0.0)
return lon_0, k0, fe, fn
@njit(nogil=True, cache=True)
def _cea_fwd_point(lon_deg, lat_deg, lon0, k0, e, a, qp):
lam = math.radians(lon_deg) - lon0
phi = math.radians(lat_deg)
q = _authalic_q(math.sin(phi), e)
x = a * k0 * lam
y = a * q / (2.0 * k0)
return x, y
@njit(nogil=True, cache=True)
def _cea_inv_point(x, y, lon0, k0, e, a, qp, apa):
lam = x / (a * k0)
ratio = 2.0 * y * k0 / (a * qp)
if ratio > 1.0:
ratio = 1.0
elif ratio < -1.0:
ratio = -1.0
beta = math.asin(ratio)
phi = _authalic_inv(beta, apa)
return math.degrees(_norm_lon_rad(lam + lon0)), math.degrees(phi)
@njit(nogil=True, cache=True, parallel=True)
def cea_forward(lons, lats, out_x, out_y,
lon0, k0, fe, fn, e, a, qp):
for i in prange(lons.shape[0]):
x, y = _cea_fwd_point(lons[i], lats[i], lon0, k0, e, a, qp)
out_x[i] = x + fe
out_y[i] = y + fn
@njit(nogil=True, cache=True, parallel=True)
def cea_inverse(xs, ys, out_lon, out_lat,
lon0, k0, fe, fn, e, a, qp, apa):
for i in prange(xs.shape[0]):
out_lon[i], out_lat[i] = _cea_inv_point(
xs[i] - fe, ys[i] - fn, lon0, k0, e, a, qp, apa)
# ---------------------------------------------------------------------------
# Shared: Meridional arc length (pj_mlfn / pj_enfn / pj_inv_mlfn)
# Used by Sinusoidal ellipsoidal
# ---------------------------------------------------------------------------
def _mlfn_coeffs(es):
"""Precompute 5 coefficients for meridional arc length.
Matches PROJ's pj_enfn exactly. Returns array en[0..4].
"""
en = np.empty(5, dtype=np.float64)
# Constants from PROJ mlfn.cpp
en[0] = 1.0 - es * (0.25 + es * (0.046875 + es * (0.01953125 + es * 0.01068115234375)))
en[1] = es * (0.75 - es * (0.046875 + es * (0.01953125 + es * 0.01068115234375)))
t = es * es
en[2] = t * (0.46875 - es * (0.013020833333333334 + es * 0.007120768229166667))
en[3] = t * es * (0.3645833333333333 - es * 0.005696614583333333)
en[4] = t * es * es * 0.3076171875
return en
@njit(nogil=True, cache=True)
def _mlfn(phi, sinphi, cosphi, en):
"""Meridional arc length from equator to phi.
Matches PROJ's pj_mlfn: recurrence in sin^2(phi).
"""
cphi = cosphi * sinphi # = sin(2*phi)/2
sphi = sinphi * sinphi # = sin^2(phi)
return en[0] * phi - cphi * (en[1] + sphi * (en[2] + sphi * (en[3] + sphi * en[4])))
@njit(nogil=True, cache=True)
def _inv_mlfn(arg, e2, en):
"""Inverse meridional arc length: M -> phi. Newton iteration."""
k = 1.0 / (1.0 - e2)
phi = arg
for _ in range(20):
s = math.sin(phi)
c = math.cos(phi)
t = 1.0 - e2 * s * s
dphi = (arg - _mlfn(phi, s, c, en)) * t * math.sqrt(t) * k
phi += dphi
if abs(dphi) < 1e-14:
break
return phi
# Precompute for WGS84
_MLFN_EN = _mlfn_coeffs(_WGS84_E2)
# ---------------------------------------------------------------------------
# Sinusoidal (ellipsoidal)
# ---------------------------------------------------------------------------
def _sinu_params(crs):
"""Extract Sinusoidal parameters from a pyproj CRS.
Returns (lon0, fe, fn) or None.
"""
try:
d = crs.to_dict()
except Exception:
return None
if d.get('proj') != 'sinu':
return None
if not _is_wgs84_compatible_ellipsoid(crs):
return None
lon_0 = math.radians(d.get('lon_0', 0.0))
fe = d.get('x_0', 0.0)
fn = d.get('y_0', 0.0)
return lon_0, fe, fn
@njit(nogil=True, cache=True)
def _sinu_fwd_point(lon_deg, lat_deg, lon0, e2, a, en):
phi = math.radians(lat_deg)
lam = math.radians(lon_deg) - lon0
s = math.sin(phi)
c = math.cos(phi)
ms = _mlfn(phi, s, c, en)
x = a * lam * c / math.sqrt(1.0 - e2 * s * s)
y = a * ms
return x, y
@njit(nogil=True, cache=True)
def _sinu_inv_point(x, y, lon0, e2, a, en):
phi = _inv_mlfn(y / a, e2, en)
s = math.sin(phi)
c = math.cos(phi)
if abs(c) < 1e-14:
lam = 0.0
else:
lam = x * math.sqrt(1.0 - e2 * s * s) / (a * c)
return math.degrees(_norm_lon_rad(lam + lon0)), math.degrees(phi)
@njit(nogil=True, cache=True, parallel=True)
def sinu_forward(lons, lats, out_x, out_y,
lon0, fe, fn, e2, a, en):
for i in prange(lons.shape[0]):
x, y = _sinu_fwd_point(lons[i], lats[i], lon0, e2, a, en)
out_x[i] = x + fe
out_y[i] = y + fn
@njit(nogil=True, cache=True, parallel=True)
def sinu_inverse(xs, ys, out_lon, out_lat,
lon0, fe, fn, e2, a, en):
for i in prange(xs.shape[0]):
out_lon[i], out_lat[i] = _sinu_inv_point(
xs[i] - fe, ys[i] - fn, lon0, e2, a, en)
# ---------------------------------------------------------------------------
# Lambert Azimuthal Equal Area (LAEA) -- oblique & polar
# ---------------------------------------------------------------------------
def _laea_params(crs):
"""Extract LAEA parameters from a pyproj CRS.
Returns (lon0, lat0, sinb1, cosb1, dd, xmf, ymf, rq, qp, fe, fn, mode)
where mode: 0=OBLIQ, 1=EQUIT, 2=N_POLE, 3=S_POLE.
Or None if not LAEA.
"""
try:
d = crs.to_dict()
except Exception:
return None
if d.get('proj') != 'laea':
return None
if not _is_wgs84_compatible_ellipsoid(crs):
return None
lon_0 = math.radians(d.get('lon_0', 0.0))
lat_0 = math.radians(d.get('lat_0', 0.0))
fe = d.get('x_0', 0.0)
fn = d.get('y_0', 0.0)
e = _WGS84_E
a = _WGS84_A
e2 = _WGS84_E2
qp = _authalic_q(1.0, e)
rq = math.sqrt(0.5 * qp)
EPS10 = 1e-10
if abs(lat_0 - math.pi / 2) < EPS10:
mode = 2 # N_POLE
elif abs(lat_0 + math.pi / 2) < EPS10:
mode = 3 # S_POLE
elif abs(lat_0) < EPS10:
mode = 1 # EQUIT
else:
mode = 0 # OBLIQ
if mode == 0: # OBLIQ
sinphi0 = math.sin(lat_0)
q0 = _authalic_q(sinphi0, e)
sinb1 = q0 / qp
cosb1 = math.sqrt(1.0 - sinb1 * sinb1)
m1 = math.cos(lat_0) / math.sqrt(1.0 - e2 * sinphi0 * sinphi0)
dd = m1 / (rq * cosb1)
# PROJ: xmf = rq * dd, ymf = rq / dd
xmf = rq * dd
ymf = rq / dd
elif mode == 1: # EQUIT
sinb1 = 0.0
cosb1 = 1.0
m1 = math.cos(lat_0) / math.sqrt(1.0 - e2 * math.sin(lat_0)**2)
dd = m1 / rq
xmf = rq * dd
ymf = rq / dd
else: # POLAR
sinb1 = 1.0 if mode == 2 else -1.0
cosb1 = 0.0
dd = 1.0
xmf = rq
ymf = rq
return lon_0, lat_0, sinb1, cosb1, dd, xmf, ymf, rq, qp, fe, fn, mode
@njit(nogil=True, cache=True)
def _laea_fwd_point(lon_deg, lat_deg, lon0, sinb1, cosb1,
xmf, ymf, rq, qp, e, a, e2, mode):
phi = math.radians(lat_deg)
lam = math.radians(lon_deg) - lon0
sinphi = math.sin(phi)
q = (1.0 - e2) * (sinphi / (1.0 - e2 * sinphi * sinphi)
+ math.atanh(e * sinphi) / e)
sinb = q / qp
if sinb > 1.0:
sinb = 1.0
elif sinb < -1.0:
sinb = -1.0
cosb = math.sqrt(1.0 - sinb * sinb)
coslam = math.cos(lam)
sinlam = math.sin(lam)
if mode == 0: # OBLIQ
denom = 1.0 + sinb1 * sinb + cosb1 * cosb * coslam
if denom < 1e-30:
denom = 1e-30
b = math.sqrt(2.0 / denom)
x = a * xmf * b * cosb * sinlam
y = a * ymf * b * (cosb1 * sinb - sinb1 * cosb * coslam)
elif mode == 1: # EQUIT
denom = 1.0 + cosb * coslam
if denom < 1e-30:
denom = 1e-30
b = math.sqrt(2.0 / denom)
x = a * xmf * b * cosb * sinlam
y = a * ymf * b * sinb
elif mode == 2: # N_POLE
q_diff = qp - q
if q_diff < 0.0:
q_diff = 0.0
rho = a * math.sqrt(q_diff)
x = rho * sinlam
y = -rho * coslam
else: # S_POLE
q_diff = qp + q
if q_diff < 0.0:
q_diff = 0.0
rho = a * math.sqrt(q_diff)
x = rho * sinlam
y = rho * coslam
return x, y
@njit(nogil=True, cache=True)
def _laea_inv_point(x, y, lon0, sinb1, cosb1,
xmf, ymf, rq, qp, e, a, e2, mode, apa):
if mode == 2 or mode == 3: # POLAR
x_a = x / a
y_a = y / a
rho = math.hypot(x_a, y_a)
if rho < 1e-30:
return math.degrees(lon0), 90.0 if mode == 2 else -90.0
q = qp - rho * rho
if mode == 3:
q = -(qp - rho * rho)
lam = math.atan2(x_a, y_a)
else:
lam = math.atan2(x_a, -y_a)
else: # OBLIQ or EQUIT
# PROJ: x /= dd, y *= dd (undo the xmf/ymf scaling)
xn = x / (a * xmf) # = x / (a * rq * dd)
yn = y / (a * ymf) # = y / (a * rq / dd) = y * dd / (a * rq)
rho = math.hypot(xn, yn)
if rho < 1e-30:
return math.degrees(lon0), math.degrees(math.asin(sinb1))
sce = 2.0 * math.asin(0.5 * rho / rq)
sinz = math.sin(sce)
cosz = math.cos(sce)
if mode == 0: # OBLIQ
ab = cosz * sinb1 + yn * sinz * cosb1 / rho
lam = math.atan2(xn * sinz,
rho * cosb1 * cosz - yn * sinb1 * sinz)
else: # EQUIT
ab = yn * sinz / rho
lam = math.atan2(xn * sinz, rho * cosz)
q = qp * ab
# q -> phi via authalic inverse
ratio = q / qp
if ratio > 1.0:
ratio = 1.0
elif ratio < -1.0:
ratio = -1.0
beta = math.asin(ratio)
phi = beta + apa[0] * math.sin(2.0 * beta) + apa[1] * math.sin(4.0 * beta) + apa[2] * math.sin(6.0 * beta)
return math.degrees(_norm_lon_rad(lam + lon0)), math.degrees(phi)
@njit(nogil=True, cache=True, parallel=True)
def laea_forward(lons, lats, out_x, out_y,
lon0, sinb1, cosb1, xmf, ymf, rq, qp,
fe, fn, e, a, e2, mode):
for i in prange(lons.shape[0]):
x, y = _laea_fwd_point(lons[i], lats[i], lon0, sinb1, cosb1,
xmf, ymf, rq, qp, e, a, e2, mode)
out_x[i] = x + fe
out_y[i] = y + fn
@njit(nogil=True, cache=True, parallel=True)
def laea_inverse(xs, ys, out_lon, out_lat,
lon0, sinb1, cosb1, xmf, ymf, rq, qp,
fe, fn, e, a, e2, mode, apa):
for i in prange(xs.shape[0]):
out_lon[i], out_lat[i] = _laea_inv_point(
xs[i] - fe, ys[i] - fn, lon0, sinb1, cosb1,
xmf, ymf, rq, qp, e, a, e2, mode, apa)
# ---------------------------------------------------------------------------
# Polar Stereographic (N_POLE / S_POLE only)
# ---------------------------------------------------------------------------
def _stere_params(crs):
"""Extract Polar Stereographic parameters.
Returns (lon0, k0, akm1, fe, fn, is_south) or None.
Supports EPSG codes for UPS and common polar stereographic CRSs,
and generic stere/ups proj definitions with polar lat_0.
"""
try:
d = crs.to_dict()
except Exception:
return None
proj = d.get('proj', '')
if proj not in ('stere', 'ups', 'sterea'):
return None
if not _is_wgs84_compatible_ellipsoid(crs):
return None
lat_0 = d.get('lat_0', 0.0)
if abs(abs(lat_0) - 90.0) > 1e-6:
return None # only polar modes
is_south = lat_0 < 0
lon_0 = math.radians(d.get('lon_0', 0.0))
lat_ts = d.get('lat_ts', None)
k0 = d.get('k_0', d.get('k', None))
e = _WGS84_E
e2 = _WGS84_E2
a = _WGS84_A
if k0 is not None:
k0 = float(k0)
elif lat_ts is not None:
lat_ts_r = math.radians(abs(lat_ts))
sinlts = math.sin(lat_ts_r)
coslts = math.cos(lat_ts_r)
# k0 from latitude of true scale
m_ts = coslts / math.sqrt(1.0 - e2 * sinlts * sinlts)
t_ts = math.tan(math.pi / 4.0 - lat_ts_r / 2.0) * math.pow(
(1.0 + e * sinlts) / (1.0 - e * sinlts), e / 2.0)
t_90 = 0.0 # tan(pi/4 - pi/4) = 0 at the pole
# For polar: k0 = m_ts / (2 * t_ts) * (something)
# Actually, for UPS/polar stereographic:
# akm1 = a * m_ts / sqrt((1+e)^(1+e) * (1-e)^(1-e)) / (2 * t_ts)
# But simpler: akm1 = a * k0 * 2 / sqrt((1+e)^(1+e)*(1-e)^(1-e))
# Let's compute akm1 directly