Coverage for pygeodesy/utm.py: 97%

265 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-02-07 13:12 -0500

1 

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

3 

4u'''I{Veness}' Universal Transverse Mercator (UTM) projection. 

5 

6Classes L{Utm} and L{UTMError} and functions L{parseUTM5}, L{toUtm8} and 

7L{utmZoneBand5}. 

8 

9Pure Python implementation of UTM / WGS-84 conversion functions using 

10an ellipsoidal earth model, transcoded from JavaScript originals by 

11I{(C) Chris Veness 2011-2016} published under the same MIT Licence**, see 

12U{UTM<https://www.Movable-Type.co.UK/scripts/latlong-utm-mgrs.html>} and 

13U{Module utm<https://www.Movable-Type.co.UK/scripts/geodesy/docs/module-utm.html>}. 

14 

15The U{UTM<https://WikiPedia.org/wiki/Universal_Transverse_Mercator_coordinate_system>} 

16system is a 2-dimensional Cartesian coordinate system providing another way 

17to identify locations on the surface of the earth. UTM is a set of 60 

18transverse Mercator projections, normally based on the WGS-84 ellipsoid. 

19Within each zone, coordinates are represented as B{C{easting}}s and B{C{northing}}s, 

20measured in metres. 

21 

22This module includes some of I{Charles Karney}'s U{'Transverse Mercator with an 

23accuracy of a few nanometers'<https://ArXiv.org/pdf/1002.1417v3.pdf>}, 2011 

24(building on Krüger's U{'Konforme Abbildung des Erdellipsoids in der Ebene' 

25<https://bib.GFZ-Potsdam.DE/pub/digi/krueger2.pdf>}, 1912) and C++ class 

26U{TransverseMercator<https://GeographicLib.SourceForge.io/C++/doc/ 

27classGeographicLib_1_1TransverseMercator.html>}. 

28 

29Some other references are U{Universal Transverse Mercator coordinate system 

30<https://WikiPedia.org/wiki/Universal_Transverse_Mercator_coordinate_system>}, 

31U{Transverse Mercator Projection<https://GeographicLib.SourceForge.io/tm.html>} 

32and Henrik Seidel U{'Die Mathematik der Gauß-Krueger-Abbildung' 

33<https://DE.WikiPedia.org/wiki/Gauß-Krüger-Koordinatensystem>}, 2006. 

34''' 

35 

36from pygeodesy.basics import len2, map2, neg # splice 

37from pygeodesy.constants import EPS, EPS0, _K0_UTM, _0_0, _0_0001 

38from pygeodesy.datums import _ellipsoidal_datum, _WGS84 

39from pygeodesy.dms import degDMS, parseDMS2 

40from pygeodesy.errors import MGRSError, RangeError, _ValueError, \ 

41 _xkwds_get 

42from pygeodesy.fmath import fdot3, hypot, hypot1 

43from pygeodesy.interns import MISSING, NN, _by_, _COMMASPACE_, _N_, \ 

44 _NS_, _outside_, _range_, _S_, _scale0_, \ 

45 _SPACE_, _UTM_, _V_, _X_, _zone_, _under 

46from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS 

47# from pygeodesy.named import _xnamed # from .utmupsBase 

48from pygeodesy.namedTuples import EasNor2Tuple, UtmUps5Tuple, \ 

49 UtmUps8Tuple, UtmUpsLatLon5Tuple 

50from pygeodesy.props import deprecated_method, property_doc_, \ 

51 Property_RO 

52from pygeodesy.streprs import Fmt, unstr 

53from pygeodesy.units import Band, Int, Lat, Lon, Meter, Zone 

54from pygeodesy.utily import atan1, degrees90, degrees180, sincos2 

55from pygeodesy.utmupsBase import _hemi, _LLEB, _parseUTMUPS5, _to4lldn, \ 

56 _to3zBhp, _to3zll, _UPS_LATS, _UPS_ZONE, \ 

57 _UTM_LAT_MAX, _UTM_ZONE_MAX, \ 

58 _UTM_LAT_MIN, _UTM_ZONE_MIN, \ 

59 _UTM_ZONE_OFF_MAX, UtmUpsBase, _xnamed 

60 

61from math import asinh, atanh, atan2, cos, cosh, degrees, fabs, \ 

62 radians, sin, sinh, tan, tanh 

63from operator import mul as _mul 

64 

65__all__ = _ALL_LAZY.utm 

66__version__ = '23.12.07' 

67 

68_Bands = 'CDEFGHJKLMNPQRSTUVWXX' # UTM latitude bands C..X (no 

69# I|O) 8° each, covering 80°S to 84°N and X repeated for 80-84°N 

