Coverage for pygeodesy/geohash.py: 96%

283 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-12-12 14:24 -0500

1 

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

3 

4u'''Geohash en-/decoding. 

5 

6Classes L{Geohash} and L{GeohashError} and several functions to 

7encode, decode and inspect I{geohashes}. 

8 

9Transcoded from JavaScript originals by I{(C) Chris Veness 2011-2015} 

10and published under the same MIT Licence**, see U{Geohashes 

11<https://www.Movable-Type.co.UK/scripts/geohash.html>}. 

12 

13See also U{Geohash<https://WikiPedia.org/wiki/Geohash>}, 

14U{Geohash<https://GitHub.com/vinsci/geohash>}, 

15U{PyGeohash<https://PyPI.org/project/pygeohash>} and 

16U{Geohash-Javascript<https://GitHub.com/DaveTroy/geohash-js>}. 

17''' 

18 

19from pygeodesy.basics import isodd, isstr, map2 

20from pygeodesy.constants import EPS, R_M, _floatuple, _0_0, _0_5, _180_0, \ 

21 _360_0, _90_0, _N_90_0, _N_180_0 # PYCHOK used! 

22from pygeodesy.dms import parse3llh # parseDMS2 

23from pygeodesy.errors import _ValueError, _xkwds 

24from pygeodesy.fmath import favg 

25from pygeodesy.formy import equirectangular_ as _equirectangular_, \ 

26 equirectangular, euclidean, haversine, vincentys 

27from pygeodesy.interns import NN, _COMMA_, _DOT_, _E_, _N_, _NE_, _NW_, \ 

28 _S_, _SE_, _SW_, _W_ 

29from pygeodesy.lazily import _ALL_LAZY, _ALL_OTHER 

30from pygeodesy.named import _NamedDict, _NamedTuple, nameof, _xnamed 

31from pygeodesy.namedTuples import Bounds2Tuple, Bounds4Tuple, \ 

32 LatLon2Tuple, PhiLam2Tuple 

33from pygeodesy.props import deprecated_function, deprecated_method, \ 

34 deprecated_property_RO, Property_RO 

35from pygeodesy.streprs import fstr 

36from pygeodesy.units import Degrees_, Int, Lat, Lon, Precision_, Str, \ 

37 _xStrError 

38 

39from math import fabs, ldexp, log10, radians 

40 

41__all__ = _ALL_LAZY.geohash 

42__version__ = '23.12.03' 

43 

44 

45class _GH(object): 

46 '''(INTERNAL) Lazily defined constants. 

47 ''' 

48 def _4d(self, n, e, s, w): # helper 

49 return dict(N=(n, e), S=(s, w), 

50 E=(e, n), W=(w, s)) 

51 

52 @Property_RO 

53 def Borders(self): 

54 return self._4d('prxz', 'bcfguvyz', '028b', '0145hjnp') 

55 

56 Bounds4 = (_N_90_0, _N_180_0, _90_0, _180_0) 

57 

58 @Property_RO 

59 def DecodedBase32(self): # inverse GeohashBase32 map 

60 return dict((c, i) for i, c in enumerate(self.GeohashBase32)) 

61 

62 # Geohash-specific base32 map 

63 GeohashBase32 = '0123456789bcdefghjkmnpqrstuvwxyz' # no a, i, j and o 

64 

65 @Property_RO 

66 def Neighbors(self): 

67 return self._4d('p0r21436x8zb9dcf5h7kjnmqesgutwvy', 

68 'bc01fg45238967deuvhjyznpkmstqrwx', 

69 '14365h7k9dcfesgujnmqp0r2twvyx8zb', 

70 '238967debc01fg45kmstqrwxuvhjyznp') 

71 

72 @Property_RO 

73 def Sizes(self): # lat-, lon and radial size (in meter) 

74 # ... where radial = sqrt(latSize * lonWidth / PI) 

75 return (_floatuple(20032e3, 20000e3, 11292815.096), # 0 

76 _floatuple( 5003e3, 5000e3, 2821794.075), # 1 

77 _floatuple( 650e3, 1225e3, 503442.397), # 2 

78 _floatuple( 156e3, 156e3, 88013.575), # 3 

79 _floatuple( 19500, 39100, 15578.683), # 4 

80 _floatuple( 4890, 4890, 2758.887), # 5 

81 _floatuple( 610, 1220, 486.710), # 6 

82 _floatuple( 153, 153, 86.321), # 7 

83 _floatuple( 19.1, 38.2, 15.239), # 8 

84 _floatuple( 4.77, 4.77, 2.691), # 9 

85 _floatuple( 0.596, 1.19, 0.475), # 10 

86 _floatuple( 0.149, 0.149, 0.084), # 11 

87 _floatuple( 0.0186, 0.0372, 0.015)) # 12 _MaxPrec 

