Coverage for pygeodesy/mgrs.py: 99%

267 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-29 12:40 -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, _isin, _splituple, _xinstanceof 

39from pygeodesy.constants import _0_5 

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_, _DMAIN_, _easting_, \ 

45 _invalid_, _northing_, _SPACE_, _W_, _Y_, \ 

46 _Z_, _zone_ 

47from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS 

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

49from pygeodesy.namedTuples import EasNor2Tuple, UtmUps5Tuple 

50from pygeodesy.props import deprecated_property_RO, property_RO, Property_RO 

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

52from pygeodesy.units import Easting, Northing, Str, _100km 

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

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

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

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

57 

58__all__ = _ALL_LAZY.mgrs 

59__version__ = '25.05.12' 

60 

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

62_AtoPx_ = _AtoZnoIO_.tillP 

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

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

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

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

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

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

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

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

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

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

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

74_polar_ = _SPACE_('polar', _zone_) 

75 

76 

77class Mgrs(_NamedBase): 

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

79 with method to convert to UTM coordinates. 

80 ''' 

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

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

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

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

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

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

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

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

89 

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

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

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

93 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

109 

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

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

112 

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

114 ''' 

115 if name: 

116 self.name = name 

117 

118 if not (zone or EN or band): 

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

120 try: 

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

122 en = str(EN) 

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

124 raise ValueError() # caught below 

125 self._EN = en.upper() 

126 _ = self._EN2m # check E and N 

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

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

129 

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

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

132 if not _isin(datum, None, Mgrs._datum): 

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

134 

135 if resolution: 

136 self.resolution = resolution 

137 

138 def __str__(self): 

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

140 

141 @property_RO 

142 def band(self): 

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

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

145 ''' 

146 return self._band 

147 

148 @Property_RO 

149 def bandLatitude(self): 

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

151 ''' 

152 return self._bandLat 

153 

154 @Property_RO 

155 def datum(self): 

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

157 ''' 

158 return self._datum 

159 

160 @deprecated_property_RO 

161 def digraph(self): 

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

163 return self.EN 

164 

165 @property_RO 

166 def EN(self): 

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

168 ''' 

169 return self._EN 

170 

171 @deprecated_property_RO 

172 def en100k(self): 

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

174 return self.EN 

175 

176 @Property_RO 

177 def _EN2m(self): 

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

179 

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

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

182 ''' 

183 EN = self.EN 

184 if self.isUTM: 

185 i = self.zone - 1 

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

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

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

189 # similarly, get northing from the N row 

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

191 elif self.isUPS: 

192 B = self.band 

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

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

195 else: 

196 raise _AssertionError(zone=self.zone) 

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

198 

199 @property_RO 

200 def easting(self): 

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

202 ''' 

203 return self._easting 

204 

205 @Property_RO 

206 def eastingnorthing(self): 

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

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

209 ''' 

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

211 

212 @Property_RO 

213 def isUPS(self): 

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

215 ''' 

216 return self._zone == _UPS_ZONE 

217 

218 @Property_RO 

219 def isUTM(self): 

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

221 ''' 

222 return _UTM_ZONE_MIN <= self._zone <= _UTM_ZONE_MAX 

223 

224 @property_RO 

225 def northing(self): 

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

227 ''' 

228 return self._northing 

229 

230 @Property_RO 

231 def northingBottom(self): 

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

233 ''' 

234 a = self.bandLatitude 

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

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

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

238 

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

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

241 

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

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

244 

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

246 

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

248 ''' 

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

250 name=self._name__(name)) 

251 

252 @property 

253 def resolution(self): 

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

255 or C{0} if undefined. 

256 ''' 

257 return self._resolution 

258 

259 @resolution.setter # PYCHOK setter! 

260 def resolution(self, resolution): 

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

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

263 

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

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

266 ''' 

267 if resolution: # and resolution > 0 

268 r = _resolution10(resolution, Error=MGRSError) 

269 else: 

