Coverage for pygeodesy/utmupsBase.py: 97%

236 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-08-20 14:00 -0400

1 

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

3 

4u'''(INTERNAL) Private class C{UtmUpsBase}, functions and constants 

5for L{epsg}, L{etm}, L{mgrs}, L{ups} and L{utm}. 

6''' 

7 

8from pygeodesy.basics import isint, isscalar, isstr, neg_, \ 

9 _xinstanceof, _xsubclassof 

10from pygeodesy.constants import _float, _0_0, _0_5, _N_90_0, _180_0 

11from pygeodesy.datums import _ellipsoidal_datum, _WGS84 

12from pygeodesy.dms import degDMS, parseDMS2 

13from pygeodesy.ellipsoidalBase import LatLonEllipsoidalBase as _LLEB 

14from pygeodesy.errors import _or, ParseError, _parseX, _ValueError, \ 

15 _xkwds, _xkwds_get, _xkwds_not 

16from pygeodesy.interns import NN, _A_, _B_, _COMMA_, _Error_, \ 

17 _gamma_, _n_a_, _not_, _N_, _NS_, _PLUS_, \ 

18 _scale_, _SPACE_, _Y_, _Z_, _under 

19from pygeodesy.lazily import _ALL_DOCS, _ALL_MODS as _MODS 

20from pygeodesy.named import _NamedBase, nameof, notOverloaded, _xnamed 

21from pygeodesy.namedTuples import EasNor2Tuple, LatLonDatum5Tuple 

22from pygeodesy.props import deprecated_method, property_doc_, _update_all, \ 

23 deprecated_property_RO, Property_RO, property_RO 

24from pygeodesy.streprs import Fmt, fstr, _fstrENH2, _xattrs, _xzipairs 

25from pygeodesy.units import Band, Easting, Northing, Scalar, Zone 

26from pygeodesy.utily import _Wrap, wrap360 

27 

28__all__ = () 

29__version__ = '23.08.06' 

30 

31_UPS_BANDS = _A_, _B_, _Y_, _Z_ # UPS polar bands SE, SW, NE, NW 

32# _UTM_BANDS = _MODS.utm._Bands 

33 

34_UTM_LAT_MAX = _float( 84) # PYCHOK for export (C{degrees}) 

35_UTM_LAT_MIN = _float(-80) # PYCHOK for export (C{degrees}) 

36 

37_UPS_LAT_MAX = _UTM_LAT_MAX - _0_5 # PYCHOK includes 30' UTM overlap 

38_UPS_LAT_MIN = _UTM_LAT_MIN + _0_5 # PYCHOK includes 30' UTM overlap 

39 

40_UPS_LATS = {_A_: _N_90_0, _Y_: _UTM_LAT_MAX, # UPS band bottom latitudes, 

41 _B_: _N_90_0, _Z_: _UTM_LAT_MAX} # PYCHOK see .Mgrs.bandLatitude 

42 

43_UTM_ZONE_MAX = 60 # PYCHOK for export 

44_UTM_ZONE_MIN = 1 # PYCHOK for export 

45_UTM_ZONE_OFF_MAX = 60 # PYCHOK max Central meridian offset (C{degrees}) 

46 

47_UPS_ZONE = _UTM_ZONE_MIN - 1 # PYCHOK for export 

48_UPS_ZONE_STR = Fmt.zone(_UPS_ZONE) # PYCHOK for export 

49 

50_UTMUPS_ZONE_INVALID = -4 # PYCHOK for export too 

51_UTMUPS_ZONE_MAX = _UTM_ZONE_MAX # PYCHOK for export too, by .units.py 

52_UTMUPS_ZONE_MIN = _UPS_ZONE # PYCHOK for export too, by .units.py 

53 

54# _MAX_PSEUDO_ZONE = -1 

55# _MIN_PSEUDO_ZONE = -4 

56# _UTMUPS_ZONE_MATCH = -3 

57# _UTMUPS_ZONE_STANDARD = -1 

58# _UTM = -2 

59 

60 

61def _hemi(lat, N=0): # imported by .ups, .utm 

62 '''Return the hemisphere letter. 

63 

64 @arg lat: Latitude (C{degrees} or C{radians}). 

65 @kwarg N: Minimal North latitude, C{0} or C{_N_}. 

66 

67 @return: C{'N'|'S'} for north-/southern hemisphere. 

68 ''' 

69 return _NS_[int(lat < N)] 

70 

71 

72def _to4lldn(latlon, lon, datum, name, wrap=False): 

73 '''(INTERNAL) Return 4-tuple (C{lat, lon, datum, name}). 

74 ''' 

