Coverage for pygeodesy/utm.py: 97%

264 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-05-25 12:04 -0400

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, _under 

39from pygeodesy.dms import degDMS, parseDMS2 

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

41 _xkwds_get, _xkwds_pop2 

42from pygeodesy.fmath import fdot3, hypot, hypot1, _operator 

43# from pygeodesy.internals import _under # from .datums 

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

45 _NS_, _outside_, _range_, _S_, _scale0_, \ 

46 _SPACE_, _UTM_, _V_, _X_, _zone_ 

47# from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS # from .named 

48from pygeodesy.named import _name__, _name2__, _ALL_LAZY, _MODS 

49from pygeodesy.namedTuples import EasNor2Tuple, UtmUps5Tuple, \ 

50 UtmUps8Tuple, UtmUpsLatLon5Tuple 

51from pygeodesy.props import deprecated_method, property_doc_, \ 

52 Property_RO 

53from pygeodesy.streprs import Fmt, unstr 

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

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

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

57 _to3zBhp, _to3zll, _UPS_LATS, _UPS_ZONE, \ 

58 _UTM_LAT_MAX, _UTM_ZONE_MAX, \ 

59 _UTM_LAT_MIN, _UTM_ZONE_MIN, \ 

60 _UTM_ZONE_OFF_MAX, UtmUpsBase 

61 

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

63 radians, sin, sinh, tan, tanh 

64# import operator as _operator # from .fmath 

65 

66__all__ = _ALL_LAZY.utm 

67__version__ = '24.05.21' 

68 

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

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

71_bandLat_ = 'bandLat' 

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

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

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

75 

76 

77class UTMError(_ValueError): 

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

79 ''' 

80 pass 

81 

82 

83class _Kseries(object): 

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

85 

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

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

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

89 ''' 

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

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

92 

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

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

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

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

97 ''' 

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

99 _m2, _x = map2, _operator.mul 

100 

101 self._ab = AB 

102 self._pq = _m2(_x, j2, AB) 

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

104 

105 x2 = _m2(_x, j2, (x,) * n) 

106 self._chx = _m2(cosh, x2) 

107 self._shx = _m2(sinh, x2) 

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

109 

110 y2 = _m2(_x, j2, (y,) * n) 

111 self._cy = _m2(cos, y2) 

112 self._sy = _m2(sin, y2) 

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

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

115 

116 def xs(self, x0): 

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

118 ''' 

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

120 

121 def ys(self, y0): 

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

123 ''' 

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

125 

126 def ps(self, p0): 

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

128 ''' 

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

130 

131 def qs(self, q0): 

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

133 ''' 

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

135 

136 

137def _cmlon(zone): 

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

139 ''' 

140 return (zone * 6) - 183 

141 

142 

143def _false2(e, n, h): 

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

145 ''' 

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

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

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

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

150 if h == _S_: 

151 n += _FalseNorthing # make n relative to equator 

152 return e, n 

153 

154 

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

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

157 ''' 

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

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

160 elif _xkwds_get(strict_Error, strict=True): 

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

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

163 E = _xkwds_get(strict_Error, Error=RangeError) 

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

165 else: 

166 return NN # None 

167 

168 

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

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

171 

172 @arg zone: Zone number or string. 

173 @arg band: Band letter. 

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

175 

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

177 ''' 

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

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

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

181 raise Error(zone=zone) 

182 

183 b = None 

184 if B: 

185 if z == _UPS_ZONE: # polar 

186 try: 

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

188 except KeyError: 

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

190 else: # UTM 

191 b = _Bands.find(B) 

192 if b < 0: 

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

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

195 B = Band(B) 

196 elif Error is not UTMError: 

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

198 

199 return Zone(z), B, b 

200 

201 

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

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

204 

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

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

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

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

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

210 

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

212 ''' 

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

214 

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

216 if fabs(x) > _UTM_ZONE_OFF_MAX: 

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

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

219 

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

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

222 x = _SvalbardXzone.get(z, None) 

223 if x: # Svalbard/Spitsbergen archipelago 

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

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

226 z += 1 # SouthWestern Norway 

227 

228 if cmoff: # lon off central meridian 

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

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

231 

232 

233def _to7zBlldfn(latlon, lon, datum, falsed, zone, strict, Error, **name_cmoff): 

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

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

