Coverage for pygeodesy/mgrs.py: 99%

266 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-04-09 11:05 -0400

1 

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

3 

4u'''Military Grid Reference System (MGRS/NATO) references. 

5 

6Classes L{Mgrs}, L{Mgrs4Tuple} and L{Mgrs6Tuple} and functions L{parseMGRS} 

7and L{toMgrs}. 

8 

9Pure Python implementation of MGRS, UTM and UPS conversions covering the entire 

10I{ellipsoidal} earth, transcoded from I{Chris Veness}' JavaScript originals U{MGRS 

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

12<https://www.Movable-Type.co.UK/scripts/geodesy/docs/module-mgrs.html>} and from 

13I{Charles Karney}'s C++ class U{MGRS<https://GeographicLib.SourceForge.io/C++/doc/ 

14classGeographicLib_1_1MGRS.html>}. 

15 

16MGRS references comprise a grid zone designation (GZD), a 100 Km grid (square) 

17tile identification and an easting and northing (in C{meter}). The GZD consists 

18of a longitudinal zone (or column) I{number} and latitudinal band (row) I{letter} 

19in the UTM region between 80°S and 84°N. Each zone (column) is 6° wide and each 

20band (row) is 8° high, except top band 'X' is 12° tall. In UPS polar regions 

21below 80°S and above 84°N the GZD contains only a single I{letter}, C{'A'} or 

22C{'B'} near the south and C{'Y'} or C{'Z'} around the north pole (for west 

23respectively east longitudes). 

24 

25See also the U{United States National Grid<https://www.FGDC.gov/standards/projects/ 

26FGDC-standards-projects/usng/fgdc_std_011_2001_usng.pdf>} and U{Military Grid 

27Reference System<https://WikiPedia.org/wiki/Military_grid_reference_system>}. 

28 

29See module L{pygeodesy.ups} for env variable C{PYGEODESY_UPS_POLES} determining 

30the UPS encoding I{at} the south and north pole. 

31 

32Set env variable C{PYGEODESY_GEOCONVERT} to the (fully qualified) path of the 

33C{GeoConvert} executable to run this module as I{python[3] -m pygeodesy.mgrs} 

34and compare the MGRS results with those from I{Karney}'s utility U{GeoConvert 

35<https://GeographicLib.sourceforge.io/C++/doc/GeoConvert.1.html>}. 

36''' 

37 

38from pygeodesy.basics import halfs2, _splituple, _xinstanceof 

39# from pygeodesy.constants import _0_5 # from .units 

40from pygeodesy.datums import _ellipsoidal_datum, _WGS84 

41from pygeodesy.errors import _AssertionError, MGRSError, _parseX, \ 

42 _ValueError, _xkwds 

43from pygeodesy.interns import NN, _0_, _A_, _AtoZnoIO_, _band_, _B_, \ 

44 _COMMASPACE_, _datum_, _easting_, _invalid_, \ 

45 _northing_, _SPACE_, _W_, _Y_, _Z_, _zone_ 

46from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS 

47from pygeodesy.named import _name2__, _NamedBase, _NamedTuple, _Pass 

48from pygeodesy.namedTuples import EasNor2Tuple, UtmUps5Tuple 

49from pygeodesy.props import deprecated_property_RO, property_RO, Property_RO 

50from pygeodesy.streprs import enstr2, _enstr2m3, Fmt, _resolution10, _xzipairs 

51from pygeodesy.units import Easting, Northing, Str, _100km, _0_5 

52from pygeodesy.units import _1um, _2000km # PYCHOK used! 

53from pygeodesy.ups import _hemi, toUps8, Ups, _UPS_ZONE 

54from pygeodesy.utm import toUtm8, _to3zBlat, Utm, _UTM_ZONE_MAX, _UTM_ZONE_MIN 

55# from pygeodesy.utmupsBase import _UTM_ZONE_MAX, _UTM_ZONE_MIN # from .utm 

56 

57__all__ = _ALL_LAZY.mgrs 

58__version__ = '24.11.06' 

59 

60_AN_ = 'AN' # default south pole grid tile and band B 

61_AtoPx_ = _AtoZnoIO_.tillP 

62# <https://GitHub.com/hrbrmstr/mgrs/blob/master/src/mgrs.c> 

63_FeUPS = {_A_: 8, _B_: 20, _Y_: 8, _Z_: 20} # falsed offsets (C{_100kms}) 

64_FnUPS = {_A_: 8, _B_: 8, _Y_: 13, _Z_: 13} # falsed offsets (C{_100kms}) 