70_bandLat_ = 'bandLat' 

71_FalseEasting = Meter( 500e3) # falsed offset (C{meter}) 

72_FalseNorthing = Meter(10000e3) # falsed offset (C{meter}) 

73_SvalbardXzone = {32: 9, 34: 21, 36: 33} # [zone] longitude 

74 

75 

76class UTMError(_ValueError): 

77 '''Universal Transverse Mercator (UTM parse or other L{Utm} issue. 

78 ''' 

79 pass 

80 

81 

82class _Kseries(object): 

83 '''(INTERNAL) Alpha or Beta Krüger series. 

84 

85 Krüger series summations for B{C{eta}}, B{C{ksi}}, B{C{p}} and B{C{q}}, 

86 caching the C{cos}, C{cosh}, C{sin} and C{sinh} values for 

87 the given B{C{eta}} and B{C{ksi}} angles (in C{radians}). 

88 ''' 

89 def __init__(self, AB, x, y): 

90 '''(INTERNAL) New Alpha or Beta Krüger series 

91 

92 @arg AB: Krüger Alpha or Beta series coefficients 

93 (C{4-, 6- or 8-tuple}). 

94 @arg x: Eta angle (C{radians}). 

95 @arg y: Ksi angle (C{radians}). 

96 ''' 

97 n, j2 = len2(range(2, len(AB) * 2 + 1, 2)) 

98 

99 self._ab = AB 

100 self._pq = map2(_mul, j2, AB) 

101# assert len(self._ab) == len(self._pq) == n 

102 

103 x2 = map2(_mul, j2, (x,) * n) 

104 self._chx = map2(cosh, x2) 

105 self._shx = map2(sinh, x2) 

106# assert len(x2) == len(self._chx) == len(self._shx) == n 

107 

108 y2 = map2(_mul, j2, (y,) * n) 

109 self._cy = map2(cos, y2) 

110 self._sy = map2(sin, y2) 

111 # self._sy, self._cy = splice(sincos2(*y2)) # PYCHOK false 

112# assert len(y2) == len(self._cy) == len(self._sy) == n 

113 

114 def xs(self, x0): 

115 '''(INTERNAL) Eta summation (C{float}). 

116 ''' 

117 return fdot3(self._ab, self._cy, self._shx, start=x0) 

118 

119 def ys(self, y0): 

120 '''(INTERNAL) Ksi summation (C{float}). 

121 ''' 

122 return fdot3(self._ab, self._sy, self._chx, start=y0) 

123 

124 def ps(self, p0): 

125 '''(INTERNAL) P summation (C{float}). 

126 ''' 

127 return fdot3(self._pq, self._cy, self._chx, start=p0) 

128 

129 def qs(self, q0): 

130 '''(INTERNAL) Q summation (C{float}). 

131 ''' 

132 return fdot3(self._pq, self._sy, self._shx, start=q0) 

133 

134 

135def _cmlon(zone): 

136 '''(INTERNAL) Central meridian longitude (C{degrees180}). 

137 ''' 

138 return (zone * 6) - 183 

139 

140 

141def _false2(e, n, h): 

142 '''(INTERNAL) False easting and northing. 

143 ''' 

144 # Karney, "Test data for the transverse Mercator projection (2009)" 

145 # <https://GeographicLib.SourceForge.io/C++/doc/transversemercator.html> 

146 # and <https://Zenodo.org/record/32470#.W4LEJS2ZON8> 

147 e += _FalseEasting # make e relative to central meridian 

148 if h == _S_: 

149 n += _FalseNorthing # make n relative to equator 

150 return e, n 

151 

152 

153def _toBand(lat, *unused, **strict_Error): # see ups._toBand 

154 '''(INTERNAL) Get the I{latitudinal} Band (row) letter. 

155 ''' 

156 if _UTM_LAT_MIN <= lat < _UTM_LAT_MAX: # [-80, 84) like Veness 

157 return _Bands[int(lat - _UTM_LAT_MIN) >> 3] 

158 elif _xkwds_get(strict_Error, strict=True): 

159 r = _range_(_UTM_LAT_MIN, _UTM_LAT_MAX, ropen=True) 

160 t = _SPACE_(_outside_, _UTM_, _range_, r) 

161 E = _xkwds_get(strict_Error, Error=RangeError) 

162 raise E(lat=degDMS(lat), txt=t) 

163 else: 

164 return NN # None 

165 

166 

167def _to3zBlat(zone, band, Error=UTMError): # in .mgrs 

168 '''(INTERNAL) Check and return zone, Band and band latitude. 

169 

170 @arg zone: Zone number or string. 

171 @arg band: Band letter. 

172 @arg Error: Exception to raise (L{UTMError}). 

173 

174 @return: 3-Tuple (zone, Band, latitude). 

175 ''' 

