1

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

3

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

5

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

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

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

9 and C{geoid} model files.

10

11 L{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.

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

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

15 require those packages to be installed.

16

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

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

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

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

21

22 Typical usage

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

24

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

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

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

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

29

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

31

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

33 arguments to select different interpolation options

34

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

36

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

38

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

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

41

42 or

43

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

45

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

47

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

49

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

51

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

53

54 or as 2 lists, 2 tuples, etc.

55

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

57

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

59 courtesy of SBFRF.

60

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

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

63 to be installed.

64

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

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

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

68

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

70 U{Geoid height<https://GeographicLib.SourceForge.io/html/geoid.html>} and U{Installing

71 the Geoid datasets<https://GeographicLib.SourceForge.io/html/geoid.html#geoidinst>},

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

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

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

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

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

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

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

79 Avoiding_Pitfalls_Related_to_Ellipsoid_Height_and_Height_Above_Mean_Sea_Level>}.

80'''

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

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

83

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

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

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

87# from pygeodesy.dms import parseDMS2 # _MODS

88 from pygeodesy.errors import _incompatible, LenError, RangeError, _SciPyIssue

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

90# from pygoedesy.formy import heightOrthometric # _MODS

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

92 _HeightsBase, _ellipsoidal_datum, _Wrap

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

94 _DOT_, _E_, _height_, _in_, _kind_, _knots_, \

95 _lat_, _linear_, _lon_, _mean_, _N_, _n_a_, _not_, \

96 _numpy_, _on_, _outside_, _S_, _s_, _scipy_, \

97 _SPACE_, _stdev_, _supported_, _tbd_, _W_, _width_

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

99 from pygeodesy.named import _Named, _NamedTuple, notOverloaded

100# from pygeodesy.namedTuples import LatLon3Tuple # _MODS

101 from pygeodesy.props import Property_RO, property_RO

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

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

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

105

106 from math import floor

107 import os.path as _os_path

108 from os import SEEK_CUR as _SEEK_CUR, SEEK_SET as _SEEK_SET

109 from struct import calcsize as _calcsize, unpack as _unpack

110

111 try:

112 from StringIO import StringIO as _BytesIO # reads bytes

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

114

115 except ImportError: # Python 3+

116 from io import BytesIO as _BytesIO # PYCHOK expected

117

118__all__ = _ALL_LAZY.geoids

119__version__ = '23.08.15'

120

121_assert_ = 'assert'

122_bHASH_ = b'#'

123_endian_ = 'endian'

124_format_ = '%s %r'

125_header_ = 'header'

126# temporarily hold a single instance for each int value

127_intCs = {}

128_interp2d_ks = {-2: _linear_,

129 -3: _cubic_,

130 -5: 'quintic'}

131_lli_ = 'lli'

132_non_increasing_ = 'non-increasing'

133_rb_ = 'rb'

134

135

136 class _GeoidBase(_HeightsBase):

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

138 '''

139 _cropped = None

140# _datum = _WGS84 # from _HeightsBase

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

142 _endian = _tbd_

143 _geoid = _n_a_

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

145 _interp2d = None # interp2d interpolation

146 _kind = 3 # order for interp2d, RectBivariateSpline

147# _kmin = 2 # min number of knots

148 _knots = 0 # nlat * nlon

149 _mean = None # fixed in GeoidKarney

150# _name = NN # _Named

151 _nBytes = 0 # numpy size in bytes, float64

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

153 _sizeB = 0 # geoid file size in bytes

154 _smooth = 0 # used only for RectBivariateSpline

155 _stdev = None # fixed in GeoidKarney

156 _u2B = 0 # np.itemsize or undefined

157

158 _lat_d = _0_0 # increment, +tive

159 _lat_lo = _0_0 # lower lat, south

160 _lat_hi = _0_0 # upper lat, noth

161 _lon_d = _0_0 # increment, +tive

162 _lon_lo = _0_0 # left lon, west

163 _lon_hi = _0_0 # right lon, east

164 _lon_of = _0_0 # forward lon offset

165 _lon_og = _0_0 # reverse lon offset

166

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

168 _yx_hits = None # cache hits, ala Karney

169

170 def __init__(self, hs, p):

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

172 and several internal geoid attributes.

173

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

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

176 other geoid parameters (C{INTERNAL}).

177

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

179 invalid B{C{kind}}.

180

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

182

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

184 C{-.RectBivariateSpline} issue.

185

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

187 C{-.RectBivariateSpline} warning as

188 exception.

189 '''

190 spi = self.scipy_interpolate

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

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

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

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

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

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

197

198 # both axes and bounding box

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

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

201

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

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

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

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

206 k = self.kind

207 if k in _interp2d_ks:

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

209 elif 1 <= k <= 5:

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

211 s=self._smooth).ev

212 else:

213 raise GeoidError(kind=k)

214

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

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

217 self._knots = p.knots # grid knots

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

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

220 # shrink the box by 1 unit on every side

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

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

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

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

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

226

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

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

229

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

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

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

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

234 return the I{orthometric} height instead of the

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

236

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

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

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

240

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

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

243 geoid file is closed.

244

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

246 or longitude range.

247

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

249 C{-.RectBivariateSpline} issue.

250

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

252 C{-.RectBivariateSpline} warning as

253 exception.

254

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

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

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

258

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

260 '''

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

262

263 def __enter__(self):

264 '''Open context.

265 '''

266 return self

267

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

269 '''Close context.

270 '''

271 self.close()

272 # return None # XXX False

273

274 def __repr__(self):

275 return self.toStr()

276

277 def __str__(self):

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

279

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

281 # handle __call__

282 _H = _MODS.formy.heightOrthometric if H else None

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

284 try:

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

286 for i, lli in enumerate(llis):

287 N = self._hGeoid(*_w(lli.lat, lli.lon))

288 if _H: # convert to orthometric

289 N = _H(lli, N)

290 hs.append(N)

291 return _as(hs)

292

293 except (GeoidError, RangeError) as x:

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

295 t = _lli_ if _as is _ascalar else Fmt.SQUARE(llis=i)

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

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

298 except Exception as x:

299 if scipy and self.scipy:

300 raise _SciPyIssue(x)

301 else:

302 raise

303

304 @Property_RO

305 def _center(self):

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

307 '''

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

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

310

311 def center(self, LatLon=None):

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

313

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

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

316

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

318 lon, height)} otherwise a B{C{LatLon}} instance

319 with the lat-, longitude and geoid height of the

320 center grid location.

321 '''

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

323

324 def close(self):

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

326 '''

327 if not self.closed:

328 self._egm.close()

329 self._egm = None

330

331 @property_RO

332 def closed(self):

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

334 '''

335 return self._egm is None

336

337 @Property_RO

338 def cropped(self):

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

340 '''

341 return self._cropped

342

343 @Property_RO

344 def dtype(self):

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

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

347 '''

348 return self._hs_y_x.dtype

349

350 @Property_RO

351 def endian(self):

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

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

354 '''

355 return self._endian

356

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

358 # only used for .interpolate.interp2d, but

359 # overwritten for .RectBivariateSpline,

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

361 return self._interp2d(x, y)

362

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

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

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

366 if m != n:

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

368 if d < 0:

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

370 for i in range(1, m):

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

372 if e < EPS: # non-increasing axis

373 i = Fmt.SQUARE(name, i)

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

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

376

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

378 notOverloaded(self, lat, lon)

379

380 def _gyx2g2(self, y, x):

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

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

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

384

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

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

387

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

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

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

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

392

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

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

395

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

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

398

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

400 geoid's lat- or longitude range.

401

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

403 C{-.RectBivariateSpline} issue.

404

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

406 C{-.RectBivariateSpline} warning as

407 exception.

408 '''

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

410

411 def _hGeoid(self, lat, lon):

412 out = self.outside(lat, lon)

413 if out:

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

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

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

417

418 @Property_RO

419 def _highest(self):

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

421 '''

422 return self._llh3minmax(True)

423

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

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

426

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

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

429

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

431 lon, height)} otherwise a B{C{LatLon}} instance

432 with the lat-, longitude and geoid height of the

433 highest grid location.

434 '''

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

436

437 @Property_RO

438 def hits(self):

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

440 '''

441 return self._yx_hits

442

443 @Property_RO

444 def kind(self):

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

446 '''

447 return self._kind

448

449 @Property_RO

450 def knots(self):

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

452 '''

453 return self._knots

454

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

456 notOverloaded(self, lat, lon)

457

458 @property_RO

459 def _LL3T(self):

460 '''(INTERNAL) Get L{LatLon3Tuple} once.

461 '''

462 T = _MODS.namedTuples.LatLon3Tuple

463 _GeoidBase._LL3T = T # overwrite poperty_RO

464 return T

465

466 def _llh3(self, lat, lon):

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

468

469 def _llh3LL(self, llh, LatLon):

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

471

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

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

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

475 # numpy.argmin.html#numpy.argmin>

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

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

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

479

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

481 # numpy.fromfile, like .frombuffer

482 g.seek(offset, _SEEK_SET)

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

484

485 @Property_RO

486 def _lowerleft(self):

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

488 '''

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

490

491 def lowerleft(self, LatLon=None):

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

493

494 @kwarg LatLon: Optional class to return the location

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

496

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

498 lon, height)} otherwise a B{C{LatLon}} instance

