1

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

3

4 u'''World Geographic Reference System (WGRS) en-/decoding, aka GEOREF.

5

6 Class L{Georef} and several functions to encode, decode and inspect WGRS

7(or GEOREF) references.

8

9 Transcoded from I{Charles Karney}'s C++ class U{Georef

10<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Georef.html>},

11 but with modified C{precision} and extended with C{height} and C{radius}.

12

13@see: U{World Geographic Reference System

14 <https://WikiPedia.org/wiki/World_Geographic_Reference_System>}.

15'''

16# from pygeodesy.basics import isstr # from .named

17 from pygeodesy.constants import INT0, _float, _off90, _0_001, \

18 _0_5, _1_0, _2_0, _60_0, _1000_0

19 from pygeodesy.dms import parse3llh

20 from pygeodesy.errors import _ValueError, _xattr, _xStrError

21 from pygeodesy.interns import NN, _0to9_, _AtoZnoIO_, _COMMA_, \

22 _height_, _INV_, _radius_, _SPACE_

23 from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY

24 from pygeodesy.named import _name2__, nameof, isstr, Property_RO

25 from pygeodesy.namedTuples import LatLon2Tuple, LatLonPrec3Tuple

26# from pygeodesy.props import Property_RO # from .named

27 from pygeodesy.streprs import Fmt, _0wd

28 from pygeodesy.units import Height, Int, Lat, Lon, Precision_, \

29 Radius, Scalar_, Str

30 from pygeodesy.utily import ft2m, m2ft, m2NM

31

32 from math import floor

33

34__all__ = _ALL_LAZY.wgrs

35__version__ = '24.08.15'

36

37_Base = 10

38_BaseLen = 4

39_DegChar = _AtoZnoIO_.tillQ

40_Digits = _0to9_

41_LatOrig = -90

42_LatTile = _AtoZnoIO_.tillM

43_LonOrig = -180

44_LonTile = _AtoZnoIO_

45_60B = 60000000000 # == 60_000_000_000 == 60e9

46_MaxPrec = 11

47_Tile = 15 # tile size in degrees

48

49_MaxLen = _BaseLen + 2 * _MaxPrec

50_MinLen = _BaseLen - 2

51

52_LatOrig_60B = _LatOrig * _60B

53_LonOrig_60B = _LonOrig * _60B

54

55_float_Tile = _float(_Tile)

56_LatOrig_Tile = _float(_LatOrig) / _Tile

57_LonOrig_Tile = _float(_LonOrig) / _Tile

58

59

60 def _divmod3(x, _Orig_60B):

61 '''(INTERNAL) Convert B{C{x}} to 3_tuple C{(tile, modulo, fraction)}/

62 '''

63 i = int(floor(x * _60B))

64 i, x = divmod(i - _Orig_60B, _60B)

65 xt, xd = divmod(i, _Tile)

66 return xt, xd, x

67

68

69 def _2fll(lat, lon):

70 '''(INTERNAL) Convert lat, lon.

71 '''

72 # lat, lon = parseDMS2(lat, lon)

73 return (Lat(lat, Error=WGRSError),

74 Lon(lon, Error=WGRSError))

75

76

77 def _2geostr2(georef):

78 '''(INTERNAL) Check a georef string.

79 '''

80 try:

81 n, g = len(georef), georef.upper()

82 p, o = divmod(n, 2)

83 if o or n < _MinLen or n > _MaxLen \

84 or g.startswith(_INV_) or not g.isalnum():

85 raise ValueError()

86 return g, _2Precision(p - 1)

87

88 except (AttributeError, TypeError, ValueError) as x:

89 raise WGRSError(Georef.__name__, georef, cause=x)

90

91

92 def _2Precision(precision):

93 '''(INTERNAL) Return a L{Precision_} instance.

94 '''

95 return Precision_(precision, Error=WGRSError, low=0, high=_MaxPrec)

96

97

98 class WGRSError(_ValueError):

99 '''World Geographic Reference System (WGRS) encode, decode or other L{Georef} issue.

100 '''

101 pass

102

103

104 class Georef(Str):

105 '''Georef class, a named C{str}.

106 '''

107 # no str.__init__ in Python 3

108 def __new__(cls, lat_gll, lon=None, height=None, precision=3, name=NN):