270 r = 0 

271 if self._resolution != r: 

272 self._resolution = r 

273 

274 @Property_RO 

275 def tilesize(self): 

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

277 ''' 

278 assert _MODS.utmups._MGRS_TILE is _100km 

279 return _100km 

280 

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

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

283 

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

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

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

287 lower left corner (C{bool}). 

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

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

290 

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

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

293 scale)}. 

294 

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

296 

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

298 

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

300 ''' 

301 u = self.toUtmUps(center=center) 

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

303 

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

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

306 

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

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

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

310 

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

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

313 

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

315 UTM/UPS coordinates). 

316 

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

318 ''' 

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

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

321 

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

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

324 

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

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

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

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

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

330 

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

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

333 

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

335 

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

337 

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

339 ''' 

340 zB = self.zoneB 

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

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

343 

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

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

346 

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

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

349 @kwarg center: Optionally, center easting and northing 

350 by the resolution (C{bool}). 

351 

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

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

354 northing, band)}. 

355 

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

357 ''' 

358 if self.isUTM: 

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

360 return self._toUtmUps(Ups, center) 

361 

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

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

364 

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

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

367 @kwarg center: Optionally, center easting and northing 

368 by the resolution (C{bool}). 

369 

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

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

372 northing, band)}. 

373 

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

375 ''' 

376 if self.isUPS: 

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

378 return self._toUtmUps(Utm, center) 

379 

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

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

382 

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

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

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

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

387 @kwarg center: Optionally, center easting and northing 

388 by the resolution (C{bool}). 

389 

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

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

392 hemipole, easting, northing, band)}. 

393 ''' 

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

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

396 

397 def _toUtmUps(self, U, center): 

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

399 ''' 

400 e, n = self._EN2m 

401 e += self.easting 

402 n += self.northing 

403 if self.isUTM: 

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

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

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

407 if b > 0: 

408 b = int(b) + 1 

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

410 n += b * _2000km 

411 if center: 

412 c = self.resolution 

413 if c: 

414 c *= _0_5 

415 e += c 

416 n += c 

417 z = self.zone 

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

419 B = self.band 

420 m = self.name 

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

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

423 

424 @property_RO 

425 def zone(self): 

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

427 ''' 

428 return self._zone 

429 

430 @Property_RO 

431 def zoneB(self): 

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

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

434 ''' 

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

436 

437 

438class Mgrs4Tuple(_NamedTuple): 

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

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

441 

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

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

444 I{polar} region letter. 

445 ''' 

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

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

448 

449 @deprecated_property_RO 

450 def digraph(self): 

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

452 return self.EN # PYCHOK or [1] 

453 

454 def toMgrs(self, **Mgrs_and_kwds): 

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

456 ''' 

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

458 

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

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

461 

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

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

464 

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

466 northing, band, datum)}. 

467 ''' 

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

469 B = z[-1:] 

470 if B.isalpha(): 

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

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

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

474 else: 

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

476 return t 

477 

478 

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

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

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

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

483 

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

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

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

487 ''' 

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

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

490 

491 @deprecated_property_RO 

492 def digraph(self): 

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

494 return self.EN # PYCHOK or [1] 

495 

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

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

498 ''' 

499 kwds = dict(self.items()) 

500 if self.name: 

501 kwds.update(name=self.name) 

502 if Mgrs_kwds: 

503 kwds.update(Mgrs_kwds) 

504 return Mgrs(**kwds) 

505 

506 

507class _RE(object): 

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

509 ''' 

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

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

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

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

514 

515 @Property_RO 

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

517 import re # PYCHOK warning locale.Error 

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

519 

520 @Property_RO 

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

522 import re # PYCHOK warning locale.Error 

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

524 

525 @Property_RO 

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

527 import re # PYCHOK warning locale.Error 

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

529 

530 @Property_RO 

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

532 import re # PYCHOK warning locale.Error 

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

534 

535_RE = _RE() # PYCHOK singleton 