176 z, B, _ = _to3zBhp(zone, band, Error=Error) 

177 if not (_UTM_ZONE_MIN <= z <= _UTM_ZONE_MAX or 

178 (_UPS_ZONE == z and Error is MGRSError)): 

179 raise Error(zone=zone) 

180 

181 b = None 

182 if B: 

183 if z == _UPS_ZONE: # polar 

184 try: 

185 b = Lat(_UPS_LATS[B], name=_bandLat_) 

186 except KeyError: 

187 raise Error(band=band or B, zone=z) 

188 else: # UTM 

189 b = _Bands.find(B) 

190 if b < 0: 

191 raise Error(band=band or B, zone=z) 

192 b = Int((b << 3) - 80, name=_bandLat_) 

193 B = Band(B) 

194 elif Error is not UTMError: 

195 raise Error(band=band, txt=MISSING) 

196 

197 return Zone(z), B, b 

198 

199 

200def _to4zBll(lat, lon, cmoff=True, strict=True, Error=RangeError): 

201 '''(INTERNAL) Return zone, Band and lat- and (central) longitude in degrees. 

202 

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

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

205 @kwarg cmoff: Offset B{C{lon}} from zone's central meridian. 

206 @kwarg strict: Restrict B{C{lat}} to UTM ranges (C{bool}). 

207 @kwarg Error: Error for out of UTM range B{C{lat}}s. 

208 

209 @return: 4-Tuple (zone, Band, lat, lon). 

210 ''' 

211 z, lat, lon = _to3zll(lat, lon) # in .utmupsBase 

212 

213 x = lon - _cmlon(z) # z before Norway/Svalbard 

214 if fabs(x) > _UTM_ZONE_OFF_MAX: 

215 t = _SPACE_(_outside_, _UTM_, _zone_, str(z), _by_, degDMS(x, prec=6)) 

216 raise Error(lon=degDMS(lon), txt=t) 

217 

218 B = _toBand(lat, strict=strict, Error=Error) 

219 if B == _X_: # and 0 <= lon < 42: z = int(lon + 183) // 6 + 1 

220 x = _SvalbardXzone.get(z, None) 

221 if x: # Svalbard/Spitsbergen archipelago 

222 z += 1 if lon >= x else -1 

223 elif B == _V_ and z == 31 and lon >= 3: 

224 z += 1 # SouthWestern Norway 

225 

226 if cmoff: # lon off central meridian 

227 lon -= _cmlon(z) # z after Norway/Svalbard 

228 return Zone(z), (Band(B) if B else None), Lat(lat), Lon(lon) 

229 

230 

231def _to7zBlldfn(latlon, lon, datum, falsed, name, zone, strict, Error, **cmoff): 

232 '''(INTERNAL) Determine 7-tuple (zone, band, lat, lon, datum, 

233 falsed, name) for methods L{toEtm8} and L{toUtm8}. 

234 ''' 

235 f = falsed and _xkwds_get(cmoff, cmoff=True) # DEPRECATED 

236 lat, lon, d, name = _to4lldn(latlon, lon, datum, name) 

237 z, B, lat, lon = _to4zBll(lat, lon, cmoff=f, strict=strict) 

238 if zone: # re-zone for ETM/UTM 

239 r, _, _ = _to3zBhp(zone, B) 

240 if r != z: 

241 if not _UTM_ZONE_MIN <= r <= _UTM_ZONE_MAX: 

242 raise Error(zone=zone) 

243 if f: # re-offset from central meridian 

244 lon += _cmlon(z) - _cmlon(r) 

245 z = r 

246 return z, B, lat, lon, d, f, name 

247 

248 

249class Utm(UtmUpsBase): 

250 '''Universal Transverse Mercator (UTM) coordinate. 

251 ''' 

252# _band = NN # latitudinal band letter ('C'|..|'X', no 'I'|'O') 

253 _Bands = _Bands # latitudinal Band letters (C{tuple}) 

254 _Error = UTMError # or etm.ETMError 

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

256 _scale0 = _K0_UTM # central scale factor (C{scalar}) 

257 _zone = 0 # longitudinal zone (C{int} 1..60) 

258 

259 def __init__(self, zone=31, hemisphere=_N_, easting=166022, # PYCHOK expected 

260 northing=0, band=NN, datum=_WGS84, falsed=True, 

261 gamma=None, scale=None, name=NN, **convergence): 