75 try: 

76 # if lon is not None: 

77 # raise AttributeError 

78 lat, lon = float(latlon.lat), float(latlon.lon) 

79 _xinstanceof(_LLEB, LatLonDatum5Tuple, latlon=latlon) 

80 if wrap: 

81 _Wrap.latlon(lat, lon) 

82 d = datum or latlon.datum 

83 except AttributeError: 

84 lat, lon = _Wrap.latlonDMS2(latlon, lon) if wrap else \ 

85 parseDMS2(latlon, lon) # clipped 

86 d = datum or _WGS84 

87 return lat, lon, d, (name or nameof(latlon)) 

88 

89 

90def _to3zBhp(zone, band, hemipole=NN, Error=_ValueError): # imported by .epsg, .ups, .utm, .utmups 

91 '''Parse UTM/UPS zone, Band letter and hemisphere/pole letter. 

92 

93 @arg zone: Zone with/-out Band (C{scalar} or C{str}). 

94 @kwarg band: Optional I{longitudinal/polar} Band letter (C{str}). 

95 @kwarg hemipole: Optional hemisphere/pole letter (C{str}). 

96 @kwarg Error: Optional error to raise, overriding the default 

97 C{ValueError}. 

98 

99 @return: 3-Tuple (C{zone, Band, hemisphere/pole}) as (C{int, str, 

100 'N'|'S'}) where C{zone} is C{0} for UPS or C{1..60} for 

101 UTM and C{Band} is C{'A'..'Z'} I{NOT} checked for valid 

102 UTM/UPS bands. 

103 

104 @raise ValueError: Invalid B{C{zone}}, B{C{band}} or B{C{hemipole}}. 

105 ''' 

106 try: 

107 B, z = band, _UTMUPS_ZONE_INVALID 

108 if isscalar(zone): 

109 z = int(zone) 

110 elif zone and isstr(zone): 

111 if zone.isdigit(): 

112 z = int(zone) 

113 elif len(zone) > 1: 

114 B = zone[-1:] 

115 z = int(zone[:-1]) 

116 elif zone.upper() in _UPS_BANDS: # single letter 

117 B = zone 

118 z = _UPS_ZONE 

119 

120 if _UTMUPS_ZONE_MIN <= z <= _UTMUPS_ZONE_MAX: 

121 hp = hemipole[:1].upper() 

122 if hp in _NS_ or not hp: 

123 z = Zone(z) 

124 B = Band(B.upper()) 

125 if B.isalpha(): 

126 return z, B, (hp or _hemi(B, _N_)) 

127 elif not B: 

128 return z, B, hp 

129 

130 raise ValueError # _invalid_ 

131 except (AttributeError, IndexError, TypeError, ValueError) as x: 

132 raise Error(zone=zone, band=B, hemipole=hemipole, cause=x) 

133 

134 

135def _to3zll(lat, lon): # imported by .ups, .utm 

136 '''Wrap lat- and longitude and determine UTM zone. 

137 

138 @arg lat: Latitude (C{degrees}). 

139 @arg lon: Longitude (C{degrees}). 

140 

141 @return: 3-Tuple (C{zone, lat, lon}) as (C{int}, C{degrees90}, 

142 C{degrees180}) where C{zone} is C{1..60} for UTM. 

143 ''' 

144 x = wrap360(lon + _180_0) # use wrap360 to get ... 

145 z = int(x) // 6 + 1 # ... longitudinal UTM zone [1, 60] and ... 

146 return Zone(z), lat, (x - _180_0) # ... -180 <= lon < 180 

147 

148 

149class UtmUpsBase(_NamedBase): 

150 '''(INTERNAL) Base class for L{Utm} and L{Ups} coordinates. 

151 ''' 

152 _band = NN # latitude band letter ('A..Z') 

153 _Bands = NN # valid Band letters, see L{Utm} and L{Ups} 

154 _datum = _WGS84 # L{Datum} 

155 _easting = _0_0 # Easting, see B{C{falsed}} (C{meter}) 

156 _Error = None # I{Must be overloaded}, see function C{notOverloaded} 

157 _falsed = True # falsed easting and northing (C{bool}) 

158 _gamma = None # meridian conversion (C{degrees}) 

159 _hemisphere = NN # hemisphere ('N' or 'S'), different from UPS pole 

160 _latlon = None # cached toLatLon (C{LatLon} or C{._toLLEB}) 

161 _northing = _0_0 # Northing, see B{C{falsed}} (C{meter}) 

162 _scale = None # grid or point scale factor (C{scalar}) or C{None} 