499 with the lat-, longitude and geoid height of the

500 lower-left, SW grid corner.

501 '''

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

503

504 @Property_RO

505 def _loweright(self):

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

507 '''

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

509

510 def loweright(self, LatLon=None):

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

512

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

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

515

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

517 lon, height)} otherwise a B{C{LatLon}} instance

518 with the lat-, longitude and geoid height of the

519 lower-right, SE grid corner.

520 '''

521

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

523

524 lowerright = loweright # synonymous

525

526 @Property_RO

527 def _lowest(self):

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

529 '''

530 return self._llh3minmax(False)

531

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

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

534

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

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

537

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

539 lon, height)} otherwise a B{C{LatLon}} instance

540 with the lat-, longitude and geoid height of the

541 lowest grid location.

542 '''

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

544

545 @Property_RO

546 def mean(self):

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

548 '''

549 if self._mean is None: # see GeoidKarney

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

551 return self._mean

552

553 @property_RO

554 def name(self):

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

556 '''

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

558

559 @Property_RO

560 def nBytes(self):

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

562 '''

563 return self._nBytes

564

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

566 # open the geoid file

567 try:

568 self._geoid = _os_path.basename(geoid)

569 self._sizeB = _os_path.getsize(geoid)

570 g = open(geoid, _rb_)

