Coverage for pygeodesy/geoids.py: 96%

674 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2024-08-02 18:24 -0400

1 

2# -*- coding: utf-8 -*- 

3 

4u'''Geoid models and geoid height interpolations. 

5 

6Classes L{GeoidG2012B}, L{GeoidKarney} and L{GeoidPGM} to interpolate the 

7height of various U{geoid<https://WikiPedia.org/wiki/Geoid>}s at C{LatLon} 

8locations or separate lat-/longitudes using different interpolation methods 

9and C{geoid} model files. 

10 

11L{GeoidKarney} is a transcoding of I{Charles Karney}'s C++ class U{Geoid 

12<https://GeographicLib.SourceForge.io/C++/doc/geoid.html>} to pure Python. 

13The L{GeoidG2012B} and L{GeoidPGM} interpolators both depend on U{scipy 

14<https://SciPy.org>} and U{numpy<https://PyPI.org/project/numpy>} and 

15require those packages to be installed. 

16 

17In addition, each geoid interpolator needs C{grid knots} (down)loaded from 

18a C{geoid} model file, I{specific to the interpolator}, more details below 

19and in the documentation of the interpolator class. For each interpolator, 

20there are several interpolation choices, like I{linear}, I{cubic}, etc. 

21 

22Typical usage 

23============= 

24 

251. Choose one of the interpolator classes L{GeoidG2012B}, L{GeoidKarney} 

26or L{GeoidPGM} and download a C{geoid} model file, containing locations with 

27known heights also referred to as the C{grid knots}. See the documentation 

28of the interpolator class for references to available C{grid} models. 

29 

30C{>>> from pygeodesy import GeoidG2012B # or -Karney or -PGM as GeoidXyz} 

31 

322. Instantiate an interpolator with the C{geoid} model file and use keyword 

33arguments to select different interpolation options 

34 

35C{>>> ginterpolator = GeoidXyz(geoid_model_file, **options)} 

36 

373. Get the interpolated geoid height of other C{LatLon} location(s) with 

38 

39C{>>> ll = LatLon(1, 2, ...)} 

40 

41C{>>> h = ginterpolator(ll)} 

42 

43or 

44 

45C{>>> h0, h1, h2, ... = ginterpolator(ll0, ll1, ll2, ...)} 

46 

47or a list, tuple, generator, etc. of C{LatLon}s 

48 

49C{>>> hs = ginterpolator(lls)} 

50 

514. For separate lat- and longitudes invoke the C{.height} method as 

52 

53C{>>> h = ginterpolator.height(lat, lon)} 

54 

55or as 2 lists, 2 tuples, etc. 

56 

57C{>>> hs = ginterpolator.height(lats, lons)} 

58 

595. An example is in U{issue #64<https://GitHub.com/mrJean1/PyGeodesy/issues/64>}, 

60courtesy of SBFRF. 

61 

62@note: Classes L{GeoidG2012B} and L{GeoidPGM} require both U{numpy 

63 <https://PyPI.org/project/numpy>} and U{scipy<https://PyPI.org/project/scipy>} 

64 to be installed. 

65 

66@note: Errors from C{scipy} are raised as L{SciPyError}s. Warnings issued by 

67 C{scipy} can be thrown as L{SciPyWarning} exceptions, provided Python 

68 C{warnings} are filtered accordingly, see L{SciPyWarning}. 

69 

70@see: I{Karney}'s U{GeographicLib<https://GeographicLib.SourceForge.io/C++/doc/index.html>}, 

71 U{Geoid height<https://GeographicLib.SourceForge.io/C++/doc/geoid.html>} and U{Installing 

72 the Geoid datasets<https://GeographicLib.SourceForge.io/C++/doc/geoid.html#geoidinst>}, 

73 U{SciPy<https://docs.SciPy.org/doc/scipy/reference/interpolate.html>} interpolation 

74 U{RectBivariateSpline<https://docs.SciPy.org/doc/scipy/reference/generated/scipy. 

75 interpolate.RectBivariateSpline.html>} and U{interp2d<https://docs.SciPy.org/doc/scipy/ 

76 reference/generated/scipy.interpolate.interp2d.html>}, functions L{elevations.elevation2} 

77 and L{elevations.geoidHeight2}, U{I{Ellispoid vs Orthometric Elevations}<https:// 

78 www.YouTube.com/watch?v=dX6a6kCk3Po>} and U{I{Pitfalls Related to Ellipsoid Height 

79 and Height Above Mean Sea Level (AMSL)}<https://Wiki.ROS.org/mavros#mavros.2FPlugins. 

80 Avoiding_Pitfalls_Related_to_Ellipsoid_Height_and_Height_Above_Mean_Sea_Level>}. 

81''' 

82# make sure int/int division yields float quotient, see .basics 

83from __future__ import division as _; del _ # PYCHOK semicolon 

84 

85from pygeodesy.basics import len2, map1, isodd, ub2str as _ub2str 

86from pygeodesy.constants import EPS, _float as _F, _0_0, _1_0, _180_0, _360_0 

87# from pygeodesy.datums import _ellipsoidal_datum # from .heights 

88# from pygeodesy.dms import parseDMS2 # _MODS 

89from pygeodesy.errors import _incompatible, LenError, RangeError, SciPyError, \ 

90 _SciPyIssue, _xkwds_pop2 

91from pygeodesy.fmath import favg, Fdot, fdot, Fhorner, frange 

92# from pygoedesy.formy import heightOrthometric # _MODS 

93from pygeodesy.heights import _as_llis2, _ascalar, _height_called, HeightError, \ 

94 _HeightsBase, _ellipsoidal_datum, _Wrap 

95# from pygeodesy.internals import _version2 # _MODS 

96from pygeodesy.interns import MISSING, NN, _4_, _COLONSPACE_, _COMMASPACE_, _cubic_, \ 

97 _E_, _height_, _in_, _kind_, _lat_, _linear_, _lon_, \ 

98 _mean_, _N_, _n_a_, _numpy_, _on_, _outside_, _S_, _s_, \ 

99 _scipy_, _SPACE_, _stdev_, _tbd_, _W_, _width_ 

100from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS, _FOR_DOCS 

101from pygeodesy.named import _name__, _Named, _NamedTuple 

102# from pygeodesy.namedTuples import LatLon3Tuple # _MODS 

103from pygeodesy.props import deprecated_method, Property_RO, property_RO, property_ROver 

104from pygeodesy.streprs import attrs, Fmt, fstr, pairs 

105from pygeodesy.units import Height, Int_, Lat, Lon 

106# from pygeodesy.utily import _Wrap # from .heights 

107 

108from math import floor 

109import os.path as _os_path 

110from os import SEEK_CUR as _SEEK_CUR, SEEK_SET as _SEEK_SET 

111from struct import calcsize as _calcsize, unpack as _unpack 

112try: 

113 from StringIO import StringIO as _BytesIO # reads bytes 

114 _ub2str = str # PYCHOK convert bytes to str for egm*.pgm text 

115 

116except ImportError: # Python 3+ 

117 from io import BytesIO as _BytesIO # PYCHOK expected 

118 

119__all__ = _ALL_LAZY.geoids 

120__version__ = '24.07.25' 

121 

122_assert_ = 'assert' 

123_bHASH_ = b'#' 

124_endian_ = 'endian' 

125_format_ = '%s %r' 

126_header_ = 'header' 

127_intCs = {} # cache int value 

128_interp2d_ks = {-2: _linear_, 

129 -3: _cubic_, 

130 -5: 'quintic'} 

131_lli_ = 'lli' 

132_non_increasing_ = 'non-increasing' 

133_rb_ = 'rb' 

134_supported_ = 'supported' 

135 

136 

137class _GeoidBase(_HeightsBase): 

138 '''(INTERNAL) Base class for C{Geoid...}s. 

139 ''' 

140 _cropped = None 

141# _datum = _WGS84 # from _HeightsBase 

142 _egm = None # open C{egm*.pgm} geoid file 

143 _endian = _tbd_ 

144 _geoid = _n_a_ 

145 _hs_y_x = None # numpy 2darray, row-major order 

146 _interp2d = None # interp2d interpolation 

147 _kind = 3 # order for interp2d, RectBivariateSpline 

148# _kmin = 2 # min number of knots 

149 _knots = 0 # nlat * nlon 

150 _mean = None # fixed in GeoidKarney 

151# _name = NN # _Named 

152 _nBytes = 0 # numpy size in bytes, float64 

153 _pgm = None # PGM attributes, C{_PGM} or C{None} 

154 _sizeB = 0 # geoid file size in bytes 

155 _smooth = 0 # used only for RectBivariateSpline 

156 _stdev = None # fixed in GeoidKarney 

157 _u2B = 0 # np.itemsize or undefined 

158 

159 _lat_d = _0_0 # increment, +tive 

160 _lat_lo = _0_0 # lower lat, south 

161 _lat_hi = _0_0 # upper lat, noth 

162 _lon_d = _0_0 # increment, +tive 

163 _lon_lo = _0_0 # left lon, west 

164 _lon_hi = _0_0 # right lon, east 

165 _lon_of = _0_0 # forward lon offset 

166 _lon_og = _0_0 # reverse lon offset 

167 

168 _center = None # (lat, lon, height) 

169 _yx_hits = None # cache hits, ala Karney 

170 

171 def __init__(self, hs, p): 

172 '''(INTERNAL) Set up the grid axes, the C{SciPy} interpolator 

173 and several internal geoid attributes. 

174 

175 @arg hs: Grid knots with known height (C{numpy 2darray}). 

176 @arg p: The C{slat, wlon, nlat, nlon, dlat, dlon} and 

177 other geoid parameters (C{INTERNAL}). 

178 

179 @raise GeoidError: Incompatible grid B{C{hs}} shape or 

180 invalid B{C{kind}}. 

181 

182 @raise LenError: Mismatch grid B{C{hs}} axis. 

183 

184 @raise SciPyError: A C{scipy.interpolate.inter2d} or 

185 C{-.RectBivariateSpline} issue. 

186 

187 @raise SciPyWarning: A C{scipy.interpolate.inter2d} or 

188 C{-.RectBivariateSpline} warning as 

189 exception. 

190 

191 @note: C{scipy.interpolate.interp2d} has been C{DEPRECATED}, 

192 specify keyword argument C{B{kind}=1..5} to use 

193 C{scipy.interpolate.RectBivariateSpline}. 

194 ''' 

195 spi = self.scipy_interpolate 

196 # for 2d scipy.interpolate.interp2d(xs, ys, hs, ...) and 

197 # scipy.interpolate.RectBivariateSpline(ys, xs, hs, ...) 

198 # require the shape of hs to be (len(ys), len(xs)), note 

199 # the different (xs, ys, ...) and (ys, xs, ...) orders 

200 if (p.nlat, p.nlon) != hs.shape: 

201 raise GeoidError(shape=hs.shape, txt=_incompatible((p.nlat, p.nlon))) 

202 

203 # both axes and bounding box 

204 ys, self._lat_d = self._gaxis2(p.slat, p.dlat, p.nlat, _lat_ + _s_) 

205 xs, self._lon_d = self._gaxis2(p.wlon, p.dlon, p.nlon, _lon_ + _s_) 

206 

207 bb = ys[0], ys[-1], xs[0], xs[-1] + p.dlon # fudge lon_hi 

208 # geoid grids are typically stored in row-major order, some 

209 # with rows (90..-90) reversed and columns (0..360) wrapped 

210 # to Easten longitude, 0 <= east < 180 and 180 <= west < 360 

211 k = self.kind 

212 if k in _interp2d_ks: # .interp2d DEPRECATED since scipy 1.10 

213 if self._scipy_version() < (1, 10): 

214 self._interp2d = spi.interp2d(xs, ys, hs, kind=_interp2d_ks[k]) 

215 else: # call and overwrite the DEPRECATED .interp2d 

216 self._interp2d = self._interp2d(xs, ys, hs, k) 

217 elif 1 <= k <= 5: 

218 self._ev = spi.RectBivariateSpline(ys, xs, hs, bbox=bb, ky=k, kx=k, 

219 s=self._smooth).ev 

220 else: 

221 raise GeoidError(kind=k) 

222 

223 self._hs_y_x = hs # numpy 2darray, row-major 

224 self._nBytes = hs.nbytes # numpy size in bytes 

225 self._knots = p.knots # grid knots 

226 self._lon_of = float(p.flon) # forward offset 

227 self._lon_og = float(p.glon) # reverse offset 

