Coverage for pygeodesy/utmupsBase.py: 98%

234 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-06-10 14:08 -0400

1 

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

3 

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

5for modules 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_not 

16# from pygeodesy.internals import _name__, _under # from .named 

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

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

19 _S_, _scale_, _SPACE_, _Y_, _Z_ 

20from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS 

21from pygeodesy.named import _NamedBase, _xnamed, _name__, _under 

22from pygeodesy.namedTuples import EasNor2Tuple, LatLonDatum5Tuple 

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

24 deprecated_property_RO, Property_RO, property_RO 

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

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

27from pygeodesy.utily import _Wrap, wrap360 

28 

29__all__ = _ALL_LAZY.utmupsBase 

30__version__ = '24.06.09' 

31 

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

33# _UTM_BANDS = _MODS.utm._Bands 

34 

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

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

37 

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

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

40 

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

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

43 

44_UTM_ZONE_MAX = 60 # PYCHOK for export 

45_UTM_ZONE_MIN = 1 # PYCHOK for export 

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

47 

48_UPS_ZONE = _UTM_ZONE_MIN - 1 # PYCHOK for export 

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

50 

51_UTMUPS_ZONE_INVALID = -4 # PYCHOK for export too 

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

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

54 

55# _MAX_PSEUDO_ZONE = -1 

56# _MIN_PSEUDO_ZONE = -4 

57# _UTMUPS_ZONE_MATCH = -3 

58# _UTMUPS_ZONE_STANDARD = -1 

59# _UTM = -2 

60 

61 

62class UtmUpsBase(_NamedBase): 

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

64 ''' 

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

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

67 _datum = _WGS84 # L{Datum} 

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

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

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

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

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

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

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

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

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

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

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

79 

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

81 gamma=None, scale=None): 

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

83 ''' 

84 E = self._Error 

85 if not E: # PYCHOK no cover 

86 self._notOverloaded(callername=_under(_Error_)) 

87 

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

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

90 

91 if band: 

92 self._band1(band) 

93 

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

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

96 

97 if not falsed: 

98 self._falsed = False 

99 

100 if gamma is not self._gamma: 

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

102 if scale is not self._scale: 

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

104 

105 def __repr__(self): 

106 return self.toRepr(B=True) 

107 

108 def __str__(self): 

109 return self.toStr() 

110 

111 def _band1(self, band): 

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

113 ''' 

114 if band: 

115 _xinstanceof(str, band=band) 

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

117# self._notOverloaded(callername=_under('Bands')) 

118 if band not in self._Bands: 

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

120 raise self._Error(band=band, txt_not_=t) 

121 self._band = band 

122 elif self._band: # reset 

123 self._band = NN 

124 

125 @deprecated_property_RO 

126 def convergence(self): 

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

128 return self.gamma 

129 

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

131 def datum(self): 

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

133 ''' 

134 return self._datum 

135 

136 @datum.setter # PYCHOK setter! 

137 def datum(self, datum): 

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

139 ''' 

140 d = _ellipsoidal_datum(datum) 

141 if self._datum != d: 

142 _update_all(self) 

143 self._datum = d 

144 

145 @Property_RO 

146 def easting(self): 

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

148 ''' 

149 return self._easting 

150 

151 @Property_RO 

152 def eastingnorthing(self): 

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

154 ''' 

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

156 

157 def eastingnorthing2(self, falsed=True): 

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

159 

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

161 (C{bool}), otherwise unfalsed. 

162 

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

164 ''' 

165 e, n = self.falsed2 

166 if self.falsed and not falsed: 

167 e, n = neg_(e, n) 

168 elif falsed and not self.falsed: 

169 pass 

170 else: 

171 e = n = _0_0 

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

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

174 

175 @Property_RO 

176 def _epsg(self): 

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

178 ''' 

179 return _MODS.epsg.Epsg(self) 

180 

181 @Property_RO 

182 def falsed(self): 

183 '''Are easting and northing falsed (C{bool})? 

184 ''' 

185 return self._falsed 

186 

187 @Property_RO 

188 def falsed2(self): # PYCHOK no cover 

189 '''I{Must be overloaded}.''' 

190 self._notOverloaded(self) 

191 

192 @Property_RO 

193 def gamma(self): 

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

195 if not available. 

196 ''' 

197 return self._gamma 

198 

199 @property_RO 

200 def hemisphere(self): 

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

202 ''' 

203 if not self._hemisphere: 

204 self._toLLEB() 

205 return self._hemisphere 

206 

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

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

209 ''' 

210 ll = self._latlon 

211 if LatLon is None: 

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

213 ll.gamma, ll.scale) 

214 else: 

215 _xsubclassof(_LLEB, LatLon=LatLon) 

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

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

218 ll, _under(_gamma_), _under(_scale_)) 

219 return _xnamed(r, ll.name) 

220 

221 def _latlon5args(self, ll, g, k, _toBand, unfalse, *other): 

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