262 '''New L{Utm} UTM coordinate. 

263 

264 @kwarg zone: Longitudinal UTM zone (C{int}, 1..60) or zone with/-out 

265 I{latitudinal} Band letter (C{str}, '1C'|..|'60X'). 

266 @kwarg hemisphere: Northern or southern hemisphere (C{str}, C{'N[orth]'} 

267 or C{'S[outh]'}). 

268 @kwarg easting: Easting, see B{C{falsed}} (C{meter}). 

269 @kwarg northing: Northing, see B{C{falsed}} (C{meter}). 

270 @kwarg band: Optional, I{latitudinal} band (C{str}, 'C'|..|'X', no 'I'|'O'). 

271 @kwarg datum: Optional, this coordinate's datum (L{Datum}, L{Ellipsoid}, 

272 L{Ellipsoid2} or L{a_f2Tuple}). 

273 @kwarg falsed: If C{True}, both B{C{easting}} and B{C{northing}} are 

274 falsed (C{bool}). 

275 @kwarg gamma: Optional meridian convergence, bearing off grid North, 

276 clockwise from true North (C{degrees}) or C{None}. 

277 @kwarg scale: Optional grid scale factor (C{scalar}) or C{None}. 

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

279 @kwarg convergence: DEPRECATED, use keyword argument C{B{gamma}=None}. 

280 

281 @raise TypeError: Invalid or near-spherical B{C{datum}}. 

282 

283 @raise UTMError: Invalid B{C{zone}}, B{C{hemishere}}, B{C{easting}}, 

284 B{C{northing}}, B{C{band}}, B{C{convergence}} or 

285 B{C{scale}}. 

286 ''' 

287 if name: 

288 self.name = name 

289 

290 self._zone, B, _ = _to3zBlat(zone, band) 

291 

292 h = str(hemisphere)[:1].upper() 

293 if h not in _NS_: 

294 raise self._Error(hemisphere=hemisphere) 

295 

296 e, n = easting, northing # Easting(easting), ... 

297# if not falsed: 

298# e, n = _false2(e, n, h) 

299# # check easting/northing (with 40km overlap 

300# # between zones) - is this worthwhile? 

301# @raise RangeError: If B{C{easting}} or B{C{northing}} outside 

302# the valid UTM range. 

303# if 120e3 > e or e > 880e3: 

304# raise RangeError(easting=easting) 

305# if 0 > n or n > _FalseNorthing: 

306# raise RangeError(northing=northing) 

307 

308 self._hemisphere = h 

309 UtmUpsBase.__init__(self, e, n, band=B, datum=datum, falsed=falsed, 

310 gamma=gamma, scale=scale, **convergence) 

311 

312 def __eq__(self, other): 

313 return isinstance(other, Utm) and other.zone == self.zone \ 

314 and other.hemisphere == self.hemisphere \ 

315 and other.easting == self.easting \ 

316 and other.northing == self.northing \ 

317 and other.band == self.band \ 

318 and other.datum == self.datum 

319 

320 def __repr__(self): 

321 return self.toRepr(B=True) 

322 

323 def __str__(self): 

324 return self.toStr() 

325 

326 def _xcopy2(self, Xtm, name=NN): 

327 '''(INTERNAL) Make copy as an B{C{Xtm}} instance. 

328 

329 @arg Xtm: Class to return the copy (C{Xtm=Etm}, C{Xtm=Utm} or 

330 C{self.classof}). 

331 ''' 

332 return Xtm(self.zone, self.hemisphere, self.easting, self.northing, 

333 band=self.band, datum=self.datum, falsed=self.falsed, 

334 gamma=self.gamma, scale=self.scale, name=name or self.name) 

335 

336 @property_doc_(''' the I{latitudinal} band.''') 

337 def band(self): 

338 '''Get the I{latitudinal} band (C{'C'|..|'X'}). 

339 ''' 

340 if not self._band: 

341 self._toLLEB() 

342 return self._band 

343 

344 @band.setter # PYCHOK setter! 

345 def band(self, band): 

346 '''Set or reset the I{latitudinal} band letter (C{'C'|..|'X'}) 

347 or C{None} or C{""} to reset. 

348 

349 @raise TypeError: Invalid B{C{band}}. 

350 

351 @raise ValueError: Invalid B{C{band}}. 

352 ''' 

353 self._band1(band) 

354 

355 @Property_RO 

356 def _etm(self): 

357 '''(INTERNAL) Cache for method L{toEtm}. 

358 ''' 

359 return self._xcopy2(_MODS.etm.Etm) 

360 

361 @Property_RO 

362 def falsed2(self): 

363 '''Get the easting and northing falsing (L{EasNor2Tuple}C{(easting, northing)}). 

364 ''' 

365 e = n = 0 

366 if self.falsed: 

367 e = _FalseEasting # relative to central meridian 

368 if self.hemisphere == _S_: # relative to equator 