65_JtoZx_ = 'JKLPQRSTUXYZZ' # _AtoZnoDEIMNOVW.fromJ, duplicate Z 

66# 100 Km grid tile UTM column (E) letters, repeating every third zone 

67_LeUTM = _AtoZnoIO_.tillH, _AtoZnoIO_.fromJ.tillR, _AtoZnoIO_.fromS # grid E colums 

68# 100 Km grid tile UPS column (E) letters for each polar zone 

69_LeUPS = {_A_: _JtoZx_, _B_: 'ABCFGHJKLPQR', _Y_: _JtoZx_, _Z_: 'ABCFGHJ'} 

70# 100 Km grid tile UTM and UPS row (N) letters, repeating every other zone 

71_LnUTM = _AtoZnoIO_.tillV, _AtoZnoIO_.fromF.tillV + _AtoZnoIO_.tillE # grid N rows 

72_LnUPS = {_A_: _AtoZnoIO_, _B_: _AtoZnoIO_, _Y_: _AtoPx_, _Z_: _AtoPx_} 

73_polar_ = _SPACE_('polar', _zone_) 

74 

75 

76class Mgrs(_NamedBase): 

77 '''Military Grid Reference System (MGRS/NATO) references, 

78 with method to convert to UTM coordinates. 

79 ''' 

80 _band = NN # latitudinal (C..X) or polar (ABYZ) band 

81 _bandLat = None # band latitude (C{degrees90} or C{None}) 

82 _datum = _WGS84 # Datum (L{Datum}) 

83 _easting = 0 # Easting (C{meter}), within 100 Km grid tile 

84 _EN = NN # EN digraph (C{str}), 100 Km grid tile 

85 _northing = 0 # Northing (C{meter}), within 100 Km grid tile 

86 _resolution = 0 # from L{parseMGRS}, centering (C{meter}) 

87 _zone = 0 # longitudinal or polar zone (C{int}), 0..60 

88 

89 def __init__(self, zone=0, EN=NN, easting=0, northing=0, band=NN, 

90 datum=_WGS84, resolution=0, **name): 

91 '''New L{Mgrs} Military grid reference. 

92 

93 @arg zone: The 6° I{longitudinal} zone (C{int}), 1..60 covering 

94 180°W..180°E or C{0} for I{polar} regions or (C{str}) 

95 with the zone number and I{latitudinal} band letter. 

96 @arg EN: Two-letter EN digraph (C{str}), grid tile I{using only} 

97 the I{AA} aka I{MGRS-New} (row) U{lettering scheme 

98 <http://Wikipedia.org/wiki/Military_Grid_Reference_System>}. 

99 @kwarg easting: Easting (C{meter}), within 100 Km grid tile. 

100 @kwarg northing: Northing (C{meter}), within 100 Km grid tile. 

101 @kwarg band: Optional, I{latitudinal} band or I{polar} region letter 

102 (C{str}), 'C'|..|'X' covering 80°S..84°N (no 'I'|'O'), 

103 'A'|'B' at the south or 'Y'|'Z' at the north pole. 

104 @kwarg datum: This reference's datum (L{Datum}, L{Ellipsoid}, 

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

106 @kwarg resolution: Optional resolution (C{meter}), C{0} for default. 

107 @kwarg name: Optional C{B{name}=NN} (C{str}). 

108 

109 @raise MGRSError: Invalid B{C{zone}}, B{C{EN}}, B{C{easting}}, 

110 B{C{northing}}, B{C{band}} or B{C{resolution}}. 

111 

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

113 ''' 

114 if name: 

115 self.name = name 

116 

117 if not (zone or EN or band): 

118 EN, band = _AN_, _B_ # default, south pole 

119 try: 

120 self._zone, self._band, self._bandLat = _to3zBlat(zone, band, Error=MGRSError) 

121 en = str(EN) 

122 if len(en) != 2 or not en.isalpha(): 

123 raise ValueError() # caught below 

124 self._EN = en.upper() 

125 _ = self._EN2m # check E and N 

126 except (IndexError, KeyError, TypeError, ValueError): 

127 raise MGRSError(band=band, EN=EN, zone=zone) 

128 

129 self._easting = Easting(easting, Error=MGRSError) 

130 self._northing = Northing(northing, Error=MGRSError) 

131 if datum not in (None, Mgrs._datum): 

132 self._datum = _ellipsoidal_datum(datum, name=name) # XXX raiser=_datum_ 

133 

134 if resolution: 