236 ''' 

237 f, n = _xkwds_pop2(name_cmoff, cmoff=falsed) # DEPRECATED 

238 n = _name__(**n) # _UnexpectedError 

239 lat, lon, d, n = _to4lldn(latlon, lon, datum, n) 

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

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

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

243 if r != z: 

244 if not _UTM_ZONE_MIN <= r <= _UTM_ZONE_MAX: 

245 raise Error(zone=zone) 

246 if f: # re-offset from central meridian 

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

248 z = r 

249 return z, B, lat, lon, d, f, n 

250 

251 

252class Utm(UtmUpsBase): 

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

254 ''' 

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

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

257 _Error = UTMError # or etm.ETMError 

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

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

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

261 

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

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

264 gamma=None, scale=None, **name_convergence): 

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

266 

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

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

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

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

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

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

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

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

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

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

277 falsed (C{bool}). 

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

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

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

281 @kwarg name_convergence: Optional C{B{name}=NN} (C{str}) and DEPRECATED 

282 C{B{convergence}=None}, instead use C{B{gamma}=None}. 

283 

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

285 

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

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

288 B{C{scale}}. 

289 ''' 

290 c = name_convergence 

291 if c: 

292 n, c = _name2__(**c) 

293 if n: 

294 self.name = n 

295 

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

297 

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

299 if h not in _NS_: 

300 raise self._Error(hemisphere=hemisphere) 

301 

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

303# if not falsed: 

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

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

306# # between zones) - is this worthwhile? 

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

308# the valid UTM range. 

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

310# raise RangeError(easting=easting) 

311# if 0 > n or n > _FalseNorthing: 

312# raise RangeError(northing=northing) 

313 

314 self._hemisphere = h 

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

316 gamma=gamma, scale=scale, **c) 

317 

318 def __eq__(self, other): 

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

320 and other.hemisphere == self.hemisphere \ 

321 and other.easting == self.easting \ 

322 and other.northing == self.northing \ 

323 and other.band == self.band \ 

324 and other.datum == self.datum 

325 

326 def __repr__(self): 

327 return self.toRepr(B=True) 

328 

329 def __str__(self): 

330 return self.toStr() 

331 

332 def _xcopy2(self, Xtm, **name): 

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

334 

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

336 C{self.classof}). 

337 ''' 

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

339 band=self.band, datum=self.datum, falsed=self.falsed, 

340 gamma=self.gamma, scale=self.scale, name=self._name__(name)) 

341 

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

343 def band(self): 

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

345 ''' 

346 if not self._band: 

347 self._toLLEB() 

348 return self._band 

349 

350 @band.setter # PYCHOK setter! 

351 def band(self, band): 

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

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

354 

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

356 

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

358 ''' 

359 self._band1(band) 

360 

361 @Property_RO 

362 def _etm(self): 

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

364 ''' 

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

366 

367 @Property_RO 

368 def falsed2(self): 

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

370 ''' 

371 e = n = 0 

372 if self.falsed: 

373 e = _FalseEasting # relative to central meridian 

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

375 n = _FalseNorthing 

376 return EasNor2Tuple(e, n) 

377 

378 def parse(self, strUTM, **name): 

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

380 

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

382 see function L{parseUTM5}. 

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

384 overriding this name. 

385 

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

387 

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

389 

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

391 ''' 

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

393 name=self._name__(name)) 

394 

395 @deprecated_method 

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

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

398 return self.parse(strUTM) 

399 

400 @Property_RO 

401 def pole(self): 

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

403 ''' 

404 return NN # N/A for UTM 

405 

406 def toEtm(self): 

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

408 

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

410 ''' 

411 return self._etm 

412 

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

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

415 

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

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

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

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

420 if falsed (C{bool}). 

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

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

423 

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

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

426 gamma, scale)}. 

427 

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

429 

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

431 

432 ''' 

433 if eps < EPS: 

434 eps = EPS # less doesn't converge 

435 

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

437 return self._latlon5(LatLon) 

438 else: 

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

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

441 

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

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

444 ''' 

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

446 

447 E = self.datum.ellipsoid 

448 # from Karney 2011 Eq 15-22, 36 

449 A0 = self.scale0 * E.A 

450 if A0 < EPS0: 

451 raise self._Error(meridional=A0) 

452 x = x / A0 # /= chokes PyChecker 

453 y = y / A0 

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

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

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

457 

458 sy, cy = sincos2(y) 

459 shx = sinh(x) 

460 H = hypot(shx, cy) 

461 if H < EPS0: 

462 raise self._Error(H=H) 

463 

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

465 p = _0_0 # previous d 

466 e = _0_0001 * eps 

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

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

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

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

471 break 

472 p = d 

473 else: 

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

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

476 

477 a = atan1(T) # phi, lat 

478 b = atan2(shx, cy) 

479 if unfalse and self.falsed: 

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

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

482 

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

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

485 q = K.qs(0) 

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

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

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

489 ll._iteration = i 

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

491 

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

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

494 

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

496 MGRS grid references). 

497 

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

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

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

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

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

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

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

505 

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

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

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

509 ''' 

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