369 n = _FalseNorthing 

370 return EasNor2Tuple(e, n) 

371 

372 def parse(self, strUTM, name=NN): 

373 '''Parse a string to a similar L{Utm} instance. 

374 

375 @arg strUTM: The UTM coordinate (C{str}), 

376 see function L{parseUTM5}. 

377 @kwarg name: Optional instance name (C{str}), 

378 overriding this name. 

379 

380 @return: The similar instance (L{Utm}). 

381 

382 @raise UTMError: Invalid B{C{strUTM}}. 

383 

384 @see: Functions L{pygeodesy.parseUPS5} and L{pygeodesy.parseUTMUPS5}. 

385 ''' 

386 return parseUTM5(strUTM, datum=self.datum, Utm=self.classof, 

387 name=name or self.name) 

388 

389 @deprecated_method 

390 def parseUTM(self, strUTM): # PYCHOK no cover 

391 '''DEPRECATED, use method L{Utm.parse}.''' 

392 return self.parse(strUTM) 

393 

394 @Property_RO 

395 def pole(self): 

396 '''Get the top center of (stereographic) projection, C{""} always. 

397 ''' 

398 return NN # N/A for UTM 

399 

400 def toEtm(self): 

401 '''Copy this UTM to an ETM coordinate. 

402 

403 @return: The ETM coordinate (L{Etm}). 

404 ''' 

405 return self._etm 

406 

407 def toLatLon(self, LatLon=None, eps=EPS, unfalse=True, **LatLon_kwds): 

408 '''Convert this UTM coordinate to an (ellipsoidal) geodetic point. 

409 

410 @kwarg LatLon: Optional, ellipsoidal class to return the geodetic 

411 point (C{LatLon}) or C{None}. 

412 @kwarg eps: Optional convergence limit, L{EPS} or above (C{float}). 

413 @kwarg unfalse: Unfalse B{C{easting}} and B{C{northing}} 

414 if falsed (C{bool}). 

415 @kwarg LatLon_kwds: Optional, additional B{C{LatLon}} keyword 

416 arguments, ignored if C{B{LatLon} is None}. 

417 

418 @return: This UTM as (B{C{LatLon}}) or if B{C{LatLon}} is 

419 C{None}, as L{LatLonDatum5Tuple}C{(lat, lon, datum, 

420 gamma, scale)}. 

421 

422 @raise TypeError: Invalid B{C{datum}} or B{C{LatLon}} is not ellipsoidal. 

423 

424 @raise UTMError: Invalid meridional radius or H-value. 

425 

426 ''' 

427 if eps < EPS: 

428 eps = EPS # less doesn't converge 

429 

430 if self._latlon and self._latlon._toLLEB_args == (unfalse, eps): 

431 return self._latlon5(LatLon) 

432 else: 

433 self._toLLEB(unfalse=unfalse, eps=eps) 

434 return self._latlon5(LatLon, **LatLon_kwds) 

435 

436 def _toLLEB(self, unfalse=True, eps=EPS): # PYCHOK signature 

437 '''(INTERNAL) Compute (ellipsoidal) lat- and longitude. 

438 ''' 

439 x, y = self.eastingnorthing2(falsed=not unfalse) 

440 

441 E = self.datum.ellipsoid 

442 # from Karney 2011 Eq 15-22, 36 

443 A0 = self.scale0 * E.A 

444 if A0 < EPS0: 

445 raise self._Error(meridional=A0) 

446 x = x / A0 # /= chokes PyChecker 

447 y = y / A0 

448 K = _Kseries(E.BetaKs, x, y) # Krüger series 

449 x = neg(K.xs(-x)) # η' eta 

450 y = neg(K.ys(-y)) # ξ' ksi 

451 

452 sy, cy = sincos2(y) 

453 shx = sinh(x) 

454 H = hypot(shx, cy) 

455 if H < EPS0: 

456 raise self._Error(H=H) 

457 

458 T = sy / H # τʹ == τ0 

459 p = _0_0 # previous d 

460 e = _0_0001 * eps 

461 for T, i, d in E._es_tauf3(T, T): # 4-5 trips 

462 # d may toggle on +/-1.12e-16 or +/-4.47e-16, 

463 # see the references at C{Ellipsoid.es_tauf} 

464 if fabs(d) < eps or fabs(d + p) < e: 

465 break 

466 p = d 

467 else: 

468 t = unstr(self.toLatLon, eps=eps, unfalse=unfalse) 

469 raise self._Error(Fmt.no_convergence(d, eps), txt=t) 

470 

471 a = atan1(T) # phi, lat 

472 b = atan2(shx, cy) 

473 if unfalse and self.falsed: 