88 

89_GH = _GH() # PYCHOK singleton 

90_MaxPrec = 12 

91 

92 

93def _2bounds(LatLon, LatLon_kwds, s, w, n, e, name=NN): 

94 '''(INTERNAL) Return SW and NE bounds. 

95 ''' 

96 if LatLon is None: 

97 r = Bounds4Tuple(s, w, n, e, name=name) 

98 else: 

99 sw = _xnamed(LatLon(s, w, **LatLon_kwds), name) 

100 ne = _xnamed(LatLon(n, e, **LatLon_kwds), name) 

101 r = Bounds2Tuple(sw, ne, name=name) 

102 return r # _xnamed(r, name) 

103 

104 

105def _2center(bounds): 

106 '''(INTERNAL) Return the C{bounds} center. 

107 ''' 

108 return (favg(bounds.latN, bounds.latS), 

109 favg(bounds.lonE, bounds.lonW)) 

110 

111 

112def _2fll(lat, lon, *unused): 

113 '''(INTERNAL) Convert lat, lon to 2-tuple of floats. 

114 ''' 

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

116 return (Lat(lat, Error=GeohashError), 

117 Lon(lon, Error=GeohashError)) 

118 

119 

120def _2Geohash(geohash): 

121 '''(INTERNAL) Check or create a Geohash instance. 

122 ''' 

123 return geohash if isinstance(geohash, Geohash) else \ 

124 Geohash(geohash) 

125 

126 

127def _2geostr(geohash): 

128 '''(INTERNAL) Check a geohash string. 

129 ''' 

130 try: 

131 if not (0 < len(geohash) <= _MaxPrec): 

132 raise ValueError 

133 geostr = geohash.lower() 

134 for c in geostr: 

135 if c not in _GH.DecodedBase32: 

136 raise ValueError 

137 return geostr 

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

139 raise GeohashError(Geohash.__name__, geohash, cause=x) 

140 

141 

142class Geohash(Str): 

143 '''Geohash class, a named C{str}. 

144 ''' 

145 # no str.__init__ in Python 3 

146 def __new__(cls, cll, precision=None, name=NN): 

147 '''New L{Geohash} from an other L{Geohash} instance or C{str} 

148 or from a C{LatLon} instance or C{str}. 

149 

150 @arg cll: Cell or location (L{Geohash}, C{LatLon} or C{str}). 

151 @kwarg precision: Optional, the desired geohash length (C{int} 

152 1..12), see function L{geohash.encode} for 

153 some examples. 

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

155 

156 @return: New L{Geohash}. 

157 

158 @raise GeohashError: INValid or non-alphanumeric B{C{cll}}. 

159 

160 @raise TypeError: Invalid B{C{cll}}. 

161 ''' 

162 ll = None 

163 

164 if isinstance(cll, Geohash): 

165 gh = _2geostr(str(cll)) 

166 

167 elif isstr(cll): 

168 if _COMMA_ in cll: 

169 ll = _2fll(*parse3llh(cll)) 

170 gh = encode(*ll, precision=precision) 

171 else: 

172 gh = _2geostr(cll) 

173 

174 else: # assume LatLon 

175 try: 

176 ll = _2fll(cll.lat, cll.lon) 

177 gh = encode(*ll, precision=precision) 

178 except AttributeError: 

179 raise _xStrError(Geohash, cll=cll, Error=GeohashError) 

180 

181 self = Str.__new__(cls, gh, name=name or nameof(cll)) 

182 self._latlon = ll 

183 return self 

184 

185 @deprecated_property_RO 

186 def ab(self): 

187 '''DEPRECATED, use property C{philam}.''' 

188 return self.philam 

189 

190 def adjacent(self, direction, name=NN): 

191 '''Determine the adjacent cell in the given compass direction. 

192 

193 @arg direction: Compass direction ('N', 'S', 'E' or 'W'). 

194 @kwarg name: Optional name (C{str}), otherwise the name 

195 of this cell plus C{.D}irection. 

196 

197 @return: Geohash of adjacent cell (L{Geohash}). 

198 

199 @raise GeohashError: Invalid geohash or B{C{direction}}. 

200 ''' 