135 self.resolution = resolution 

136 

137 def __str__(self): 

138 return self.toStr(sep=_SPACE_) # for backward compatibility 

139 

140 @property_RO 

141 def band(self): 

142 '''Get the I{latitudinal} band C{'C'|..|'X'} (no C{'I'|'O'}) 

143 or I{polar} region C{'A'|'B'|'Y'|'Z'}) letter (C{str}). 

144 ''' 

145 return self._band 

146 

147 @Property_RO 

148 def bandLatitude(self): 

149 '''Get the band latitude (C{degrees90}). 

150 ''' 

151 return self._bandLat 

152 

153 @Property_RO 

154 def datum(self): 

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

156 ''' 

157 return self._datum 

158 

159 @deprecated_property_RO 

160 def digraph(self): 

161 '''DEPRECATED, use property C{EN}.''' 

162 return self.EN 

163 

164 @property_RO 

165 def EN(self): 

166 '''Get the 2-letter grid tile (C{str}). 

167 ''' 

168 return self._EN 

169 

170 @deprecated_property_RO 

171 def en100k(self): 

172 '''DEPRECATED, use property C{EN}.''' 

173 return self.EN 

174 

175 @Property_RO 

176 def _EN2m(self): 

177 '''(INTERNAL) Get the grid 2-tuple (easting, northing) in C{meter}. 

178 

179 @note: Raises AssertionError, IndexError or KeyError: Invalid 

180 C{zone} number, C{EN} letter or I{polar} region letter. 

181 ''' 

182 EN = self.EN 

183 if self.isUTM: 

184 i = self.zone - 1 

185 # get easting from the E column (note, +1 because 

186 # easting starts at 166e3 due to 500 Km falsing) 

187 e = _LeUTM[i % 3].index(EN[0]) + 1 

188 # similarly, get northing from the N row 

189 n = _LnUTM[i % 2].index(EN[1]) 

190 elif self.isUPS: 

191 B = self.band 

192 e = _LeUPS[B].index(EN[0]) + _FeUPS[B] 

193 n = _LnUPS[B].index(EN[1]) + _FnUPS[B] 

194 else: 

195 raise _AssertionError(zone=self.zone) 

196 return float(e * _100km), float(n * _100km) # meter 

197 

198 @property_RO 

199 def easting(self): 

200 '''Get the easting (C{meter} within grid tile). 

201 ''' 

202 return self._easting 

203 

204 @Property_RO 

205 def eastingnorthing(self): 

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

207 I{within} the MGRS grid tile, both in C{meter}. 

208 ''' 

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

210 

211 @Property_RO 

212 def isUPS(self): 

213 '''Is this MGRS in a (polar) UPS zone (C{bool}). 

214 ''' 

215 return self._zone == _UPS_ZONE 

216 

217 @Property_RO 

218 def isUTM(self): 

219 '''Is this MGRS in a (non-polar) UTM zone (C{bool}). 

220 ''' 

221 return _UTM_ZONE_MIN <= self._zone <= _UTM_ZONE_MAX 

222 

223 @property_RO 

224 def northing(self): 

225 '''Get the northing (C{meter} within grid tile). 

226 ''' 

227 return self._northing 

228 

229 @Property_RO 

230 def northingBottom(self): 

231 '''Get the northing of the band bottom (C{meter}). 

232 ''' 

233 a = self.bandLatitude 

234 u = toUtm8(a, 0, datum=self.datum, Utm=None) if self.isUTM else \ 

235 toUps8(a, 0, datum=self.datum, Ups=None) 

236 return int(u.northing / _100km) * _100km 

237 

238 def parse(self, strMGRS, **name): 

239 '''Parse a string to a similar L{Mgrs} instance. 

240 

241 @arg strMGRS: The MGRS reference (C{str}), see function L{parseMGRS}. 

242 @kwarg name: Optional C{B{name}=NN} (C{str}), overriding this name. 

243 

244 @return: The similar instance (L{Mgrs}). 

245 

246 @raise MGRSError: Invalid B{C{strMGRS}}. 

247 ''' 

248 return parseMGRS(strMGRS, datum=self.datum, Mgrs=self.classof, 

249 name=self._name__(name)) 

250 

251 @property 

252 def resolution(self): 

253 '''Get the MGRS resolution (C{meter}, power of 10) 

254 or C{0} if undefined. 

255 ''' 

256 return self._resolution 

257 

258 @resolution.setter # PYCHOK setter! 

259 def resolution(self, resolution): 