474 b += radians(_cmlon(self.zone)) 

475 ll = _LLEB(degrees90(a), degrees180(b), datum=self.datum, name=self.name) 

476 

477 # gamma and scale: Karney 2011 Eq 26, 27 and 28 

478 p = neg(K.ps(-1)) 

479 q = K.qs(0) 

480 s = hypot(p, q) * E.a / A0 

481 ll._gamma = degrees(atan1(tan(y) * tanh(x)) + atan2(q, p)) 

482 ll._scale = (E.e2s(sin(a)) * hypot1(T) * H / s) if s else s # INF? 

483 ll._iteration = i 

484 self._latlon5args(ll, _toBand, unfalse, eps) 

485 

486 def toRepr(self, prec=0, fmt=Fmt.SQUARE, sep=_COMMASPACE_, B=False, cs=False, **unused): # PYCHOK expected 

487 '''Return a string representation of this UTM coordinate. 

488 

489 Note that UTM coordinates are rounded, not truncated (unlike 

490 MGRS grid references). 

491 

492 @kwarg prec: Number of (decimal) digits, unstripped (C{int}). 

493 @kwarg fmt: Enclosing backets format (C{str}). 

494 @kwarg sep: Optional separator between name:value pairs (C{str}). 

495 @kwarg B: Optionally, include latitudinal band (C{bool}). 

496 @kwarg cs: Optionally, include meridian convergence and grid 

497 scale factor (C{bool} or non-zero C{int} to specify 

498 the precison like B{C{prec}}). 

499 

500 @return: This UTM as a string C{"[Z:09[band], H:N|S, E:meter, 

501 N:meter]"} plus C{", C:degrees, S:float"} if B{C{cs}} is 

502 C{True} (C{str}). 

503 ''' 

504 return self._toRepr(fmt, B, cs, prec, sep) 

505 

506 def toStr(self, prec=0, sep=_SPACE_, B=False, cs=False): # PYCHOK expected 

507 '''Return a string representation of this UTM coordinate. 

508 

509 To distinguish from MGRS grid zone designators, a space is 

510 left between the zone and the hemisphere. 

511 

512 Note that UTM coordinates are rounded, not truncated (unlike 

513 MGRS grid references). 

514 

515 @kwarg prec: Number of (decimal) digits, unstripped (C{int}). 

516 @kwarg sep: Optional separator to join (C{str}) or C{None} 

517 to return an unjoined C{tuple} of C{str}s. 

518 @kwarg B: Optionally, include latitudinal band (C{bool}). 

519 @kwarg cs: Optionally, include meridian convergence and grid 

520 scale factor (C{bool} or non-zero C{int} to specify 

521 the precison like B{C{prec}}). 

522 

523 @return: This UTM as a string with C{zone[band], hemisphere, 

524 easting, northing, [convergence, scale]} in 

525 C{"00 N|S meter meter"} plus C{" degrees float"} if 

526 B{C{cs}} is C{True} (C{str}). 

527 ''' 

528 return self._toStr(self.hemisphere, B, cs, prec, sep) 

529 

530 def toUps(self, pole=NN, eps=EPS, falsed=True, **unused): 

531 '''Convert this UTM coordinate to a UPS coordinate. 

532 

533 @kwarg pole: Optional top/center of the UPS projection, 

534 (C{str}, 'N[orth]'|'S[outh]'). 

535 @kwarg eps: Optional convergence limit, L{EPS} or above 

536 (C{float}), see method L{Utm.toLatLon}. 

537 @kwarg falsed: False both easting and northing (C{bool}). 

538 

539 @return: The UPS coordinate (L{Ups}). 

540 ''' 

541 u = self._ups 

542 if u is None or u.pole != (pole or u.pole) or falsed != bool(u.falsed): 

543 ll = self.toLatLon(LatLon=_LLEB, eps=eps, unfalse=True) 

544 ups = _MODS.ups 

545 self._ups = u = ups.toUps8(ll, Ups=ups.Ups, falsed=falsed, 

546 name=self.name, pole=pole) 

547 return u 

548 

549 def toUtm(self, zone, eps=EPS, falsed=True, **unused): 

550 '''Convert this UTM coordinate to a different zone. 

551 

552 @arg zone: New UTM zone (C{int}). 

553 @kwarg eps: Optional convergence limit, L{EPS} or above 

554 (C{float}), see method L{Utm.toLatLon}. 

555 @kwarg falsed: False both easting and northing (C{bool}). 

556 

557 @return: The UTM coordinate (L{Utm}). 

558 ''' 

559 if zone == self.zone and falsed == self.falsed: 

560 return self.copy() 

561 elif zone: 

562 u = self._utm 