109 '''New L{Georef} from an other L{Georef} instance or georef

110 C{str} or from a C{LatLon} instance or lat-/longitude C{str}.

111

112 @arg lat_gll: Latitude (C{degrees90}), a georef (L{Georef},

113 C{str}) or a location (C{LatLon}, C{LatLon*Tuple}).

114 @kwarg lon: Logitude (C{degrees180)}, required if B{C{lat_gll}}

115 is C{degrees90}, ignored otherwise.

116 @kwarg height: Optional height in C{meter}, used if B{C{lat_gll}}

117 is a location.

118 @kwarg precision: The desired georef resolution and length (C{int}

119 0..11), see L{encode<pygeodesy.wgrs.encode>}.

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

121

122 @return: New L{Georef}.

123

124 @raise RangeError: Invalid B{C{lat_gll}} or B{C{lon}}.

125

126 @raise TypeError: Invalid B{C{lat_gll}} or B{C{lon}}.

127

128 @raise WGRSError: INValid B{C{lat_gll}}.

129 '''

130 if lon is None:

131 if isinstance(lat_gll, Georef):

132 g, ll, p = str(lat_gll), lat_gll.latlon, lat_gll.precision

133 elif isstr(lat_gll):

134 if _COMMA_ in lat_gll or _SPACE_ in lat_gll:

135 lat, lon, h = parse3llh(lat_gll, height=height)

136 g, ll, p = _encode3(lat, lon, precision, h=h)

137 else:

138 g, ll = lat_gll.upper(), None

139 try:

140 _, p = _2geostr2(g) # validate

141 except WGRSError: # R00H00?

142 p = None # = decode5(g).precision?

143 else: # assume LatLon

144 try:

145 g, ll, p = _encode3(lat_gll.lat, lat_gll.lon, precision,

146 h=_xattr(lat_gll, height=height))

147 except AttributeError:

148 raise _xStrError(Georef, gll=lat_gll) # Error=WGRSError

149 else:

150 g, ll, p = _encode3(lat_gll, lon, precision, h=height)

151

152 self = Str.__new__(cls, g, name=name or nameof(lat_gll))

153 self._latlon = ll

154 self._precision = p

155 return self

156

157 @Property_RO

158 def decoded3(self):

159 '''Get this georef's attributes (L{LatLonPrec3Tuple}).

160 '''

161 lat, lon = self.latlon

162 return LatLonPrec3Tuple(lat, lon, self.precision, name=self.name)

163

164 @Property_RO

165 def decoded5(self):

166 '''Get this georef's attributes (L{LatLonPrec5Tuple}) with

167 height and radius set to C{None} if missing.

168 '''

169 return self.decoded3.to5Tuple(self.height, self.radius)

170

171 @Property_RO

172 def _decoded5(self):

173 '''(INTERNAL) Initial L{LatLonPrec5Tuple}.

174 '''

175 return decode5(self)

176

177 @Property_RO

178 def height(self):

179 '''Get this georef's height in C{meter} or C{None} if missing.

180 '''

181 return self._decoded5.height

182

183 @Property_RO

184 def latlon(self):

185 '''Get this georef's (center) lat- and longitude (L{LatLon2Tuple}).

186 '''

187 lat, lon = self._latlon or self._decoded5[:2]

188 return LatLon2Tuple(lat, lon, name=self.name)

189

190 @Property_RO

191 def latlonheight(self):

192 '''Get this georef's (center) lat-, longitude and height (L{LatLon3Tuple}),

193 with height set to C{INT0} if missing.

194 '''

195 return self.latlon.to3Tuple(self.height or INT0)

196

197 @Property_RO

198 def precision(self):

199 '''Get this georef's precision (C{int}).

200 '''

201 p = self._precision

202 return self._decoded5.precision if p is None else p

203

204 @Property_RO

205 def radius(self):

206 '''Get this georef's radius in C{meter} or C{None} if missing.

207 '''

208 return self._decoded5.radius

209

210 def toLatLon(self, LatLon=None, height=None, **name_LatLon_kwds):