260 '''Set the MGRS resolution (C{meter}, power of 10) 

261 or C{0} to undefine and disable UPS/UTM centering. 

262 

263 @raise MGRSError: Invalid B{C{resolution}}, over 

264 C{1.e+5} or under C{1.e-6}. 

265 ''' 

266 if resolution: # and resolution > 0 

267 r = _resolution10(resolution, Error=MGRSError) 

268 else: 

269 r = 0 

270 if self._resolution != r: 

271 self._resolution = r 

272 

273 @Property_RO 

274 def tilesize(self): 

275 '''Get the MGRS grid tile size (C{meter}). 

276 ''' 

277 assert _MODS.utmups._MGRS_TILE is _100km 

278 return _100km 

279 

280 def toLatLon(self, LatLon=None, center=True, **toLatLon_kwds): 

281 '''Convert this MGRS grid reference to a UTM coordinate. 

282 

283 @kwarg LatLon: Optional, ellipsoidal class to return the 

284 geodetic point (C{LatLon}) or C{None}. 

285 @kwarg center: Optionally, return the grid's center or 

286 lower left corner (C{bool}). 

287 @kwarg toLatLon_kwds: Optional, additional L{Utm.toLatLon} 

288 and B{C{LatLon}} keyword arguments. 

289 

290 @return: A B{C{LatLon}} instance or if C{B{LatLon} is None} 

291 a L{LatLonDatum5Tuple}C{(lat, lon, datum, gamma, 

292 scale)}. 

293 

294 @raise TypeError: If B{C{LatLon}} is not ellipsoidal. 

295 

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

297 

298 @see: Methods L{Mgrs.toUtm} and L{Utm.toLatLon}. 

299 ''' 

300 u = self.toUtmUps(center=center) 

301 return u.toLatLon(LatLon=LatLon, **toLatLon_kwds) 

302 

303 def toRepr(self, fmt=Fmt.SQUARE, sep=_COMMASPACE_, **prec): # PYCHOK expected 

304 '''Return a string representation of this MGRS grid reference. 

305 

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

307 @kwarg sep: Separator between name:values (C{str}). 

308 @kwarg prec: Precision (C{int}), see method L{Mgrs.toStr}. 

309 

310 @return: This Mgrs as "[Z:[dd]B, G:EN, E:easting, N:northing]" 

311 (C{str}), with C{B{sep} ", "}. 

312 

313 @note: MGRS grid references are truncated, not rounded (unlike 

314 UTM/UPS coordinates). 

315 

316 @raise ValueError: Invalid B{C{prec}}. 

317 ''' 

318 t = self.toStr(sep=None, **prec) 

319 return _xzipairs('ZGEN', t, sep=sep, fmt=fmt) 

320 

321 def toStr(self, prec=0, sep=NN): # PYCHOK expected 

322 '''Return this MGRS grid reference as a string. 

323 

324 @kwarg prec: Precision, the number of I{decimal} digits (C{int}) or if 

325 negative, the number of I{units to drop}, like MGRS U{PRECISION 

326 <https://GeographicLib.SourceForge.io/C++/doc/GeoConvert.1.html#PRECISION>}. 

327 @kwarg sep: Optional separator to join (C{str}) or C{None} to return an unjoined 

328 3-C{tuple} of C{str}s. 

329 

330 @return: This Mgrs as 4-tuple C{("dd]B", "EN", "easting", "northing")} if C{B{sep}=NN} 

331 or "[dd]B EN easting northing" (C{str}) with C{B{sep} " "}. 

332 

333 @note: Both C{easting} and C{northing} strings are C{NN} or missing if C{B{prec} <= -5}. 

334 

335 @note: MGRS grid references are truncated, not rounded (unlike UTM/UPS). 

336 

337 @raise ValueError: Invalid B{C{prec}}. 

338 ''' 

339 zB = self.zoneB 

340 t = enstr2(self._easting, self._northing, prec, zB, self.EN) 

341 return t if sep is None else sep.join(t).rstrip() 

342 

343 def toUps(self, Ups=Ups, center=False): 

344 '''Convert this MGRS grid reference to a UPS coordinate. 

345 

346 @kwarg Ups: Optional class to return the UPS coordinate 

347 (L{Ups}) or C{None}. 

348 @kwarg center: Optionally, center easting and northing 

349 by the resolution (C{bool}). 

350 

351 @return: A B{C{Ups}} instance or if C{B{Ups} is None} 

352 a L{UtmUps5Tuple}C{(zone, hemipole, easting, 

353 northing, band)}. 

354 

355 @raise MGRSError: This MGRS is a I{non-polar} UTM reference. 

356 ''' 