563 if u is None or u.zone != zone or falsed != u.falsed: 

564 ll = self.toLatLon(LatLon=_LLEB, eps=eps, unfalse=True) 

565 self._utm = u = toUtm8(ll, Utm=self.classof, falsed=falsed, 

566 name=self.name, zone=zone) 

567 return u 

568 raise self._Error(zone=zone) 

569 

570 @Property_RO 

571 def zone(self): 

572 '''Get the (longitudinal) zone (C{int}, 1..60). 

573 ''' 

574 return self._zone 

575 

576 

577def _parseUTM5(strUTM, datum, Xtm, falsed, Error=UTMError, name=NN): # imported by .etm 

578 '''(INTERNAL) Parse a string representing a UTM coordinate, 

579 consisting of C{"zone[band] hemisphere easting northing"}, 

580 see L{pygeodesy.parseETM5} and L{parseUTM5}. 

581 ''' 

582 z, h, e, n, B = _parseUTMUPS5(strUTM, None, Error=Error) 

583 if _UTM_ZONE_MIN > z or z > _UTM_ZONE_MAX or (B and B not in _Bands): 

584 raise Error(strUTM=strUTM, zone=z, band=B) 

585 

586 if Xtm is None: 

587 r = UtmUps5Tuple(z, h, e, n, B, Error=Error, name=name) 

588 else: 

589 r = Xtm(z, h, e, n, band=B, datum=datum, falsed=falsed) 

590 if name: 

591 r = _xnamed(r, name, force=True) 

592 return r 

593 

594 

595def parseUTM5(strUTM, datum=_WGS84, Utm=Utm, falsed=True, name=NN): 

596 '''Parse a string representing a UTM coordinate, consisting 

597 of C{"zone[band] hemisphere easting northing"}. 

598 

599 @arg strUTM: A UTM coordinate (C{str}). 

600 @kwarg datum: Optional datum to use (L{Datum}, L{Ellipsoid}, 

601 L{Ellipsoid2} or L{a_f2Tuple}). 

602 @kwarg Utm: Optional class to return the UTM coordinate 

603 (L{Utm}) or C{None}. 

604 @kwarg falsed: Both easting and northing are falsed (C{bool}). 

605 @kwarg name: Optional B{C{Utm}} name (C{str}). 

606 

607 @return: The UTM coordinate (B{C{Utm}}) or if B{C{Utm}} 

608 is C{None}, a L{UtmUps5Tuple}C{(zone, hemipole, 

609 easting, northing, band)}. The C{hemipole} is 

610 the C{'N'|'S'} hemisphere. 

611 

612 @raise UTMError: Invalid B{C{strUTM}}. 

613 

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

615 ''' 

616 return _parseUTM5(strUTM, datum, Utm, falsed, name=name) 

617 

618 

619def toUtm8(latlon, lon=None, datum=None, Utm=Utm, falsed=True, 

620 name=NN, strict=True, 

621 zone=None, **cmoff): 

622 '''Convert a lat-/longitude point to a UTM coordinate. 

623 

624 @arg latlon: Latitude (C{degrees}) or an (ellipsoidal) 

625 geodetic C{LatLon} point. 

626 @kwarg lon: Optional longitude (C{degrees}) or C{None}. 

627 @kwarg datum: Optional datum for this UTM coordinate, 

628 overriding B{C{latlon}}'s datum (L{Datum}, 

629 L{Ellipsoid}, L{Ellipsoid2} or L{a_f2Tuple}). 

630 @kwarg Utm: Optional class to return the UTM coordinate 

631 (L{Utm}) or C{None}. 

632 @kwarg falsed: False both easting and northing (C{bool}). 

633 @kwarg name: Optional B{C{Utm}} name (C{str}). 

634 @kwarg strict: Restrict B{C{lat}} to UTM ranges (C{bool}). 

635 @kwarg zone: Optional UTM zone to enforce (C{int} or C{str}). 

636 @kwarg cmoff: DEPRECATED, use B{C{falsed}}. Offset longitude 

637 from the zone's central meridian (C{bool}). 

638 

639 @return: The UTM coordinate (B{C{Utm}}) or if B{C{Utm}} is 

640 C{None} or not B{C{falsed}}, a L{UtmUps8Tuple}C{(zone, 

641 hemipole, easting, northing, band, datum, gamma, 

642 scale)}. The C{hemipole} is the C{'N'|'S'} hemisphere. 

643 

644 @raise RangeError: If B{C{lat}} outside the valid UTM bands or if 

645 B{C{lat}} or B{C{lon}} outside the valid range 

646 and L{pygeodesy.rangerrors} set to C{True}. 

647 

648 @raise TypeError: Invalid B{C{datum}} or B{C{latlon}} not ellipsoidal. 

649 

650 @raise UTMError: Invalid B{C{zone}}. 

651 

652 @raise ValueError: If B{C{lon}} value is missing or if 

653 B{C{latlon}} is invalid. 

654 

655 @note: Implements Karney’s method, using 8-th order Krüger series, 

656 giving results accurate to 5 nm (or better) for distances 

657 up to 3,900 Km from the central meridian. 

658 ''' 