211 '''Return (the center of) this georef cell as a C{LatLon}.

212

213 @kwarg LatLon: Class to use (C{LatLon}) or C{None}.

214 @kwarg height: Optional height (C{meter}), overriding this height.

215 @kwarg name_LatLon_kwds: Optional C{B{name}=NN} (C{str}) and optional,

216 additional B{C{LatLon}} keyword arguments, ignored if

217 C{B{LatLon} is None}.

218

219 @return: This georef location (B{C{LatLon}}) or if C{B{LatLon} is None},

220 a L{LatLon3Tuple}C{(lat, lon, height)}.

221

222 @raise TypeError: Invalid B{C{LatLon}} or B{C{name_LatLon_kwds}}.

223 '''

224 n, kwds = _name2__(name_LatLon_kwds, _or_nameof=self)

225 h = (self.height or INT0) if height is None else height # _heigHt

226 r = self.latlon.to3Tuple(h) if LatLon is None else LatLon(

227 *self.latlon, height=h, **kwds)

228 return r.renamed(n) if n else r

229

230

231 def decode3(georef, center=True):

232 '''Decode a C{georef} to lat-, longitude and precision.

233

234 @arg georef: To be decoded (L{Georef} or C{str}).

235 @kwarg center: If C{True}, use the georef's center, otherwise

236 the south-west, lower-left corner (C{bool}).

237

238 @return: A L{LatLonPrec3Tuple}C{(lat, lon, precision)}.

239

240 @raise WGRSError: Invalid B{C{georef}}, INValid, non-alphanumeric

241 or odd length B{C{georef}}.

242 '''

243 def _digit(ll, g, i, m):

244 d = _Digits.find(g[i])

245 if d < 0 or d >= m:

246 raise _Error(i)

247 return ll * m + d

248

249 def _Error(i):

250 return WGRSError(Fmt.SQUARE(georef=i), georef)

251

252 def _index(chars, g, i):

253 k = chars.find(g[i])

254 if k < 0:

255 raise _Error(i)

256 return k

257

258 g, precision = _2geostr2(georef)

259 lon = _index(_LonTile, g, 0) + _LonOrig_Tile

260 lat = _index(_LatTile, g, 1) + _LatOrig_Tile

261

262 u = _1_0

263 if precision > 0:

264 lon = lon * _Tile + _index(_DegChar, g, 2)

265 lat = lat * _Tile + _index(_DegChar, g, 3)

266 m, p = 6, precision - 1

267 for i in range(_BaseLen, _BaseLen + p):

268 lon = _digit(lon, g, i, m)

269 lat = _digit(lat, g, i + p, m)

270 u *= m

271 m = _Base

272 u *= _Tile

273

274 if center:

275 lon = lon * _2_0 + _1_0

276 lat = lat * _2_0 + _1_0

277 u *= _2_0

278 u = _Tile / u

279 return LatLonPrec3Tuple(Lat(lat * u, Error=WGRSError),

280 Lon(lon * u, Error=WGRSError),

281 precision, name=nameof(georef))

282

283

284 def decode5(georef, center=True):

285 '''Decode a C{georef} to lat-, longitude, precision, height and radius.

286

287 @arg georef: To be decoded (L{Georef} or C{str}).

288 @kwarg center: If C{True}, use the georef's center, otherwise the

289 south-west, lower-left corner (C{bool}).

290

291 @return: A L{LatLonPrec5Tuple}C{(lat, lon, precision, height, radius)}

292 where C{height} and/or C{radius} are C{None} if missing.

293

294 @raise WGRSError: Invalid B{C{georef}}.

295 '''

296 def _h2m(kft, g_n):

297 return Height(ft2m(kft * _1000_0), name=g_n, Error=WGRSError)

298

299 def _r2m(NM, g_n):

300 return Radius(NM / m2NM(1), name=g_n, Error=WGRSError)

301

302 def _split2(g, Unit, _2m):

303 n = Unit.__name__

304 i = max(g.find(n[0]), g.rfind(n[0]))

305 if i > _BaseLen:

306 return g[:i], _2m(int(g[i+1:]), _SPACE_(georef, n))

307 else:

308 return g, None

309

310 g = Str(georef, Error=WGRSError)

311

312 g, h = _split2(g, Height, _h2m) # H is last

313 g, r = _split2(g, Radius, _r2m) # R before H

314