223 ''' 

224 ll._gamma = g 

225 ll._scale = k 

226 ll._toLLEB_args = (unfalse,) + other 

227 if unfalse: 

228 if not self._band: 

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

230 if not self._hemisphere: 

231 self._hemisphere = _hemi(ll.lat) 

232 self._latlon = ll 

233 

234 @Property_RO 

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

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

237 ''' 

238 return _lowerleft(self, 0) 

239 

240 @Property_RO 

241 def _mgrs(self): 

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

243 ''' 

244 return _toMgrs(self) 

245 

246 @Property_RO 

247 def _mgrs_lowerleft(self): 

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

249 ''' 

250 utmups = self._lowerleft 

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

252 

253 @Property_RO 

254 def northing(self): 

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

256 ''' 

257 return self._northing 

258 

259 @Property_RO 

260 def scale(self): 

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

262 ''' 

263 return self._scale 

264 

265 @Property_RO 

266 def scale0(self): 

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

268 ''' 

269 return self._scale0 

270 

271 @deprecated_method 

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

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

274 

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

276 ''' 

277 return self.eastingnorthing2(falsed=falsed) 

278 

279 def toEpsg(self): 

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

281 

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

283 

284 @raise EPSGError: See L{Epsg}. 

285 ''' 

286 return self._epsg 

287 

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

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

290 self._notOverloaded(**kwds) 

291 

292 def toMgrs(self, center=False): 

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

294 

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

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

297 meter} (C{scalar}). 

298 

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

300 

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

302 

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

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

305 ''' 

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

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

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

309 

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

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

312 ''' 

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

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

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

316 

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

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

319 ''' 

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

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

322 if cs: 

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

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

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

326 _n_a_ if self.scale is None else 

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

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

329 

330 

331def _hemi(lat, N=0): # in .ups, .utm 

332 '''Return the hemisphere letter. 

333 

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

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

336 

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

338 ''' 

339 return _S_ if lat < N else _N_ 

340 

341 

342def _lowerleft(utmups, center): # in .ellipsoidalBase._lowerleft 

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

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

345 ''' 

346 if center: 

347 e = n = -center 

348 else: 

349 for c in (50, 500, 5000): 

350 t = c * 2 

351 e = int(utmups.easting % t) 

352 n = int(utmups.northing % t) 

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

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

355 break 

356 else: 

357 return utmups # unchanged 

358 

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

360 gamma=utmups.gamma, 

361 scale=utmups.scale, name=utmups.name) 

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

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

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

365 

366 

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

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

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

370 

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

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

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

374 

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

376 band}). 

377 

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

379 ''' 

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

381 u = strUTMUPS.lstrip() 

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

383 raise ValueError(_not_(_UPS_ZONE_STR)) 

384 

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

386 if len(u) < 4: 

387 raise ValueError(_not_(sep)) 

388 

389 z, h = u[:2] 

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

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

392 

393 if z.isdigit(): 

394 z, B = int(z), band 

395 else: 

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

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

398 # int('') raises ValueError 

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

400 break 

401 else: 

402 raise ValueError(z) 

403 

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

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

406 

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

408 strUTMUPS=strUTMUPS, Error=Error) 

409 

410 

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

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

413 ''' 

414 try: 

415 # if lon is not None: 

416 # raise AttributeError 

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

418 _xinstanceof(_LLEB, LatLonDatum5Tuple, latlon=latlon) 

419 if wrap: 

420 _Wrap.latlon(lat, lon) 

421 d = datum or latlon.datum 

422 except AttributeError: # TypeError 

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

424 parseDMS2(latlon, lon) # clipped 

425 d = datum or _WGS84 

426 return lat, lon, d, _name__(name, _or_nameof=latlon) 

427 

428 

429def _toMgrs(utmups): 

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

431 ''' 

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

433 

434 

435def _to3zBhp(zone, band, hemipole=NN, Error=_ValueError): # in .epsg, .ups, .utm, .utmups 

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

437 

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

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

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

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

442 C{ValueError}. 

443 

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

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

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

447 UTM/UPS bands. 

448 

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

450 ''' 

451 try: 

452 B, z = band, _UTMUPS_ZONE_INVALID 

453 if isscalar(zone): 

454 z = int(zone) 

455 elif zone and isstr(zone): 

456 if zone.isdigit(): 

457 z = int(zone) 

458 elif len(zone) > 1: 

459 B = zone[-1:] 

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

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

462 B = zone 

463 z = _UPS_ZONE 

464 

465 if _UTMUPS_ZONE_MIN <= z <= _UTMUPS_ZONE_MAX: 

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

467 if hp in _NS_ or not hp: 

468 z = Zone(z) 

469 B = Band(B.upper()) 

470 if B.isalpha(): 

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

472 elif not B: 

473 return z, B, hp 

474 

475 raise ValueError() # _invalid_ 

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

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

478 

479 

480def _to3zll(lat, lon): # in .ups, .utm 

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

482 

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

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

485 

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

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

488 ''' 

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

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

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

492 

493 

494__all__ += _ALL_DOCS(UtmUpsBase) 

495 

496# **) MIT License 

497# 

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

499# 

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

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

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

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

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

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

506# 

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

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

509# 

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

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

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

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

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

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

516# OTHER DEALINGS IN THE SOFTWARE.