201 # based on <https://GitHub.com/DaveTroy/geohash-js> 

202 

203 D = direction[:1].upper() 

204 if D not in _GH.Neighbors: 

205 raise GeohashError(direction=direction) 

206 

207 e = 1 if isodd(len(self)) else 0 

208 

209 c = self[-1:] # last hash char 

210 i = _GH.Neighbors[D][e].find(c) 

211 if i < 0: 

212 raise GeohashError(geohash=self) 

213 

214 p = self[:-1] # hash without last char 

215 # check for edge-cases which don't share common prefix 

216 if p and (c in _GH.Borders[D][e]): 

217 p = Geohash(p).adjacent(D) 

218 

219 n = name or self.name 

220 if n: 

221 n = _DOT_(n, D) 

222 # append letter for direction to parent 

223 return Geohash(p + _GH.GeohashBase32[i], name=n) 

224 

225 @Property_RO 

226 def _bounds(self): 

227 '''(INTERNAL) Cache for L{bounds}. 

228 ''' 

229 return bounds(self) 

230 

231 def bounds(self, LatLon=None, **LatLon_kwds): 

232 '''Return the lower-left SW and upper-right NE bounds of this 

233 geohash cell. 

234 

235 @kwarg LatLon: Optional class to return I{bounds} (C{LatLon}) 

236 or C{None}. 

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

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

239 

240 @return: A L{Bounds2Tuple}C{(latlonSW, latlonNE)} of B{C{LatLon}}s 

241 or a L{Bounds4Tuple}C{(latS, lonW, latN, lonE)} if 

242 C{B{LatLon} is None}, 

243 ''' 

244 r = self._bounds 

245 return r if LatLon is None else \ 

246 _2bounds(LatLon, LatLon_kwds, *r, name=self.name) 

247 

248 def _distanceTo(self, func_, other, **kwds): 

249 '''(INTERNAL) Helper for distances, see C{formy._distanceTo*}. 

250 ''' 

251 lls = self.latlon + _2Geohash(other).latlon 

252 return func_(*lls, **kwds) 

253 

254 def distanceTo(self, other): 

255 '''Estimate the distance between this and an other geohash 

256 based the cell sizes. 

257 

258 @arg other: The other geohash (L{Geohash}, C{LatLon} or C{str}). 

259 

260 @return: Approximate distance (C{meter}). 

261 

262 @raise TypeError: The B{C{other}} is not a L{Geohash}, 

263 C{LatLon} or C{str}. 

264 ''' 

265 other = _2Geohash(other) 

266 

267 n = min(len(self), len(other), len(_GH.Sizes)) 

268 if n: 

269 for n in range(n): 

270 if self[n] != other[n]: 

271 break 

272 return _GH.Sizes[n][2] 

273 

274 @deprecated_method 

275 def distance1To(self, other): # PYCHOK no cover 

276 '''DEPRECATED, use method L{distanceTo}.''' 

277 return self.distanceTo(other) 

278 

279 distance1 = distance1To 

280 

281 @deprecated_method 

282 def distance2To(self, other, radius=R_M, adjust=False, wrap=False): # PYCHOK no cover 

283 '''DEPRECATED, use method L{equirectangularTo}.''' 

284 return self.equirectangularTo(other, radius=radius, adjust=adjust, wrap=wrap) 

285 

286 distance2 = distance2To 

287 

288 @deprecated_method 

289 def distance3To(self, other, radius=R_M, wrap=False): # PYCHOK no cover 

290 '''DEPRECATED, use method L{haversineTo}.''' 

291 return self.haversineTo(other, radius=radius, wrap=wrap) 

292 

293 distance3 = distance3To 

294 

295 def equirectangularTo(self, other, radius=R_M, **adjust_limit_wrap): 

296 '''Approximate the distance between this and an other geohash 

297 using function L{pygeodesy.equirectangular}. 

298 

299 @arg other: The other geohash (L{Geohash}, C{LatLon} or C{str}). 

300 @kwarg radius: Mean earth radius, ellipsoid or datum 

301 (C{meter}, L{Ellipsoid}, L{Ellipsoid2}, 

302 L{Datum} or L{a_f2Tuple}) or C{None}. 

303 @kwarg adjust_limit_wrap: Optional keyword arguments for 

304 function L{pygeodesy.equirectangular_}, 

305 overriding defaults C{B{adjust}=False, 

306 B{limit}=None} and C{B{wrap}=False}. 

307 

308 @return: Distance (C{meter}, same units as B{C{radius}} or the 

309 ellipsoid or datum axes or C{radians I{squared}} if 

310 B{C{radius}} is C{None} or C{0}). 

311 

312 @raise TypeError: The B{C{other}} is not a L{Geohash}, C{LatLon} 

313 or C{str} or invalid B{C{radius}}. 

314 

315 @see: U{Local, flat earth approximation 

316 <https://www.EdWilliams.org/avform.htm#flat>}, functions 

317 ''' 