315 return decode3(g, center=center).to5Tuple(h, r)

316

317

318 def encode(lat, lon, precision=3, height=None, radius=None): # MCCABE 14

319 '''Encode a lat-/longitude as a C{georef} of the given precision.

320

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

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

323 @kwarg precision: Optional, the desired C{georef} resolution and length

324 (C{int} 0..11).

325 @kwarg height: Optional, height in C{meter}, see U{Designation of area

326 <https://WikiPedia.org/wiki/World_Geographic_Reference_System>}.

327 @kwarg radius: Optional, radius in C{meter}, see U{Designation of area

328 <https://WikiPedia.org/wiki/World_Geographic_Reference_System>}.

329

330 @return: The C{georef} (C{str}).

331

332 @raise RangeError: Invalid B{C{lat}} or B{C{lon}}.

333

334 @raise WGRSError: Invalid B{C{precision}}, B{C{height}} or B{C{radius}}.

335

336 @note: The B{C{precision}} value differs from I{Karney}'s U{Georef<https://

337 GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Georef.html>}.

338 The C{georef} length is M{2 * (precision + 1)} and the C{georef}

339 resolution is I{15°} for B{C{precision}} 0:, I{1°} for 1, I{1′} for 2,

340 I{0.1′} for 3, I{0.01′} for 4, ... up to I{10**(2 - precision)′}.

341 '''

342 def _option(name, m, m2_, K):

343 f = Scalar_(m, name=name, Error=WGRSError)

344 return NN(name[0].upper(), int(m2_(f * K) + _0_5))

345

346 g, _, _ = _encode3(lat, lon, precision)

347 if radius is not None: # R before H

348 g += _option(_radius_, radius, m2NM, _1_0)

349 if height is not None: # H is last

350 g += _option(_height_, height, m2ft, _0_001)

351 return g

352

353

354 def _encode3(lat, lon, precision, h=None):

355 '''Return 3-tuple C{(georef, (lat, lon), p)}.

356 '''

357 p = _2Precision(precision)

358

359 lat, lon = _2fll(lat, lon)

360

361 if h is None:

362 xt, xd, x = _divmod3( lon, _LonOrig_60B)

363 yt, yd, y = _divmod3(_off90(lat), _LatOrig_60B)

364

365 g = _LonTile[xt], _LatTile[yt]

366 if p > 0:

367 g += _DegChar[xd], _DegChar[yd]

368 p -= 1

369 if p > 0:

370 d = pow(_Base, _MaxPrec - p)

371 x = _0wd(p, x // d)

372 y = _0wd(p, y // d)

373 g += x, y

374 g = NN.join(g)

375 else:

376 g = encode(lat, lon, precision=p, height=h)

377

378 return g, (lat, lon), p # XXX Georef(''.join(g))

379

380

381 def precision(res):

382 '''Determine the L{Georef} precision to meet a required (geographic)

383 resolution.

384

385 @arg res: The required resolution (C{degrees}).

386

387 @return: The L{Georef} precision (C{int} 0..11).

388

389 @raise ValueError: Invalid B{C{res}}.

390

391 @see: Function L{wgrs.encode} for more C{precision} details.

392 '''

393 r = Scalar_(res=res)

394 for p in range(_MaxPrec):

395 if resolution(p) <= r:

396 return p

397 return _MaxPrec

398

399

400 def resolution(prec):

401 '''Determine the (geographic) resolution of a given L{Georef} precision.

402

403 @arg prec: The given precision (C{int}).

404

405 @return: The (geographic) resolution (C{degrees}).

406

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

408

409 @see: Function L{wgrs.encode} for more C{precision} details.

410 '''

411 p = Int(prec=prec, Error=WGRSError)

412 if p > 1:

413 p = min(p, _MaxPrec) - 1

414 r = _1_0 / (pow(_Base, p) * _60_0)

415 elif p < 1:

416 r = _float_Tile

417 else:

418 r = _1_0

419 return r

420

421

422__all__ += _ALL_DOCS(decode3, decode5, # functions

423 encode, precision, resolution)

424

425# **) MIT License

426#

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

428#

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

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

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

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

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

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

435#

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

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

438#

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

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

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

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

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

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

445# OTHER DEALINGS IN THE SOFTWARE.