1

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

3

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

5

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

7 L{utmZoneBand5}.

8

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

10 an ellipsoidal earth model, transcoded from JavaScript originals by

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

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

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

14

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

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

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

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

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

20 measured in metres.

21

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

23 accuracy 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

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

27 classGeographicLib_1_1TransverseMercator.html>}.

28

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

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

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

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

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

34'''

35

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

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

38 from pygeodesy.datums import _ellipsoidal_datum, _WGS84

39 from pygeodesy.dms import degDMS, parseDMS2

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

41 _xkwds_get

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

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

44 from 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

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

49 from pygeodesy.namedTuples import EasNor2Tuple, UtmUps5Tuple, \

50 UtmUps8Tuple, UtmUpsLatLon5Tuple

51 from pygeodesy.props import deprecated_method, property_doc_, \

52 Property_RO

53 from pygeodesy.streprs import Fmt, unstr

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

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

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

57 _to3zBhp, _to3zll, _UPS_LATS, _UPS_ZONE, \

58 _UTM_LAT_MAX, _UTM_ZONE_MAX, _under, \

59 _UTM_LAT_MIN, _UTM_ZONE_MIN, _xnamed, \

60 _UTM_ZONE_OFF_MAX, UtmUpsBase

61

62 from 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.02.29'

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

77 class UTMError(_ValueError):

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

79 '''

80 pass

81

82

83 class _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

137 def _cmlon(zone):

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

139 '''

140 return (zone * 6) - 183

141

142

143 def _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

155 def _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

169 def _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

202 def _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

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

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

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

236 '''

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

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

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

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

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

242 if r != z:

243 if not _UTM_ZONE_MIN <= r <= _UTM_ZONE_MAX:

244 raise Error(zone=zone)

245 if f: # re-offset from central meridian

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

247 z = r

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

249

250

251 class Utm(UtmUpsBase):

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

253 '''

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

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

256 _Error = UTMError # or etm.ETMError

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

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

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

260

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

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

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

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

265

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

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

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

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

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

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

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

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

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

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

276 falsed (C{bool}).

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

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

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

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

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

282

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

284

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

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

287 B{C{scale}}.

288 '''

289 if name:

290 self.name = name

291

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

293

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

295 if h not in _NS_:

296 raise self._Error(hemisphere=hemisphere)

297

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

299# if not falsed:

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

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

302# # between zones) - is this worthwhile?

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

304# the valid UTM range.

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

306# raise RangeError(easting=easting)

307# if 0 > n or n > _FalseNorthing:

308# raise RangeError(northing=northing)

309

310 self._hemisphere = h

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

312 gamma=gamma, scale=scale, **convergence)

313

314 def __eq__(self, other):

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

316 and other.hemisphere == self.hemisphere \

317 and other.easting == self.easting \

318 and other.northing == self.northing \

319 and other.band == self.band \

320 and other.datum == self.datum

321

322 def __repr__(self):

323 return self.toRepr(B=True)

324

325 def __str__(self):

326 return self.toStr()

327

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

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

330

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

332 C{self.classof}).

333 '''

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

335 band=self.band, datum=self.datum, falsed=self.falsed,

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

337

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

339 def band(self):

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

341 '''

342 if not self._band:

343 self._toLLEB()

344 return self._band

345

346 @band.setter # PYCHOK setter!

347 def band(self, band):

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

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

350

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

352

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

354 '''

355 self._band1(band)

356

357 @Property_RO

358 def _etm(self):

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

360 '''

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

362

363 @Property_RO

364 def falsed2(self):

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

366 '''

367 e = n = 0

368 if self.falsed:

369 e = _FalseEasting # relative to central meridian

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

371 n = _FalseNorthing

372 return EasNor2Tuple(e, n)

373

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

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

376

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

378 see function L{parseUTM5}.

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

380 overriding this name.

381

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

383

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

385

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

387 '''

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

389 name=name or self.name)

390

391 @deprecated_method

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

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

394 return self.parse(strUTM)

395

396 @Property_RO

397 def pole(self):

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

399 '''

400 return NN # N/A for UTM

401

402 def toEtm(self):

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

404

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

406 '''

407 return self._etm

408

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

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

411

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

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

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

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

416 if falsed (C{bool}).

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

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

419

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

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

422 gamma, scale)}.

423

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

425

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

427

428 '''

429 if eps < EPS:

430 eps = EPS # less doesn't converge

431

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

433 return self._latlon5(LatLon)

434 else:

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

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

437

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

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

440 '''

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

442

443 E = self.datum.ellipsoid

444 # from Karney 2011 Eq 15-22, 36

445 A0 = self.scale0 * E.A

446 if A0 < EPS0:

447 raise self._Error(meridional=A0)

448 x = x / A0 # /= chokes PyChecker

449 y = y / A0

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

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

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

453

454 sy, cy = sincos2(y)

455 shx = sinh(x)

456 H = hypot(shx, cy)

457 if H < EPS0:

458 raise self._Error(H=H)

459

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

461 p = _0_0 # previous d

462 e = _0_0001 * eps

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

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

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

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

467 break

468 p = d

469 else:

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

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

472

473 a = atan1(T) # phi, lat

474 b = atan2(shx, cy)

475 if unfalse and self.falsed:

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

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

478

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

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

481 q = K.qs(0)

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

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

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

485 ll._iteration = i

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

487

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

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

490

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

492 MGRS grid references).

493

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

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

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

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

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

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

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

501

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

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

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

505 '''

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

507

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

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

510

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

512 left between the zone and the hemisphere.

513

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

515 MGRS grid references).

516

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

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

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

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

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

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

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

524

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

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

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

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

529 '''

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

531

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

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

534

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

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

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

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

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

540

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

542 '''

543 u = self._ups

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

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

546 ups = _MODS.ups

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

548 name=self.name, pole=pole)

549 return u

550

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

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

553

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

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

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

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

558

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

560 '''

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

562 return self.copy()

563 elif zone:

564 u = self._utm

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

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

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

568 name=self.name, zone=zone)

569 return u

570 raise self._Error(zone=zone)

571

572 @Property_RO

573 def zone(self):

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

575 '''

576 return self._zone

577

578

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

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

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

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

583 '''

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

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

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

587

588 if Xtm is None:

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

590 else:

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

592 if name:

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

594 return r

595

596

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

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

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

600

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

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

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

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

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

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

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

608

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

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

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

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

613

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

615

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

617 '''

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

619

620

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

622 name=NN, strict=True,

623 zone=None, **cmoff):

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

625

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

627 geodetic C{LatLon} point.

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

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

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

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

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

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

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

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

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

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

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

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

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 if

655 B{C{latlon}} 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, name = _to7zBlldfn(latlon, lon, datum,

662 falsed, name, zone,

663 strict, UTMError, **cmoff)

664 d = _ellipsoidal_datum(d, name=name)

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, name, latlon, EPS)

696

697

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

699 name, 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=name)

707 else:

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

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

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

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

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=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.