571 except (IOError, OSError) as x:

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

573

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

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

576 self._kind = int(kind)

577 if name:

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

579 if smooth:

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

581

582 return g

583

584 def outside(self, lat, lon):

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

586 lat-/longitude or crop range.

587

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

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

590

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

592 empty C{str} if inside.

593 '''

594 return (_S_ if lat < self._lat_lo else

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

596 (_W_ if lon < self._lon_lo else

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

598

599 @Property_RO

600 def pgm(self):

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

602 '''

603 return self._pgm

604

605 @Property_RO

606 def sizeB(self):

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

608 '''

609 return self._sizeB

610

611 @Property_RO

612 def smooth(self):

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

614 '''

615 return self._smooth

616

617 @Property_RO

618 def stdev(self):

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

620 '''

621 if self._stdev is None: # see GeoidKarney

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

623 return self._stdev

624

625 def _swne(self, crop):

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

627 try:

628 if len(crop) == 2:

629 try: # sw, ne LatLons

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

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

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

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

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

635 swne = crop

636 if len(swne) == 4:

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

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

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

640 return s, w, n, e

641 except (IndexError, TypeError, ValueError):

642 pass

643 raise GeoidError(crop=crop)

644

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

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

647

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

649 default). Trailing zero decimals are stripped

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

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

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

653

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

655 '''

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

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

658 (self.lowerleft, self.upperright,

659 self.center,

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

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

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

663 attrs( 'cropped', 'dtype', _endian_, 'hits', _knots_, 'nBytes',

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

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

666

667 @Property_RO

668 def u2B(self):

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

670 '''

671 return self._u2B

672

673 @Property_RO

674 def _upperleft(self):

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

676 '''

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

678

679 def upperleft(self, LatLon=None):

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

681

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

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

684

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

686 lon, height)} otherwise a B{C{LatLon}} instance

687 with the lat-, longitude and geoid height of the

688 upper-left, NW grid corner.

689 '''

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

691

692 @Property_RO

693 def _upperright(self):

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

695 '''

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

697

698 def upperright(self, LatLon=None):

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

700

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

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

703

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

705 lon, height)} otherwise a B{C{LatLon}} instance

706 with the lat-, longitude and geoid height of the

707 upper-right, NE grid corner.

708 '''

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

710

711

712 class GeoidError(HeightError):

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

714 '''

715 pass

716

717

718 class GeoidG2012B(_GeoidBase):

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

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

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

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

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

