1

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

3

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

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

6'''

7

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

9 _xinstanceof, _xsubclassof

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

11 from pygeodesy.datums import _ellipsoidal_datum, _WGS84

12 from pygeodesy.dms import degDMS, parseDMS2

13 from pygeodesy.ellipsoidalBase import LatLonEllipsoidalBase as _LLEB

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

15 _xkwds, _xkwds_get, _xkwds_not

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

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

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

19 _scale_, _SPACE_, _Y_, _Z_

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

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

22 from pygeodesy.namedTuples import EasNor2Tuple, LatLonDatum5Tuple

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

24 deprecated_property_RO, Property_RO, property_RO

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

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

27 from pygeodesy.utily import _Wrap, wrap360

28

29__all__ = _ALL_LAZY.utmupsBase

30__version__ = '24.05.13'

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

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

63 '''Return the hemisphere letter.

64

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

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

67

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

69 '''

70 return _NS_[int(lat < N)]

71

72

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

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

75 '''

76 try:

77 # if lon is not None:

78 # raise AttributeError

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

80 _xinstanceof(_LLEB, LatLonDatum5Tuple, latlon=latlon)

81 if wrap:

82 _Wrap.latlon(lat, lon)

83 d = datum or latlon.datum

84 except AttributeError:

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

86 parseDMS2(latlon, lon) # clipped

87 d = datum or _WGS84

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

89

90

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

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

93

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

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

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

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

98 C{ValueError}.

99

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

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

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

103 UTM/UPS bands.

104

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

106 '''

107 try:

108 B, z = band, _UTMUPS_ZONE_INVALID

109 if isscalar(zone):

110 z = int(zone)

111 elif zone and isstr(zone):

112 if zone.isdigit():

113 z = int(zone)

114 elif len(zone) > 1:

115 B = zone[-1:]

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

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

118 B = zone

119 z = _UPS_ZONE

120

121 if _UTMUPS_ZONE_MIN <= z <= _UTMUPS_ZONE_MAX:

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

123 if hp in _NS_ or not hp:

124 z = Zone(z)

125 B = Band(B.upper())

126 if B.isalpha():

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

128 elif not B:

129 return z, B, hp

130

131 raise ValueError # _invalid_

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

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

134

135

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

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

138

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

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

141

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

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

144 '''

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

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

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

148

149

150 class UtmUpsBase(_NamedBase):

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

152 '''

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

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

155 _datum = _WGS84 # L{Datum}

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

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

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

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

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

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

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

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

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

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

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

167

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

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

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

171 '''

172 E = self._Error

173 if not E: # PYCHOK no cover

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

175

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

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

178

179 if band:

180 self._band1(band)

181

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

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

184

185 if not falsed:

186 self._falsed = False

187

188 if convergence: # for backward compatibility

189 gamma = _xkwds_get(convergence, convergence=gamma)

190 if gamma is not self._gamma:

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

192 if scale is not self._scale:

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

194

195 def __repr__(self):

196 return self.toRepr(B=True)

197

198 def __str__(self):

199 return self.toStr()

200

201 def _band1(self, band):

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

203 '''

204 if band:

205 _xinstanceof(str, band=band)

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

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

208 if band not in self._Bands:

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

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

211 self._band = band

212 elif self._band: # reset

213 self._band = NN

214

215 @deprecated_property_RO

216 def convergence(self):

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

218 return self.gamma

219

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

221 def datum(self):

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

223 '''

224 return self._datum

225

226 @datum.setter # PYCHOK setter!

227 def datum(self, datum):

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

229 '''

230 d = _ellipsoidal_datum(datum)

231 if self._datum != d:

232 _update_all(self)

233 self._datum = d

234

235 @Property_RO

236 def easting(self):

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

238 '''

239 return self._easting

240

241 @Property_RO

242 def eastingnorthing(self):

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

244 '''

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

246

247 def eastingnorthing2(self, falsed=True):

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

249

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

251 (C{bool}), otherwise unfalsed.

252

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

254 '''