318 lls = self.latlon + _2Geohash(other).latlon 

319 kwds = _xkwds(adjust_limit_wrap, adjust=False, limit=None, wrap=False) 

320 return equirectangular( *lls, radius=radius, **kwds) if radius else \ 

321 _equirectangular_(*lls, **kwds).distance2 

322 

323 def euclideanTo(self, other, radius=R_M, **adjust_wrap): 

324 '''Approximate the distance between this and an other geohash 

325 using function L{pygeodesy.euclidean}. 

326 

327 @arg other: The other geohash (L{Geohash}, C{LatLon} or C{str}). 

328 @kwarg radius: Mean earth radius, ellipsoid or datum 

329 (C{meter}, L{Ellipsoid}, L{Ellipsoid2}, 

330 L{Datum} or L{a_f2Tuple}). 

331 @kwarg adjust_wrap: Optional keyword arguments for function 

332 L{pygeodesy.euclidean}. 

333 

334 @return: Distance (C{meter}, same units as B{C{radius}} or the 

335 ellipsoid or datum axes). 

336 

337 @raise TypeError: The B{C{other}} is not a L{Geohash}, C{LatLon} 

338 or C{str} or invalid B{C{radius}}. 

339 ''' 

340 return self._distanceTo(euclidean, other, radius=radius, 

341 **adjust_wrap) 

342 

343 def haversineTo(self, other, **radius_wrap): 

344 '''Compute the distance between this and an other geohash using 

345 the L{pygeodesy.haversine} formula. 

346 

347 @arg other: The other geohash (L{Geohash}, C{LatLon} or C{str}). 

348 @kwarg radius_wrap: Optional keyword arguments for function 

349 L{pygeodesy.haversine}. 

350 

351 @return: Distance (C{meter}, same units as B{C{radius}} or the 

352 ellipsoid or datum axes). 

353 

354 @raise TypeError: The B{C{other}} is not a L{Geohash}, C{LatLon} 

355 or C{str} or invalid B{C{radius}}. 

356 ''' 

357 return self._distanceTo(haversine, other, **radius_wrap) 

358 

359 @Property_RO 

360 def latlon(self): 

361 '''Get the lat- and longitude of (the approximate center of) 

362 this geohash as a L{LatLon2Tuple}C{(lat, lon)} in C{degrees}. 

363 ''' 

364 lat, lon = self._latlon or _2center(self.bounds()) 

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

366 

367 @Property_RO 

368 def neighbors(self): 

369 '''Get all 8 adjacent cells as a L{Neighbors8Dict}C{(N, NE, 

370 E, SE, S, SW, W, NW)} of L{Geohash}es. 

371 ''' 

372 return Neighbors8Dict(N=self.N, NE=self.NE, E=self.E, SE=self.SE, 

373 S=self.S, SW=self.SW, W=self.W, NW=self.NW, 

374 name=self.name) 

375 

376 @Property_RO 

377 def philam(self): 

378 '''Get the lat- and longitude of (the approximate center of) 

379 this geohash as a L{PhiLam2Tuple}C{(phi, lam)} in C{radians}. 

380 ''' 

381 return PhiLam2Tuple(map2(radians, self.latlon), name=self.name) # *map2 

382 

383 @Property_RO 

384 def precision(self): 

385 '''Get this geohash's precision (C{int}). 

386 ''' 

387 return len(self) 

388 

389 @Property_RO 

390 def sizes(self): 

391 '''Get the lat- and longitudinal size of this cell as 

392 a L{LatLon2Tuple}C{(lat, lon)} in (C{meter}). 

393 ''' 

394 z = _GH.Sizes 

395 n = min(len(z) - 1, max(self.precision, 1)) 

396 return LatLon2Tuple(z[n][:2], name=self.name) # *z XXX Height, Width? 

397 

398 def toLatLon(self, LatLon=None, **LatLon_kwds): 