724 U{Guam and Northern Mariana Islands

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

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

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

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

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

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

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

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

733

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

735 C{g2012b*.bin} grid files.

736 '''

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

738 kind=3, name=NN, smooth=0):

739 '''New L{GeoidG2012B} interpolator.

740

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

742 @kwarg crop: Optional crop box, not supported (C{None}).

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

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

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

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

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

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

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

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

751 @kwarg name: Optional geoid name (C{str}).

752 @kwarg smooth: Smoothing factor for U{RectBivariateSpline

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

754 scipy.interpolate.RectBivariateSpline.html>}

755 only (C{int}).

756

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

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

759

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

761 not installed.

762

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

764

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

766

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

768 warning as exception.

769

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

771 '''

772 if crop is not None:

773 raise GeoidError(crop=crop, txt=_not_(_supported_))

774

775 g = self._open(g2012b_bin, datum, kind, name, smooth)

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

777

778 try:

779 p = _Gpars()

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

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

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

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

784 # skip 4xf8, get 3xi4

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

786 if ien == 1: # correct endian

787 p.knots = p.nlat * p.nlon

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

789 and 1 < p.nlon < n:

790 self._endian = en_+'f4'

791 break

792 else: # couldn't validate endian

793 raise GeoidError(_endian_)

794

795 # get the first 4xf8

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

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

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

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

800 _GeoidBase.__init__(self, hs, p)

801

802 except Exception as x:

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

804 finally:

805 g.close()

806

807 def _g2ll2(self, lat, lon):

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

809 return lat, lon

810

811 def _ll2g2(self, lat, lon):

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

813 return lat, lon

814

815 if _FOR_DOCS:

816 __call__ = _GeoidBase.__call__

817 height = _GeoidBase.height

818

819

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

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

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

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

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

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

826 '''

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

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

829

830

831 def _I(i):

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

833 '''

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

835

836

837 def _T(*cs):

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

839 '''

840 return map1(_I, *cs)

841

842

843 class GeoidKarney(_GeoidBase):

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

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

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

847 html/geoid.html#geoidinst>} datasets using bilinear or U{cubic

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

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

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

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

852

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

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

855 datasets.

856 '''

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

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

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

860 _T(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),

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

862 _T(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),

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

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

865 _T(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),

866 _T(0, 0, 0, 0, 0, 0, 93, -93, -93, 93, 0, 0),

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

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

869

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

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

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

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

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

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

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

877 _T(0, 0, -60, 60, 60, -60, 60, -60, -60, 60, 0, 0),

878 _T(-60, 60, 0, 60, -60, 0, 0, 60, -60, 0, -60, 60),

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

880

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

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

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

884 _T(0, 0, 93, -93, -93, 93, 0, 0, 0, 0, 0, 0),

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

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

887 _T(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),

888 _T(0, 0, -93, 93, 93, -93, 0, 0, 0, 0, 0, 0),

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

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

891

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

893 _T(1, 0),

894 _T(0, 1),

895 _T(1, 1))

896

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

898 _T( 1, -1),

899 _T(-1, 0),

900 _T( 0, 0),

901 _T( 1, 0),

902 _T( 2, 0),

903 _T(-1, 1),

904 _T( 0, 1),

905 _T( 1, 1),

906 _T( 2, 1),

907 _T( 0, 2),

908 _T( 1, 2))

909

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

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

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

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

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

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

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

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

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

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

920 _nBytes = None # not applicable

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

922 _smooth = None # not applicable

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

924 _u2B = _calcsize(_endian) # pixelsize_ in bytes

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

926 _Ru2B = 0 # row of pixelsize_s in bytes

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

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

929 _yx_hits = 0 # cache hits

930

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

932 kind=3, name=NN, smooth=None):

933 '''New L{GeoidKarney} interpolator.

934

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

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

937 note below.

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

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

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

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

942 C{LatLon} instances.

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

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

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

946 for C{cubic}.

947 @kwarg name: Optional geoid name (C{str}).

948 @kwarg smooth: Smoothing factor, unsupported (C{None}).

949

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

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

952

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

954

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

956

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

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

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

960 '''

961 if smooth is not None:

962 raise GeoidError(smooth=smooth, txt=_not_(_supported_))

963

964 if kind in (2,):

965 self._evH = self._ev2H

966 elif kind not in (3,):

967 raise GeoidError(kind=kind)

968

969 self._egm = g = self._open(egm_pgm, datum, kind, name, smooth)

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

971

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

973 self._Ru2B = _calcsize(self._Rendian)

974

975 self._knots = p.knots # grid knots

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

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

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

979 self._lat_lo, self._lon_lo, \

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

981 self._cropped = True if crop else False

982

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

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

985

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

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

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

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

990 return the I{orthometric} height instead of the

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

992

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

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

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

996

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

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

999 geoid file is closed.

1000

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

1002 or longitude range.

1003

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

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

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

1007

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

1009 '''

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

1011

1012 def _c0c3v(self, y, x):

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

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

1015 p = self._pgm

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

1017 # read 4x4 ushorts, drop the 4 corners

1018 g = self._egm

1019 e = self._4endian

1020 n = self._4u2B

1021 R = self._Ru2B

1022

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

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

1025 b += R

1026 g.seek(b, _SEEK_SET)

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

1028 b += R

1029 g.seek(b, _SEEK_SET)

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

1031 b += R

1032 g.seek(b, _SEEK_SET)

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

1034 j = 1

1035

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

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

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

1039

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

1041

1042 @Property_RO

1043 def dtype(self):

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

1045 '''

1046 return 'ushort'

1047

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

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

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

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

1052 fy -= y

1053 fx -= x

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

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

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

1057 return H.fsum()

1058

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

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

1061 if self._yxH == yx:

1062 t = self._yxHt

1063 self._yx_hits += 1

1064 else:

1065 y, x = self._yxH = yx

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

1067 v = _1_0, -fx, fx

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

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

1070 return H

1071

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

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

1074 if self._yxH == yx:

1075 t = self._yxHt

1076 self._yx_hits += 1

1077 else:

1078 self._yxH = yx

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

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

1081 self._yxHt = t = tuple(t)

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

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

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

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

1086 v = _1_0, fx, fy

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

1088 H *= fy

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

1090 H *= fy

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

1092 return H

1093

1094 _evH = _ev3H # overriden for kind == 2

1095

1096 def _g2ll2(self, lat, lon):

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

1098 while lon > _180_0:

1099 lon -= _360_0

1100 return lat, lon

1101

1102 def _g2yx2(self, lat, lon):

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

1104 p = self._pgm

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

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

1107

1108 def _gyx2g2(self, y, x):

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

1110 p = self._pgm

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

1112

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

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

1115

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

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

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

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

1120

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

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

1123

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

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

1126 geoid file is closed.

1127

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

1129 geoid's lat- or longitude range.

1130 '''

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

1132

1133 @Property_RO

1134 def _highest_ltd(self):

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

1136 '''

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

1138

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

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

1141

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

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

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

1145

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

1147 lon, height)} otherwise a B{C{LatLon}} instance

1148 with the lat-, longitude and geoid height at the

1149 highest grid location.

1150 '''

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

1152 return self._llh3LL(llh, LatLon)

1153

1154 def _lat2y2(self, lat2):

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

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

1157 for lat in lat2:

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

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

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

1161

1162 def _ll2g2(self, lat, lon):

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

1164 while lon < 0:

1165 lon += _360_0

1166 return lat, lon

1167

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

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

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

1171 y = x = 0

1172 h = self._raw(y, x)

1173 if highest:

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

1175 m = max(r)

1176 if m > h:

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

1178 else: # lowest

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

1180 m = min(r)

1181 if m < h:

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

1183 h *= self._pgm.Scale

1184 h += self._pgm.Offset

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

1186

1187 @Property_RO

1188 def _lowest_ltd(self):

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

1190 '''

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

1192

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

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

1195

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

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

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

1199

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

1201 lon, height)} otherwise a B{C{LatLon}} instance

1202 with the lat-, longitude and geoid height of the

1203 lowest grid location.

1204 '''

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

1206 return self._llh3LL(llh, LatLon)

1207

1208 def _raw(self, y, x):

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

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

1211 p = self._pgm

1212 if x < 0:

1213 x += p.nlon

1214 elif x >= p.nlon:

1215 x -= p.nlon

1216 h = p.nlon // 2

1217 if y < 0:

1218 y = -y

1219 elif y >= p.nlat:

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

1221 else:

1222 h = 0

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

1224 self._seek(y, x)

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

1226 return h[0]

1227

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

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

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

1231

1232 def _raw2(self, *lat2):

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

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

1235 p = self._pgm

1236 g = self._egm

1237 e = self._Rendian

1238 n = self._Ru2B

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

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

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

1242 for y in range(s, t):

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

1244

1245 def _seek(self, y, x):

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

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

1248 if g:

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

1250 g.seek(b, _SEEK_SET)

1251 return b # position

1252 raise GeoidError('closed file: %r' % (p.egm,)) # IOError

1253

1254

1255 class GeoidPGM(_GeoidBase):

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

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

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

1259 html/geoid.html#geoidinst>} datasets but based on C{SciPy}

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

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

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

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

1264

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

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

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

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

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

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

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

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

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

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

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

1276 '''

1277 _endian = '>u2'

1278

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

1280 kind=3, name=NN, smooth=0):

1281 '''New L{GeoidPGM} interpolator.

1282

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1297 @kwarg name: Optional geoid name (C{str}).

1298 @kwarg smooth: Smoothing factor for U{RectBivariateSpline

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

1300 scipy.interpolate.RectBivariateSpline.html>}

1301 only (C{int}).

1302

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

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

1305

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

1307

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

1309

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

1311

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

1313 warning as exception.

1314

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

1316

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

1318 html/geoid.html#geoidinst>} file sizes are based on a 2-byte

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

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

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

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

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

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

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

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

1327

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

1329 '''

1330 np = self.numpy

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

1332

1333 g = self._open(egm_pgm, datum, kind, name, smooth)

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

1335 if crop:

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

1337 self._g2ll2 = self._g2ll2_cropped

1338 self._ll2g2 = self._ll2g2_cropped

1339 if map2(int, np.__version__.split(_DOT_)[:2]) < (1, 9):

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

1341 self._cropped = True

1342 else:

1343 self._cropped = False

1344

1345 try:

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

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

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

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

1350 if p.Offset: # offset

1351 hs = p.Offset + hs

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

1353 hs = np.flipud(hs)

1354 _GeoidBase.__init__(self, hs, p)

1355 except Exception as x:

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

1357 finally:

1358 g.close()

1359

1360 def _g2ll2(self, lat, lon):

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

1362 while lon > _180_0:

1363 lon -= _360_0

1364 return lat, lon

1365

1366 def _g2ll2_cropped(self, lat, lon):

1367 # convert cropped grid (lat, lon) to earth (lat, lon)

1368 return lat, lon - self._lon_og

1369

1370 def _ll2g2(self, lat, lon):

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

1372 while lon < 0:

1373 lon += _360_0

1374 return lat, lon

1375

1376 def _ll2g2_cropped(self, lat, lon):

1377 # convert earth (lat, lon) to cropped grid (lat, lon)

1378 return lat, lon + self._lon_of

1379

1380 if _FOR_DOCS:

1381 __call__ = _GeoidBase.__call__

1382 height = _GeoidBase.height

1383

1384

1385 class _Gpars(_Named):

1386 '''(INTERNAL) Basic geoid parameters.

1387 '''

1388 # interpolator parameters

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

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

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

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

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

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

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

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

1397

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

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

1400

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

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

1403

1404 def __repr__(self):

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

1406 a in dir(self.__class__)

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

1408 return _COLONSPACE_(self, t)

1409

1410 def __str__(self):

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

1412

1413

1414 class _PGM(_Gpars):

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

1416

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

1418 # Description WGS84 EGM96, 5-minute grid

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

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

1421 # MaxBilinearError 0.140

1422 # RMSBilinearError 0.005

1423 # MaxCubicError 0.003

1424 # RMSCubicError 0.001

1425 # Offset -108

1426 # Scale 0.003

1427 # Origin 90N 0E

1428 # AREA_OR_POINT Point

1429 # Vertical_Datum WGS84

1430 <width> <height>

1431 <pixel>

1432 ...

1433 '''

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

1435 egm = None

1436 glon = 180 # reverse offset, uncropped

1437# pgm = NN # name

1438 sizeB = 0

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

1440

1441 @staticmethod

1442 def _llstr2floats(latlon):

1443 # llstr to (lat, lon) floats

1444 lat, lon = latlon.split()

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

1446

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

1448 AREA_OR_POINT = str

1449 DateTime = str

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

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

1452 MaxBilinearError = float

1453 MaxCubicError = float

1454 Offset = float

1455 Origin = _llstr2floats

1456 Pixel = 0

1457 RMSBilinearError = float

1458 RMSCubicError = float

1459 Scale = float

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

1461 Vertical_Datum = str

1462

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

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

1465 '''

1466 self.name = pgm # geoid file name

1467 if itemsize:

1468 self._u2B = itemsize

1469 if sizeB:

1470 self.sizeB = sizeB

1471

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

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

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

1475

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

1477 try: # ignore empty ones or comments

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

1479 if t.startswith(_bHASH_):

1480 t = t.lstrip(_bHASH_).lstrip()

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

1482 f = getattr(_PGM, a, None)

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

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

1485 elif t:

1486 break

1487 except (TypeError, ValueError):

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

1489 else: # should never get here

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

1491

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

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

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

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

1496 raise ValueError

1497 except (TypeError, ValueError):

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

1499

1500 try: # must be 16 bit pixel height

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

1502 self.Pixel = int(t)

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

1504 raise ValueError

1505 except (TypeError, ValueError):

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

1507

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

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

1510 setattr(self, a, None)

1511

1512 if self.Origin is None:

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

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

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

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

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

1518

1519 self.skip = g.tell()

1520 self.knots = nlat * nlon

1521

1522 self.nlat, self.nlon = nlat, nlon

1523 self.slat, self.wlon = self.Origin

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

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

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

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

1528

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

1530 n = float(self.slat)

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

1532 w = self.wlon - self.glon

1533 e = w + self.dlon * nlon

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

1535

1536 n = self.sizeB - self.skip

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

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

1539

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

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

1542 '''

1543 # flon offset for both west and east

1544 f = 360 if west < 0 else 0

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

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

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

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

1549 s += 1 # s > n

1550 e += 1 # e > w

1551

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

1553 # handle special cases

1554 if (s - n) > hi:

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

1556 if (e - w) > wi:

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

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

1559 return g # use entire geoid as-is

1560

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

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

1563

1564 if e > wi > w: # wrap around

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

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

1567 elif e > w:

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

1569 else:

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

1571

1572 # convert to bytes

1573 r *= self.u2B

1574 p *= self.u2B

1575 q = wi * self.u2B # stride

1576 # number of rows and cols to skip from

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

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

1579 # sanity check

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

1581 or z > self.sizeB:

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

1583

1584 # can't use _BytesIO since numpy

1585 # needs .fileno attr in .fromfile

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

1587 # reading (s - n) rows, forward

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

1589 g.seek(z, _SEEK_SET)

1590 # Python 2 tmpfile.write returns None

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

1592 if p: # wrap around to start of row

1593 g.seek(-q, _SEEK_CUR)

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

1595 # Python 2 tmpfile.write returns None

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

1597 z += q

1598 c.flush()

1599 g.close()

1600

1601 s -= n # nlat

1602 e -= w # nlon

1603 k = s * e # knots

1604 z = k * self.u2B

1605 if t != z:

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

1607

1608 # update the _Gpars accordingly, note attributes

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

1610 self.slat += n * self.dlat

1611 self.wlon += w * self.dlon

1612 self.nlat = s

1613 self.nlon = e

1614 self.flon = self.glon = f

1615

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

1617 self.knots = k

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

1619

1620 c.seek(0, _SEEK_SET)

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

1622 return c

1623

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

1625 t = fmt % args

1626 e = self.pgm or NN

1627 if e:

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

1629 return PGMError(t)

1630

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

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

1633 # with .dlat decreasing from 90N .slat

1634 lat -= self.slat

1635 lon += flon - self.wlon

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

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

1638

1639 def _tmpfile(self):

1640 # create a tmpfile to hold the cropped geoid grid

1641 try:

1642 from tempfile import NamedTemporaryFile as tmpfile

1643 except ImportError: # Python 2.7.16-

1644 from os import tmpfile

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

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

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

1648 return f

1649

1650 @Property_RO

1651 def pgm(self):

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

1653 '''

1654 return self.name

1655

1656

1657 class PGMError(GeoidError):

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

1659 '''

1660 pass

1661

1662

1663 def egmGeoidHeights(GeoidHeights_dat):

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

1665 html/geoid.html#geoidinst>} height tests from U{GeoidHeights.dat

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

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

1668 geoid.html#testgeoid>}.

1669

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

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

1672

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

1674 egm84, egm96, egm2008)}.