357 if self.isUTM: 

358 raise MGRSError(zoneB=self.zoneB, txt_not_=_polar_) 

359 return self._toUtmUps(Ups, center) 

360 

361 def toUtm(self, Utm=Utm, center=False): 

362 '''Convert this MGRS grid reference to a UTM coordinate. 

363 

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

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

366 @kwarg center: Optionally, center easting and northing 

367 by the resolution (C{bool}). 

368 

369 @return: A B{C{Utm}} instance or if C{B{Utm} is None} 

370 a L{UtmUps5Tuple}C{(zone, hemipole, easting, 

371 northing, band)}. 

372 

373 @raise MGRSError: This MGRS is a I{polar} UPS reference. 

374 ''' 

375 if self.isUPS: 

376 raise MGRSError(zoneB=self.zoneB, txt=_polar_) 

377 return self._toUtmUps(Utm, center) 

378 

379 def toUtmUps(self, Utm=Utm, Ups=Ups, center=False): 

380 '''Convert this MGRS grid reference to a UTM or UPS coordinate. 

381 

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

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

384 @kwarg Ups: Optional class to return the UPS coordinate 

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

386 @kwarg center: Optionally, center easting and northing 

387 by the resolution (C{bool}). 

388 

389 @return: A B{C{Utm}} or B{C{Ups}} instance or if C{B{Utm} 

390 or B{Ups} is None} a L{UtmUps5Tuple}C{(zone, 

391 hemipole, easting, northing, band)}. 

392 ''' 

393 return self._toUtmUps((Utm if self.isUTM else 

394 (Ups if self.isUPS else None)), center) 

395 

396 def _toUtmUps(self, U, center): 

397 '''(INTERNAL) Helper for C{.toUps} and C{.toUtm}. 

398 ''' 

399 e, n = self._EN2m 

400 e += self.easting 

401 n += self.northing 

402 if self.isUTM: 

403 # 100 Km row letters repeat every 2,000 Km north; 

404 # add 2,000 Km blocks to get into required band 

405 b = (self.northingBottom - n) / _2000km 

406 if b > 0: 

407 b = int(b) + 1 

408 b = min(b, (3 if self.band == _W_ else 4)) 

409 n += b * _2000km 

410 if center: 

411 c = self.resolution 

412 if c: 

413 c *= _0_5 

414 e += c 

415 n += c 

416 z = self.zone 

417 h = _hemi(self.bandLatitude) # _S_ if self.band < _N_ else _N_ 

418 B = self.band 

419 m = self.name 

420 return UtmUps5Tuple(z, h, e, n, B, name=m, Error=MGRSError) if U is None \ 

421 else U(z, h, e, n, B, name=m, datum=self.datum) 

422 

423 @property_RO 

424 def zone(self): 

425 '''Get the I{longitudinal} zone (C{int}), 1..60 or 0 for I{polar}. 

426 ''' 

427 return self._zone 

428 

429 @Property_RO 

430 def zoneB(self): 

431 '''Get the I{polar} region letter or the I{longitudinal} zone digits 

432 plus I{latitudinal} band letter (C{str}). 

433 ''' 

434 return self.band if self.isUPS else NN(Fmt.zone(self.zone), self.band) 

435 

436 

437class Mgrs4Tuple(_NamedTuple): 

438 '''4-Tuple C{(zone, EN, easting, northing)}, C{zone} and grid 

439 tile C{EN} as C{str}, C{easting} and C{northing} in C{meter}. 

440 

441 @note: The C{zone} consists of either the I{longitudinal} zone 

442 number plus the I{latitudinal} band letter or only the 

443 I{polar} region letter. 

444 ''' 

445 _Names_ = (_zone_, 'EN', _easting_, _northing_) 

446 _Units_ = ( Str, Str, Easting, Northing) 

447 

448 @deprecated_property_RO 

449 def digraph(self): 

450 '''DEPRECATED, use attribute C{EN}.''' 

451 return self.EN # PYCHOK or [1] 

452 

453 def toMgrs(self, **Mgrs_and_kwds): 

454 '''Return this L{Mgrs4Tuple} as an L{Mgrs} instance. 

455 ''' 

456 return self.to6Tuple(NN, _WGS84).toMgrs(**Mgrs_and_kwds) 

457 

458 def to6Tuple(self, band=NN, datum=_WGS84): 