163# _scale0 = _K0 # central scale factor (C{scalar}) 

164 _ups = None # cached toUps (L{Ups}) 

165 _utm = None # cached toUtm (L{Utm}) 

166 

167 def __init__(self, easting, northing, band=NN, datum=None, falsed=True, 

168 gamma=None, scale=None, **convergence): 

169 '''(INTERNAL) New L{UtmUpsBase}. 

170 ''' 

171 E = self._Error 

172 if not E: # PYCHOK no cover 

173 notOverloaded(self, callername=_under(_Error_)) 

174 

175 self._easting = Easting(easting, Error=E) 

176 self._northing = Northing(northing, Error=E) 

177 

178 if band: 

179 self._band1(band) 

180 

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

182 self._datum = _ellipsoidal_datum(datum) # raiser=_datum_, name=band 

183 

184 if not falsed: 

185 self._falsed = False 

186 

187 if convergence: # for backward compatibility 

188 gamma = _xkwds_get(convergence, convergence=gamma) 

189 if gamma is not self._gamma: 

190 self._gamma = Scalar(gamma=gamma, Error=E) 

191 if scale is not self._scale: 

192 self._scale = Scalar(scale=scale, Error=E) 

193 

194 def __repr__(self): 

195 return self.toRepr(B=True) 

196 

197 def __str__(self): 

198 return self.toStr() 

199 

200 def _band1(self, band): 

201 '''(INTERNAL) Re/set the latitudinal or polar band. 

202 ''' 

203 if band: 

204 _xinstanceof(str, band=band) 

205# if not self._Bands: # PYCHOK no cover 

206# notOverloaded(self, callername=_under('Bands')) 

207 if band not in self._Bands: 

208 t = _or(*sorted(set(map(repr, self._Bands)))) 

209 raise self._Error(band=band, txt=_not_(t)) 

210 self._band = band 

211 elif self._band: # reset 

212 self._band = NN 

213 

214 @deprecated_property_RO 

215 def convergence(self): 

216 '''DEPRECATED, use property C{gamma}.''' 

217 return self.gamma 

218 

219 @property_doc_(''' the (ellipsoidal) datum of this coordinate.''') 

220 def datum(self): 

221 '''Get the datum (L{Datum}). 

222 ''' 

223 return self._datum 

224 

225 @datum.setter # PYCHOK setter! 

226 def datum(self, datum): 

227 '''Set the (ellipsoidal) datum L{Datum}, L{Ellipsoid}, L{Ellipsoid2} or L{a_f2Tuple}). 

228 ''' 

229 d = _ellipsoidal_datum(datum) 

230 if self._datum != d: 

231 _update_all(self) 

232 self._datum = d 

233 

234 @Property_RO 

235 def easting(self): 

236 '''Get the easting (C{meter}). 

237 ''' 

238 return self._easting 

239 

240 @Property_RO 

241 def eastingnorthing(self): 

242 '''Get easting and northing (L{EasNor2Tuple}C{(easting, northing)}). 

243 ''' 

244 return EasNor2Tuple(self.easting, self.northing) 

245 

246 def eastingnorthing2(self, falsed=True): 

247 '''Return easting and northing, falsed or unfalsed. 

248 

249 @kwarg falsed: If C{True} return easting and northing falsed 

250 (C{bool}), otherwise unfalsed. 

251 

252 @return: An L{EasNor2Tuple}C{(easting, northing)} in C{meter}. 

253 ''' 

254 e, n = self.falsed2 

255 if self.falsed and not falsed: 

256 e, n = neg_(e, n) 

257 elif falsed and not self.falsed: 

258 pass 

259 else: 

260 e = n = _0_0 

261 return EasNor2Tuple(Easting( e + self.easting, Error=self._Error), 

262 Northing(n + self.northing, Error=self._Error)) 

263 

264 @Property_RO 

265 def _epsg(self): 

266 '''(INTERNAL) Cache for method L{toEpsg}. 

267 ''' 

268 return _MODS.epsg.Epsg(self) 

269 

270 @Property_RO 

271 def falsed(self): 

272 '''Get easting and northing falsed (C{bool}). 

273 ''' 

274 return self._falsed 

275 

276 @Property_RO 

277 def falsed2(self): # PYCHOK no cover 

278 '''(INTERNAL) I{Must be overloaded}, see function C{notOverloaded}. 

279 ''' 

280 notOverloaded(self) 

281 

282 @Property_RO 

283 def gamma(self): 

284 '''Get the meridian convergence (C{degrees}) or C{None} 

285 if not available. 

286 ''' 

287 return self._gamma 

288 