1675

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

1677

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

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

1680 C{test/testGeoids.py}.

1681 '''

1682 dat = GeoidHeights_dat

1683 if isinstance(dat, bytes):

1684 dat = _BytesIO(dat)

1685

1686 try:

1687 dat.seek(0, _SEEK_SET) # reset

1688 except AttributeError as x:

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

1690

1691 for t in dat.readlines():

1692 t = t.strip()

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

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

1695 while lon > _180_0: # EasternLon to earth lon

1696 lon -= _360_0

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

1698

1699

1700__all__ += _ALL_DOCS(_GeoidBase)

1701

1702 if __name__ == '__main__':

1703

1704 from pygeodesy.lazily import printf, _sys

1705

1706 _crop = ()

1707 _GeoidEGM = GeoidKarney

1708 _kind = 3

1709

1710 geoids = _sys.argv[1:]

1711 while geoids:

1712 geoid = geoids.pop(0)

1713

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

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

1716

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

1718 _GeoidEGM = GeoidKarney

1719

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

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

1722

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

1724 _GeoidEGM = GeoidPGM

1725

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

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

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

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

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

1731 # The height of the EGM96 geoid at Timbuktu

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

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

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

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

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

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

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

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

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

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

1742 try:

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

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

1745 except (GeoidError, RangeError) as x:

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

1747

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

1749 g = GeoidG2012B(geoid, kind=_kind)

1750 printf(g.toStr())

1751

1752 else:

1753 raise GeoidError(grid=repr(geoid))

1754

1755_I = int # PYCHOK unused _I

1756 del _intCs # trash ints cache

1757

1758# **) MIT License

1759#

1760# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.

1761#

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

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

1764# to deal in the Software without restriction, including without limitation

1765# the rights to use, copy, modify, merge, publish, distribute, sublicense,

1766# and/or sell copies of the Software, and to permit persons to whom the

1767# Software is furnished to do so, subject to the following conditions:

1768#

1769# The above copyright notice and this permission notice shall be included

1770# in all copies or substantial portions of the Software.

1771#

1772# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS

1773# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

1774# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

1775# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR

1776# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

1777# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

1778# OTHER DEALINGS IN THE SOFTWARE.

1779

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

1781# _lowerleft = -90, -179, -30.1500 # egm2008-1.pgm

1782# _lowerleft = -90, -179, -29.5350 # egm96-5.pgm

1783# _lowerleft = -90, -179, -29.7120 # egm84-15.pgm

1784

1785# _center = 0, 0, 17.2260 # egm2008-1.pgm

1786# _center = 0, 0, 17.1630 # egm96-5.pgm

1787# _center = 0, 0, 18.3296 # egm84-15.pgm

1788

1789# _upperright = 90, 180, 14.8980 # egm2008-1.pgm

1790# _upperright = 90, 180, 13.6050 # egm96-5.pgm

1791# _upperright = 90, 180, 13.0980 # egm84-15.pgm

1792

1793

1794# % python3 -m pygeodesy.geoids [-Karney] ../testGeoids/egm*.pgm

1795#

1796# 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)

1797#

1798# _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'

1799#

1800# Timbuktu GeoidKarney('egm2008-1.pgm').height(16.775833, -3.009444): 28.7881 vs 28.7880

1801# Timbuktu GeoidKarney('egm2008-1.pgm').height(16.776, -3.009): 28.7880 vs 28.7880

1802#

1803# 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)

1804#

1805# _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'

1806#

1807# Timbuktu GeoidKarney('egm84-15.pgm').height(16.775833, -3.009444): 31.2983 vs 31.2979

1808# Timbuktu GeoidKarney('egm84-15.pgm').height(16.776, -3.009): 31.2979 vs 31.2979

1809#

1810# 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)

1811#

1812# _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'

1813#

1814# Timbuktu GeoidKarney('egm96-5.pgm').height(16.775833, -3.009444): 28.7068 vs 28.7067

1815# Timbuktu GeoidKarney('egm96-5.pgm').height(16.776, -3.009): 28.7067 vs 28.7067

1816

1817

1818# % python3 -m pygeodesy.geoids -Karney ../testGeoids/egm*.pgm

1819#

1820# 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)

1821#

1822# _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'

1823#

1824# Timbuktu GeoidKarney('egm2008-1.pgm').height(16.775833, -3.009444): 28.7881 vs 28.7880

1825# Timbuktu GeoidKarney('egm2008-1.pgm').height(16.776, -3.009): 28.7880 vs 28.7880

1826#

1827# 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)

1828#

1829# _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'

1830#

1831# Timbuktu GeoidKarney('egm84-15.pgm').height(16.775833, -3.009444): 31.2983 vs 31.2979

1832# Timbuktu GeoidKarney('egm84-15.pgm').height(16.776, -3.009): 31.2979 vs 31.2979

1833#

1834# 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)

1835#

1836# _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'

1837#

1838# Timbuktu GeoidKarney('egm96-5.pgm').height(16.775833, -3.009444): 28.7068 vs 28.7067

1839# Timbuktu GeoidKarney('egm96-5.pgm').height(16.776, -3.009): 28.7067 vs 28.7067

1840

1841

1842# % python2 -m pygeodesy.geoids -PGM ../testGeoids/egm*.pgm

1843#

1844# 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)

1845#

1846# _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'

1847#

1848# Timbuktu GeoidPGM('egm2008-1.pgm').height(16.775833, -3.009444): 28.7881 vs 28.7880

1849# Timbuktu GeoidPGM('egm2008-1.pgm').height(16.776, -3.009): 28.7880 vs 28.7880

1850#

1851# 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)

1852#

1853# _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'

1854#

1855# Timbuktu GeoidPGM('egm84-15.pgm').height(16.775833, -3.009444): 31.2979 vs 31.2979

1856# Timbuktu GeoidPGM('egm84-15.pgm').height(16.776, -3.009): 31.2975 vs 31.2979

1857#

1858# 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)

1859#

1860# _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'

1861#

1862# Timbuktu GeoidPGM('egm96-5.pgm').height(16.775833, -3.009444): 28.7065 vs 28.7067

1863# Timbuktu GeoidPGM('egm96-5.pgm').height(16.776, -3.009): 28.7064 vs 28.7067