459 '''Extend this L{Mgrs4Tuple} to a L{Mgrs6Tuple}. 

460 

461 @kwarg band: The band (C{str}). 

462 @kwarg datum: The datum (L{Datum}). 

463 

464 @return: An L{Mgrs6Tuple}C{(zone, EN, easting, 

465 northing, band, datum)}. 

466 ''' 

467 z = self.zone # PYCHOK or [0] 

468 B = z[-1:] 

469 if B.isalpha(): 

470 z = z[:-1] or Fmt.zone(0) 

471 t = Mgrs6Tuple(z, self.EN, self.easting, self.northing, # PYCHOK attrs 

472 band or B, datum, name=self.name) 

473 else: 

474 t = self._xtend(Mgrs6Tuple, band, datum) 

475 return t 

476 

477 

478class Mgrs6Tuple(_NamedTuple): # XXX only used above 

479 '''6-Tuple C{(zone, EN, easting, northing, band, datum)}, with 

480 C{zone}, grid tile C{EN} and C{band} as C{str}, C{easting} 

481 and C{northing} in C{meter} and C{datum} a L{Datum}. 

482 

483 @note: The C{zone} is the I{longitudinal} zone C{"01".."60"} 

484 or C{"00"} for I{polar} regions and C{band} is the 

485 I{latitudinal} band or I{polar} region letter. 

486 ''' 

487 _Names_ = Mgrs4Tuple._Names_ + (_band_, _datum_) 

488 _Units_ = Mgrs4Tuple._Units_ + ( Str, _Pass) 

489 

490 @deprecated_property_RO 

491 def digraph(self): 

492 '''DEPRECATED, use attribute C{EN}.''' 

493 return self.EN # PYCHOK or [1] 

494 

495 def toMgrs(self, Mgrs=Mgrs, **Mgrs_kwds): 

496 '''Return this L{Mgrs6Tuple} as an L{Mgrs} instance. 

497 ''' 

498 kwds = dict(self.items()) 

499 if self.name: 

500 kwds.update(name=self.name) 

501 if Mgrs_kwds: 

502 kwds.update(Mgrs_kwds) 

503 return Mgrs(**kwds) 

504 

505 

506class _RE(object): 

507 '''(INTERNAL) Lazily compiled C{re}gex-es to parse MGRS strings. 

508 ''' 

509 _EN = '([A-Z]{2})' # 2-letter grid tile designation 

510 _en = '([0-9]+)' # easting_northing digits, 2-10+ 

511 _pB = '([ABYZ]{1})' # polar region letter, pseudo-zone 0 

512 _zB = '([0-9]{1,2}[C-X]{1})' # zone number and band letter, no I|O 

513 

514 @Property_RO 

515 def pB_EN(self): # split polar "BEN" into 2 parts 

516 import re # PYCHOK warning locale.Error 

517 return re.compile(_RE._pB + _RE._EN, re.IGNORECASE) 

518 

519 @Property_RO 

520 def pB_EN_en(self): # split polar "BEN1235..." into 3 parts 

521 import re # PYCHOK warning locale.Error 

522 return re.compile(_RE._pB + _RE._EN + _RE._en, re.IGNORECASE) 

523 

524 @Property_RO 

525 def zB_EN(self): # split "1[2]BEN" into 2 parts 

526 import re # PYCHOK warning locale.Error 

527 return re.compile(_RE._zB + _RE._EN, re.IGNORECASE) 

528 

529 @Property_RO 

530 def zB_EN_en(self): # split "1[2]BEN1235..." into 3 parts 

531 import re # PYCHOK warning locale.Error 

532 return re.compile(_RE._zB + _RE._EN + _RE._en, re.IGNORECASE) 

533 

534_RE = _RE() # PYCHOK singleton 

535 

536 

537def parseMGRS(strMGRS, datum=_WGS84, Mgrs=Mgrs, **name): 

538 '''Parse a string representing a MGRS grid reference, 

539 consisting of C{"[zone]Band, EN, easting, northing"}. 

540 

541 @arg strMGRS: MGRS grid reference (C{str}). 

542 @kwarg datum: Optional datum to use (L{Datum}). 

543 @kwarg Mgrs: Optional class to return the MGRS grid 

544 reference (L{Mgrs}) or C{None}. 

545 @kwarg name: Optional B{C{Mgrs}} C{B{name}=NN} (C{str}). 

546 

547 @return: The MGRS grid reference as B{C{Mgrs}} or if 

548 C{B{Mgrs} is None} as an L{Mgrs4Tuple}C{(zone, 

549 EN, easting, northing)}. 

550 

551 @raise MGRSError: Invalid B{C{strMGRS}}. 

552 ''' 