399 '''Return (the approximate center of) this geohash cell 

400 as an instance of the supplied C{LatLon} class. 

401 

402 @arg LatLon: Class to use (C{LatLon}) or C{None}. 

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

404 keyword arguments, ignored if 

405 C{B{LatLon} is None}. 

406 

407 @return: This geohash location (B{C{LatLon}}) or a 

408 L{LatLon2Tuple}C{(lat, lon)} if B{C{LatLon}} 

409 is C{None}. 

410 

411 @raise TypeError: Invalid B{C{LatLon}} or B{C{LatLon_kwds}}. 

412 ''' 

413 return self.latlon if LatLon is None else _xnamed(LatLon( 

414 *self.latlon, **LatLon_kwds), self.name) 

415 

416 def vincentysTo(self, other, **radius_wrap): 

417 '''Compute the distance between this and an other geohash using 

418 the L{pygeodesy.vincentys} formula. 

419 

420 @arg other: The other geohash (L{Geohash}, C{LatLon} or C{str}). 

421 @kwarg radius_wrap: Optional keyword arguments for function 

422 L{pygeodesy.vincentys}. 

423 

424 @return: Distance (C{meter}, same units as B{C{radius}} or the 

425 ellipsoid or datum axes). 

426 

427 @raise TypeError: The B{C{other}} is not a L{Geohash}, C{LatLon} 

428 or C{str} or invalid B{C{radius}}. 

429 ''' 

430 return self._distanceTo(vincentys, other, **radius_wrap) 

431 

432 @Property_RO 

433 def N(self): 

434 '''Get the cell North of this (L{Geohash}). 

435 ''' 

436 return self.adjacent(_N_) 

437 

438 @Property_RO 

439 def S(self): 

440 '''Get the cell South of this (L{Geohash}). 

441 ''' 

442 return self.adjacent(_S_) 

443 

444 @Property_RO 

445 def E(self): 

446 '''Get the cell East of this (L{Geohash}). 

447 ''' 

448 return self.adjacent(_E_) 

449 

450 @Property_RO 

451 def W(self): 

452 '''Get the cell West of this (L{Geohash}). 

453 ''' 

454 return self.adjacent(_W_) 

455 

456 @Property_RO 

457 def NE(self): 

458 '''Get the cell NorthEast of this (L{Geohash}). 

459 ''' 

460 return self.N.E 

461 

462 @Property_RO 

463 def NW(self): 

464 '''Get the cell NorthWest of this (L{Geohash}). 

465 ''' 

466 return self.N.W 

467 

468 @Property_RO 

469 def SE(self): 

470 '''Get the cell SouthEast of this (L{Geohash}). 

471 ''' 

472 return self.S.E 

473 

474 @Property_RO 

475 def SW(self): 

476 '''Get the cell SouthWest of this (L{Geohash}). 

477 ''' 

478 return self.S.W 

479 

480 

481class GeohashError(_ValueError): 

482 '''Geohash encode, decode or other L{Geohash} issue. 

483 ''' 

484 pass 

485 

486 

487class Neighbors8Dict(_NamedDict): 

488 '''8-Dict C{(N, NE, E, SE, S, SW, W, NW)} of L{Geohash}es, 

489 providing key I{and} attribute access to the items. 

490 ''' 

491 _Keys_ = (_N_, _NE_, _E_, _SE_, _S_, _SW_, _W_, _NW_) 

492 

493 def __init__(self, **kwds): # PYCHOK no *args 

494 kwds = _xkwds(kwds, **_Neighbors8Defaults) 

495 _NamedDict.__init__(self, **kwds) # name=... 

496 

497 

498_Neighbors8Defaults = dict(zip(Neighbors8Dict._Keys_, (None,) * 

499 len(Neighbors8Dict._Keys_))) # XXX frozendict 

500 

501 

502def bounds(geohash, LatLon=None, **LatLon_kwds): 

503 '''Returns the lower-left SW and upper-right NE corners of a geohash. 

504 

505 @arg geohash: To be bound (L{Geohash}). 

506 @kwarg LatLon: Optional class to return the bounds (C{LatLon}) 

507 or C{None}. 

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

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

510 

511 @return: A L{Bounds2Tuple}C{(latlonSW, latlonNE)} of B{C{LatLon}}s 

512 or if B{C{LatLon}} is C{None}, a L{Bounds4Tuple}C{(latS, 

513 lonW, latN, lonE)}. 

514 

515 @raise TypeError: The B{C{geohash}} is not a L{Geohash}, C{LatLon} 

516 or C{str} or invalid B{C{LatLon}} or invalid 

517 B{C{LatLon_kwds}}. 

518 

519 @raise GeohashError: Invalid or C{null} B{C{geohash}}. 

520 ''' 