255 e, n = self.falsed2

256 if self.falsed and not falsed:

257 e, n = neg_(e, n)

258 elif falsed and not self.falsed:

259 pass

260 else:

261 e = n = _0_0

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

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

264

265 @Property_RO

266 def _epsg(self):

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

268 '''

269 return _MODS.epsg.Epsg(self)

270

271 @Property_RO

272 def falsed(self):

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

274 '''

275 return self._falsed

276

277 @Property_RO

278 def falsed2(self): # PYCHOK no cover

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

280 self._notOverloaded(self)

281

282 @Property_RO

283 def gamma(self):

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

285 if not available.

286 '''

287 return self._gamma

288

289 @property_RO

290 def hemisphere(self):

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

292 '''

293 if not self._hemisphere:

294 self._toLLEB()

295 return self._hemisphere

296

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

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

299 '''

300 ll = self._latlon

301 if LatLon is None:

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

303 ll.gamma, ll.scale)

304 else:

305 _xsubclassof(_LLEB, LatLon=LatLon)

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

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

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

309 return _xnamed(r, ll.name)

310

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

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

313 '''

314 ll._toLLEB_args = (unfalse,) + other

315 if unfalse:

316 if not self._band:

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

318 if not self._hemisphere:

319 self._hemisphere = _hemi(ll.lat)

320 self._latlon = ll

321

322 @Property_RO

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

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

325 '''

326 return _lowerleft(self, 0)

327

328 @Property_RO

329 def _mgrs(self):

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

331 '''

332 return _toMgrs(self)

333

334 @Property_RO

335 def _mgrs_lowerleft(self):

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

337 '''

338 utmups = self._lowerleft

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

340

341 @Property_RO

342 def northing(self):

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

344 '''

345 return self._northing

346

347 @Property_RO

348 def scale(self):

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

350 '''

351 return self._scale

352

353 @Property_RO

354 def scale0(self):

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

356 '''

357 return self._scale0

358

359 @deprecated_method

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

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

362

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

364 '''

365 return self.eastingnorthing2(falsed=falsed)

366

367 def toEpsg(self):

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

369

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

371

372 @raise EPSGError: See L{Epsg}.

373 '''

374 return self._epsg

375

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

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

378 self._notOverloaded(**kwds)

379

380 def toMgrs(self, center=False):

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

382

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

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

385 meter} (C{scalar}).

386

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

388

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

390

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

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

393 '''

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

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

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

397

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

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

400 '''

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

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

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

404

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

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

407 '''

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

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

410 if cs:

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

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

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

414 _n_a_ if self.scale is None else

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

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

417

418

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

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

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

422 '''

423 if center:

424 e = n = -center

425 else:

426 c = 5 # center

427 for _ in range(3):

428 c *= 10 # 50, 500, 5000

429 t = c * 2

430 e = int(utmups.easting % t)

431 n = int(utmups.northing % t)

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

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

434 break

435 else:

436 return utmups # unchanged

437

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

439 gamma=utmups.gamma,

440 scale=utmups.scale)

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

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

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

444

445

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

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

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

449

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

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

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

453

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

455 band}).

456

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

458 '''

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

460 u = strUTMUPS.lstrip()

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

462 raise ValueError(_not_(_UPS_ZONE_STR))

463

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

465 if len(u) < 4:

466 raise ValueError(_not_(sep))

467

468 z, h = u[:2]

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

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

471

472 if z.isdigit():

473 z, B = int(z), band

474 else:

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

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

477 # int('') raises ValueError

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

479 break

480 else:

481 raise ValueError(z)

482

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

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

485

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

487 strUTMUPS=strUTMUPS, Error=Error)

488

489

490 def _toMgrs(utmups):

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

492 '''

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

494

495

496__all__ += _ALL_DOCS(UtmUpsBase)

497

498# **) MIT License

499#

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

501#

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

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

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

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

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

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

508#

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

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

511#

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

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

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

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

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

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

518# OTHER DEALINGS IN THE SOFTWARE.