553 def _mg(s, re_UTM, re_UPS): # return re.match groups 

554 m = re_UTM.match(s) 

555 if m: 

556 return m.groups() 

557 m = re_UPS.match(s.lstrip(_0_)) 

558 if m: 

559 return m.groups() 

560# m = m.groups() 

561# t = '00' + m[0] 

562# return (t,) + m[1:] 

563 raise ValueError(_SPACE_(repr(s), _invalid_)) 

564 

565 def _MGRS(strMGRS, datum, Mgrs, name): 

566 m = _splituple(strMGRS.strip()) 

567 if len(m) == 1: # [01]BEN1234512345' 

568 m = _mg(m[0], _RE.zB_EN_en, _RE.pB_EN_en) 

569 m = m[:2] + halfs2(m[2]) 

570 elif len(m) == 2: # [01]BEN 1234512345' 

571 m = _mg(m[0], _RE.zB_EN, _RE.pB_EN) + halfs2(m[1]) 

572 elif len(m) == 3: # [01]BEN 12345 12345' 

573 m = _mg(m[0], _RE.zB_EN, _RE.pB_EN) + m[1:] 

574 if len(m) != 4: # [01]B EN 12345 12345 

575 raise ValueError 

576 

577 zB, EN = m[0].upper(), m[1].upper() 

578 if zB[-1:] in 'IO': 

579 raise ValueError(_SPACE_(repr(m[0]), _invalid_)) 

580 e, n, m = _enstr2m3(*m[2:]) 

581 

582 if Mgrs is None: 

583 r = Mgrs4Tuple(zB, EN, e, n, **name) 

584 _ = r.toMgrs(resolution=m) # validate 

585 else: 

586 r = Mgrs(zB, EN, e, n, datum=datum, resolution=m, **name) 

587 return r 

588 

589 return _parseX(_MGRS, strMGRS, datum, Mgrs, name, 

590 strMGRS=strMGRS, Error=MGRSError) 

591 

592 

593def toMgrs(utmups, Mgrs=Mgrs, **name_Mgrs_kwds): 

594 '''Convert a UTM or UPS coordinate to an MGRS grid reference. 

595 

596 @arg utmups: A UTM or UPS coordinate (L{Utm}, L{Etm} or L{Ups}). 

597 @kwarg Mgrs: Optional class to return the MGRS grid reference (L{Mgrs}) 

598 or C{None}. 

599 @kwarg name_Mgrs_kwds: Optional C{B{name}=NN} (C{str}) and optionally, 

600 additional B{C{Mgrs}} keyword arguments, ignored if C{B{Mgrs} 

601 is None}. 

602 

603 @return: The MGRS grid reference as B{C{Mgrs}} or if C{B{Mgrs} is None} as 

604 an L{Mgrs6Tuple}C{(zone, EN, easting, northing, band, datum)}. 

605 

606 @raise MGRSError: Invalid B{C{utmups}}. 

607 

608 @raise TypeError: If B{C{utmups}} is not L{Utm}, L{Etm} nor L{Ups}. 

609 ''' 

610# _MODS.utmups.utmupsValidate(utmups, MGRS=True, Error-MGRSError) 

611 _xinstanceof(Utm, Ups, utmups=utmups) # Utm, Etm, Ups 

612 try: 

613 e, n = utmups.eastingnorthing2(falsed=True) 

614 E, e = _um100km2(e) 

615 N, n = _um100km2(n) 

616 B, z = utmups.band, utmups.zone 

617 if _UTM_ZONE_MIN <= z <= _UTM_ZONE_MAX: 

618 i = z - 1 

619 # columns in zone 1 are A-H, zone 2 J-R, zone 3 S-Z, 

620 # then repeating every 3rd zone (note E-1 because 

621 # eastings start at 166e3 due to 500km false origin) 

622 EN = _LeUTM[i % 3][E - 1] 

623 # rows in even zones are A-V, in odd zones are F-E 

624 EN += _LnUTM[i % 2][N % len(_LnUTM[0])] 

625 elif z == _UPS_ZONE: 

626 EN = _LeUPS[B][E - _FeUPS[B]] 

627 EN += _LnUPS[B][N - _FnUPS[B]] 

628 else: 

629 raise _ValueError(zone=z) 

630 except (IndexError, TypeError, ValueError) as x: 