521 gh = _2Geohash(geohash) 

522 if len(gh) < 1: 

523 raise GeohashError(geohash=geohash) 

524 

525 s, w, n, e = _GH.Bounds4 

526 try: 

527 d = True 

528 for c in gh.lower(): 

529 i = _GH.DecodedBase32[c] 

530 for m in (16, 8, 4, 2, 1): 

531 if d: # longitude 

532 if i & m: 

533 w = favg(w, e) 

534 else: 

535 e = favg(w, e) 

536 else: # latitude 

537 if i & m: 

538 s = favg(s, n) 

539 else: 

540 n = favg(s, n) 

541 d = not d 

542 except KeyError: 

543 raise GeohashError(geohash=geohash) 

544 

545 return _2bounds(LatLon, LatLon_kwds, s, w, n, e, 

546 name=nameof(geohash)) 

547 

548 

549def _bounds3(geohash): 

550 '''(INTERNAL) Return 3-tuple C{(bounds, height, width)}. 

551 ''' 

552 b = bounds(geohash) 

553 return b, (b.latN - b.latS), (b.lonE - b.lonW) 

554 

555 

556def decode(geohash): 

557 '''Decode a geohash to lat-/longitude of the (approximate 

558 centre of) geohash cell to reasonable precision. 

559 

560 @arg geohash: To be decoded (L{Geohash}). 

561 

562 @return: 2-Tuple C{(latStr, lonStr)}, both C{str}. 

563 

564 @raise TypeError: The B{C{geohash}} is not a L{Geohash}, 

565 C{LatLon} or C{str}. 

566 

567 @raise GeohashError: Invalid or null B{C{geohash}}. 

568 ''' 

569 b, h, w = _bounds3(geohash) 

570 lat, lon = _2center(b) 

571 

572 # round to near centre without excessive precision to 

573 # ⌊2-log10(Δ°)⌋ decimal places, strip trailing zeros 

574 return (fstr(lat, prec=int(2 - log10(h))), 

575 fstr(lon, prec=int(2 - log10(w)))) # strs! 

576 

577 

578def decode2(geohash, LatLon=None, **LatLon_kwds): 

579 '''Decode a geohash to lat-/longitude of the (approximate 

580 centre of) geohash cell to reasonable precision. 

581 

582 @arg geohash: To be decoded (L{Geohash}). 

583 @kwarg LatLon: Optional class to return the location (C{LatLon}) 

584 or C{None}. 

585 @kwarg LatLon_kwds: Optional, addtional B{C{LatLon}} keyword 

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

587 

588 @return: L{LatLon2Tuple}C{(lat, lon)}, both C{degrees} if 

589 C{B{LatLon} is None}, otherwise a B{C{LatLon}} instance. 

590 

591 @raise TypeError: The B{C{geohash}} is not a L{Geohash}, 

592 C{LatLon} or C{str}. 

593 

594 @raise GeohashError: Invalid or null B{C{geohash}}. 

595 ''' 

596 t = map2(float, decode(geohash)) 

597 r = LatLon2Tuple(t) if LatLon is None else LatLon(*t, **LatLon_kwds) # *t 

598 return _xnamed(r, decode2.__name__) 

599 

600 

601def decode_error(geohash): 

602 '''Return the relative lat-/longitude decoding errors for 

603 this geohash. 

604 

605 @arg geohash: To be decoded (L{Geohash}). 

606 

607 @return: A L{LatLon2Tuple}C{(lat, lon)} with the lat- and 

608 longitudinal errors in (C{degrees}). 

609 

610 @raise TypeError: The B{C{geohash}} is not a L{Geohash}, 

611 C{LatLon} or C{str}. 

612 

613 @raise GeohashError: Invalid or null B{C{geohash}}. 

614 ''' 

615 _, h, w = _bounds3(geohash) 

616 return LatLon2Tuple(h * _0_5, # Height error 

617 w * _0_5) # Width error 

618 

619 

620def distance_(geohash1, geohash2): 

621 '''Estimate the distance between two geohash (from the cell sizes). 

622 

623 @arg geohash1: First geohash (L{Geohash}, C{LatLon} or C{str}). 

624 @arg geohash2: Second geohash (L{Geohash}, C{LatLon} or C{str}). 

625 

626 @return: Approximate distance (C{meter}). 

627 

628 @raise TypeError: If B{C{geohash1}} or B{C{geohash2}} is 

629 not a L{Geohash}, C{LatLon} or C{str}. 

630 ''' 