289 @property_RO 

290 def hemisphere(self): 

291 '''Get the hemisphere (C{str}, 'N'|'S'). 

292 ''' 

293 if not self._hemisphere: 

294 self._toLLEB() 

295 return self._hemisphere 

296 

297 def _latlon5(self, LatLon, **LatLon_kwds): 

298 '''(INTERNAL) Get cached C{._toLLEB} as B{C{LatLon}} instance. 

299 ''' 

300 ll = self._latlon 

301 if LatLon is None: 

302 r = LatLonDatum5Tuple(ll.lat, ll.lon, ll.datum, 

303 ll.gamma, ll.scale) 

304 else: 

305 _xsubclassof(_LLEB, LatLon=LatLon) 

306 kwds = _xkwds(LatLon_kwds, datum=ll.datum) 

307 r = _xattrs(LatLon(ll.lat, ll.lon, **kwds), 

308 ll, _under(_gamma_), _under(_scale_)) 

309 return _xnamed(r, ll.name) 

310 

311 def _latlon5args(self, ll, _toBand, unfalse, *other): 

312 '''(INTERNAL) See C{._toLLEB} methods, functions C{ups.toUps8} and C{utm._toXtm8} 

313 ''' 

314 ll._toLLEB_args = (unfalse,) + other 

315 if unfalse: 

316 if not self._band: 

317 self._band = _toBand(ll.lat, ll.lon) 

318 if not self._hemisphere: 

319 self._hemisphere = _hemi(ll.lat) 

320 self._latlon = ll 

321 

322 @Property_RO 

323 def _lowerleft(self): # by .ellipsoidalBase._lowerleft 

324 '''Get this UTM or UPS C{un}-centered (L{Utm} or L{Ups}) to its C{lowerleft}. 

325 ''' 

326 return _lowerleft(self, 0) 

327 

328 @Property_RO 

329 def _mgrs(self): 

330 '''(INTERNAL) Cache for method L{toMgrs}. 

331 ''' 

332 return _toMgrs(self) 

333 

334 @Property_RO 

335 def _mgrs_lowerleft(self): 

336 '''(INTERNAL) Cache for method L{toMgrs}, I{un}-centered. 

337 ''' 

338 utmups = self._lowerleft 

339 return self._mgrs if utmups is self else _toMgrs(utmups) 

340 

341 @Property_RO 

342 def northing(self): 

343 '''Get the northing (C{meter}). 

344 ''' 

345 return self._northing 

346 

347 @Property_RO 

348 def scale(self): 

349 '''Get the grid scale (C{float}) or C{None}. 

350 ''' 

351 return self._scale 

352 

353 @Property_RO 

354 def scale0(self): 

355 '''Get the central scale factor (C{float}). 

356 ''' 

357 return self._scale0 

358 

359 @deprecated_method 

360 def to2en(self, falsed=True): # PYCHOK no cover 

361 '''DEPRECATED, use method C{eastingnorthing2}. 

362 

363 @return: An L{EasNor2Tuple}C{(easting, northing)}. 

364 ''' 

365 return self.eastingnorthing2(falsed=falsed) 

366 

367 def toEpsg(self): 

368 '''Determine the B{EPSG (European Petroleum Survey Group)} code. 

369 

370 @return: C{EPSG} code (C{int}). 

371 

372 @raise EPSGError: See L{Epsg}. 

373 ''' 

374 return self._epsg 

375 

376 def _toLLEB(self, **kwds): # PYCHOK no cover 

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

378 ''' 

379 notOverloaded(self, **kwds) 

380 

381 def toMgrs(self, center=False): 

382 '''Convert this UTM/UPS coordinate to an MGRS grid reference. 

383 

384 @kwarg center: If C{True}, I{un}-center this UTM or UPS to 

385 its C{lowerleft} (C{bool}) or by C{B{center} 

386 meter} (C{scalar}). 

387 

388 @return: The MGRS grid reference (L{Mgrs}). 

389 

390 @see: Function L{pygeodesy.toMgrs} in module L{mgrs} for more details. 

391 

392 @note: If not specified, the I{latitudinal} C{band} is computed from 

393 the (geodetic) latitude and the C{datum}. 

394 ''' 

395 return self._mgrs if center in (False, 0, _0_0) else ( 

396 self._mgrs_lowerleft if center in (True,) else 

397 _toMgrs(_lowerleft(self, center))) # PYCHOK indent 

398 

399 def _toRepr(self, fmt, B, cs, prec, sep): # PYCHOK expected 

400 '''(INTERNAL) Return a representation for this ETM/UTM/UPS coordinate. 