228 # shrink the box by 1 unit on every side 

229 # bb += self._lat_d, -self._lat_d, self._lon_d, -self._lon_d 

230 self._lat_lo = float(bb[0]) 

231 self._lat_hi = float(bb[1]) 

232 self._lon_lo = float(bb[2] - p.glon) 

233 self._lon_hi = float(bb[3] - p.glon) 

234 

235 def __call__(self, *llis, **wrap_H): 

236 '''Interpolate the geoid height for one or several locations. 

237 

238 @arg llis: One or more locations (C{LatLon}s), all positional. 

239 @kwarg wrap_H: Keyword arguments C{B{wrap}=False} (C{bool}) and 

240 C{B{H}=False} (C{bool}). If C{B{wrap} is True}, 

241 wrap or I{normalize} all B{C{llis}} locations. If 

242 C{B{H} is True}, return the I{orthometric} height 

243 instead of the I{geoid} height at each location. 

244 

245 @return: A single interpolated geoid (or orthometric) height 

246 (C{float}) or a list or tuple of interpolated geoid 

247 (or orthometric) heights (C{float}s). 

248 

249 @raise GeoidError: Insufficient number of B{C{llis}}, an 

250 invalid B{C{lli}} or the C{egm*.pgm} 

251 geoid file is closed. 

252 

253 @raise RangeError: An B{C{lli}} is outside this geoid's lat- 

254 or longitude range. 

255 

256 @raise SciPyError: A C{scipy.interpolate.inter2d} or 

257 C{-.RectBivariateSpline} issue. 

258 

259 @raise SciPyWarning: A C{scipy.interpolate.inter2d} or 

260 C{-.RectBivariateSpline} warning as 

261 exception. 

262 

263 @note: To obtain I{orthometric} heights, each B{C{llis}} 

264 location must have an ellipsoid C{height} or C{h} 

265 attribute, otherwise C{height=0} is used. 

266 

267 @see: Function L{pygeodesy.heightOrthometric}. 

268 ''' 

269 return self._called(llis, True, **wrap_H) 

270 

271 def __enter__(self): 

272 '''Open context. 

273 ''' 

274 return self 

275 

276 def __exit__(self, *unused): # PYCHOK exc_type, exc_value, exc_traceback) 

277 '''Close context. 

278 ''' 

279 self.close() 

280 # return None # XXX False 

281 

282 def __repr__(self): 

283 return self.toStr() 

284 

285 def __str__(self): 

286 return Fmt.PAREN(self.classname, repr(self.name)) 

287 

288 def _called(self, llis, scipy, wrap=False, H=False): 

289 # handle __call__ 

290 _H = self._heightOrthometric if H else None 

291 _as, llis = _as_llis2(llis, Error=GeoidError) 

292 hs, _w = [], _Wrap._latlonop(wrap) 

293 _a, _h = hs.append, self._hGeoid 

294 try: 

295 for i, lli in enumerate(llis): 

296 N = _h(*_w(lli.lat, lli.lon)) 

297 # orthometric or geoid height 

298 _a(_H(lli, N) if _H else N) 

299 return _as(hs) 

300 

301 except (GeoidError, RangeError) as x: 

302 # XXX avoid str(LatLon()) degree symbols 

303 t = _lli_ if _as is _ascalar else Fmt.INDEX(llis=i) 

304 lli = fstr((lli.lat, lli.lon), strepr=repr) 

305 raise type(x)(t, lli, wrap=wrap, H=H, cause=x) 

306 except Exception as x: 

307 if scipy and self.scipy: 

308 raise _SciPyIssue(x) 

309 else: 

310 raise 

311 

312 @Property_RO 

313 def _center(self): 

314 ''' Cache for method L{center}. 

315 ''' 

316 return self._llh3(favg(self._lat_lo, self._lat_hi), 

317 favg(self._lon_lo, self._lon_hi)) 

318 

319 def center(self, LatLon=None): 

320 '''Return the center location and height of this geoid. 

321 

322 @kwarg LatLon: Optional class to return the location and height 

323 (C{LatLon}) or C{None}. 

324 

325 @return: If C{B{LatLon} is None}, a L{LatLon3Tuple}C{(lat, lon, 

326 height)} otherwise a B{C{LatLon}} instance with the lat-, 

327 longitude and geoid height of the center grid location. 

328 ''' 

329 return self._llh3LL(self._center, LatLon) 

330 

331 def close(self): 

332 '''Close the C{egm*.pgm} geoid file if open (and applicable). 

333 ''' 

334 if not self.closed: 

335 self._egm.close() 

336 self._egm = None 

337 

338 @property_RO 

339 def closed(self): 

340 '''Get the C{egm*.pgm} geoid file status. 

341 ''' 

342 return self._egm is None 

343 

344 @Property_RO 

345 def cropped(self): 

346 '''Is geoid cropped (C{bool} or C{None} if crop not supported). 

347 ''' 

348 return self._cropped 

349 

350 @Property_RO 

351 def dtype(self): 

352 '''Get the grid C{scipy} U{dtype<https://docs.SciPy.org/doc/numpy/ 

353 reference/generated/numpy.ndarray.dtype.html>} (C{numpy.dtype}). 

354 ''' 

355 return self._hs_y_x.dtype 

356 

357 @Property_RO 

358 def endian(self): 

359 '''Get the geoid endianess and U{dtype<https://docs.SciPy.org/ 

360 doc/numpy/reference/generated/numpy.dtype.html>} (C{str}). 

361 ''' 

362 return self._endian 

363 

364 def _ev(self, y, x): # PYCHOK expected 

365 # only used for .interpolate.interp2d, but 

366 # overwritten for .RectBivariateSpline, 

367 # note (y, x) must be flipped! 

368 return self._interp2d(x, y) 

369 

370 def _gaxis2(self, lo, d, n, name): 

371 # build grid axis, hi = lo + (n - 1) * d 

372 m, a = len2(frange(lo, n, d)) 

373 if m != n: 

374 raise LenError(self.__class__, grid=m, **{name: n}) 

375 if d < 0: 

376 d, a = -d, list(reversed(a)) 

377 for i in range(1, m): 

378 e = a[i] - a[i-1] 

379 if e < EPS: # non-increasing axis 

380 i = Fmt.INDEX(name, i) 

381 raise GeoidError(i, e, txt=_non_increasing_) 

382 return self.numpy.array(a), d 

383 

384 def _g2ll2(self, lat, lon): # PYCHOK no cover 

385 '''(INTERNAL) I{Must be overloaded}.''' 

386 self._notOverloaded(lat, lon) 

387 

388 def _gyx2g2(self, y, x): 

389 # convert grid (y, x) indices to grid (lat, lon) 

390 return ((self._lat_lo + self._lat_d * y), 

391 (self._lon_lo + self._lon_of + self._lon_d * x)) 

392 

393 def height(self, lats, lons, **wrap): 

394 '''Interpolate the geoid height for one or several lat-/longitudes. 

395 

396 @arg lats: Latitude or latitudes (C{degrees} or C{degrees}s). 

397 @arg lons: Longitude or longitudes (C{degrees} or C{degrees}s). 

398 @kwarg wrap: If C{True}, wrap or I{normalize} all B{C{lats}} 

399 and B{C{lons}} locations (C{bool}). 

400 

401 @return: A single interpolated geoid height (C{float}) or a 

402 list of interpolated geoid heights (C{float}s). 

403 

404 @raise GeoidError: Insufficient or non-matching number of 

405 B{C{lats}} and B{C{lons}}. 

406 

407 @raise RangeError: A B{C{lat}} or B{C{lon}} is outside this 

408 geoid's lat- or longitude range. 

409 

410 @raise SciPyError: A C{scipy.interpolate.inter2d} or 

411 C{-.RectBivariateSpline} issue. 

412 

413 @raise SciPyWarning: A C{scipy.interpolate.inter2d} or 

414 C{-.RectBivariateSpline} warning as 

415 exception. 

416 ''' 

417 return _height_called(self, lats, lons, Error=GeoidError, **wrap) 

418 

419 @property_ROver 

420 def _heightOrthometric(self): 

421 return _MODS.formy.heightOrthometric # overwrite property_ROver 

422 

423 def _hGeoid(self, lat, lon): 

424 out = self.outside(lat, lon) 

425 if out: 

426 lli = fstr((lat, lon), strepr=repr) 

427 raise RangeError(lli=lli, txt=_SPACE_(_outside_, _on_, out)) 

428 return float(self._ev(*self._ll2g2(lat, lon))) 

429 

430 @Property_RO 

431 def _highest(self): 

432 '''(INTERNAL) Cache for L{highest} method. 

433 ''' 

434 return self._llh3minmax(True) 

435 

436 def highest(self, LatLon=None, **unused): 

437 '''Return the location and largest height of this geoid. 

438 

439 @kwarg LatLon: Optional class to return the location and height 

440 (C{LatLon}) or C{None}. 

441 

442 @return: If C{B{LatLon} is None}, a L{LatLon3Tuple}C{(lat, lon, 

443 height)} otherwise a B{C{LatLon}} instance with the lat-, 

444 longitude and geoid height of the highest grid location. 

445 ''' 

446 return self._llh3LL(self._highest, LatLon) 

447 

448 @Property_RO 

449 def hits(self): 

450 '''Get the number of cache hits (C{int} or C{None}). 

451 ''' 

452 return self._yx_hits 

453 

454 @deprecated_method 

455 def _interp2d(self, xs, ys, hs=(), k=0): # overwritten in .__init__ above 

456 '''DEPRECATED on 23.01.06, use keyword argument C{B{kind}=1..5}.''' 

457 # assert k in _interp2d_ks # and len(hs) == len(xs) == len(ys) 

458 try: 

459 return self.scipy_interpolate.interp2d(xs, ys, hs, kind=_interp2d_ks[k]) 

460 except AttributeError as x: 

461 raise SciPyError(interp2d=MISSING, kind=k, cause=x) 

462 

463 @Property_RO 

464 def kind(self): 

465 '''Get the interpolator kind and order (C{int}). 

466 ''' 

467 return self._kind 

468 

469 @Property_RO 

470 def knots(self): 

471 '''Get the number of grid knots (C{int}). 

472 ''' 

473 return self._knots 

474 

475 def _ll2g2(self, lat, lon): # PYCHOK no cover 

476 '''(INTERNAL) I{Must be overloaded}.''' 

477 self._notOverloaded(lat, lon) 

478 

479 @property_ROver 

480 def _LL3T(self): 

481 '''(INTERNAL) Get L{LatLon3Tuple}, I{once}. 

482 ''' 

483 return _MODS.namedTuples.LatLon3Tuple # overwrite property_ROver 

484 

485 def _llh3(self, lat, lon): 

486 return self._LL3T(lat, lon, self._hGeoid(lat, lon), name=self.name) 

487 

488 def _llh3LL(self, llh, LatLon): 

489 return llh if LatLon is None else self._xnamed(LatLon(*llh)) 

490 

491 def _llh3minmax(self, highest=True, *unused): 

492 hs, np = self._hs_y_x, self.numpy 

493 # <https://docs.SciPy.org/doc/numpy/reference/generated/ 

494 # numpy.argmin.html#numpy.argmin> 

495 arg = np.argmax if highest else np.argmin 

496 y, x = np.unravel_index(arg(hs, axis=None), hs.shape) 

497 return self._g2ll2(*self._gyx2g2(y, x)) + (float(hs[y, x]),) 

498 

499 def _load(self, g, dtype, n, offset=0): 

500 # numpy.fromfile, like .frombuffer 

501 g.seek(offset, _SEEK_SET) 

502 return self.numpy.fromfile(g, dtype, n) 

503 

504 @Property_RO 

505 def _lowerleft(self): 

506 '''(INTERNAL) Cache for L{lowerleft}. 

507 ''' 

508 return self._llh3(self._lat_lo, self._lon_lo) 

509 

510 def lowerleft(self, LatLon=None): 

511 '''Return the lower-left location and height of this geoid. 

512 

513 @kwarg LatLon: Optional class to return the location 

514 (C{LatLon}) and height or C{None}. 

515 

516 @return: If C{B{LatLon} is None}, a L{LatLon3Tuple}C{(lat, lon, height)} 

517 otherwise a B{C{LatLon}} instance with the lat-, longitude and 

518 geoid height of the lower-left, SW grid corner. 

519 ''' 

520 return self._llh3LL(self._lowerleft, LatLon) 

521 

522 @Property_RO 

523 def _loweright(self): 