631 return _2Geohash(geohash1).distanceTo(geohash2) 

632 

633 

634@deprecated_function 

635def distance1(geohash1, geohash2): 

636 '''DEPRECATED, used L{geohash.distance_}.''' 

637 return distance_(geohash1, geohash2) 

638 

639 

640@deprecated_function 

641def distance2(geohash1, geohash2): 

642 '''DEPRECATED, used L{geohash.equirectangular_}.''' 

643 return equirectangular_(geohash1, geohash2) 

644 

645 

646@deprecated_function 

647def distance3(geohash1, geohash2): 

648 '''DEPRECATED, used L{geohash.haversine_}.''' 

649 return haversine_(geohash1, geohash2) 

650 

651 

652def encode(lat, lon, precision=None): 

653 '''Encode a lat-/longitude as a C{geohash}, either to the specified 

654 precision or if not provided, to an automatically evaluated 

655 precision. 

656 

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

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

659 @kwarg precision: Optional, the desired geohash length (C{int} 

660 1..12). 

661 

662 @return: The C{geohash} (C{str}). 

663 

664 @raise GeohashError: Invalid B{C{lat}}, B{C{lon}} or B{C{precision}}. 

665 ''' 

666 lat, lon = _2fll(lat, lon) 

667 

668 if precision is None: 

669 # Infer precision by refining geohash until 

670 # it matches precision of supplied lat/lon. 

671 for p in range(1, _MaxPrec + 1): 

672 gh = encode(lat, lon, p) 

673 ll = map2(float, decode(gh)) 

674 if fabs(lat - ll[0]) < EPS and \ 

675 fabs(lon - ll[1]) < EPS: 

676 return gh 

677 p = _MaxPrec 

678 else: 

679 p = Precision_(precision, Error=GeohashError, low=1, high=_MaxPrec) 

680 

681 b = i = 0 

682 d, gh = True, [] 

683 s, w, n, e = _GH.Bounds4 

684 

685 while p > 0: 

686 i += i 

687 if d: # bisect longitude 

688 m = favg(e, w) 

689 if lon < m: 

690 e = m 

691 else: 

692 w = m 

693 i += 1 

694 else: # bisect latitude 

695 m = favg(n, s) 

696 if lat < m: 

697 n = m 

698 else: 

699 s = m 

700 i += 1 

701 d = not d 

702 

703 b += 1 

704 if b == 5: 

705 # 5 bits gives a character: 

706 # append it and start over 

707 gh.append(_GH.GeohashBase32[i]) 

708 b = i = 0 

709 p -= 1 

710 

711 return NN.join(gh) 

712 

713 

714def equirectangular_(geohash1, geohash2, radius=R_M): 

715 '''Approximate the distance between two geohashes using the 

716 L{pygeodesy.equirectangular} formula. 

717 

718 @arg geohash1: First geohash (L{Geohash}, C{LatLon} or C{str}). 

719 @arg geohash2: Second geohash (L{Geohash}, C{LatLon} or C{str}). 

720 @kwarg radius: Mean earth radius (C{meter}) or C{None}. 

721 

722 @return: Approximate distance (C{meter}, same units as 

723 B{C{radius}}). 

724 

725 @raise TypeError: If B{C{geohash1}} or B{C{geohash2}} is 

726 not a L{Geohash}, C{LatLon} or C{str}. 

727 ''' 

728 return _2Geohash(geohash1).equirectangularTo(geohash2, radius=radius) 

729 

730 

731def haversine_(geohash1, geohash2, radius=R_M): 

732 '''Compute the great-circle distance between two geohashes 

733 using the L{pygeodesy.haversine} formula. 

734 

735 @arg geohash1: First geohash (L{Geohash}, C{LatLon} or C{str}). 

736 @arg geohash2: Second geohash (L{Geohash}, C{LatLon} or C{str}). 

737 @kwarg radius: Mean earth radius (C{meter}). 

738 

739 @return: Great-circle distance (C{meter}, same units as 

740 B{C{radius}}). 

741 

742 @raise TypeError: If B{C{geohash1}} or B{C{geohash2}} is 

743 not a L{Geohash}, C{LatLon} or C{str}. 

744 ''' 

745 return _2Geohash(geohash1).haversineTo(geohash2, radius=radius) 

746 

747 

748def neighbors(geohash): 