511 

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

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

514 

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

516 left between the zone and the hemisphere. 

517 

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

519 MGRS grid references). 

520 

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

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

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

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

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

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

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

528 

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

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

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

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

533 ''' 

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

535 

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

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

538 

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

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

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

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

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

544 

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

546 ''' 

547 u = self._ups 

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

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

550 ups = _MODS.ups 

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

552 name=self.name, pole=pole) 

553 return u 

554 

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

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

557 

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

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

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

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

562 

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

564 ''' 

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

566 return self.copy() 

567 elif zone: 

568 u = self._utm 

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

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

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

572 name=self.name, zone=zone) 

573 return u 

574 raise self._Error(zone=zone) 

575 

576 @Property_RO 

577 def zone(self): 

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

579 ''' 

580 return self._zone 

581 

582 

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

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

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

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

587 ''' 

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

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

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

591 

592 return UtmUps5Tuple(z, h, e, n, B, Error=Error, **name) if Xtm is None else \ 

593 Xtm(z, h, e, n, band=B, datum=datum, falsed=falsed, **name) 

594 

595 

596def parseUTM5(strUTM, datum=_WGS84, Utm=Utm, falsed=True, **name): 

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

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

599 

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

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

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

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

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

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

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

607 

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

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

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

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

612 

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

614 

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

616 ''' 

617 return _parseUTM5(strUTM, datum, Utm, falsed, **name) 

618 

619 

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

621 strict=True, zone=None, **name_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}), required 

627 if B{C{latlon}} is in C{degrees}. 

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

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

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

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

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

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

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 name_cmoff: Optional B{C{Utm}} C{B{name}=NN} (C{str}) 

637 and DEPRECATED C{B{cmoff}=True} to offset longitude 

638 from the zone's central meridian (C{bool}), instead 

639 use C{B{falsed}=True}. 

640 

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

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

643 hemipole, easting, northing, band, datum, gamma, 

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

645 

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

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

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

649 

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

651 

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

653 

654 @raise ValueError: If B{C{lon}} value is missing or B{C{latlon}} 

655 is invalid. 

656 

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

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

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

660 ''' 

661 z, B, lat, lon, d, f, n = _to7zBlldfn(latlon, lon, datum, 

662 falsed, zone, strict, 

663 UTMError, **name_cmoff) 

664 d = _ellipsoidal_datum(d, name=n) 

665 E = d.ellipsoid 

666 

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

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

669 sb, cb = sincos2(b) 

670 

671 T = tan(a) 

672 T12 = hypot1(T) 

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

674 

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

676 H = hypot(T_, cb) 

677 

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

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

680 

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

682 

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

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

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

686 

687 # convergence: Karney 2011 Eq 23, 24 

688 p_ = K.ps(1) 

689 q_ = K.qs(0) 

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

691 # scale: Karney 2011 Eq 25 

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

693 

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

695 B, d, g, k, f, n, latlon, EPS) 

696 

697 

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

699 n, latlon, eps, Error=UTMError): 

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

701 ''' 

702 h = _hemi(lat) 

703 if f: 

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

705 if Xtm is None: # DEPRECATED 

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

707 else: 

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

709 gamma=g, scale=k, name=n) 

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

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

712 latlon._gamma = g 

713 latlon._scale = k 

714 elif not r._band: 

715 r._band = _toBand(lat) 

716 return r 

717 

718 

719def utmZoneBand5(lat, lon, cmoff=False, **name): 

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

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

722 

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

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

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

726 meridian (C{bool}). 

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

728 

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

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

731 UTM hemisphere. 

732 

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

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

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

736 

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

738 ''' 

739 lat, lon = parseDMS2(lat, lon) 

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

741 return UtmUpsLatLon5Tuple(z, B, _hemi(lat), lat, lon, **name) 

742 

743# **) MIT License 

744# 

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

746# 

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

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

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

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

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

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

753# 

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

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

756# 

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

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

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

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

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

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

763# OTHER DEALINGS IN THE SOFTWARE.