524 '''(INTERNAL) Cache for L{loweright}. 

525 ''' 

526 return self._llh3(self._lat_lo, self._lon_hi) 

527 

528 def loweright(self, LatLon=None): 

529 '''Return the lower-right location and height of this geoid. 

530 

531 @kwarg LatLon: Optional class to return the location and height 

532 (C{LatLon}) or C{None}. 

533 

534 @return: If C{B{LatLon} is None}, a L{LatLon3Tuple}C{(lat, lon, height)} 

535 otherwise a B{C{LatLon}} instance with the lat-, longitude and 

536 geoid height of the lower-right, SE grid corner. 

537 ''' 

538 

539 return self._llh3LL(self._loweright, LatLon) 

540 

541 lowerright = loweright # synonymous 

542 

543 @Property_RO 

544 def _lowest(self): 

545 '''(INTERNAL) Cache for L{lowest}. 

546 ''' 

547 return self._llh3minmax(False) 

548 

549 def lowest(self, LatLon=None, **unused): 

550 '''Return the location and lowest height of this geoid. 

551 

552 @kwarg LatLon: Optional class to return the location and height 

553 (C{LatLon}) or C{None}. 

554 

555 @return: If C{B{LatLon} is None}, a L{LatLon3Tuple}C{(lat, lon, 

556 height)} otherwise a B{C{LatLon}} instance with the lat-, 

557 longitude and geoid height of the lowest grid location. 

558 ''' 

559 return self._llh3LL(self._lowest, LatLon) 

560 

561 @Property_RO 

562 def mean(self): 

563 '''Get the mean of this geoid's heights (C{float}). 

564 ''' 

565 if self._mean is None: # see GeoidKarney 

566 self._mean = float(self.numpy.mean(self._hs_y_x)) 

567 return self._mean 

568 

569 @property_RO 

570 def name(self): 

571 '''Get the name of this geoid (C{str}). 

572 ''' 

573 return _HeightsBase.name.fget(self) or self._geoid # recursion 

574 

575 @Property_RO 

576 def nBytes(self): 

577 '''Get the grid in-memory size in bytes (C{int}). 

578 ''' 

579 return self._nBytes 

580 

581 def _open(self, geoid, datum, kind, name, smooth): 

582 # open the geoid file 

583 try: 

584 self._geoid = _os_path.basename(geoid) 

585 self._sizeB = _os_path.getsize(geoid) 

586 g = open(geoid, _rb_) 

587 except (IOError, OSError) as x: 

588 raise GeoidError(geoid=geoid, cause=x) 

589 

590 if datum not in (None, self._datum): 

591 self._datum = _ellipsoidal_datum(datum, name=name) 

592 self._kind = int(kind) 

593 if name: 

594 _HeightsBase.name.fset(self, name) # rename 

595 if smooth: 

596 self._smooth = Int_(smooth=smooth, Error=GeoidError, low=0) 

597 

598 return g 

599 

600 def outside(self, lat, lon): 

601 '''Check whether a location is outside this geoid's 

602 lat-/longitude or crop range. 

603 

604 @arg lat: The latitude (C{degrees}). 

605 @arg lon: The longitude (C{degrees}). 

606 

607 @return: A 1- or 2-character C{str} if outside or an 

608 empty C{str} if inside. 

609 ''' 

610 return (_S_ if lat < self._lat_lo else 

611 (_N_ if lat > self._lat_hi else NN)) + \ 

612 (_W_ if lon < self._lon_lo else 

613 (_E_ if lon > self._lon_hi else NN)) 

614 

615 @Property_RO 

616 def pgm(self): 

617 '''Get the PGM attributes (C{_PGM} or C{None} if not available/applicable). 

618 ''' 

619 return self._pgm 

620 

621 @Property_RO 

622 def sizeB(self): 

623 '''Get the geoid grid file size in bytes (C{int}). 

624 ''' 

625 return self._sizeB 

626 

627 @Property_RO 

628 def smooth(self): 

629 '''Get the C{RectBivariateSpline} smoothing (C{int}). 

630 ''' 

631 return self._smooth 

632 

633 @Property_RO 

634 def stdev(self): 

635 '''Get the standard deviation of this geoid's heights (C{float}) or C{None}. 

636 ''' 

637 if self._stdev is None: # see GeoidKarney 

638 self._stdev = float(self.numpy.std(self._hs_y_x)) 

639 return self._stdev 

640 

641 def _swne(self, crop): 

642 # crop box to 4-tuple (s, w, n, e) 

643 try: 

644 if len(crop) == 2: 

645 try: # sw, ne LatLons 

646 swne = (crop[0].lat, crop[0].lon, 

647 crop[1].lat, crop[1].lon) 

648 except AttributeError: # (s, w), (n, e) 

649 swne = tuple(crop[0]) + tuple(crop[1]) 

650 else: # (s, w, n, e) 

651 swne = crop 

652 if len(swne) == 4: 

653 s, w, n, e = map(float, swne) 

654 if -90 <= s <= (n - _1_0) <= 89 and \ 

655 -180 <= w <= (e - _1_0) <= 179: 

656 return s, w, n, e 

657 except (IndexError, TypeError, ValueError): 

658 pass 

659 raise GeoidError(crop=crop) 

660 

661 def toStr(self, prec=3, sep=_COMMASPACE_): # PYCHOK signature 

662 '''This geoid and all geoid attributes as a string. 

663 

664 @kwarg prec: Number of decimal digits (0..9 or C{None} for 

665 default). Trailing zero decimals are stripped 

666 for B{C{prec}} values of 1 and above, but kept 

667 for negative B{C{prec}} values. 

668 @kwarg sep: Separator to join (C{str}). 

669 

670 @return: Geoid name and attributes (C{str}). 

671 ''' 

672 s = 1 if self.kind < 0 else 2 

673 t = tuple(Fmt.PAREN(m.__name__, fstr(m(), prec=prec)) for m in 

674 (self.lowerleft, self.upperright, 

675 self.center, 

676 self.highest, self.lowest)) + \ 

677 attrs( _mean_, _stdev_, prec=prec, Nones=False) + \ 

678 attrs((_kind_, 'smooth')[:s], prec=prec, Nones=False) + \ 

679 attrs( 'cropped', 'dtype', _endian_, 'hits', 'knots', 'nBytes', 

680 'sizeB', _scipy_, _numpy_, prec=prec, Nones=False) 

681 return _COLONSPACE_(self, sep.join(t)) 

682 

683 @Property_RO 

684 def u2B(self): 

685 '''Get the PGM itemsize in bytes (C{int}). 

686 ''' 

687 return self._u2B 

688 

689 @Property_RO 

690 def _upperleft(self): 

691 '''(INTERNAL) Cache for method L{upperleft}. 

692 ''' 

693 return self._llh3(self._lat_hi, self._lon_lo) 

694 

695 def upperleft(self, LatLon=None): 

696 '''Return the upper-left location and height of this geoid. 

697 

698 @kwarg LatLon: Optional class to return the location and height 

699 (C{LatLon}) or C{None}. 

700 

701 @return: If C{B{LatLon} is None}, a L{LatLon3Tuple}C{(lat, lon, height)} 

702 otherwise a B{C{LatLon}} instance with the lat-, longitude and 

703 geoid height of the upper-left, NW grid corner. 

704 ''' 

705 return self._llh3LL(self._upperleft, LatLon) 

706 

707 @Property_RO 

708 def _upperright(self): 

709 '''(INTERNAL) Cache for method L{upperright}. 

710 ''' 

711 return self._llh3(self._lat_hi, self._lon_hi) 

712 

713 def upperright(self, LatLon=None): 

714 '''Return the upper-right location and height of this geoid. 

715 

716 @kwarg LatLon: Optional class to return the location and height 

717 (C{LatLon}) or C{None}. 

718 

719 @return: If C{B{LatLon} is None}, a L{LatLon3Tuple}C{(lat, lon, height)} 

720 otherwise a B{C{LatLon}} instance with the lat-, longitude and 

721 geoid height of the upper-right, NE grid corner. 

722 ''' 

723 return self._llh3LL(self._upperright, LatLon) 

724 

725 

726class GeoidError(HeightError): 

727 '''Geoid interpolator C{Geoid...} or interpolation issue. 

728 ''' 

729 pass 

730 

731 

732class GeoidG2012B(_GeoidBase): 

733 '''Geoid height interpolator for U{GEOID12B Model 

734 <https://www.NGS.NOAA.gov/GEOID/GEOID12B/>} grids U{CONUS 

735 <https://www.NGS.NOAA.gov/GEOID/GEOID12B/GEOID12B_CONUS.shtml>}, 

736 U{Alaska<https://www.NGS.NOAA.gov/GEOID/GEOID12B/GEOID12B_AK.shtml>}, 

737 U{Hawaii<https://www.NGS.NOAA.gov/GEOID/GEOID12B/GEOID12B_HI.shtml>}, 

738 U{Guam and Northern Mariana Islands 

739 <https://www.NGS.NOAA.gov/GEOID/GEOID12B/GEOID12B_GMNI.shtml>}, 

740 U{Puerto Rico and U.S. Virgin Islands 

741 <https://www.NGS.NOAA.gov/GEOID/GEOID12B/GEOID12B_PRVI.shtml>} and 

742 U{American Samoa<https://www.NGS.NOAA.gov/GEOID/GEOID12B/GEOID12B_AS.shtml>} 

743 based on C{SciPy} U{RectBivariateSpline<https://docs.SciPy.org/doc/ 

744 scipy/reference/generated/scipy.interpolate.RectBivariateSpline.html>} 

745 or U{interp2d<https://docs.SciPy.org/doc/scipy/reference/generated/ 

746 scipy.interpolate.interp2d.html>} interpolation. 

747 

748 Use any of the binary C{le} (little endian) or C{be} (big endian) 

749 C{g2012b*.bin} grid files. 

750 ''' 

751 def __init__(self, g2012b_bin, datum=None, # NAD 83 Ellipsoid 

752 kind=3, smooth=0, **name_crop): 

753 '''New L{GeoidG2012B} interpolator. 

754 

755 @arg g2012b_bin: A C{GEOID12B} grid file name (C{.bin}). 

756 @kwarg datum: Optional grid datum (L{Datum}, L{Ellipsoid}, L{Ellipsoid2} 

757 or L{a_f2Tuple}), default C{WGS84}. 

758 @kwarg kind: C{scipy.interpolate} order (C{int}), use 1..5 for 

759 U{RectBivariateSpline<https://docs.SciPy.org/doc/scipy/ 

760 reference/generated/scipy.interpolate.RectBivariateSpline.html>}, 

761 -2 for U{interp2d linear<https://docs.SciPy.org/doc/scipy/ 

762 reference/generated/scipy.interpolate.interp2d.html>}, -3 

763 for C{interp2d cubic} or -5 for C{interp2d quintic}. 

764 @kwarg smooth: Smoothing factor for U{RectBivariateSpline 

765 <https://docs.SciPy.org/doc/scipy/reference/generated/ 

766 scipy.interpolate.RectBivariateSpline.html>} 

767 only (C{int}). 

768 @kwarg name_crop: Optional geoid C{B{name}=NN} (C{str}) and UNSUPPORTED 

769 keyword argument C{B{crop}}, use C{B{crop}=None} to ignore. 

770 

771 @raise GeoidError: G2012B grid file B{C{g2012b_bin}} issue or invalid 

772 B{C{crop}}, B{C{kind}} or B{C{smooth}}. 

773 

774 @raise ImportError: Package C{numpy} or C{scipy} not found or not 

775 installed. 

776 

777 @raise LenError: Grid file B{C{g2012b_bin}} axis mismatch. 

778 

779 @raise SciPyError: A C{RectBivariateSpline} or C{inter2d} issue. 

780 

781 @raise SciPyWarning: A C{RectBivariateSpline} or C{inter2d} 

782 warning as exception. 

783 

784 @raise TypeError: Invalid B{C{datum}}. 

785 

786 @note: C{scipy.interpolate.interp2d} has been C{DEPRECATED}, specify 

787 C{B{kind}=1..5} for C{scipy.interpolate.RectBivariateSpline}. 

788 ''' 

789 crop, name = _xkwds_pop2(name_crop, crop=None) 

790 if crop is not None: 

791 raise GeoidError(crop=crop, txt_not_=_supported_) 

792 

793 g = self._open(g2012b_bin, datum, kind, _name__(**name), smooth) 

794 _ = self.numpy # import numpy for ._load and 

795 

796 try: 