631 raise MGRSError(B=B, E=E, N=N, utmups=utmups, cause=x) 

632 

633 t, kwds = _name2__(name_Mgrs_kwds, _or_nameof=utmups) 

634 if Mgrs is None: 

635 r = Mgrs4Tuple(Fmt.zone(z), EN, e, n, name=t) \ 

636 .to6Tuple(B, utmups.datum) 

637 else: 

638 kwds = _xkwds(kwds, band=B, datum=utmups.datum, name=t) 

639 r = Mgrs(z, EN, e, n, **kwds) 

640 return r 

641 

642 

643def _um100km2(m): 

644 '''(INTERNAL) An MGRS east-/northing truncated to micrometer (um) 

645 precision and to grid tile C{M} and C{m}eter within the tile. 

646 ''' 

647 m = int(m / _1um) * _1um # micrometer 

648 M, m = divmod(m, _100km) 

649 return int(M), m 

650 

651 

652if __name__ == '__main__': 

653 

654 def _main(): 

655 

656 from pygeodesy.ellipsoidalVincenty import LatLon, fabs 

657 from pygeodesy.internals import _fper, printf 

658 from pygeodesy.karney import _Xables 

659 

660# from math import fabs # from .ellipsoidalVincenty 

661 

662 # <https://GeographicLib.sourceforge.io/C++/doc/GeoConvert.1.html> 

663 G = _Xables.GeoConvert(_Xables.bin_) 

664 if _Xables.X_OK(G): 

665 from pygeodesy.internals import _popen2 

666 printf(' using: %s', _Xables.name_version(G, base=False)) 

667 cmd = G, '-m' # -m converts latlon to MGRS 

668 else: 

669 printf(' sorry: %s', _Xables.X_not(G)) 

670 cmd = _popen2 = None 

671 

672 e = n = 0 

673 try: 

674 for lat in range(-90, 91, 1): 

675 printf('%6s: lat %s ...', n, lat, end=NN, flush=True) 

676 nl = _MODS.os.linesep 

677 for lon in range(-180, 181, 1): 

678 m = LatLon(lat, lon).toMgrs() 

679 if _popen2: # and cmd 

680 t = '%s %s' % (lat, lon) 

681 g = _popen2(cmd, stdin=t)[0] 

682 t = m.toStr() # sep=NN 

683 if t != g: 

684 e += 1 

685 printf('%s%6s: %s: %r vs %r (lon %s)', nl, -e, m, t, g, lon) 

686 nl = NN 

687 t = m.toLatLon(LatLon=LatLon) 

688 d = max(fabs(t.lat - lat), fabs(t.lon - lon)) 

689 if d > 1e-9 and -90 < lat < 90 and -180 < lon < 180: 

690 e += 1 

691 printf('%s%6s: %s: %s vs %s %.6e', nl, -e, m, t.latlon, 

692 (float(lat), float(lon)), d) 

693 nl = NN 

694 n += 1 

695 if nl: 

696 printf(' OK') 

697 except KeyboardInterrupt: 

698 printf(nl) 

699 

700 printf('%6s: %s errors (%s)', n, (e if e else 'no'), _fper(e, n, prec=2)) 

701 

702 _main() 

703 

704 

705# % python3 -m pygeodesy.mgrs 

706# using: /opt/local/bin/GeoConvert -m ... 

707# 0: lat -90 ... OK 

708# 361: lat -89 ... OK 

709# 722: lat -88 ... OK 

710# 1083: lat -87 ... OK 

711# 1444: lat -86 ... OK 

712# 1805: lat -85 ... OK 

713# 2166: lat -84 ... OK 

714# 2527: lat -83 ... OK 

715# 2888: lat -82 ... OK 

716# 3249: lat -81 ... OK 

717# 3610: lat -80 ... OK 

718# ... 

719# 61370: lat 80 ... OK 

720# 61731: lat 81 ... OK 

721# 62092: lat 82 ... OK 

722# 62453: lat 83 ... OK 

723# 62814: lat 84 ... OK 

724# 63175: lat 85 ... OK 

725# 63536: lat 86 ... OK 

726# 63897: lat 87 ... OK 

727# 64258: lat 88 ... OK 

728# 64619: lat 89 ... OK 

729# 64980: lat 90 ... OK 

730# 65341: no errors (0.00%) 

731 

732# **) MIT License 

733# 

734# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved. 

735# 

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

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

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

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

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

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

742# 

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

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

745# 

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

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

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

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

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

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

752# OTHER DEALINGS IN THE SOFTWARE.