-
Notifications
You must be signed in to change notification settings - Fork 57
/
geoids.py
1741 lines (1466 loc) · 73 KB
/
geoids.py
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
# -*- coding: utf-8 -*-
u'''Classes L{GeoidG2012B}, L{GeoidKarney} and L{GeoidPGM} to interpolate
the height of various U{geoid<https://WikiPedia.org/wiki/Geoid>}s at
C{LatLon} locations or separate lat-/longitudes using different
interpolation methods and C{geoid} files.
L{GeoidKarney} is a transcription of I{Charles Karney's} C++ class U{Geoid
<https://GeographicLib.SourceForge.io/html/geoid.html>} to pure Python.
The L{GeoidG2012B} and L{GeoidPGM} interpolators both depend on
U{scipy<https://SciPy.org>} and U{numpy<https://PyPI.org/project/numpy>}
and require those packages to be installed.
In addition, each geoid interpolator needs C{grid knots} to be
(down)loaded from a geoid file, specific to the interpolator, more
details below. For each interpolator, there are several interpolation
choices, like I{linear}, I{cubic}, etc.
Typical usage is as follows. First create an interpolator from a
geoid file, also referred to as the C{grid knots}.
C{ginterpolator = GeoidXyz(grid_file, **options)}
Get the interpolated geoid height of C{LatLon} location(s) with
C{h = ginterpolator(ll)}
or
C{h0, h1, h2, ... = ginterpolator(ll0, ll1, ll2, ...)}
or
C{hs = ginterpolator(lls)} # C{list, tuple, generator, ...}
For separate lat-/longitudes invoke the C{.height} method
C{h = ginterpolator.height(lat, lon)}
or
C{h0, h1, h2, ... = ginterpolator.height(lats, lons)} # C{list, ...}
Errors from C{scipy} are raised as L{SciPyError}s. Warnings issued by
C{scipy} can be thrown as L{SciPyWarning} exceptions, provided Python
C{warnings} are filtered accordingly, see L{SciPyWarning}.
@see: Charles Karney's U{GeographicLib<https://GeographicLib.SourceForge.io/
html/index.html>}, U{Geoid height<https://GeographicLib.SourceForge.io/
html/geoid.html>} and U{Installing the Geoid datasets<https://
GeographicLib.SourceForge.io/html/geoid.html#geoidinst>}, U{SciPy
<https://docs.SciPy.org/doc/scipy/reference/interpolate.html>}
interpolation U{RectBivariateSpline<https://docs.SciPy.org/doc/scipy/
reference/generated/scipy.interpolate.RectBivariateSpline.html>}
and U{interp2d<https://docs.SciPy.org/doc/scipy/reference/generated/
scipy.interpolate.interp2d.html>} and the functions
L{elevations.elevation2} and L{elevations.geoidHeight2}.
'''
from pygeodesy.basics import EPS, len2, map1, map2, property_RO
from pygeodesy.datum import Datum, Datums
from pygeodesy.dms import parseDMS2
from pygeodesy.errors import _incompatible, LenError, RangeError, _SciPyIssue
from pygeodesy.fmath import favg, Fdot, fdot, Fhorner, frange
from pygeodesy.heights import _allis2, _ascalar, \
_HeightBase, HeightError
from pygeodesy.interns import _COMMA_SPACE_, _cubic_, _E_, _item_cs, \
_item_pr, _item_ps, _item_sq, _knots_, \
_lat_, _linear_, _lon_, _N_, _n_a_, NN, \
_outside_, _S_, _utf_8_, _W_
from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _FOR_DOCS
from pygeodesy.named import LatLon3Tuple, _Named, _NamedTuple, \
notOverloaded
from pygeodesy.streprs import attrs, fstr, pairs
from pygeodesy.units import Int_
from math import floor
import os.path as _os_path
from os import SEEK_CUR as _SEEK_CUR, SEEK_SET as _SEEK_SET
from struct import calcsize as _calcsize, unpack as _unpack
try:
from StringIO import StringIO as _BytesIO # reads bytes
_b2str = str # convert bytes to str
except ImportError: # Python 3+
from io import BytesIO as _BytesIO # PYCHOK expected
def _b2str(bs): # used only for egm*.pgm text
return bs.decode(_utf_8_)
__all__ = _ALL_LAZY.geoids
__version__ = '20.07.08'
# temporarily hold a single instance for each int value
_intCs = {}
_interp2d_ks = {-2: _linear_,
-3: _cubic_,
-5: 'quintic'}
_not_supported_ = 'not supported'
class _GeoidBase(_HeightBase):
'''(INTERNAL) Base class for C{Geoid...}s.
'''
_cropped = None
_datum = Datums.WGS84
_endian = 'tbd'
_geoid = _n_a_
_hs_y_x = None # numpy 2darray, row-major order
_interp2d = None # interp2d interpolation
_kind = 3 # order for interp2d, RectBivariateSpline
_knots = 0 # nlat * nlon
_mean = None
# _name = NN # _Named
_nBytes = 0 # numpy size in bytes, float64
_pgm = None
_sizeB = 0 # geoid file size in bytes
_smooth = 0 # used only for RectBivariateSpline
_stdev = None
_lat_d = 0.0 # increment, +tive
_lat_lo = 0.0 # lower lat, south
_lat_hi = 0.0 # upper lat, noth
_lon_d = 0.0 # increment, +tive
_lon_lo = 0.0 # left lon, west
_lon_hi = 0.0 # right lon, east
_lon_of = 0.0 # forward lon offset
_lon_og = 0.0 # reverse lon offset
_center = None # (lat, lon, height)
_highest = None # (lat, lon, height)
_lowerleft = None # (lat, lon, height)
_lowerright = None # (lat, lon, height)
_lowest = None # (lat, lon, height)
_upperleft = None # (lat, lon, height)
_upperright = None # (lat, lon, height)
_yx_hits = None # cache hits, ala Karney
def __init__(self, hs, p):
'''(INTERNAL) Set up the grid axes, the C{SciPy} interpolator
and several internal geoid attributes.
@arg hs: Grid knots with known height (C{numpy 2darray}).
@arg p: The C{slat, wlon, nlat, nlon, dlat, dlon} and
other geoid parameters (C{INTERNAL}).
@raise GeoidError: Incompatible grid B{C{hs}} shape or
invalid B{C{kind}}.
@raise LenError: Mismatch grid B{C{hs}} axis.
@raise SciPyError: A C{scipy.interpolate.inter2d} or
C{-.RectBivariateSpline} issue.
@raise SciPyWarning: A C{scipy.interpolate.inter2d} or
C{-.RectBivariateSpline} warning as
exception.
'''
# for 2d scipy.interpolate.interp2d(xs, ys, hs, ...) and
# scipy.interpolate.RectBivariateSpline(ys, xs, hs, ...)
# require the shape of hs to be (len(ys), len(xs)), note
# the different (xs, ys, ...) and (ys, xs, ...) orders
if (p.nlat, p.nlon) != hs.shape:
raise GeoidError(shape=hs.shape, txt=_incompatible((p.nlat, p.nlon)))
# both axes and bounding box
ys, self._lat_d = self._gaxis2(p.slat, p.dlat, p.nlat, 'lats')
xs, self._lon_d = self._gaxis2(p.wlon, p.dlon, p.nlon, 'lons')
bb = ys[0], ys[-1], xs[0], xs[-1] + p.dlon # fudge lon_hi
# geoid grids are typically stored in row-major order, some
# with rows (90..-90) reversed and columns (0..360) wrapped
# to Easten longitude, 0 <= east < 180 and 180 <= west < 0
k = self._kind
if k in _interp2d_ks:
self._interp2d = self._spi.interp2d(xs, ys, hs, kind=_interp2d_ks[k])
elif 1 <= k <= 5:
self._ev = self._spi.RectBivariateSpline(ys, xs, hs, bbox=bb,
ky=k, kx=k,
s=self._smooth).ev
else:
raise GeoidError(kind=k)
self._hs_y_x = hs # numpy 2darray, row-major
self._nBytes = hs.nbytes # numpy size in bytes
self._knots = p.knots # grid knots
self._lon_of = float(p.flon) # forward offset
self._lon_og = float(p.glon) # reverse offset
# shrink the box by 1 unit on every side
# bb += self._lat_d, -self._lat_d, self._lon_d, -self._lon_d
self._lat_lo = float(bb[0])
self._lat_hi = float(bb[1])
self._lon_lo = float(bb[2] - p.glon)
self._lon_hi = float(bb[3] - p.glon)
def __call__(self, *llis):
'''Interpolate the geoid height for one or several locations.
@arg llis: The location or locations (C{LatLon}, ... or
C{LatLon}s).
@return: A single interpolated geoid height (C{float}) or
a list or tuple of interpolated geoid heights
(C{float}s).
@raise GeoidError: Insufficient number of B{C{llis}} or an
invalid B{C{lli}}.
@raise RangeError: An B{C{lli}} is outside this geoid's lat-
or longitude range.
@raise SciPyError: A C{scipy.interpolate.inter2d} or
C{-.RectBivariateSpline} issue.
@raise SciPyWarning: A C{scipy.interpolate.inter2d} or
C{-.RectBivariateSpline} warning as
exception.
'''
return self._called(llis, True)
def __repr__(self):
return self.toStr()
def __str__(self):
return _item_pr(self.classname, self.name)
def _called(self, llis, scipy):
# handle __call__
_as, llis = _allis2(llis, Error=GeoidError)
try:
hs = []
for i, lli in enumerate(llis):
hs.append(self._hGeoid(lli.lat, lli.lon))
return _as(hs)
except (GeoidError, RangeError) as x:
# XXX avoid str(LatLon()) degree symbols
t = 'lli' if _as is _ascalar else _item_sq(llis=i)
lli = fstr((lli.lat, lli.lon), strepr=repr)
raise type(x)(t, lli, txt=str(x))
except Exception as x:
if scipy and self.scipy:
raise _SciPyIssue(x)
else:
raise
def _ev(self, y, x): # PYCHOK expected
# only used for .interpolate.interp2d, but
# overwritten for .RectBivariateSpline,
# note (y, x) must be flipped!
return self._interp2d(x, y)
def _gaxis2(self, lo, d, n, name):
# build grid axis, hi = lo + (n - 1) * d
m, a = len2(frange(lo, n, d))
if m != n:
raise LenError(self.__class__, grid=m, **{name: n})
if d < 0:
d, a = -d, list(reversed(a))
for i in range(1, m):
e = a[i] - a[i-1]
if e < EPS: # non-increasing axis
raise GeoidError(_item_sq(name, i), e, txt='non-increasing')
return self._np.array(a), d
def _g2ll2(self, lat, lon): # PYCHOK no cover
notOverloaded(self, self._g2ll2, lat, lon)
def _gyx2g2(self, y, x):
# convert grid (y, x) indices to grid (lat, lon)
return ((self._lat_lo + self._lat_d * y),
(self._lon_lo + self._lon_of + self._lon_d * x))
def _hGeoid(self, lat, lon):
out = self.outside(lat, lon)
if out:
lli = fstr((lat, lon), strepr=repr)
raise RangeError('lli', lli, txt='%s on %s' % (_outside_, out))
return float(self._ev(*self._ll2g2(lat, lon)))
def _ll2g2(self, lat, lon): # PYCHOK no cover
notOverloaded(self, self._ll2g2, lat, lon)
def _llh3(self, lat, lon):
r = LatLon3Tuple(lat, lon, self._hGeoid(lat, lon))
return self._xnamed(r)
def _llh3LL(self, llh, LatLon):
return llh if LatLon is None else LatLon(*llh)
def _llh3minmax(self, highest=True, *unused):
hs, np = self._hs_y_x, self._np
# <https://docs.SciPy.org/doc/numpy/reference/generated/
# numpy.argmin.html#numpy.argmin>
arg = self._np.argmax if highest else self._np.argmin
y, x = np.unravel_index(arg(hs, axis=None), hs.shape)
return self._g2ll2(*self._gyx2g2(y, x)) + (float(hs[y, x]),)
def _load(self, g, dtype, n, offset=0):
# numpy.fromfile, like .frombuffer
g.seek(offset, _SEEK_SET)
return self._np.fromfile(g, dtype, n)
def _open(self, geoid, datum, kind, name, smooth):
# open the geoid file
try:
self._geoid = _os_path.basename(geoid)
self._sizeB = _os_path.getsize(geoid)
g = open(geoid, 'rb')
except (IOError, OSError) as x:
raise GeoidError(geoid=geoid, txt=str(x))
if datum and isinstance(datum, Datum):
self._datum = datum
self._kind = int(kind)
if name:
_HeightBase.name.fset(self, name) # recursion
if smooth:
self._smooth = Int_(smooth, name='smooth', Error=GeoidError, low=0)
return g
def _swne(self, crop):
# crop box to 4-tuple (s, w, n, e)
try:
if len(crop) == 2:
try: # sw, ne LatLons
swne = (crop[0].lat, crop[0].lon,
crop[1].lat, crop[1].lon)
except AttributeError: # (s, w), (n, e)
swne = tuple(crop[0]) + tuple(crop[1])
else: # (s, w, n, e)
swne = crop
if len(swne) == 4:
s, w, n, e = map(float, swne)
if -90 <= s <= (n - 1) <= 89 and \
-180 <= w <= (e - 1) <= 179:
return s, w, n, e
except (IndexError, TypeError, ValueError):
pass
raise GeoidError(crop=crop)
def center(self, LatLon=None):
'''Return the center location and height of this geoid.
@kwarg LatLon: Optional class to return the location and height
(C{LatLon}) or C{None}.
@return: If B{C{LatLon}} is C{None}, a L{LatLon3Tuple}C{(lat,
lon, height)} otherwise a B{C{LatLon}} instance
with the lat-, longitude and height of the grid
center location.
'''
if self._center is None:
self._center = self._llh3(favg(self._lat_lo, self._lat_hi),
favg(self._lon_lo, self._lon_hi))
return self._llh3LL(self._center, LatLon)
@property_RO
def cropped(self):
'''Is geoid cropped (C{bool} or C{None} if crop not supported).
'''
return self._cropped
@property_RO
def dtype(self):
'''Get the grid C{scipy} U{dtype<https://docs.SciPy.org/doc/numpy/
reference/generated/numpy.ndarray.dtype.html>} (C{numpy.dtype}).
'''
return self._hs_y_x.dtype
@property_RO
def endian(self):
'''Get the geoid endianess and U{dtype<https://docs.SciPy.org/
doc/numpy/reference/generated/numpy.dtype.html>} (C{str}).
'''
return self._endian
def height(self, lats, lons):
'''Interpolate the geoid height for one or several lat-/longitudes.
@arg lats: Latitude or latitudes (C{degrees} or C{degrees}s).
@arg lons: Longitude or longitudes (C{degrees} or C{degrees}s).
@return: A single interpolated geoid height (C{float}) or a
list of interpolated geoid heights (C{float}s).
@raise GeoidError: Insufficient or non-matching number of
B{C{lats}} and B{C{lons}}.
@raise RangeError: A B{C{lat}} or B{C{lon}} is outside this
geoid's lat- or longitude range.
@raise SciPyError: A C{scipy.interpolate.inter2d} or
C{-.RectBivariateSpline} issue.
@raise SciPyWarning: A C{scipy.interpolate.inter2d} or
C{-.RectBivariateSpline} warning as
exception.
'''
return _HeightBase._height(self, lats, lons, Error=GeoidError)
def highest(self, LatLon=None, **unused):
'''Return the location and largest height of this geoid.
@kwarg LatLon: Optional class to return the location and height
(C{LatLon}) or C{None}.
@return: If B{C{LatLon}} is C{None}, a L{LatLon3Tuple}C{(lat,
lon, height)} otherwise a B{C{LatLon}} instance
with the lat-, longitude and height of the highest
grid location.
'''
if self._highest is None:
self._highest = self._llh3minmax(True)
return self._llh3LL(self._highest, LatLon)
@property_RO
def hits(self):
'''Get the number of cache hits (C{int} or C{None}).
'''
return self._yx_hits
@property_RO
def kind(self):
'''Get the interpolator kind and order (C{int}).
'''
return self._kind
@property_RO
def knots(self):
'''Get the number of grid knots (C{int}).
'''
return self._knots
def lowerleft(self, LatLon=None):
'''Return the lower-left location and height of this geoid.
@kwarg LatLon: Optional class to return the location
(C{LatLon}) and height or C{None}.
@return: If B{C{LatLon}} is C{None}, a L{LatLon3Tuple}C{(lat,
lon, height)} otherwise a B{C{LatLon}} instance
with the lat-, longitude and height of the lower-left,
SW grid corner.
'''
if self._lowerleft is None:
self._lowerleft = self._llh3(self._lat_lo, self._lon_lo)
return self._llh3LL(self._lowerleft, LatLon)
def lowerright(self, LatLon=None):
'''Return the lower-right location and height of this geoid.
@kwarg LatLon: Optional class to return the location and height
(C{LatLon}) or C{None}.
@return: If B{C{LatLon}} is C{None}, a L{LatLon3Tuple}C{(lat,
lon, height)} otherwise a B{C{LatLon}} instance
with the lat-, longitude and height of the lower-right,
SE grid corner.
'''
if self._lowerright is None:
self._lowerright = self._llh3(self._lat_lo, self._lon_hi)
return self._llh3LL(self._lowerright, LatLon)
def lowest(self, LatLon=None, **unused):
'''Return the location and the lowest height of this geoid.
@kwarg LatLon: Optional class to return the location and height
(C{LatLon}) or C{None}.
@return: If B{C{LatLon}} is C{None}, a L{LatLon3Tuple}C{(lat,
lon, height)} otherwise a B{C{LatLon}} instance
with the lat-, longitude and height of the lowest
grid location.
'''
if self._lowest is None:
self._lowest = self._llh3minmax(False)
return self._llh3LL(self._lowest, LatLon)
@property_RO
def mean(self):
'''Get the mean of this geoid's heights (C{float}).
'''
if self._mean is None:
self._mean = float(self._np.mean(self._hs_y_x))
return self._mean
@property_RO
def name(self):
'''Get the name of this geoid (C{str}).
'''
return _HeightBase.name.fget(self) or self._geoid # recursion
@property_RO
def nBytes(self):
'''Get the grid in-memory size in bytes (C{int}).
'''
return self._nBytes
@property_RO
def numpy(self):
'''Get the imported C{numpy} version (C{str}).
'''
return self._np_v
def outside(self, lat, lon):
'''Check whether a location is outside this geoid's
lat-/longitude or crop range.
@arg lat: The latitude (C{degrees}).
@arg lon: The longitude (C{degrees}).
@return: A 1- or 2-character C{str} if outside or an
empty C{str} if inside.
'''
return (_S_ if lat < self._lat_lo else
(_N_ if lat > self._lat_hi else NN)) + \
(_W_ if lon < self._lon_lo else
(_E_ if lon > self._lon_hi else NN))
@property_RO
def pgm(self):
'''Get the PGM attributes (C{_PGM} or C{None} if not available/applicable).
'''
return self._pgm
@property_RO
def scipy(self):
'''Get the imported C{scipy} version (C{str}).
'''
return self._sp_v
@property_RO
def sizeB(self):
'''Get the geoid grid file size in bytes (C{int}).
'''
return self._sizeB
@property_RO
def smooth(self):
'''Get the C{RectBivariateSpline} smoothing (C{int}).
'''
return self._smooth
@property_RO
def stdev(self):
'''Get the standard deviation of this geoid's heights (C{float}).
'''
if self._stdev is None:
self._stdev = float(self._np.std(self._hs_y_x))
return self._stdev
def toStr(self, prec=3, sep=_COMMA_SPACE_): # PYCHOK signature
'''This geoid and all geoid attributes as a string.
@kwarg prec: Optional number of decimal digits (0..9 or
C{None} for default). Trailing zero decimals
are stripped for B{C{prec}} values of 1 and above,
but kept for negative B{C{prec}} values.
@kwarg sep: Optional separator (C{str}).
@return: Geoid name and attributes (C{str}).
'''
s = 1 if self.kind < 0 else 2
t = tuple(_item_ps(m.__name__, fstr(m(), prec=prec)) for m in
(self.lowerleft, self.upperright,
self.center,
self.highest, self.lowest)) + \
attrs( 'mean', 'stdev', prec=prec, Nones=False) + \
attrs(('kind', 'smooth')[:s], prec=prec, Nones=False) + \
attrs( 'cropped', 'dtype', 'endian', 'hits', _knots_, 'nBytes',
'sizeB', 'scipy', 'numpy', prec=prec, Nones=False)
return _item_cs(self, sep.join(t))
def upperleft(self, LatLon=None):
'''Return the upper-left location and height of this geoid.
@kwarg LatLon: Optional class to return the location and height
(C{LatLon}) or C{None}.
@return: If B{C{LatLon}} is C{None}, a L{LatLon3Tuple}C{(lat,
lon, height)} otherwise a B{C{LatLon}} instance
with the lat-, longitude and height of the upper-left,
NW grid corner.
'''
if self._upperleft is None:
self._upperleft = self._llh3(self._lat_hi, self._lon_lo)
return self._llh3LL(self._upperleft, LatLon)
def upperright(self, LatLon=None):
'''Return the upper-right location and height of this geoid.
@kwarg LatLon: Optional class to return the location and height
(C{LatLon}) or C{None}.
@return: If B{C{LatLon}} is C{None}, a L{LatLon3Tuple}C{(lat,
lon, height)} otherwise a B{C{LatLon}} instance
with the lat-, longitude and height of the upper-right,
NE grid corner.
'''
if self._upperright is None:
self._upperright = self._llh3(self._lat_hi, self._lon_hi)
return self._llh3LL(self._upperright, LatLon)
class GeoidError(HeightError):
'''Geoid interpolator C{Geoid...} or interpolation issue.
'''
pass
class GeoidG2012B(_GeoidBase):
'''Geoid height interpolator for U{GEOID12B Model
<https://www.NGS.NOAA.gov/GEOID/GEOID12B/>} grids U{CONUS
<https://www.NGS.NOAA.gov/GEOID/GEOID12B/GEOID12B_CONUS.shtml>},
U{Alaska<https://www.NGS.NOAA.gov/GEOID/GEOID12B/GEOID12B_AK.shtml>},
U{Hawaii<https://www.NGS.NOAA.gov/GEOID/GEOID12B/GEOID12B_HI.shtml>},
U{Guam and Northern Mariana Islands
<https://www.NGS.NOAA.gov/GEOID/GEOID12B/GEOID12B_GMNI.shtml>},
U{Puerto Rico and U.S. Virgin Islands
<https://www.NGS.NOAA.gov/GEOID/GEOID12B/GEOID12B_PRVI.shtml>} and
U{American Samoa<https://www.NGS.NOAA.gov/GEOID/GEOID12B/GEOID12B_AS.shtml>}
based on C{SciPy} U{RectBivariateSpline<https://docs.SciPy.org/doc/
scipy/reference/generated/scipy.interpolate.RectBivariateSpline.html>}
or U{interp2d<https://docs.SciPy.org/doc/scipy/reference/generated/
scipy.interpolate.interp2d.html>} interpolation.
Use any of the binary C{le} (little endian) or C{be} (big endian)
C{g2012b*.bin} grid files.
'''
def __init__(self, g2012b_bin, crop=None, datum=None, # NAD 83 Ellipsoid
kind=3, name=NN, smooth=0):
'''New L{GeoidG2012B} interpolator.
@arg g2012b_bin: A C{GEOID12B} grid file name (C{.bin}).
@kwarg crop: Optional crop box, not supported (C{None}).
@kwarg datum: Optional grid datum (C{Datum}), default C{WGS84}.
@kwarg kind: C{scipy.interpolate} order (C{int}), use 1..5 for
U{RectBivariateSpline<https://docs.SciPy.org/doc/scipy/
reference/generated/scipy.interpolate.RectBivariateSpline.html>},
-2 for U{interp2d linear<https://docs.SciPy.org/doc/scipy/
reference/generated/scipy.interpolate.interp2d.html>}, -3
for C{interp2d cubic} or -5 for C{interp2d quintic}.
@kwarg name: Optional geoid name (C{str}).
@kwarg smooth: Smoothing factor for U{RectBivariateSpline
<https://docs.SciPy.org/doc/scipy/reference/generated/
scipy.interpolate.RectBivariateSpline.html>}
only (C{int}).
@raise GeoidError: G2012B grid file B{C{g2012b_bin}} issue, non-C{None}
B{C{crop}} or invalid B{C{kind}} or B{C{smooth}}.
@raise ImportError: Package C{numpy} or C{scipy} not found
or not installed.
@raise LenError: Grid file B{C{g2012b_bin}} axis mismatch.
@raise SciPyError: A C{RectBivariateSpline} or C{inter2d} issue.
@raise SciPyWarning: A C{RectBivariateSpline} or C{inter2d}
warning as exception.
'''
if crop is not None:
raise GeoidError(crop=crop, txt=_not_supported_)
np, _ = self._NumSciPy()
g = self._open(g2012b_bin, datum, kind, name, smooth)
try:
p = _Gpars()
n = self.sizeB // 4 - 11 # number of f4 heights
# U{numpy dtype formats are different from Python struct formats
# <https://docs.SciPy.org/doc/numpy-1.15.0/reference/arrays.dtypes.html>}
for en_f4 in ('<f4', '>f4'):
en_ = en_f4[:1]
# skip 4xf8, get 3xi4
p.nlat, p.nlon, ien = map(int, self._load(g, en_+'i4', 3, 32))
if ien == 1: # correct endian
p.knots = p.nlat * p.nlon
if p.knots == n and 1 < p.nlat < n \
and 1 < p.nlon < n:
self._endian = en_f4
break
else: # couldn't validate endian
raise GeoidError('endianess')
# get the first 4xf8
p.slat, p.wlon, p.dlat, p.dlon = map(float, self._load(g, en_+'f8', 4))
# read all f4 heights, ignoring the first 4xf8 and 3xi4
hs = self._load(g, en_f4, n, 44).reshape(p.nlat, p.nlon)
p.wlon -= 360 # western-most East longitude to earth (..., lon)
_GeoidBase.__init__(self, hs, p)
except Exception as x:
raise _SciPyIssue(x, 'in', repr(g2012b_bin))
finally:
g.close()
def _g2ll2(self, lat, lon):
# convert grid (lat, lon) to earth (lat, lon)
return lat, lon
def _ll2g2(self, lat, lon):
# convert earth (lat, lon) to grid (lat, lon)
return lat, lon
if _FOR_DOCS:
__call__ = _GeoidBase.__call__
height = _GeoidBase.height
class GeoidHeight5Tuple(_NamedTuple): # .geoids.py
'''5-Tuple C{(lat, lon, egm84, egm96, egm2008)} for U{GeoidHeights.dat
<https://SourceForge.net/projects/geographiclib/files/testdata/>}
tests with the heights for 3 different EGM grids with C{-90.0 <=
lat <= 90.0} and C{-180.0 <= lon <= 180.0} degrees (and C{lon}
converted from the original C{0.0 <= EasterLon <= 360.0}).
'''
_Names_ = (_lat_, _lon_, 'egm84', 'egm96', 'egm2008')
def _I(i):
'''(INTERNAL) Cache a single C{int} constant.
'''
return _intCs.setdefault(i, i) # PYCHOK undefined due to del _intCs
def _T(*cs):
'''(INTERNAL) Cache a tuple of single C{int} constants.
'''
return map1(_I, *cs)
class GeoidKarney(_GeoidBase):
'''Geoid height interpolator for Charles Karney's U{GeographicLib
Earth Gravitational Model (EGM)<https://GeographicLib.SourceForge.io/
html/geoid.html>} geoid U{egm*.pgm<https://GeographicLib.SourceForge.io/
html/geoid.html#geoidinst>} datasets using bilinear or U{cubic
<https://dl.ACM.org/citation.cfm?id=368443>} interpolation and U{caching
<https://GeographicLib.SourceForge.io/html/geoid.html#geoidcache>}
in pure Python transcribed from Karney's U{C++ class Geoid
<https://GeographicLib.SourceForge.io/html/geoid.html#geoidinterp>}.
Use any of the geoid U{egm84-, egm96- or egm2008-*.pgm
<https://GeographicLib.SourceForge.io/html/geoid.html#geoidinst>}
datasets.
'''
_C0 = (372.0, 240.0, 372.0) # n, _ and s common denominators
# matrices c3n_, c3, c3s_, transposed from GeographicLib/Geoid.cpp
_C3 = ((_T(0, 0, 62, 124, 124, 62, 0, 0, 0, 0, 0, 0),
_T(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
_T(-131, 7, -31, -62, -62, -31, 45, 216, 156, -45, -55, -7),
_T(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
_T(138, -138, 0, 0, 0, 0, -183, 33, 153, -3, 48, -48), # PYCHOK indent
_T(144, 42, -62, -124, -124, -62, -9, 87, 99, 9, 42, -42),
_T(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
_T(0, 0, 0, 0, 0, 0, 93, -93, -93, 93, 0, 0),
_T(-102, 102, 0, 0, 0, 0, 18, 12, -12, -18, -84, 84),
_T(-31, -31, 31, 62, 62, 31, 0, -93, -93, 0, 31, 31)), # PYCHOK indent
(_T(9, -9, 9, 186, 54, -9, -9, 54, -54, 9, -9, 9),
_T(-18, 18, -88, -42, 162, -32, 8, -78, 78, -8, 18, -18),
_T(-88, 8, -18, -42, -78, 18, 18, 162, 78, -18, -32, -8),
_T(0, 0, 90, -150, 30, 30, 30, -90, 90, -30, 0, 0),
_T(96, -96, 96, -96, -24, 24, -96, -24, 144, -24, 24, -24), # PYCHOK indent
_T(90, 30, 0, -150, -90, 0, 0, 30, 90, 0, 30, -30),
_T(0, 0, -20, 60, -60, 20, -20, 60, -60, 20, 0, 0),
_T(0, 0, -60, 60, 60, -60, 60, -60, -60, 60, 0, 0),
_T(-60, 60, 0, 60, -60, 0, 0, 60, -60, 0, -60, 60),
_T(-20, -20, 0, 60, 60, 0, 0, -60, -60, 0, 20, 20)),
(_T(18, -18, 36, 210, 162, -36, 0, 0, 0, 0, -18, 18), # PYCHOK indent
_T(-36, 36, -165, 45, 141, -21, 0, 0, 0, 0, 36, -36),
_T(-122, -2, -27, -111, -75, 27, 62, 124, 124, 62, -64, 2),
_T(0, 0, 93, -93, -93, 93, 0, 0, 0, 0, 0, 0),
_T(120, -120, 147, -57, -129, 39, 0, 0, 0, 0, 66, -66), # PYCHOK indent
_T(135, 51, -9, -192, -180, 9, 31, 62, 62, 31, 51, -51),
_T(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
_T(0, 0, -93, 93, 93, -93, 0, 0, 0, 0, 0, 0),
_T(-84, 84, 18, 12, -12, -18, 0, 0, 0, 0, -102, 102),
_T(-31, -31, 0, 93, 93, 0, -31, -62, -62, -31, 31, 31)))
_BT = (_T(0, 0), # bilinear 4-tuple [i, j] indices
_T(1, 0),
_T(0, 1),
_T(1, 1))
_CM = (_T( 0, -1), # 10x12 cubic matrix [i, j] indices
_T( 1, -1),
_T(-1, 0),
_T( 0, 0),
_T( 1, 0),
_T( 2, 0),
_T(-1, 1),
_T( 0, 1),
_T( 1, 1),
_T( 2, 1),
_T( 0, 2),
_T( 1, 2))
_egm = None # open geoid file
_endian = '>H' # struct.unpack 1 ushort (big endian, unsigned short)
_4endian = '>4H' # struct.unpack 4 ushorts
_Rendian = NN # struct.unpack a row of ushorts
# _highest = (-8.4, 147.367, 85.839) if egm2008-1.pgm else (
# (-8.167, 147.25, 85.422) if egm96-5.pgm else
# (-4.5, 148.75, 81.33) # egm84-15.pgm)
# _lowest = (4.7, 78.767, -106.911) if egm2008-1.pgm else (
# (4.667, 78.833, -107.043) if egm96-5.pgm else
# (4.75, 79.25, -107.34) # egm84-15.pgm
_mean = -1.317 # from egm2008-1, -1.438 egm96-5, -0.855 egm84-15
_nBytes = None # not applicable
_nterms = len(_C3[0]) # columns length, number of row
_smooth = None # not applicable
_stdev = 29.244 # from egm2008-1, 29.227 egm96-5, 29.183 egm84-15
_u2B = _calcsize(_endian) # pixelsize_ in bytes
_4u2B = _calcsize(_4endian) # 4 pixelsize_s in bytes
_Ru2B = 0 # row of pixelsize_s in bytes
_yxH = () # cache (y, x) indices
_yxHt = () # cached 4- or 10-tuple for _ev2H resp. _ev3H
_yx_hits = 0 # cache hits
def __init__(self, egm_pgm, crop=None, datum=None, # WGS84
kind=3, name=NN, smooth=None):
'''New L{GeoidKarney} interpolator.
@arg egm_pgm: An U{EGM geoid dataset<https://GeographicLib.SourceForge.io/
html/geoid.html#geoidinst>} file name (C{egm*.pgm}).
@kwarg crop: Optional box to limit geoid locations, a 4-tuple (C{south,
west, north, east}), 2-tuple (C{(south, west), (north,
east)}) or 2, in C{degrees90} lat- and C{degrees180}
longitudes or a 2-tuple (C{LatLonSW, LatLonNE}) of
C{LatLon} instances.
@kwarg datum: Optional grid datum (C{Datum}), default C{WGS84}.
@kwarg kind: Interpolation order (C{int}), 2 for C{bilinear} or 3
for C{cubic}.
@kwarg name: Optional geoid name (C{str}).
@kwarg smooth: Smoothing factor, unsupported (C{None}).
@raise GeoidError: EGM dataset B{C{egm_pgm}} issue or invalid B{C{crop}},
B{C{kind}} or B{C{smooth}}.
@see: Class L{GeoidPGM} and function L{egmGeoidHeights}.
'''
if smooth is not None:
raise GeoidError(smooth=smooth, txt=_not_supported_)
if kind in (2,):
self._evH = self._ev2H
elif kind not in (3,):
raise GeoidError(kind=kind)
self._egm = g = self._open(egm_pgm, datum, kind, name, smooth)
self._pgm = p = _PGM(g, pgm=egm_pgm, itemsize=self.u2B, sizeB=self.sizeB)
self._Rendian = self._4endian.replace('4', str(p.nlon))
self._Ru2B = _calcsize(self._Rendian)
self._knots = p.knots # grid knots
self._lon_of = float(p.flon) # forward offset
self._lon_og = float(p.glon) # reverse offset
# set earth (lat, lon) limits (s, w, n, e)
self._lat_lo, \
self._lon_lo, \
self._lat_hi, \
self._lon_hi = self._swne(crop if crop else p.crop4)
self._cropped = True if crop else False
def __call__(self, *llis):
'''Interpolate the geoid height for one or several locations.
@arg llis: The location or locations (C{LatLon}, ... or
C{LatLon}s).
@return: A single interpolated geoid height (C{float}) or
a list or tuple of interpolated geoid heights
(C{float}s).
@raise GeoidError: Insufficient number of B{C{llis}} or an
invalid B{C{lli}}.
@raise RangeError: An B{C{lli}} is outside this geoid's lat-
or longitude range.
'''
return self._called(llis, False)
def _c0c3v(self, y, x):
# get the common denominator, the 10x12 cubic matrix and
# the 12 cubic v-coefficients around geoid index (y, x)
p = self._pgm
if 0 < x < (p.nlon - 2) and 0 < y < (p.nlat - 2):
# read 4x4 ushorts, drop the 4 corners
g = self._egm
e = self._4endian
n = self._4u2B
R = self._Ru2B
b = self._seek(y - 1, x - 1)
v = _unpack(e, g.read(n))[1:3]
b += R
g.seek(b, _SEEK_SET)
v += _unpack(e, g.read(n))
b += R
g.seek(b, _SEEK_SET)
v += _unpack(e, g.read(n))
b += R
g.seek(b, _SEEK_SET)
v += _unpack(e, g.read(n))[1:3]
j = 1
else: # likely some wrapped y and/or x's
v = self._raws(y, x, GeoidKarney._CM)
j = 0 if y < 1 else (1 if y < (p.nlat - 2) else 2)
return GeoidKarney._C0[j], GeoidKarney._C3[j], v
def _ev(self, lat, lon): # PYCHOK expected
# interpolate the geoid height at grid (lat, lon)
fy, fx = self._g2yx2(lat, lon)
y, x = int(floor(fy)), int(floor(fx))
fy -= y
fx -= x
H = self._evH(fy, fx, y, x) # ._ev3H or ._ev2H
H *= self._pgm.Scale # H.fmul(self._pgm.Scale)
H += self._pgm.Offset # H.fadd(self._pgm.Offset)
return H.fsum()
def _ev2H(self, fy, fx, *yx):
# compute the bilinear 4-tuple and interpolate raw H
if self._yxH == yx:
t = self._yxHt
self._yx_hits += 1
else:
y, x = self._yxH = yx
self._yxHt = t = self._raws(y, x, GeoidKarney._BT)
v = 1.0, -fx, fx
H = Fdot(v, t[0], t[0], t[1]) # a
H -= H * fy # c = (1 - fy) * a
H += Fdot(v, t[2], t[2], t[3]) * fy # c += b * fy
return H
def _ev3H(self, fy, fx, *yx):
# compute the cubic 10-tuple and interpolate raw H
if self._yxH == yx:
t = self._yxHt
self._yx_hits += 1
else:
self._yxH = yx
c0, c3, v = self._c0c3v(*yx)
t = [fdot(v, *c3[i]) / c0 for i in range(self._nterms)]
self._yxHt = t = tuple(t)
# GeographicLib/Geoid.cpp Geoid::height(lat, lon) ...
# real h = t[0] + fx * (t[1] + fx * (t[3] + fx * t[6])) +
# fy * (t[2] + fx * (t[4] + fx * t[7]) +
# fy * (t[5] + fx * t[8] + fy * t[9]));
H = Fdot((1, fx, fy), t[5], t[8], t[9]) * fy
H = (Fhorner(fx, t[2], t[4], t[7]) + H) * fy
H += Fhorner(fx, t[0], t[1], t[3], t[6])
return H
_evH = _ev3H # overriden for kind == 2
def _g2ll2(self, lat, lon):
# convert grid (lat, lon) to earth (lat, lon), uncropped
while lon > 180:
lon -= 360
return lat, lon
def _g2yx2(self, lat, lon):
# convert grid (lat, lon) to grid (y, x) indices
p = self._pgm
# note, slat = +90, rlat < 0 makes y >=0
return ((lat - p.slat) * p.rlat), ((lon - p.wlon) * p.rlon)
def _gyx2g2(self, y, x):
# convert grid (y, x) indices to grid (lat, lon)
p = self._pgm
return (p.slat + p.dlat * y), (p.wlon + p.dlon * x)
def _lat2y2(self, lat2):
# convert earth lat(s) to min and max grid y indices
ys, m = [], self._pgm.nlat - 1
for lat in lat2:
y, _ = self._g2yx2(*self._ll2g2(lat, 0))
ys.append(max(min(int(y), m), 0))
return min(ys), max(ys) + 1
def _ll2g2(self, lat, lon):
# convert earth (lat, lon) to grid (lat, lon), uncropped
while lon < 0:
lon += 360
return lat, lon
def _llh3minmax(self, highest=True, *lat2):
# find highest or lowest, takes 10+ secs for egm2008-1.pgm geoid
# (Python 2.7.16, macOS 10.13.6 High Sierra, iMac 3 GHz Core i3)