797 p = _Gpars() 

798 n = (self.sizeB // 4) - 11 # number of f4 heights 

799 # U{numpy dtype formats are different from Python struct formats 

800 # <https://docs.SciPy.org/doc/numpy-1.15.0/reference/arrays.dtypes.html>} 

801 for en_ in ('<', '>'): 

802 # skip 4xf8, get 3xi4 

803 p.nlat, p.nlon, ien = map(int, self._load(g, en_+'i4', 3, 32)) 

804 if ien == 1: # correct endian 

805 p.knots = p.nlat * p.nlon 

806 if p.knots == n and 1 < p.nlat < n \ 

807 and 1 < p.nlon < n: 

808 self._endian = en_+'f4' 

809 break 

810 else: # couldn't validate endian 

811 raise GeoidError(_endian_) 

812 

813 # get the first 4xf8 

814 p.slat, p.wlon, p.dlat, p.dlon = map(float, self._load(g, en_+'f8', 4)) 

815 # read all f4 heights, ignoring the first 4xf8 and 3xi4 

816 hs = self._load(g, self._endian, n, 44).reshape(p.nlat, p.nlon) 

817 p.wlon -= _360_0 # western-most East longitude to earth (..., lon) 

818 _GeoidBase.__init__(self, hs, p) 

819 

820 except Exception as x: 

821 raise _SciPyIssue(x, _in_, repr(g2012b_bin)) 

822 finally: 

823 g.close() 

824 

825 def _g2ll2(self, lat, lon): 

826 # convert grid (lat, lon) to earth (lat, lon) 

827 return lat, lon 

828 

829 def _ll2g2(self, lat, lon): 

830 # convert earth (lat, lon) to grid (lat, lon) 

831 return lat, lon 

832 

833 if _FOR_DOCS: 

834 __call__ = _GeoidBase.__call__ 

835 height = _GeoidBase.height 

836 

837 

838class GeoidHeight5Tuple(_NamedTuple): # .geoids.py 

839 '''5-Tuple C{(lat, lon, egm84, egm96, egm2008)} for U{GeoidHeights.dat 

840 <https://SourceForge.net/projects/geographiclib/files/testdata/>} 

841 tests with the heights for 3 different EGM grids at C{degrees90} 

842 and C{degrees180} degrees (after converting C{lon} from original 

843 C{0 <= EasterLon <= 360}). 

844 ''' 

845 _Names_ = (_lat_, _lon_, 'egm84', 'egm96', 'egm2008') 

846 _Units_ = ( Lat, Lon, Height, Height, Height) 

847 

848 

849def _I(i): 

850 '''(INTERNAL) Cache a single C{int} constant. 

851 ''' 

852 return _intCs.setdefault(i, i) # PYCHOK undefined due to del _intCs 

853 

854 

855def _T(*cs): 

856 '''(INTERNAL) Cache a tuple of single C{int} constants. 

857 ''' 

858 return map1(_I, *cs) 

859 

860_T0s12 = (_I(0),) * 12 # PYCHOK _T(0, 0, ..., 0) 

861 

862 

863class GeoidKarney(_GeoidBase): 

864 '''Geoid height interpolator for I{Karney}'s U{GeographicLib Earth 

865 Gravitational Model (EGM)<https://GeographicLib.SourceForge.io/C++/doc/ 

866 geoid.html>} geoid U{egm*.pgm<https://GeographicLib.SourceForge.io/ 

867 C++/doc/geoid.html#geoidinst>} datasets using bilinear or U{cubic 

868 <https://dl.ACM.org/citation.cfm?id=368443>} interpolation and U{caching 

869 <https://GeographicLib.SourceForge.io/C++/doc/geoid.html#geoidcache>} 

870 in pure Python, transcoded from I{Karney}'s U{C++ class Geoid 

871 <https://GeographicLib.SourceForge.io/C++/doc/geoid.html#geoidinterp>}. 

872 

873 Use any of the geoid U{egm84-, egm96- or egm2008-*.pgm 

874 <https://GeographicLib.SourceForge.io/C++/doc/geoid.html#geoidinst>} 

875 datasets. 

876 ''' 

877 _C0 = _F(372), _F(240), _F(372) # n, _ and s common denominators 

878 # matrices c3n_, c3, c3s_, transposed from GeographicLib/Geoid.cpp 

879 _C3 = ((_T(0, 0, 62, 124, 124, 62, 0, 0, 0, 0, 0, 0), 

880 _T0s12, 

881 _T(-131, 7, -31, -62, -62, -31, 45, 216, 156, -45, -55, -7), 

882 _T0s12, 

883 _T(138, -138, 0, 0, 0, 0, -183, 33, 153, -3, 48, -48), # PYCHOK indent 

884 _T(144, 42, -62, -124, -124, -62, -9, 87, 99, 9, 42, -42), 

885 _T0s12, 

886 _T(0, 0, 0, 0, 0, 0, 93, -93, -93, 93, 0, 0), 

887 _T(-102, 102, 0, 0, 0, 0, 18, 12, -12, -18, -84, 84), 

888 _T(-31, -31, 31, 62, 62, 31, 0, -93, -93, 0, 31, 31)), # PYCHOK indent 

889 

890 (_T(9, -9, 9, 186, 54, -9, -9, 54, -54, 9, -9, 9), 

891 _T(-18, 18, -88, -42, 162, -32, 8, -78, 78, -8, 18, -18), 

892 _T(-88, 8, -18, -42, -78, 18, 18, 162, 78, -18, -32, -8), 

893 _T(0, 0, 90, -150, 30, 30, 30, -90, 90, -30, 0, 0), 

894 _T(96, -96, 96, -96, -24, 24, -96, -24, 144, -24, 24, -24), # PYCHOK indent 

895 _T(90, 30, 0, -150, -90, 0, 0, 30, 90, 0, 30, -30), 

896 _T(0, 0, -20, 60, -60, 20, -20, 60, -60, 20, 0, 0), 

897 _T(0, 0, -60, 60, 60, -60, 60, -60, -60, 60, 0, 0), 

898 _T(-60, 60, 0, 60, -60, 0, 0, 60, -60, 0, -60, 60), 

899 _T(-20, -20, 0, 60, 60, 0, 0, -60, -60, 0, 20, 20)), 

900 

901 (_T(18, -18, 36, 210, 162, -36, 0, 0, 0, 0, -18, 18), # PYCHOK indent 

902 _T(-36, 36, -165, 45, 141, -21, 0, 0, 0, 0, 36, -36), 

903 _T(-122, -2, -27, -111, -75, 27, 62, 124, 124, 62, -64, 2), 

904 _T(0, 0, 93, -93, -93, 93, 0, 0, 0, 0, 0, 0), 

905 _T(120, -120, 147, -57, -129, 39, 0, 0, 0, 0, 66, -66), # PYCHOK indent 

906 _T(135, 51, -9, -192, -180, 9, 31, 62, 62, 31, 51, -51), 

907 _T0s12, 

908 _T(0, 0, -93, 93, 93, -93, 0, 0, 0, 0, 0, 0), 

909 _T(-84, 84, 18, 12, -12, -18, 0, 0, 0, 0, -102, 102), 

910 _T(-31, -31, 0, 93, 93, 0, -31, -62, -62, -31, 31, 31))) 

911 

912 _BT = (_T(0, 0), # bilinear 4-tuple [i, j] indices 

913 _T(1, 0), 

914 _T(0, 1), 

915 _T(1, 1)) 

916 

917 _CM = (_T( 0, -1), # 10x12 cubic matrix [i, j] indices 

918 _T( 1, -1), 

919 _T(-1, 0), 

920 _T( 0, 0), 

921 _T( 1, 0), 

922 _T( 2, 0), 

923 _T(-1, 1), 

924 _T( 0, 1), 

925 _T( 1, 1), 

926 _T( 2, 1), 

927 _T( 0, 2), 

928 _T( 1, 2)) 

929 

930 _endian = '>H' # struct.unpack 1 ushort (big endian, unsigned short) 

931 _4endian = '>4H' # struct.unpack 4 ushorts 

932 _Rendian = NN # struct.unpack a row of ushorts 

933# _highest = (-8.4, 147.367, 85.839) if egm2008-1.pgm else ( 

934# (-8.167, 147.25, 85.422) if egm96-5.pgm else 

935# (-4.5, 148.75, 81.33)) # egm84-15.pgm 

936# _lowest = (4.7, 78.767, -106.911) if egm2008-1.pgm else ( 

937# (4.667, 78.833, -107.043) if egm96-5.pgm else 

938# (4.75, 79.25, -107.34)) # egm84-15.pgm 

939 _mean = _F(-1.317) # from egm2008-1, -1.438 egm96-5, -0.855 egm84-15 

940 _nBytes = None # not applicable 

941 _nterms = len(_C3[0]) # columns length, number of row 

942 _smooth = None # not applicable 

943 _stdev = _F(29.244) # from egm2008-1, 29.227 egm96-5, 29.183 egm84-15 

944 _u2B = _calcsize(_endian) # pixelsize_ in bytes 

945 _4u2B = _calcsize(_4endian) # 4 pixelsize_s in bytes 

946 _Ru2B = 0 # row of pixelsize_s in bytes 

947 _yxH = () # cache (y, x) indices 

948 _yxHt = () # cached 4- or 10-tuple for _ev2H resp. _ev3H 

949 _yx_hits = 0 # cache hits 

950 

951 def __init__(self, egm_pgm, crop=None, datum=None, # WGS84 

952 kind=3, **name_smooth): 

953 '''New L{GeoidKarney} interpolator. 

954 

955 @arg egm_pgm: An U{EGM geoid dataset<https://GeographicLib.SourceForge.io/ 

956 C++/doc/geoid.html#geoidinst>} file name (C{egm*.pgm}), see 

957 note below. 

958 @kwarg crop: Optional box to limit geoid locations, a 4-tuple (C{south, 

959 west, north, east}), 2-tuple (C{(south, west), (north, 

960 east)}) or 2, in C{degrees90} lat- and C{degrees180} 

961 longitudes or a 2-tuple (C{LatLonSW, LatLonNE}) of 

962 C{LatLon} instances. 

963 @kwarg datum: Optional grid datum (C{Datum}, L{Ellipsoid}, L{Ellipsoid2} 

964 or L{a_f2Tuple}), default C{WGS84}. 

965 @kwarg kind: Interpolation order (C{int}), 2 for C{bilinear} or 3 

966 for C{cubic}. 

967 @kwarg name_smooth: Optional geoid C{B{name}=NN} (C{str}) and UNSUPPORTED 

968 keyword argument C{B{smooth}}, use C{B{smooth}=None} to ignore. 

969 

970 @raise GeoidError: EGM dataset B{C{egm_pgm}} issue or invalid 

971 B{C{crop}}, B{C{kind}} or B{C{smooth}}. 

972 

973 @raise TypeError: Invalid B{C{datum}}. 

974 

975 @see: Class L{GeoidPGM} and function L{egmGeoidHeights}. 

976 

977 @note: Geoid file B{C{egm_pgm}} remains open and must be closed 

978 by calling the C{close} method or by using this instance 

979 in a C{with B{GeoidKarney}(...) as ...} context. 

980 ''' 

981 smooth, name = _xkwds_pop2(name_smooth, smooth=None) 

982 if smooth is not None: 

983 raise GeoidError(smooth=smooth, txt_not_=_supported_) 

984 

985 if kind in (2,): 

986 self._evH = self._ev2H 

987 elif kind not in (3,): 

988 raise GeoidError(kind=kind) 

989 

990 self._egm = g = self._open(egm_pgm, datum, kind, _name__(**name), None) 

991 self._pgm = p = _PGM(g, pgm=egm_pgm, itemsize=self.u2B, sizeB=self.sizeB) 

992 

993 self._Rendian = self._4endian.replace(_4_, str(p.nlon)) 

994 self._Ru2B = _calcsize(self._Rendian) 

995 

996 self._knots = p.knots # grid knots 

997 self._lon_of = float(p.flon) # forward offset 

998 self._lon_og = float(p.glon) # reverse offset 

999 # set earth (lat, lon) limits (s, w, n, e) 

1000 self._lat_lo, self._lon_lo, \ 

1001 self._lat_hi, self._lon_hi = self._swne(crop if crop else p.crop4) 

1002 self._cropped = True if crop else False 

1003 

1004 def __call__(self, *llis, **wrap_H): 

1005 '''Interpolate the geoid height for one or several locations. 

1006 

1007 @arg llis: One or more locations (C{LatLon}s), all positional. 

1008 @kwarg wrap_H: Keyword arguments C{B{wrap}=False, B{H}=False}. 

1009 If C{B{wrap} is True}, wrap or I{normalize} all 

1010 B{C{llis}} locations (C{bool}). If C{B{H} is True}, 

1011 return the I{orthometric} height instead of the 

1012 I{geoid} height at each location (C{bool}). 

1013 

1014 @return: A single interpolated geoid (or orthometric) height 

1015 (C{float}) or a list or tuple of interpolated geoid 

1016 (or orthometric) heights (C{float}s). 

1017 

1018 @raise GeoidError: Insufficient number of B{C{llis}}, an 

1019 invalid B{C{lli}} or the C{egm*.pgm} 

1020 geoid file is closed. 

1021 

1022 @raise RangeError: An B{C{lli}} is outside this geoid's lat- 

1023 or longitude range. 

1024 

1025 @note: To obtain I{orthometric} heights, each B{C{llis}} 

1026 location must have an ellipsoid C{height} or C{h} 

1027 attribute, otherwise C{height=0} is used. 

1028 

1029 @see: Function L{pygeodesy.heightOrthometric}. 

1030 ''' 

1031 return self._called(llis, False, **wrap_H) 

1032 

1033 def _c0c3v(self, y, x): 

1034 # get the common denominator, the 10x12 cubic matrix and 

1035 # the 12 cubic v-coefficients around geoid index (y, x) 

1036 p = self._pgm 

1037 if 0 < x < (p.nlon - 2) and 0 < y < (p.nlat - 2): 

1038 # read 4x4 ushorts, drop the 4 corners 

1039 g = self._egm 

1040 e = self._4endian 

1041 n = self._4u2B 

1042 R = self._Ru2B 

1043 

1044 b = self._seek(y - 1, x - 1) 

1045 v = _unpack(e, g.read(n))[1:3] 

1046 b += R 

1047 g.seek(b, _SEEK_SET) 

1048 v += _unpack(e, g.read(n)) 

1049 b += R 

1050 g.seek(b, _SEEK_SET) 

1051 v += _unpack(e, g.read(n)) 

1052 b += R 

1053 g.seek(b, _SEEK_SET) 

1054 v += _unpack(e, g.read(n))[1:3] 

1055 j = 1 

1056 

1057 else: # likely some wrapped y and/or x's 

1058 v = self._raws(y, x, GeoidKarney._CM) 

1059 j = 0 if y < 1 else (1 if y < (p.nlat - 2) else 2) 

1060 

1061 return GeoidKarney._C0[j], GeoidKarney._C3[j], v 

1062 

1063 @Property_RO 

1064 def dtype(self): 

1065 '''Get the geoid's grid data type (C{str}). 

1066 ''' 

1067 return 'ushort' 

1068 

1069 def _ev(self, lat, lon): # PYCHOK expected 

1070 # interpolate the geoid height at grid (lat, lon) 

1071 fy, fx = self._g2yx2(lat, lon) 

1072 y, x = int(floor(fy)), int(floor(fx)) 

1073 fy -= y 

1074 fx -= x 

1075 H = self._evH(fy, fx, y, x) # ._ev3H or ._ev2H 

1076 H *= self._pgm.Scale # H.fmul(self._pgm.Scale) 

1077 H += self._pgm.Offset # H.fadd(self._pgm.Offset) 

1078 return H.fsum() 

1079 

1080 def _ev2H(self, fy, fx, *yx): 

1081 # compute the bilinear 4-tuple and interpolate raw H 

1082 if self._yxH == yx: 

1083 t = self._yxHt 

1084 self._yx_hits += 1 

1085 else: 

1086 y, x = self._yxH = yx 

1087 self._yxHt = t = self._raws(y, x, GeoidKarney._BT) 

1088 v = _1_0, -fx, fx 

1089 H = Fdot(v, t[0], t[0], t[1]).fmul(_1_0 - fy) # c = a * (1 - fy) 

1090 H += Fdot(v, t[2], t[2], t[3]).fmul(fy) # c += b * fy 

1091 return H 

1092 

1093 def _ev3H(self, fy, fx, *yx): 

1094 # compute the cubic 10-tuple and interpolate raw H 

1095 if self._yxH == yx: 

1096 t = self._yxHt 

1097 self._yx_hits += 1 

1098 else: 

1099 self._yxH = yx 

1100 c0, c3, v = self._c0c3v(*yx) 

1101 t = [fdot(v, *c3[i]) / c0 for i in range(self._nterms)] 

1102 self._yxHt = t = tuple(t) 

1103 # GeographicLib/Geoid.cpp Geoid::height(lat, lon) ... 

1104 # real h = t[0] + fx * (t[1] + fx * (t[3] + fx * t[6])) + 

1105 # fy * (t[2] + fx * (t[4] + fx * t[7]) + 

1106 # fy * (t[5] + fx * t[8] + fy * t[9])); 

1107 v = _1_0, fx, fy 

1108 H = Fdot(v, t[5], t[8], t[9]) 

1109 H *= fy 

1110 H += Fhorner(fx, t[2], t[4], t[7]) 

1111 H *= fy 

1112 H += Fhorner(fx, t[0], t[1], t[3], t[6]) 

1113 return H 

1114 

1115 _evH = _ev3H # overriden for kind == 2 

1116 

1117 def _g2ll2(self, lat, lon): 

1118 # convert grid (lat, lon) to earth (lat, lon), uncropped 

1119 while lon > _180_0: 

1120 lon -= _360_0 

1121 return lat, lon 

1122 

1123 def _g2yx2(self, lat, lon): 

1124 # convert grid (lat, lon) to grid (y, x) indices 

1125 p = self._pgm 

1126 # note, slat = +90, rlat < 0 makes y >=0 

1127 return ((lat - p.slat) * p.rlat), ((lon - p.wlon) * p.rlon) 

1128 

1129 def _gyx2g2(self, y, x): 

1130 # convert grid (y, x) indices to grid (lat, lon) 

1131 p = self._pgm 

1132 return (p.slat + p.dlat * y), (p.wlon + p.dlon * x) 

1133 

1134 def height(self, lats, lons, **wrap): 

1135 '''Interpolate the geoid height for one or several lat-/longitudes. 

1136 

1137 @arg lats: Latitude or latitudes (C{degrees} or C{degrees}s). 

1138 @arg lons: Longitude or longitudes (C{degrees} or C{degrees}s). 

1139 @kwarg wrap: If C{True}, wrap or I{normalize} all B{C{lats}} 

1140 and B{C{lons}} locations (C{bool}). 

1141 

1142 @return: A single interpolated geoid height (C{float}) or a 

1143 list of interpolated geoid heights (C{float}s). 

1144 

1145 @raise GeoidError: Insufficient or non-matching number of 

1146 B{C{lats}} and B{C{lons}} or the C{egm*.pgm} 

1147 geoid file is closed. 

1148 

1149 @raise RangeError: A B{C{lat}} or B{C{lon}} is outside this 

1150 geoid's lat- or longitude range. 

1151 ''' 

1152 return _height_called(self, lats, lons, Error=GeoidError, **wrap) 

1153 

1154 @Property_RO 

1155 def _highest_ltd(self): 

1156 '''(INTERNAL) Cache for L{highest} mesthod. 

1157 ''' 

1158 return self._llh3minmax(True, -12, -4) 

1159 

1160 def highest(self, LatLon=None, full=False): # PYCHOK full 

1161 '''Return the location and largest height of this geoid. 

1162 

1163 @kwarg LatLon: Optional class to return the location and height 

1164 (C{LatLon}) or C{None}. 

1165 @kwarg full: Search the full or limited latitude range (C{bool}). 

1166 

1167 @return: If C{B{LatLon} is None}, a L{LatLon3Tuple}C{(lat, lon, 

1168 height)} otherwise a B{C{LatLon}} instance with the lat-, 

1169 longitude and geoid height of the highest grid location. 

1170 ''' 

1171 llh = self._highest if full or self.cropped else self._highest_ltd 

1172 return self._llh3LL(llh, LatLon) 

1173 

1174 def _lat2y2(self, lat2): 

1175 # convert earth lat(s) to min and max grid y indices 

1176 ys, m = [], self._pgm.nlat - 1 

1177 for lat in lat2: 

1178 y, _ = self._g2yx2(*self._ll2g2(lat, 0)) 

1179 ys.append(max(min(int(y), m), 0)) 

1180 return min(ys), max(ys) + 1 

1181 

1182 def _ll2g2(self, lat, lon): 

1183 # convert earth (lat, lon) to grid (lat, lon), uncropped 

1184 while lon < 0: 

1185 lon += _360_0 

1186 return lat, lon 

1187 

1188 def _llh3minmax(self, highest=True, *lat2): 

1189 # find highest or lowest, takes 10+ secs for egm2008-1.pgm geoid 

1190 # (Python 2.7.16, macOS 10.13.6 High Sierra, iMac 3 GHz Core i3) 

1191 y = x = 0 

1192 h = self._raw(y, x) 

1193 if highest: 

1194 for j, r in self._raw2(*lat2): 

1195 m = max(r) 

1196 if m > h: 

1197 h, y, x = m, j, r.index(m) 

1198 else: # lowest 

1199 for j, r in self._raw2(*lat2): 

1200 m = min(r) 

1201 if m < h: 

1202 h, y, x = m, j, r.index(m) 

1203 h *= self._pgm.Scale 

1204 h += self._pgm.Offset 

1205 return self._g2ll2(*self._gyx2g2(y, x)) + (h,) 

1206 

1207 @Property_RO 

1208 def _lowest_ltd(self): 

1209 '''(INTERNAL) Cache for L{lowest}. 

1210 ''' 

1211 return self._llh3minmax(False, 0, 8) 

1212 

1213 def lowest(self, LatLon=None, full=False): # PYCHOK full 

1214 '''Return the location and lowest height of this geoid. 

1215 

1216 @kwarg LatLon: Optional class to return the location and height 

1217 (C{LatLon}) or C{None}. 

1218 @kwarg full: Search the full or limited latitude range (C{bool}). 

1219 

1220 @return: If C{B{LatLon} is None}, a L{LatLon3Tuple}C{(lat, lon, 

1221 height)} otherwise a B{C{LatLon}} instance with the lat-, 

1222 longitude and geoid height of the lowest grid location. 

1223 ''' 

1224 llh = self._lowest if full or self.cropped else self._lowest_ltd 

1225 return self._llh3LL(llh, LatLon) 

1226 

1227 def _raw(self, y, x): 

1228 # get the ushort geoid height at geoid index (y, x), 

1229 # like GeographicLib/Geoid.hpp real rawval(is, iy) 

1230 p = self._pgm 

1231 if x < 0: 

1232 x += p.nlon 

1233 elif x >= p.nlon: 

1234 x -= p.nlon 

1235 h = p.nlon // 2 

1236 if y < 0: 

1237 y = -y 

1238 elif y >= p.nlat: 

1239 y = (p.nlat - 1) * 2 - y 

1240 else: 

1241 h = 0 

1242 x += h if x < h else -h 

1243 self._seek(y, x) 

1244 h = _unpack(self._endian, self._egm.read(self._u2B)) 

1245 return h[0] 

1246 

1247 def _raws(self, y, x, ijs): 

1248 # get bilinear 4-tuple or 10x12 cubic matrix 

1249 return tuple(self._raw(y + j, x + i) for i, j in ijs) 

1250 

1251 def _raw2(self, *lat2): 

1252 # yield a 2-tuple (y, ushorts) for each row or for 

1253 # the rows between two (or more) earth lat values 

1254 p = self._pgm 

1255 g = self._egm 

1256 e = self._Rendian 

1257 n = self._Ru2B 

1258 # min(lat2) <= lat <= max(lat2) or 0 <= y < p.nlat 

1259 s, t = self._lat2y2(lat2) if lat2 else (0, p.nlat) 

1260 self._seek(s, 0) # to start of row s 

1261 for y in range(s, t): 

1262 yield y, _unpack(e, g.read(n)) 

1263 

1264 def _seek(self, y, x): 

1265 # position geoid to grid index (y, x) 

1266 p, g = self._pgm, self._egm 

1267 if g: 

1268 b = p.skip + (y * p.nlon + x) * self._u2B 

1269 g.seek(b, _SEEK_SET) 

1270 return b # position 

1271 raise GeoidError('closed file', txt=repr(p.egm)) # IOError 

1272 

1273 

1274class GeoidPGM(_GeoidBase): 

1275 '''Geoid height interpolator for I{Karney}'s U{GeographicLib Earth 

1276 Gravitational Model (EGM)<https://GeographicLib.SourceForge.io/C++/doc/ 

1277 geoid.html>} geoid U{egm*.pgm<https://GeographicLib.SourceForge.io/ 

1278 C++/doc/geoid.html#geoidinst>} datasets but based on C{SciPy} 

1279 U{RectBivariateSpline<https://docs.SciPy.org/doc/scipy/reference/ 

1280 generated/scipy.interpolate.RectBivariateSpline.html>} or 

1281 U{interp2d<https://docs.SciPy.org/doc/scipy/reference/generated/ 

1282 scipy.interpolate.interp2d.html>} interpolation. 

1283 

1284 Use any of the U{egm84-, egm96- or egm2008-*.pgm 

1285 <https://GeographicLib.SourceForge.io/C++/doc/geoid.html#geoidinst>} 

1286 datasets. However, unless cropped, an entire C{egm*.pgm} dataset 

1287 is loaded into the C{SciPy} U{RectBivariateSpline<https://docs.SciPy.org/ 

1288 doc/scipy/reference/generated/scipy.interpolate.RectBivariateSpline.html>} 

1289 or U{interp2d<https://docs.SciPy.org/doc/scipy/reference/generated/ 

1290 scipy.interpolate.interp2d.html>} interpolator and converted from 

1291 2-byte C{int} to 8-byte C{dtype float64}. Therefore, internal memory 

1292 usage is 4x the U{egm*.pgm<https://GeographicLib.SourceForge.io/C++/doc/ 

1293 geoid.html#geoidinst>} file size and may exceed the available memory, 

1294 especially with 32-bit Python, see properties C{.nBytes} and C{.sizeB}. 

1295 ''' 

1296 _cropped = False 

1297 _endian = '>u2' 

1298 

1299 def __init__(self, egm_pgm, crop=None, datum=None, # WGS84 

1300 kind=3, smooth=0, **name): 

1301 '''New L{GeoidPGM} interpolator. 

1302 

1303 @arg egm_pgm: An U{EGM geoid dataset<https://GeographicLib.SourceForge.io/ 

1304 C++/doc/geoid.html#geoidinst>} file name (C{egm*.pgm}). 

1305 @kwarg crop: Optional box to crop B{C{egm_pgm}}, a 4-tuple (C{south, west, 

1306 north, east}) or 2-tuple (C{(south, west), (north, east)}), 

1307 in C{degrees90} lat- and C{degrees180} longitudes or a 

1308 2-tuple (C{LatLonSW, LatLonNE}) of C{LatLon} instances. 

1309 @kwarg datum: Optional grid datum (L{Datum}, L{Ellipsoid}, L{Ellipsoid2} 

1310 or L{a_f2Tuple}), default C{WGS84}. 

1311 @kwarg kind: C{scipy.interpolate} order (C{int}), use 1..5 for 

1312 U{RectBivariateSpline<https://docs.SciPy.org/doc/scipy/ 

1313 reference/generated/scipy.interpolate.RectBivariateSpline.html>}, 

1314 -2 for U{interp2d linear<https://docs.SciPy.org/doc/scipy/ 

1315 reference/generated/scipy.interpolate.interp2d.html>}, -3 

1316 for C{interp2d cubic} or -5 for C{interp2d quintic}. 

1317 @kwarg smooth: Smoothing factor for U{RectBivariateSpline 

1318 <https://docs.SciPy.org/doc/scipy/reference/generated/ 

1319 scipy.interpolate.RectBivariateSpline.html>} 

1320 only (C{int}). 

1321 @kwarg name: Optional geoid C{B{name}=NN} (C{str}). 

1322 

1323 @raise GeoidError: EGM dataset B{C{egm_pgm}} issue or invalid B{C{crop}}, 

1324 B{C{kind}} or B{C{smooth}}. 

1325 

1326 @raise ImportError: Package C{numpy} or C{scipy} not found or not installed. 

1327 

1328 @raise LenError: EGM dataset B{C{egm_pgm}} axis mismatch. 

1329 

1330 @raise SciPyError: A C{RectBivariateSpline} or C{inter2d} issue. 

1331 

1332 @raise SciPyWarning: A C{RectBivariateSpline} or C{inter2d} 

1333 warning as exception. 

1334 

1335 @raise TypeError: Invalid B{C{datum}} or unexpected argument. 

1336 

1337 @note: C{scipy.interpolate.interp2d} has been C{DEPRECATED}, specify 

1338 C{B{kind}=1..5} for C{scipy.interpolate.RectBivariateSpline}. 

1339 

1340 @note: The U{GeographicLib egm*.pgm<https://GeographicLib.SourceForge.io/ 

1341 C++/doc/geoid.html#geoidinst>} file sizes are based on a 2-byte 

1342 C{int} height converted to 8-byte C{dtype float64} for C{scipy} 

1343 interpolators. Therefore, internal memory usage is 4 times the 

1344 C{egm*.pgm} file size and may exceed the available memory, 

1345 especially with 32-bit Python. To reduce memory usage, set 

1346 keyword argument B{C{crop}} to the region of interest. For example 

1347 C{B{crop}=(20, -125, 50, -65)} covers the U{conterminous US<https:// 

1348 www.NGS.NOAA.gov/GEOID/GEOID12B/maps/GEOID12B_CONUS_grids.png>} 

1349 (CONUS), less than 3% of the entire C{egm2008-1.pgm} dataset. 

1350 

1351 @see: Class L{GeoidKarney} and function L{egmGeoidHeights}. 

1352 ''' 

1353 np = self.numpy 

1354 self._u2B = np.dtype(self.endian).itemsize 

1355 

1356 g = self._open(egm_pgm, datum, kind, _name__(**name), smooth) 

1357 self._pgm = p = _PGM(g, pgm=egm_pgm, itemsize=self.u2B, sizeB=self.sizeB) 

1358 if crop: 

1359 g = p._cropped(g, abs(kind) + 1, *self._swne(crop)) 

1360 if _MODS.internals._version2(np.__version__) < (1, 9): 

1361 g = open(g.name, _rb_) # reopen tempfile for numpy 1.8.0- 

1362 self._cropped = True 

1363 try: 

1364 # U{numpy dtype formats are different from Python struct formats 

1365 # <https://docs.SciPy.org/doc/numpy-1.15.0/reference/arrays.dtypes.html>} 

1366 # read all heights, skipping the PGM header lines, converted to float 

1367 hs = self._load(g, self.endian, p.knots, p.skip).reshape(p.nlat, p.nlon) * p.Scale 

1368 if p.Offset: # offset 

1369 hs = p.Offset + hs 

1370 if p.dlat < 0: # flip the rows 

1371 hs = np.flipud(hs) 

1372 _GeoidBase.__init__(self, hs, p) 

1373 except Exception as x: 

1374 raise _SciPyIssue(x, _in_, repr(egm_pgm)) 

1375 finally: 

1376 g.close() 

1377 

1378 def _g2ll2(self, lat, lon): 

1379 # convert grid (lat, lon) to earth (lat, lon), un-/cropped 

1380 if self._cropped: 

1381 lon -= self._lon_of 

1382 else: 

1383 while lon > _180_0: 

1384 lon -= _360_0 

1385 return lat, lon 

1386 

1387 def _ll2g2(self, lat, lon): 

1388 # convert earth (lat, lon) to grid (lat, lon), un-/cropped 

1389 if self._cropped: 

1390 lon += self._lon_of 

1391 else: 

1392 while lon < 0: 

1393 lon += _360_0 

1394 return lat, lon 

1395 

1396 if _FOR_DOCS: 

1397 __call__ = _GeoidBase.__call__ 

1398 height = _GeoidBase.height 

1399 

1400 

1401class _Gpars(_Named): 

1402 '''(INTERNAL) Basic geoid parameters. 

1403 ''' 

1404 # interpolator parameters 

1405 dlat = 0 # +/- latitude resolution in C{degrees} 

1406 dlon = 0 # longitude resolution in C{degrees} 

1407 nlat = 1 # number of latitude knots (C{int}) 

1408 nlon = 0 # number of longitude knots (C{int}) 

1409 rlat = 0 # +/- latitude resolution in C{float}, 1 / .dlat 

1410 rlon = 0 # longitude resolution in C{float}, 1 / .dlon 

1411 slat = 0 # nothern- or southern most latitude (C{degrees90}) 

1412 wlon = 0 # western-most longitude in Eastern lon (C{degrees360}) 

1413 

1414 flon = 0 # forward, earth to grid longitude offset 

1415 glon = 0 # reverse, grid to earth longitude offset 

1416 

1417 knots = 0 # number of knots, nlat * nlon (C{int}) 

1418 skip = 0 # header bytes to skip (C{int}) 

1419 

1420 def __repr__(self): 

1421 t = _COMMASPACE_.join(pairs((a, getattr(self, a)) for 

1422 a in dir(self.__class__) 

1423 if a[:1].isupper())) 

1424 return _COLONSPACE_(self, t) 

1425 

1426 def __str__(self): 

1427 return Fmt.PAREN(self.classname, repr(self.name)) 

1428 

1429 

1430class _PGM(_Gpars): 

1431 '''(INTERNAL) Parse an C{egm*.pgm} geoid dataset file. 

1432 

1433 # Geoid file in PGM format for the GeographicLib::Geoid class 

1434 # Description WGS84 EGM96, 5-minute grid 

1435 # URL https://Earth-Info.NGA.mil/GandG/wgs84/gravitymod/egm96/egm96.html 

1436 # DateTime 2009-08-29 18:45:03 

1437 # MaxBilinearError 0.140 

1438 # RMSBilinearError 0.005 

1439 # MaxCubicError 0.003 

1440 # RMSCubicError 0.001 

1441 # Offset -108 

1442 # Scale 0.003 

1443 # Origin 90N 0E 

1444 # AREA_OR_POINT Point 

1445 # Vertical_Datum WGS84 

1446 <width> <height> 

1447 <pixel> 

1448 ... 

1449 ''' 

1450 crop4 = () # 4-tuple (C{south, west, north, east}). 

1451 egm = None 

1452 glon = 180 # reverse offset, uncropped 

1453# pgm = NN # name 

1454 sizeB = 0 

1455 u2B = 2 # item size of grid height (C{int}). 

1456 

1457 @staticmethod 

1458 def _llstr2floats(latlon): 

1459 # llstr to (lat, lon) floats 

1460 lat, lon = latlon.split() 

1461 return _MODS.dms.parseDMS2(lat, lon) 

1462 

1463 # PGM file attributes, CamelCase but not .istitle() 

1464 AREA_OR_POINT = str 

1465 DateTime = str 

1466 Description = str # 'WGS84 EGM96, 5-minute grid' 

1467 Geoid = str # 'file in PGM format for the GeographicLib::Geoid class' 

1468 MaxBilinearError = float 

1469 MaxCubicError = float 

1470 Offset = float 

1471 Origin = _llstr2floats 

1472 Pixel = 0 

1473 RMSBilinearError = float 

1474 RMSCubicError = float 

1475 Scale = float 

1476 URL = str # 'https://Earth-Info.NGA.mil/GandG/wgs84/...' 

1477 Vertical_Datum = str 

1478 

1479 def __init__(self, g, pgm=NN, itemsize=0, sizeB=0): # MCCABE 22 

1480 '''(INTERNAL) New C{_PGM} parsed C{egm*.pgm} geoid dataset. 

1481 ''' 

1482 self.name = pgm # geoid file name 

1483 if itemsize: 

1484 self._u2B = itemsize 

1485 if sizeB: 

1486 self.sizeB = sizeB 

1487 

1488 t = g.readline() # make sure newline == '\n' 

1489 if t != b'P5\n' and t.strip() != b'P5': 

1490 raise self._Errorf(_format_, _header_, t) 

1491 

1492 while True: # read all # Attr ... lines, 

1493 try: # ignore empty ones or comments 

1494 t = g.readline().strip() 

1495 if t.startswith(_bHASH_): 

1496 t = t.lstrip(_bHASH_).lstrip() 

1497 a, v = map(_ub2str, t.split(None, 1)) 

1498 f = getattr(_PGM, a, None) 

1499 if callable(f) and a[:1].isupper(): 

1500 setattr(self, a, f(v)) 

1501 elif t: 

1502 break 

1503 except (TypeError, ValueError): 

1504 raise self._Errorf(_format_, 'Attr', t) 

1505 else: # should never get here 

1506 raise self._Errorf(_format_, _header_, g.tell()) 

1507 

1508 try: # must be (even) width and (odd) height 

1509 nlon, nlat = map(int, t.split()) 

1510 if nlon < 2 or nlon > (360 * 60) or isodd(nlon) or \ 

1511 nlat < 2 or nlat > (181 * 60) or not isodd(nlat): 

1512 raise ValueError 

1513 except (TypeError, ValueError): 

1514 raise self._Errorf(_format_, _SPACE_(_width_, _height_), t) 

1515 

1516 try: # must be 16 bit pixel height 

1517 t = g.readline().strip() 

1518 self.Pixel = int(t) 

1519 if not 255 < self.Pixel < 65536: # >u2 or >H only 

1520 raise ValueError 

1521 except (TypeError, ValueError): 

1522 raise self._Errorf(_format_, 'pixel', t) 

1523 

1524 for a in dir(_PGM): # set undefined # Attr ... to None 

1525 if a[:1].isupper() and callable(getattr(self, a)): 

1526 setattr(self, a, None) 

1527 

1528 if self.Origin is None: 

1529 raise self._Errorf(_format_, 'Origin', self.Origin) 

1530 if self.Offset is None or self.Offset > 0: 

1531 raise self._Errorf(_format_, 'Offset', self.Offset) 

1532 if self.Scale is None or self.Scale < EPS: 

1533 raise self._Errorf(_format_, 'Scale', self.Scale) 

1534 

1535 self.skip = g.tell() 

1536 self.knots = nlat * nlon 

1537 

1538 self.nlat, self.nlon = nlat, nlon 

1539 self.slat, self.wlon = self.Origin 

1540 # note, negative .dlat and .rlat since rows 

1541 # are from .slat 90N down in decreasing lat 

1542 self.dlat, self.dlon = _180_0 / (1 - nlat), _360_0 / nlon 

1543 self.rlat, self.rlon = (1 - nlat) / _180_0, nlon / _360_0 

1544 

1545 # grid corners in earth (lat, lon), .slat = 90, .dlat < 0 

1546 n = float(self.slat) 

1547 s = n + self.dlat * (nlat - 1) 

1548 w = self.wlon - self.glon 

1549 e = w + self.dlon * nlon 

1550 self.crop4 = s, w, n, e 

1551 

1552 n = self.sizeB - self.skip 

1553 if n > 0 and n != (self.knots * self.u2B): 

1554 raise self._Errorf('%s(%s x %s != %s)', _assert_, nlat, nlon, n) 

1555 

1556 def _cropped(self, g, k1, south, west, north, east): # MCCABE 15 

1557 '''Crop the geoid to (south, west, north, east) box. 

1558 ''' 

1559 # flon offset for both west and east 

1560 f = 360 if west < 0 else 0 

1561 # earth (lat, lon) to grid indices (y, x), 

1562 # note y is decreasing, i.e. n < s 

1563 s, w = self._lle2yx2(south, west, f) 

1564 n, e = self._lle2yx2(north, east, f) 

1565 s += 1 # s > n 

1566 e += 1 # e > w 

1567 

1568 hi, wi = self.nlat, self.nlon 

1569 # handle special cases 

1570 if (s - n) > hi: 

1571 n, s = 0, hi # entire lat range 

1572 if (e - w) > wi: 

1573 w, e, f = 0, wi, 180 # entire lon range 

1574 if s == hi and w == n == 0 and e == wi: 

1575 return g # use entire geoid as-is 

1576 

1577 if (e - w) < k1 or (s - n) < (k1 + 1): 

1578 raise self._Errorf(_format_, 'swne', (north - south, east - west)) 

1579 

1580 if e > wi > w: # wrap around 

1581 # read w..wi and 0..e 

1582 r, p = (wi - w), (e - wi) 

1583 elif e > w: 

1584 r, p = (e - w), 0 

1585 else: 

1586 raise self._Errorf('%s(%s < %s)', _assert_, w, e) 

1587 

1588 # convert to bytes 

1589 r *= self.u2B 

1590 p *= self.u2B 

1591 q = wi * self.u2B # stride 

1592 # number of rows and cols to skip from 

1593 # the original (.slat, .wlon) origin 

1594 z = self.skip + (n * wi + w) * self.u2B 

1595 # sanity check 

1596 if r < 2 or p < 0 or q < 2 or z < self.skip \ 

1597 or z > self.sizeB: 

1598 raise self._Errorf(_format_, _assert_, (r, p, q, z)) 

1599 

1600 # can't use _BytesIO since numpy 

1601 # needs .fileno attr in .fromfile 

1602 t, c = 0, self._tmpfile() 

1603 # reading (s - n) rows, forward 

1604 for y in range(n, s): # PYCHOK y unused 

1605 g.seek(z, _SEEK_SET) 

1606 # Python 2 tmpfile.write returns None 

1607 t += c.write(g.read(r)) or r 

1608 if p: # wrap around to start of row 

1609 g.seek(-q, _SEEK_CUR) 

1610 # assert(g.tell() == (z - w * self.u2B)) 

1611 # Python 2 tmpfile.write returns None 

1612 t += c.write(g.read(p)) or p 

1613 z += q 

1614 c.flush() 

1615 g.close() 

1616 

1617 s -= n # nlat 

1618 e -= w # nlon 

1619 k = s * e # knots 

1620 z = k * self.u2B 

1621 if t != z: 

1622 raise self._Errorf('%s(%s != %s) %s', _assert_, t, z, self) 

1623 

1624 # update the _Gpars accordingly, note attributes 

1625 # .dlat, .dlon, .rlat and .rlon remain unchanged 

1626 self.slat += n * self.dlat 

1627 self.wlon += w * self.dlon 

1628 self.nlat = s 

1629 self.nlon = e 

1630 self.flon = self.glon = f 

1631 

1632 self.crop4 = south, west, north, east 

1633 self.knots = k 

1634 self.skip = 0 # no header lines in c 

1635 

1636 c.seek(0, _SEEK_SET) 

1637 # c = open(c.name, _rb_) # reopen for numpy 1.8.0- 

1638 return c 

1639 

1640 def _Errorf(self, fmt, *args): # PYCHOK no cover 

1641 t = fmt % args 

1642 e = self.pgm or NN 

1643 if e: 

1644 t = _SPACE_(t, _in_, repr(e)) 

1645 return PGMError(t) 

1646 

1647 def _lle2yx2(self, lat, lon, flon): 

1648 # earth (lat, lon) to grid indices (y, x) 

1649 # with .dlat decreasing from 90N .slat 

1650 lat -= self.slat 

1651 lon += flon - self.wlon 

1652 return (min(self.nlat - 1, max(0, int(lat * self.rlat))), 

1653 max(0, int(lon * self.rlon))) 

1654 

1655 def _tmpfile(self): 

1656 # create a tmpfile to hold the cropped geoid grid 

1657 try: 

1658 from tempfile import NamedTemporaryFile as tmpfile 

1659 except ImportError: # Python 2.7.16- 

1660 from os import tmpfile 

1661 t = _os_path.splitext(_os_path.basename(self.pgm))[0] 

1662 f = tmpfile(mode='w+b', prefix=t or 'egm') 

1663 f.seek(0, _SEEK_SET) # force overwrite 

1664 return f 

1665 

1666 @Property_RO 

1667 def pgm(self): 

1668 '''Get the geoid file name (C{str}). 

1669 ''' 

1670 return self.name 

1671 

1672 

1673class PGMError(GeoidError): 

1674 '''Issue parsing or cropping an C{egm*.pgm} geoid dataset. 

1675 ''' 

1676 pass 

1677 

1678 

1679def egmGeoidHeights(GeoidHeights_dat): 

1680 '''Generate geoid U{egm*.pgm<https://GeographicLib.SourceForge.io/ 

1681 C++/doc/geoid.html#geoidinst>} height tests from U{GeoidHeights.dat 

1682 <https://SourceForge.net/projects/geographiclib/files/testdata/>} 

1683 U{Test data for Geoids<https://GeographicLib.SourceForge.io/C++/doc/ 

1684 geoid.html#testgeoid>}. 

1685 

1686 @arg GeoidHeights_dat: The un-gz-ed C{GeoidHeights.dat} file 

1687 (C{str} or C{file} handle). 

1688 

1689 @return: For each test, yield a L{GeoidHeight5Tuple}C{(lat, lon, 

1690 egm84, egm96, egm2008)}. 

1691 

1692 @raise GeoidError: Invalid B{C{GeoidHeights_dat}}. 

1693 

1694 @note: Function L{egmGeoidHeights} is used to test the geoids 

1695 L{GeoidKarney} and L{GeoidPGM}, see PyGeodesy module 

1696 C{test/testGeoids.py}. 

1697 ''' 

1698 dat = GeoidHeights_dat 

1699 if isinstance(dat, bytes): 

1700 dat = _BytesIO(dat) 

1701 

1702 try: 

1703 dat.seek(0, _SEEK_SET) # reset 

1704 except AttributeError as x: 

1705 raise GeoidError(GeoidHeights_dat=type(dat), cause=x) 

1706 

1707 for t in dat.readlines(): 

1708 t = t.strip() 

1709 if t and not t.startswith(_bHASH_): 

1710 lat, lon, egm84, egm96, egm2008 = map(float, t.split()) 

1711 while lon > _180_0: # EasternLon to earth lon 

1712 lon -= _360_0 

1713 yield GeoidHeight5Tuple(lat, lon, egm84, egm96, egm2008) 

1714 

1715 

1716__all__ += _ALL_DOCS(_GeoidBase) 

1717 

1718if __name__ == '__main__': 

1719 

1720 from pygeodesy.internals import printf, _sys 

1721 

1722 _crop = () 

1723 _GeoidEGM = GeoidKarney 

1724 _kind = 3 

1725 

1726 geoids = _sys.argv[1:] 

1727 while geoids: 

1728 geoid = geoids.pop(0) 

1729 

1730 if '-crop'.startswith(geoid.lower()): 

1731 _crop = 20, -125, 50, -65 # CONUS 

1732 

1733 elif '-karney'.startswith(geoid.lower()): 

1734 _GeoidEGM = GeoidKarney 

1735 

1736 elif '-kind'.startswith(geoid.lower()): 

1737 _kind = int(geoids.pop(0)) 

1738 

1739 elif '-pgm'.startswith(geoid.lower()): 

1740 _GeoidEGM = GeoidPGM 

1741 

1742 elif geoid[-4:].lower() in ('.pgm',): 

1743 g = _GeoidEGM(geoid, crop=_crop, kind=_kind) 

1744 printf(g.toStr(), nt=1, nl=1) 

1745 printf(repr(g.pgm), nt=1) 

1746 # <https://GeographicLib.SourceForge.io/cgi-bin/GeoidEval>: 

1747 # The height of the EGM96 geoid at Timbuktu 

1748 # echo 16:46:33N 3:00:34W | GeoidEval 

1749 # => 28.7068 -0.02e-6 -1.73e-6 

1750 # The 1st number is the height of the geoid, the 2nd and 

1751 # 3rd are its slopes in northerly and easterly direction 

1752 t = 'Timbuktu %s' % (g,) 

1753 k = {'egm84-15.pgm': '31.2979', 

1754 'egm96-5.pgm': '28.7067', 

1755 'egm2008-1.pgm': '28.7880'}.get(g.name.lower(), '28.7880') 

1756 ll = _MODS.dms.parseDMS2('16:46:33N', '3:00:34W', sep=':') 

1757 for ll in (ll, (16.776, -3.009),): 

1758 try: 

1759 h, ll = g.height(*ll), fstr(ll, prec=6) 

1760 printf('%s.height(%s): %.4F vs %s', t, ll, h, k) 

1761 except (GeoidError, RangeError) as x: 

1762 printf(_COLONSPACE_(t, str(x))) 

1763 

1764 elif geoid[-4:].lower() in ('.bin',): 

1765 g = GeoidG2012B(geoid, kind=_kind) 

1766 printf(g.toStr()) 

1767 

1768 else: 

1769 raise GeoidError(grid=repr(geoid)) 

1770 

1771_I = int # PYCHOK unused _I 

1772del _intCs # trash ints cache 

1773 

1774# **) MIT License 

1775# 

1776# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved. 

1777# 

1778# Permission is hereby granted, free of charge, to any person obtaining a 

1779# copy of this software and associated documentation files (the "Software"), 

1780# to deal in the Software without restriction, including without limitation 

1781# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

1782# and/or sell copies of the Software, and to permit persons to whom the 

1783# Software is furnished to do so, subject to the following conditions: 

1784# 

1785# The above copyright notice and this permission notice shall be included 

1786# in all copies or substantial portions of the Software. 

1787# 

1788# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

1789# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

1790# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

1791# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

1792# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

1793# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

1794# OTHER DEALINGS IN THE SOFTWARE. 

1795 

1796# <https://GeographicLib.SourceForge.io/cgi-bin/GeoidEval> 

1797# _lowerleft = -90, -179, -30.1500 # egm2008-1.pgm 

1798# _lowerleft = -90, -179, -29.5350 # egm96-5.pgm 

1799# _lowerleft = -90, -179, -29.7120 # egm84-15.pgm 

1800 

1801# _center = 0, 0, 17.2260 # egm2008-1.pgm 

1802# _center = 0, 0, 17.1630 # egm96-5.pgm 

1803# _center = 0, 0, 18.3296 # egm84-15.pgm 

1804 

1805# _upperright = 90, 180, 14.8980 # egm2008-1.pgm 

1806# _upperright = 90, 180, 13.6050 # egm96-5.pgm 

1807# _upperright = 90, 180, 13.0980 # egm84-15.pgm 

1808 

1809 

1810# % python3 -m pygeodesy.geoids [-Karney] ../testGeoids/egm*.pgm 

1811# 

1812# GeoidKarney('egm2008-1.pgm'): lowerleft(-90.0, -180.0, -30.15), upperright(90.0, 180.0, 14.898), center(0.0, 0.0, 17.226), highest(-8.4, 147.367, 85.839), lowest(4.7, 78.767, -106.911) 

1813# 

1814# _PGM('../testGeoids/egm2008-1.pgm'): AREA_OR_POINT='Point', DateTime='2009-08-31 06:54:00', Description='WGS84 EGM2008, 1-minute grid', Geoid='file in PGM format for the GeographicLib::Geoid class', MaxBilinearError=0.025, MaxCubicError=0.003, Offset=-108.0, Origin=LatLon2Tuple(lat=90.0, lon=0.0), Pixel=65535, RMSBilinearError=0.001, RMSCubicError=0.001, Scale=0.003, URL='http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm2008', Vertical_Datum='WGS84' 

1815# 

1816# Timbuktu GeoidKarney('egm2008-1.pgm').height(16.775833, -3.009444): 28.7881 vs 28.7880 

1817# Timbuktu GeoidKarney('egm2008-1.pgm').height(16.776, -3.009): 28.7880 vs 28.7880 

1818# 

1819# GeoidKarney('egm84-15.pgm'): lowerleft(-90.0, -180.0, -29.712), upperright(90.0, 180.0, 13.098), center(0.0, 0.0, 18.33), highest(-4.5, 148.75, 81.33), lowest(4.75, 79.25, -107.34) 

1820# 

1821# _PGM('../testGeoids/egm84-15.pgm'): AREA_OR_POINT='Point', DateTime='2009-08-29 18:45:02', Description='WGS84 EGM84, 15-minute grid', Geoid='file in PGM format for the GeographicLib::Geoid class', MaxBilinearError=0.413, MaxCubicError=0.02, Offset=-108.0, Origin=LatLon2Tuple(lat=90.0, lon=0.0), Pixel=65535, RMSBilinearError=0.018, RMSCubicError=0.001, Scale=0.003, URL='http://earth-info.nga.mil/GandG/wgs84/gravitymod/wgs84_180/wgs84_180.html', Vertical_Datum='WGS84' 

1822# 

1823# Timbuktu GeoidKarney('egm84-15.pgm').height(16.775833, -3.009444): 31.2983 vs 31.2979 

1824# Timbuktu GeoidKarney('egm84-15.pgm').height(16.776, -3.009): 31.2979 vs 31.2979 

1825# 

1826# GeoidKarney('egm96-5.pgm'): lowerleft(-90.0, -180.0, -29.535), upperright(90.0, 180.0, 13.605), center(0.0, 0.0, 17.163), highest(-8.167, 147.25, 85.422), lowest(4.667, 78.833, -107.043) 

1827# 

1828# _PGM('../testGeoids/egm96-5.pgm'): AREA_OR_POINT='Point', DateTime='2009-08-29 18:45:03', Description='WGS84 EGM96, 5-minute grid', Geoid='file in PGM format for the GeographicLib::Geoid class', MaxBilinearError=0.14, MaxCubicError=0.003, Offset=-108.0, Origin=LatLon2Tuple(lat=90.0, lon=0.0), Pixel=65535, RMSBilinearError=0.005, RMSCubicError=0.001, Scale=0.003, URL='http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm96/egm96.html', Vertical_Datum='WGS84' 

1829# 

1830# Timbuktu GeoidKarney('egm96-5.pgm').height(16.775833, -3.009444): 28.7068 vs 28.7067 

1831# Timbuktu GeoidKarney('egm96-5.pgm').height(16.776, -3.009): 28.7067 vs 28.7067 

1832 

1833 

1834# % python3 -m pygeodesy.geoids -Karney ../testGeoids/egm*.pgm 

1835# 

1836# GeoidKarney('egm2008-1.pgm'): lowerleft(-90.0, -180.0, -30.15), upperright(90.0, 180.0, 14.898), center(0.0, 0.0, 17.226), highest(-8.4, 147.367, 85.839), lowest(4.7, 78.767, -106.911) 

1837# 

1838# _PGM('../testGeoids/egm2008-1.pgm'): AREA_OR_POINT='Point', DateTime='2009-08-31 06:54:00', Description='WGS84 EGM2008, 1-minute grid', Geoid='file in PGM format for the GeographicLib::Geoid class', MaxBilinearError=0.025, MaxCubicError=0.003, Offset=-108.0, Origin=LatLon2Tuple(lat=90.0, lon=0.0), Pixel=65535, RMSBilinearError=0.001, RMSCubicError=0.001, Scale=0.003, URL='http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm2008', Vertical_Datum='WGS84' 

1839# 

1840# Timbuktu GeoidKarney('egm2008-1.pgm').height(16.775833, -3.009444): 28.7881 vs 28.7880 

1841# Timbuktu GeoidKarney('egm2008-1.pgm').height(16.776, -3.009): 28.7880 vs 28.7880 

1842# 

1843# GeoidKarney('egm84-15.pgm'): lowerleft(-90.0, -180.0, -29.712), upperright(90.0, 180.0, 13.098), center(0.0, 0.0, 18.33), highest(-4.5, 148.75, 81.33), lowest(4.75, 79.25, -107.34) 

1844# 

1845# _PGM('../testGeoids/egm84-15.pgm'): AREA_OR_POINT='Point', DateTime='2009-08-29 18:45:02', Description='WGS84 EGM84, 15-minute grid', Geoid='file in PGM format for the GeographicLib::Geoid class', MaxBilinearError=0.413, MaxCubicError=0.02, Offset=-108.0, Origin=LatLon2Tuple(lat=90.0, lon=0.0), Pixel=65535, RMSBilinearError=0.018, RMSCubicError=0.001, Scale=0.003, URL='http://earth-info.nga.mil/GandG/wgs84/gravitymod/wgs84_180/wgs84_180.html', Vertical_Datum='WGS84' 

1846# 

1847# Timbuktu GeoidKarney('egm84-15.pgm').height(16.775833, -3.009444): 31.2983 vs 31.2979 

1848# Timbuktu GeoidKarney('egm84-15.pgm').height(16.776, -3.009): 31.2979 vs 31.2979 

1849# 

1850# GeoidKarney('egm96-5.pgm'): lowerleft(-90.0, -180.0, -29.535), upperright(90.0, 180.0, 13.605), center(0.0, 0.0, 17.163), highest(-8.167, 147.25, 85.422), lowest(4.667, 78.833, -107.043) 

1851# 

1852# _PGM('../testGeoids/egm96-5.pgm'): AREA_OR_POINT='Point', DateTime='2009-08-29 18:45:03', Description='WGS84 EGM96, 5-minute grid', Geoid='file in PGM format for the GeographicLib::Geoid class', MaxBilinearError=0.14, MaxCubicError=0.003, Offset=-108.0, Origin=LatLon2Tuple(lat=90.0, lon=0.0), Pixel=65535, RMSBilinearError=0.005, RMSCubicError=0.001, Scale=0.003, URL='http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm96/egm96.html', Vertical_Datum='WGS84' 

1853# 

1854# Timbuktu GeoidKarney('egm96-5.pgm').height(16.775833, -3.009444): 28.7068 vs 28.7067 

1855# Timbuktu GeoidKarney('egm96-5.pgm').height(16.776, -3.009): 28.7067 vs 28.7067 

1856 

1857 

1858# % python2 -m pygeodesy.geoids -PGM ../testGeoids/egm*.pgm 

1859# 

1860# GeoidPGM('egm2008-1.pgm'): lowerleft(-90.0, -180.0, -30.15), upperright(90.0, 180.0, 14.898), center(0.0, 0.0, 17.226), highest(-8.4, -32.633, 85.839), lowest(4.683, -101.25, -106.911) 

1861# 

1862# _PGM('../testGeoids/egm2008-1.pgm'): AREA_OR_POINT='Point', DateTime='2009-08-31 06:54:00', Description='WGS84 EGM2008, 1-minute grid', Geoid='file in PGM format for the GeographicLib::Geoid class', MaxBilinearError=0.025, MaxCubicError=0.003, Offset=-108.0, Origin=LatLon2Tuple(lat=90.0, lon=0.0), Pixel=65535, RMSBilinearError=0.001, RMSCubicError=0.001, Scale=0.003, URL='http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm2008', Vertical_Datum='WGS84' 

1863# 

1864# Timbuktu GeoidPGM('egm2008-1.pgm').height(16.775833, -3.009444): 28.7881 vs 28.7880 

1865# Timbuktu GeoidPGM('egm2008-1.pgm').height(16.776, -3.009): 28.7880 vs 28.7880 

1866# 

1867# GeoidPGM('egm84-15.pgm'): lowerleft(-90.0, -180.0, -29.712), upperright(90.0, 180.0, 13.098), center(0.0, 0.0, 18.33), highest(-4.5, -31.25, 81.33), lowest(4.75, -100.75, -107.34) 

1868# 

1869# _PGM('../testGeoids/egm84-15.pgm'): AREA_OR_POINT='Point', DateTime='2009-08-29 18:45:02', Description='WGS84 EGM84, 15-minute grid', Geoid='file in PGM format for the GeographicLib::Geoid class', MaxBilinearError=0.413, MaxCubicError=0.02, Offset=-108.0, Origin=LatLon2Tuple(lat=90.0, lon=0.0), Pixel=65535, RMSBilinearError=0.018, RMSCubicError=0.001, Scale=0.003, URL='http://earth-info.nga.mil/GandG/wgs84/gravitymod/wgs84_180/wgs84_180.html', Vertical_Datum='WGS84' 

1870# 

1871# Timbuktu GeoidPGM('egm84-15.pgm').height(16.775833, -3.009444): 31.2979 vs 31.2979 

1872# Timbuktu GeoidPGM('egm84-15.pgm').height(16.776, -3.009): 31.2975 vs 31.2979 

1873# 

1874# GeoidPGM('egm96-5.pgm'): lowerleft(-90.0, -180.0, -29.535), upperright(90.0, 180.0, 13.605), center(0.0, -0.0, 17.179), highest(-8.167, -32.75, 85.422), lowest(4.667, -101.167, -107.043) 

1875# 

1876# _PGM('../testGeoids/egm96-5.pgm'): AREA_OR_POINT='Point', DateTime='2009-08-29 18:45:03', Description='WGS84 EGM96, 5-minute grid', Geoid='file in PGM format for the GeographicLib::Geoid class', MaxBilinearError=0.14, MaxCubicError=0.003, Offset=-108.0, Origin=LatLon2Tuple(lat=90.0, lon=0.0), Pixel=65535, RMSBilinearError=0.005, RMSCubicError=0.001, Scale=0.003, URL='http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm96/egm96.html', Vertical_Datum='WGS84' 

1877# 

1878# Timbuktu GeoidPGM('egm96-5.pgm').height(16.775833, -3.009444): 28.7065 vs 28.7067 

1879# Timbuktu GeoidPGM('egm96-5.pgm').height(16.776, -3.009): 28.7064 vs 28.7067