659 z, B, lat, lon, d, f, name = _to7zBlldfn(latlon, lon, datum, 

660 falsed, name, zone, 

661 strict, UTMError, **cmoff) 

662 d = _ellipsoidal_datum(d, name=name) 

663 E = d.ellipsoid 

664 

665 a, b = radians(lat), radians(lon) 

666 # easting, northing: Karney 2011 Eq 7-14, 29, 35 

667 sb, cb = sincos2(b) 

668 

669 T = tan(a) 

670 T12 = hypot1(T) 

671 S = sinh(E.e * atanh(E.e * T / T12)) 

672 

673 T_ = T * hypot1(S) - S * T12 

674 H = hypot(T_, cb) 

675 

676 y = atan2(T_, cb) # ξ' ksi 

677 x = asinh(sb / H) # η' eta 

678 

679 A0 = E.A * getattr(Utm, _under(_scale0_), _K0_UTM) # Utm is class or None 

680 

681 K = _Kseries(E.AlphaKs, x, y) # Krüger series 

682 y = K.ys(y) * A0 # ξ 

683 x = K.xs(x) * A0 # η 

684 

685 # convergence: Karney 2011 Eq 23, 24 

686 p_ = K.ps(1) 

687 q_ = K.qs(0) 

688 g = degrees(atan2(T_ * tan(b), hypot1(T_)) + atan2(q_, p_)) 

689 # scale: Karney 2011 Eq 25 

690 k = E.e2s(sin(a)) * T12 / H * (A0 / E.a * hypot(p_, q_)) 

691 

692 return _toXtm8(Utm, z, lat, x, y, 

693 B, d, g, k, f, name, latlon, EPS) 

694 

695 

696def _toXtm8(Xtm, z, lat, x, y, B, d, g, k, f, # PYCHOK 13+ args 

697 name, latlon, eps, Error=UTMError): 

698 '''(INTERNAL) Helper for methods L{toEtm8} and L{toUtm8}. 

699 ''' 

700 h = _hemi(lat) 

701 if f: 

702 x, y = _false2(x, y, h) 

703 if Xtm is None: # DEPRECATED 

704 r = UtmUps8Tuple(z, h, x, y, B, d, g, k, Error=Error, name=name) 

705 else: 

706 r = _xnamed(Xtm(z, h, x, y, band=B, datum=d, falsed=f, 

707 gamma=g, scale=k), name) 

708 if isinstance(latlon, _LLEB) and d is latlon.datum: # see ups.toUtm8 

709 r._latlon5args(latlon, _toBand, f, eps) # XXX weakref(latlon)? 

710 latlon._gamma = g 

711 latlon._scale = k 

712 elif not r._band: 

713 r._band = _toBand(lat) 

714 return r 

715 

716 

717def utmZoneBand5(lat, lon, cmoff=False, name=NN): 

718 '''Return the UTM zone number, Band letter, hemisphere and 

719 (clipped) lat- and longitude for a given location. 

720 

721 @arg lat: Latitude in degrees (C{scalar} or C{str}). 

722 @arg lon: Longitude in degrees (C{scalar} or C{str}). 

723 @kwarg cmoff: Offset longitude from the zone's central 

724 meridian (C{bool}). 

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

726 

727 @return: A L{UtmUpsLatLon5Tuple}C{(zone, band, hemipole, 

728 lat, lon)} where C{hemipole} is the C{'N'|'S'} 

729 UTM hemisphere. 

730 

731 @raise RangeError: If B{C{lat}} outside the valid UTM bands or if 

732 B{C{lat}} or B{C{lon}} outside the valid range 

733 and L{pygeodesy.rangerrors} set to C{True}. 

734 

735 @raise ValueError: Invalid B{C{lat}} or B{C{lon}}. 

736 ''' 

737 lat, lon = parseDMS2(lat, lon) 

738 z, B, lat, lon = _to4zBll(lat, lon, cmoff=cmoff) 

739 return UtmUpsLatLon5Tuple(z, B, _hemi(lat), lat, lon, name=name) 

740 

741# **) MIT License 

742# 

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

744# 

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

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

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

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

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

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

751# 

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

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

754# 

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

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

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

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

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

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

761# OTHER DEALINGS IN THE SOFTWARE.