536 

537 

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

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

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

541 

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

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

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

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

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

547 

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

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

550 EN, easting, northing)}. 

551 

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

553 ''' 

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

555 m = re_UTM.match(s) 

556 if m: 

557 return m.groups() 

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

559 if m: 

560 return m.groups() 

561# m = m.groups() 

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

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

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

565 

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

567 m = _splituple(strMGRS.strip()) 

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

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

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

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

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

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

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

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

576 raise ValueError 

577 

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

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

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

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

582 

583 if Mgrs is None: 

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

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

586 else: 

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

588 return r 

589 

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

591 strMGRS=strMGRS, Error=MGRSError) 

592 

593 

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

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

596 

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

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

599 or C{None}. 

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

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

602 is None}. 

603 

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

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

606 

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

608 

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

610 ''' 

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

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

613 try: 

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

615 E, e = _um100km2(e) 

616 N, n = _um100km2(n) 

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

618 if _UTM_ZONE_MIN <= z <= _UTM_ZONE_MAX: 

619 i = z - 1 

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

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

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

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

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

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

626 elif z == _UPS_ZONE: 

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

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

629 else: 

630 raise _ValueError(zone=z) 

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

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

633 

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

635 if Mgrs is None: 

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

637 .to6Tuple(B, utmups.datum) 

638 else: 

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

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

641 return r 

642 

643 

644def _um100km2(m): 

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

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

647 ''' 

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

649 M, m = divmod(m, _100km) 

650 return int(M), m 

651 

652 

653if __name__ == _DMAIN_: 

654 

655 def _main(): 

656 

657 from pygeodesy.ellipsoidalVincenty import LatLon, fabs 

658 from pygeodesy.internals import _fper, printf 

659 from pygeodesy.karney import _Xables 

660 

661# from math import fabs # from .ellipsoidalVincenty 

662 

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

664 G = _Xables.GeoConvert(_Xables.bin_) 

665 if _Xables.X_OK(G): 

666 from pygeodesy.internals import _popen2 

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

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

669 else: 

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

671 cmd = _popen2 = None 

672 

673 e = n = 0 

674 try: 

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

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

677 nl = _MODS.os.linesep 

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

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

680 if _popen2: # and cmd 

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

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

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

684 if t != g: 

685 e += 1 

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

687 nl = NN 

688 t = m.toLatLon(LatLon=LatLon) 

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

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

691 e += 1 

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

693 (float(lat), float(lon)), d) 

694 nl = NN 

695 n += 1 

696 if nl: 

697 printf(' OK') 

698 except KeyboardInterrupt: 

699 printf(nl) 

700 

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

702 

703 _main() 

704 

705 

706# % python3 -m pygeodesy.mgrs 

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

708# 0: lat -90 ... OK 

709# 361: lat -89 ... OK 

710# 722: lat -88 ... OK 

711# 1083: lat -87 ... OK 

712# 1444: lat -86 ... OK 

713# 1805: lat -85 ... OK 

714# 2166: lat -84 ... OK 

715# 2527: lat -83 ... OK 

716# 2888: lat -82 ... OK 

717# 3249: lat -81 ... OK 

718# 3610: lat -80 ... OK 

719# ... 

720# 61370: lat 80 ... OK 

721# 61731: lat 81 ... OK 

722# 62092: lat 82 ... OK 

723# 62453: lat 83 ... OK 

724# 62814: lat 84 ... OK 

725# 63175: lat 85 ... OK 

726# 63536: lat 86 ... OK 

727# 63897: lat 87 ... OK 

728# 64258: lat 88 ... OK 

729# 64619: lat 89 ... OK 

730# 64980: lat 90 ... OK 

731# 65341: no errors (0.00%) 

732 

733# **) MIT License 

734# 

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

736# 

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

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

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

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

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

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

743# 

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

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

746# 

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

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

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

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

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

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

753# OTHER DEALINGS IN THE SOFTWARE.