401 ''' 

402 t = self.toStr(prec=prec, sep=None, B=B, cs=cs) # hemipole 

403 T = 'ZHENCS'[:len(t)] 

404 return _xzipairs(T, t, sep=sep, fmt=fmt) 

405 

406 def _toStr(self, hemipole, B, cs, prec, sep): 

407 '''(INTERNAL) Return a string for this ETM/UTM/UPS coordinate. 

408 ''' 

409 z = NN(Fmt.zone(self.zone), (self.band if B else NN)) # PYCHOK band 

410 t = (z, hemipole) + _fstrENH2(self, prec, None)[0] 

411 if cs: 

412 prec = cs if isint(cs) else 8 # for backward compatibility 

413 t += (_n_a_ if self.gamma is None else 

414 degDMS(self.gamma, prec=prec, pos=_PLUS_), 

415 _n_a_ if self.scale is None else 

416 fstr(self.scale, prec=prec)) 

417 return t if sep is None else sep.join(t) 

418 

419 

420def _lowerleft(utmups, center): # by .ellipsoidalBase._lowerleft 

421 '''(INTERNAL) I{Un}-center a B{C{utmups}} to its C{lowerleft} by 

422 C{B{center} meter} or by a I{guess} if B{C{center}} is C{0}. 

423 ''' 

424 if center: 

425 e = n = -center 

426 else: 

427 c = 5 # center 

428 for _ in range(3): 

429 c *= 10 # 50, 500, 5000 

430 t = c * 2 

431 e = int(utmups.easting % t) 

432 n = int(utmups.northing % t) 

433 if (e == c and n in (c, c - 1)) or \ 

434 (n == c and e in (c, c - 1)): 

435 break 

436 else: 

437 return utmups # unchanged 

438 

439 r = _xkwds_not(None, datum=utmups.datum, 

440 gamma=utmups.gamma, 

441 scale=utmups.scale) 

442 return utmups.classof(utmups.zone, utmups.hemisphere, 

443 utmups.easting - e, utmups.northing - n, 

444 band=utmups.band, falsed=utmups.falsed, **r) 

445 

446 

447def _parseUTMUPS5(strUTMUPS, UPS, Error=ParseError, band=NN, sep=_COMMA_): 

448 '''(INTERNAL) Parse a string representing a UTM or UPS coordinate 

449 consisting of C{"zone[band] hemisphere/pole easting northing"}. 

450 

451 @arg strUTMUPS: A UTM or UPS coordinate (C{str}). 

452 @kwarg band: Optional, default Band letter (C{str}). 

453 @kwarg sep: Optional, separator to split (","). 

454 

455 @return: 5-Tuple (C{zone, hemisphere/pole, easting, northing, 

456 band}). 

457 

458 @raise ParseError: Invalid B{C{strUTMUPS}}. 

459 ''' 

460 def _UTMUPS5(strUTMUPS, UPS, band, sep): 

461 u = strUTMUPS.lstrip() 

462 if UPS and not u.startswith(_UPS_ZONE_STR): 

463 raise ValueError(_not_(_UPS_ZONE_STR)) 

464 

465 u = u.replace(sep, _SPACE_).strip().split() 

466 if len(u) < 4: 

467 raise ValueError(_not_(sep)) 

468 

469 z, h = u[:2] 

470 if h[:1].upper() not in _NS_: 

471 raise ValueError(_SPACE_(h, _not_(_NS_))) 

472 

473 if z.isdigit(): 

474 z, B = int(z), band 

475 else: 

476 for i in range(len(z)): 

477 if not z[i].isdigit(): 

478 # int('') raises ValueError 

479 z, B = int(z[:i]), z[i:] 

480 break 

481 else: 

482 raise ValueError(z) 

483 

484 e, n = map(float, u[2:4]) 

485 return z, h.upper(), e, n, B.upper() 

486 

487 return _parseX(_UTMUPS5, strUTMUPS, UPS, band, sep, 

488 strUTMUPS=strUTMUPS, Error=Error) 

489 

490 

491def _toMgrs(utmups): 

492 '''(INTERNAL) Convert a L{Utm} or L{Ups} to an L{Mgrs} instance. 

493 ''' 

494 return _MODS.mgrs.toMgrs(utmups, datum=utmups.datum, name=utmups.name) 

495 

496 

497__all__ += _ALL_DOCS(UtmUpsBase) 

498 

499# **) MIT License 

500# 

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

502# 

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

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

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

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

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

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

509# 

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

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

512# 

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

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

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

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

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

518# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

519# OTHER DEALINGS IN THE SOFTWARE.