749 '''Return the L{Geohash}es for all 8 adjacent cells. 

750 

751 @arg geohash: Cell for which neighbors are requested 

752 (L{Geohash} or C{str}). 

753 

754 @return: A L{Neighbors8Dict}C{(N, NE, E, SE, S, SW, W, NW)} 

755 of L{Geohash}es. 

756 

757 @raise TypeError: The B{C{geohash}} is not a L{Geohash}, 

758 C{LatLon} or C{str}. 

759 ''' 

760 return _2Geohash(geohash).neighbors 

761 

762 

763def precision(res1, res2=None): 

764 '''Determine the L{Geohash} precisions to meet a or both given 

765 (geographic) resolutions. 

766 

767 @arg res1: The required primary I{(longitudinal)} resolution 

768 (C{degrees}). 

769 @kwarg res2: Optional, required secondary I{(latitudinal)} 

770 resolution (C{degrees}). 

771 

772 @return: The L{Geohash} precision or length (C{int}, 1..12). 

773 

774 @raise GeohashError: Invalid B{C{res1}} or B{C{res2}}. 

775 

776 @see: C++ class U{Geohash 

777 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Geohash.html>}. 

778 ''' 

779 r = Degrees_(res1=res1, low=_0_0, Error=GeohashError) 

780 if res2 is None: 

781 t = r, r 

782 for p in range(1, _MaxPrec): 

783 if resolution2(p, None) <= t: 

784 return p 

785 

786 else: 

787 t = r, Degrees_(res2=res2, low=_0_0, Error=GeohashError) 

788 for p in range(1, _MaxPrec): 

789 if resolution2(p, p) <= t: 

790 return p 

791 

792 return _MaxPrec 

793 

794 

795class Resolutions2Tuple(_NamedTuple): 

796 '''2-Tuple C{(res1, res2)} with the primary I{(longitudinal)} and 

797 secondary I{(latitudinal)} resolution, both in C{degrees}. 

798 ''' 

799 _Names_ = ('res1', 'res2') 

800 _Units_ = ( Degrees_, Degrees_) 

801 

802 

803def resolution2(prec1, prec2=None): 

804 '''Determine the (geographic) resolutions of given L{Geohash} 

805 precisions. 

806 

807 @arg prec1: The given primary I{(longitudinal)} precision 

808 (C{int} 1..12). 

809 @kwarg prec2: Optional, secondary I{(latitudinal)} precision 

810 (C{int} 1..12). 

811 

812 @return: L{Resolutions2Tuple}C{(res1, res2)} with the 

813 (geographic) resolutions C{degrees}, where C{res2} 

814 B{C{is}} C{res1} if no B{C{prec2}} is given. 

815 

816 @raise GeohashError: Invalid B{C{prec1}} or B{C{prec2}}. 

817 

818 @see: I{Karney}'s C++ class U{Geohash 

819 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Geohash.html>}. 

820 ''' 

821 res1, res2 = _360_0, _180_0 # note ... lon, lat! 

822 

823 if prec1: 

824 p = 5 * max(0, min(Int(prec1=prec1, Error=GeohashError), _MaxPrec)) 

825 res1 = res2 = ldexp(res1, -(p - p // 2)) 

826 

827 if prec2: 

828 p = 5 * max(0, min(Int(prec2=prec2, Error=GeohashError), _MaxPrec)) 

829 res2 = ldexp(res2, -(p // 2)) 

830 

831 return Resolutions2Tuple(res1, res2) 

832 

833 

834def sizes(geohash): 

835 '''Return the lat- and longitudinal size of this L{Geohash} cell. 

836 

837 @arg geohash: Cell for which size are required (L{Geohash} or 

838 C{str}). 

839 

840 @return: A L{LatLon2Tuple}C{(lat, lon)} with the latitudinal 

841 height and longitudinal width in (C{meter}). 

842 

843 @raise TypeError: The B{C{geohash}} is not a L{Geohash}, 

844 C{LatLon} or C{str}. 

845 ''' 

846 return _2Geohash(geohash).sizes 

847 

848 

849__all__ += _ALL_OTHER(bounds, # functions 

850 decode, decode2, decode_error, distance_, 

851 encode, equirectangular_, haversine_, 

852 neighbors, precision, resolution2, sizes) 

853 

854# **) MIT License 

855# 

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

857# 

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

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

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

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

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

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

864# 

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

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

867# 

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

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

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

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

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

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

874# OTHER DEALINGS IN THE SOFTWARE.