Coverage for pygeodesy/geohash.py: 98%
365 statements
« prev ^ index » next coverage.py v7.6.0, created at 2024-08-02 18:24 -0400
« prev ^ index » next coverage.py v7.6.0, created at 2024-08-02 18:24 -0400
2# -*- coding: utf-8 -*-
4u'''I{Gustavo Niemeyer}’s U{Geohash<https://WikiPedia.org/wiki/Geohash>}.
6Class L{Geohash} and several functions to encode, decode and inspect
7C{geohashes} and optional L{Geohashed} caches.
9Originally transcoded from JavaScript originals by I{(C) Chris Veness
102011-2015} and published under the same MIT Licence**, see
11U{Geohashes<https://www.Movable-Type.co.UK/scripts/geohash.html>}.
13@see: U{Geohash<https://WikiPedia.org/wiki/Geohash>}, I{Karney}'s C++
14 U{Geohash<https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Geohash.html>},
15 U{geohash<https://GitHub.com/vinsci/geohash>},
16 U{pygeohash<https://PyPI.org/project/pygeohash>} and
17 U{geohash-js<https://GitHub.com/DaveTroy/geohash-js>}.
18'''
20from pygeodesy.basics import isstr, map2
21from pygeodesy.constants import EPS, R_M, _0_0, _0_5, _180_0, _360_0, \
22 _90_0, _N_90_0, _N_180_0 # PYCHOK used!
23from pygeodesy.errors import _ValueError, _xkwds, _xStrError
24# from pygeodesy import formy as _formy # _MODS
25from pygeodesy.interns import NN, _COMMA_, _DOT_, _E_, _height_, _N_, _NE_, \
26 _NW_, _radius_, _S_, _SE_, _SPACE_, _SW_, _W_, \
27 _width_
28from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS
29from pygeodesy.named import _name__, _NamedDict, _NamedTuple, nameof, _xnamed
30from pygeodesy.namedTuples import Bounds2Tuple, Bounds4Tuple, LatLon2Tuple, \
31 PhiLam2Tuple
32from pygeodesy.props import deprecated_function, deprecated_method, \
33 deprecated_property_RO, Property_RO, \
34 property_RO, property_ROver
35# from pygeodesy.streprs import Fmt, fstr # _MODS
36from pygeodesy.units import Degrees_, Int, Lat_, Lon_, Meter, Precision_, Str
38from math import fabs, ldexp, log10, radians
40__all__ = _ALL_LAZY.geohash
41__version__ = '24.08.02'
43_formy = _MODS.into(formy=__name__)
44_MASK5 = 16, 8, 4, 2, 1 # PYCHOK used!
45_MaxPrec = 12
48def _2bounds(LatLon, LatLon_kwds, s, w, n, e, **name):
49 '''(INTERNAL) Return SW and NE bounds.
50 '''
51 if LatLon is None:
52 r = Bounds4Tuple(s, w, n, e, **name)
53 else:
54 kwds = _xkwds(LatLon_kwds, **name)
55 r = Bounds2Tuple(LatLon(s, w, **kwds),
56 LatLon(n, e, **kwds), **name)
57 return r
60def _2center(bounds):
61 '''(INTERNAL) Return the C{bounds} center.
62 '''
63 return (_2mid(bounds.latN, bounds.latS),
64 _2mid(bounds.lonE, bounds.lonW))
67def _2dab(d, a, b):
68 '''(INTERNAL) Get delta lat or lon from center.
69 '''
70 return fabs(d - round(*_2mid_ndigits(a, b)))
73def _2fll(lat, lon, *unused):
74 '''(INTERNAL) Convert lat, lon to 2-tuple of floats.
75 '''
76 # lat, lon = parseDMS2(lat, lon)
77 return (Lat_(lat, Error=GeohashError),
78 Lon_(lon, Error=GeohashError))
81def _2Geohash(geohash):
82 '''(INTERNAL) Check or create a Geohash instance.
83 '''
84 return geohash if isinstance(geohash, Geohash) else \
85 Geohash(geohash)
88def _2latlon(s, w, n, e, fstr=None):
89 '''(INTERNAL) Get the center C{lat, lon}, rounded.
90 '''
91 lat, a = _2mid_ndigits(n, s)
92 lon, b = _2mid_ndigits(e, w)
93 return (fstr(lat, prec=a), fstr(lon, prec=b)) if fstr else \
94 (round(lat, a), round(lon, b))
97def _2mid(a, b):
98 '''(INTERNAL) Bisect C{a} to C{b}.
99 '''
100 return (a + b) * _0_5 # favg
103def _2mid_ndigits(a, b): # a > b
104 '''(INTERNAL) Return 2-tuple C{(_2mid, ndigits)}.
105 '''
106 # round to near centre without excessive
107 # precision to ⌊2-log10(Δ°)⌋ ndigits
108 return _2mid(a, b), int(2 - log10(a - b))
111def _2Precision(p):
112 '''(INTERNAL) Get a valid C{Precision}.
113 '''
114 return Precision_(p, low=1, high=_MaxPrec, Error=GeohashError)
117def _2res(res, **prec):
118 '''(INTERNAL) Get the C{res}olution for a C{prec}ision.
119 '''
120 p = max(min(Int(Error=GeohashError, **prec), _MaxPrec), 0) * 5
121 p = (p - p // 2) if res > _180_0 else (p // 2)
122 return ldexp(res, -p) if p else res
125class _GH(object):
126 '''(INTERNAL) Lazily defined constants.
127 '''
128 def _4d(self, s, w, n, e): # helper
129 return dict(S=(s, w), W=(w, s),
130 N=(n, e), E=(e, n))
132 @property_ROver
133 def Borders(self):
134 return self._4d('028b', '0145hjnp', 'prxz', 'bcfguvyz')
136 @property_ROver
137 def DecodeB32(self): # inverse EncodeB32 map
138 return dict((c, i) for i, c in enumerate(self.EncodeB32))
140 def decode2(self, geohash):
141 '''Decode C{geohash} to 2-tuple C{(lat, lon)}.
142 '''
143 swne = self.swne4(geohash)
144 return _2latlon(*swne)
146 # Geohash's base32 codes, no a, i, l and o
147 EncodeB32 = '0123456789bcdefghjkmnpqrstuvwxyz'
149 def encode(self, *lat_lon_prec_eps):
150 '''Encode C{lat, lon} to C{prec}ision or C{eps}.
151 '''
152 def _encodes(lat, lon, prec, eps=0):
153 s, w, n, e = self.SWNE4
154 E, d, _mid = self.EncodeB32, True, _2mid
155 for _ in range(prec):
156 i = 0
157 for _ in range(5): # len(_MASK5)
158 i += i
159 if d: # bisect longitude
160 a = _mid(e, w)
161 if lon < a:
162 e = a
163 else:
164 w = a
165 i += 1
166 else: # bisect latitude
167 a = _mid(n, s)
168 if lat < a:
169 n = a
170 else:
171 s = a
172 i += 1
173 d = not d
174 yield E[i]
175 if eps > 0: # infer prec
176 if _2dab(lon, e, w) < eps and \
177 _2dab(lat, n, s) < eps:
178 break
180 return NN.join(_encodes(*lat_lon_prec_eps))
182 def encode2(self, lat, lon, prec, eps):
183 '''Return 2-tuple C{geohash, (lat, lon))}.
184 '''
185 lat, lon = _2fll(lat, lon)
186 if prec:
187 p, e = _2Precision(prec), 0
188 else: # infer precision by refining geohash
189 p, e = _MaxPrec, max(eps, EPS)
190 return self.encode(lat, lon, p, e), (lat, lon)
192 @property_ROver
193 def _LatLon2Tuple(self):
195 class _LatLon2Tuple(_NamedTuple):
196 '''DEPRECATED on 2024.07.28, C{(lat, lon)} in B{C{meter}}, use L{Sizes3Tuple}.'''
197 _Names_ = LatLon2Tuple._Names_
198 _Units_ = Meter, Meter
200 return _LatLon2Tuple
202 @property_ROver
203 def Neighbors(self):
204 return self._4d('14365h7k9dcfesgujnmqp0r2twvyx8zb',
205 '238967debc01fg45kmstqrwxuvhjyznp',
206 'p0r21436x8zb9dcf5h7kjnmqesgutwvy',
207 'bc01fg45238967deuvhjyznpkmstqrwx')
209 @property_ROver
210 def Sizes(self): # height, width and radius (in meter)
211 # where radius = sqrt(height * width / PI), the
212 # radius of a circle with area (height * width)
213 T = Sizes3Tuple
214 return (T(20000e3, 20032e3, 11292815.096), # 0
215 T( 5000e3, 5003e3, 2821794.075), # 1
216 T( 650e3, 1225e3, 503442.397), # 2
217 T( 156e3, 156e3, 88013.575), # 3
218 T( 19500, 39100, 15578.683), # 4
219 T( 4890, 4890, 2758.887), # 5
220 T( 610, 1220, 486.710), # 6
221 T( 153, 153, 86.321), # 7
222 T( 19.1, 38.2, 15.239), # 8
223 T( 4.77, 4.77, 2.691), # 9
224 T( 0.596, 1.19, 0.475), # 10
225 T( 0.149, 0.149, 0.084), # 11
226 T( 0.0186, 0.0372, 0.015)) # 12 _MaxPrec
228 SWNE4 = (_N_90_0, _N_180_0, _90_0, _180_0)
230 def swne4(self, geohash, mask5=_MASK5):
231 '''Decode C{geohash} into 4-tuple C{(s, w, n, e)}.
232 '''
233 nc = len(geohash) if isstr(geohash) else 0
234 if not (0 < nc <= _MaxPrec):
235 raise GeohashError(geohash=geohash, len=nc)
236 s, w, n, e = self.SWNE4
237 D, d, _mid = self.DecodeB32, True, _2mid
238 try:
239 for j, c in enumerate(geohash.lower()):
240 i = D[c]
241 for m in mask5:
242 if d: # longitude
243 a = _mid(e, w)
244 if (i & m):
245 w = a
246 else:
247 e = a
248 else: # latitude
249 a = _mid(n, s)
250 if (i & m):
251 s = a
252 else:
253 n = a
254 d = not d
255 except KeyError:
256 c = _MODS.streprs.Fmt.INDEX(repr(c), j)
257 raise GeohashError(geohash=geohash, len=nc, txt=c)
258 return s, w, n, e
260_GH = _GH() # PYCHOK singleton
263class Geohash(Str):
264 '''Geohash class, a named C{str}.
265 '''
266 # no str.__init__ in Python 3
267 def __new__(cls, lat_ghll, lon=None, precision=None, eps=EPS, **name):
268 '''New L{Geohash} from an other L{Geohash} instance or geohash C{str}
269 or from a lat- and longitude.
271 @arg lat_ghll: Latitude (C{degrees90}), a geohash (L{Geohash},
272 C{str}) or a location (C{LatLon}, C{LatLon*Tuple}).
273 @kwarg lon: Logitude (C{degrees180)}, required if B{C{lat_ghll}}
274 is C{degrees90}, ignored otherwise.
275 @kwarg precision: The desired geohash length (C{int} 1..12) or
276 C{None} or C{0}, see L{encode<pygeodesy.geohash.encode>}.
277 @kwarg eps: Optional inference tolerance (C{degrees}), see
278 L{encode<pygeodesy.geohash.encode>}.
279 @kwarg name: Optional C{B{name}=NN} (C{str}).
281 @return: New L{Geohash}.
283 @raise GeohashError: Invalid B{C{lat_ghll}}.
285 @raise RangeError: Invalid B{C{lat_gll}} or B{C{lon}}.
287 @raise TypeError: Invalid B{C{lat_ghll}}.
288 '''
289 if lon is None:
290 if isinstance(lat_ghll, Geohash):
291 gh, ll = str(lat_ghll), lat_ghll.latlon
292 elif isstr(lat_ghll): # "lat, lon" or "geohash"
293 ll = lat_ghll.replace(_COMMA_, _SPACE_).split()
294 if len(ll) > 1:
295 gh, ll = _GH.encode2(ll[0], ll[1], precision, eps)
296 else:
297 gh, ll = lat_ghll.lower(), None
298 _ = _GH.swne4(gh, mask5=()) # validate
299 else: # assume LatLon
300 try:
301 gh, ll = _GH.encode2(lat_ghll.lat, lat_ghll.lon, precision, eps)
302 except AttributeError:
303 raise _xStrError(Geohash, ghll=lat_ghll, Error=GeohashError)
304 else:
305 gh, ll = _GH.encode2(lat_ghll, lon, precision, eps)
307 self = Str.__new__(cls, gh, name=_name__(name, _or_nameof=lat_ghll))
308 self._latlon = ll
309 return self
311 @deprecated_property_RO
312 def ab(self):
313 '''DEPRECATED, use property C{philam}.'''
314 return self.philam
316 def adjacent(self, direction, **name):
317 '''Determine the adjacent cell in the given compass direction.
319 @arg direction: Compass direction ('N', 'S', 'E' or 'W').
320 @kwarg name: Optional C{B{name}=NN} (C{str}) otherwise this
321 cell's name, either extended with C{.D}irection.
323 @return: Geohash of adjacent cell (L{Geohash}).
325 @raise GeohashError: Invalid geohash or B{C{direction}}.
326 '''
327 # based on <https://GitHub.com/DaveTroy/geohash-js>
329 D = direction[:1].upper()
330 if D not in _GH.Neighbors:
331 raise GeohashError(direction=direction)
333 e = len(self) & 1 # int(isodd(len(self)))
335 c = self[-1:] # last hash char
336 i = _GH.Neighbors[D][e].find(c)
337 if i < 0:
338 raise GeohashError(geohash=self)
340 p = self[:-1] # hash without last char
341 # check for edge-cases which don't share common prefix
342 if p and (c in _GH.Borders[D][e]):
343 p = Geohash(p).adjacent(D)
345 n = self._name__(name)
346 if n:
347 n = _DOT_(n, D)
348 # append letter for direction to parent
349 return Geohash(p + _GH.EncodeB32[i], name=n)
351 @Property_RO
352 def _bounds(self):
353 '''(INTERNAL) Cache for L{bounds}.
354 '''
355 return bounds(self)
357 def bounds(self, LatLon=None, **LatLon_kwds):
358 '''Return the lower-left SW and upper-right NE bounds of this
359 geohash cell.
361 @kwarg LatLon: Optional class to return I{bounds} (C{LatLon})
362 or C{None}.
363 @kwarg LatLon_kwds: Optional, additional B{C{LatLon}} keyword
364 arguments, ignored if C{B{LatLon} is None}.
366 @return: A L{Bounds2Tuple}C{(latlonSW, latlonNE)} of B{C{LatLon}}s
367 or a L{Bounds4Tuple}C{(latS, lonW, latN, lonE)} if
368 C{B{LatLon} is None},
369 '''
370 r = self._bounds
371 return r if LatLon is None else \
372 _2bounds(LatLon, LatLon_kwds, *r, name=self.name)
374 def _distanceTo(self, func_, other, **kwds):
375 '''(INTERNAL) Helper for distances, see C{.formy._distanceTo*}.
376 '''
377 lls = self.latlon + _2Geohash(other).latlon
378 return func_(*lls, **kwds)
380 def distanceTo(self, other):
381 '''Estimate the distance between this and an other geohash
382 based the cell sizes.
384 @arg other: The other geohash (L{Geohash}, C{LatLon} or C{str}).
386 @return: Approximate distance (C{meter}).
388 @raise TypeError: The B{C{other}} is not a L{Geohash},
389 C{LatLon} or C{str}.
390 '''
391 other = _2Geohash(other)
393 n = min(len(self), len(other), len(_GH.Sizes))
394 if n:
395 for n in range(n):
396 if self[n] != other[n]:
397 break
398 return _GH.Sizes[n].radius
400 @deprecated_method
401 def distance1To(self, other): # PYCHOK no cover
402 '''DEPRECATED, use method L{distanceTo}.'''
403 return self.distanceTo(other)
405 distance1 = distance1To
407 @deprecated_method
408 def distance2To(self, other, radius=R_M, adjust=False, wrap=False): # PYCHOK no cover
409 '''DEPRECATED, use method L{equirectangularTo}.'''
410 return self.equirectangularTo(other, radius=radius, adjust=adjust, wrap=wrap)
412 distance2 = distance2To
414 @deprecated_method
415 def distance3To(self, other, radius=R_M, wrap=False): # PYCHOK no cover
416 '''DEPRECATED, use method L{haversineTo}.'''
417 return self.haversineTo(other, radius=radius, wrap=wrap)
419 distance3 = distance3To
421 def equirectangularTo(self, other, radius=R_M, **adjust_limit_wrap):
422 '''Approximate the distance between this and an other geohash
423 using function L{pygeodesy.equirectangular}.
425 @arg other: The other geohash (L{Geohash}, C{LatLon} or C{str}).
426 @kwarg radius: Mean earth radius, ellipsoid or datum (C{meter},
427 L{Ellipsoid}, L{Ellipsoid2}, L{Datum} or L{a_f2Tuple})
428 or C{None}, see function L{pygeodesy.equirectangular}.
429 @kwarg adjust_limit_wrap: Optional keyword arguments for function
430 L{pygeodesy.equirectangular4}, overriding defaults
431 C{B{adjust}=False, B{limit}=None} and C{B{wrap}=False}.
433 @return: Distance (C{meter}, same units as B{C{radius}} or the ellipsoid
434 or datum axes or C{radians I{squared}} if B{C{radius} is None}
435 or C{0}).
437 @raise TypeError: The B{C{other}} is not a L{Geohash}, C{LatLon} or
438 C{str} or invalid B{C{radius}}.
440 @see: U{Local, flat earth approximation
441 <https://www.EdWilliams.org/avform.htm#flat>}, functions
442 '''
443 lls = self.latlon + _2Geohash(other).latlon
444 kwds = _xkwds(adjust_limit_wrap, adjust=False, limit=None, wrap=False)
445 return _formy.equirectangular( *lls, radius=radius, **kwds) if radius else \
446 _formy.equirectangular4(*lls, **kwds).distance2
448 def euclideanTo(self, other, **radius_adjust_wrap):
449 '''Approximate the distance between this and an other geohash using
450 function L{pygeodesy.euclidean}.
452 @arg other: The other geohash (L{Geohash}, C{LatLon} or C{str}).
453 @kwarg radius_adjust_wrap: Optional keyword arguments for function
454 L{pygeodesy.euclidean}.
456 @return: Distance (C{meter}, same units as B{C{radius}} or the
457 ellipsoid or datum axes).
459 @raise TypeError: The B{C{other}} is not a L{Geohash}, C{LatLon}
460 or C{str} or invalid B{C{radius}}.
461 '''
462 return self._distanceTo(_formy.euclidean, other, **radius_adjust_wrap)
464 def haversineTo(self, other, **radius_wrap):
465 '''Compute the distance between this and an other geohash using
466 the L{pygeodesy.haversine} formula.
468 @arg other: The other geohash (L{Geohash}, C{LatLon} or C{str}).
469 @kwarg radius_wrap: Optional keyword arguments for function
470 L{pygeodesy.haversine}.
472 @return: Distance (C{meter}, same units as B{C{radius}} or the
473 ellipsoid or datum axes).
475 @raise TypeError: The B{C{other}} is not a L{Geohash}, C{LatLon}
476 or C{str} or invalid B{C{radius}}.
477 '''
478 return self._distanceTo(_formy.haversine, other, **radius_wrap)
480 @Property_RO
481 def latlon(self):
482 '''Get the lat- and longitude of (the approximate center of)
483 this geohash as a L{LatLon2Tuple}C{(lat, lon)} in C{degrees}.
484 '''
485 lat, lon = self._latlon or _2center(self.bounds())
486 return LatLon2Tuple(lat, lon, name=self.name)
488 @Property_RO
489 def neighbors(self):
490 '''Get all 8 adjacent cells as a L{Neighbors8Dict}C{(N, NE,
491 E, SE, S, SW, W, NW)} of L{Geohash}es.
492 '''
493 return Neighbors8Dict(N=self.N, NE=self.NE, E=self.E, SE=self.SE,
494 S=self.S, SW=self.SW, W=self.W, NW=self.NW,
495 name=self.name)
497 @Property_RO
498 def philam(self):
499 '''Get the lat- and longitude of (the approximate center of)
500 this geohash as a L{PhiLam2Tuple}C{(phi, lam)} in C{radians}.
501 '''
502 return PhiLam2Tuple(map2(radians, self.latlon), name=self.name) # *map2
504 @Property_RO
505 def precision(self):
506 '''Get this geohash's precision (C{int}).
507 '''
508 return len(self)
510 @deprecated_property_RO
511 def sizes(self):
512 '''DEPRECATED on 2024.07.28, use property C{Geohash.sizes3}.'''
513 t = self.sizes3
514 return _GH._LatLon2Tuple(t.height, t.width, name=t.name)
516 @Property_RO
517 def sizes3(self):
518 '''Get the lat-, longitudinal and radial size of this cell as
519 a L{Sizes3Tuple}C{(height, width, radius)}, all C{meter}.
520 '''
521 z = _GH.Sizes
522 n = min(len(z) - 1, max(self.precision, 1))
523 return Sizes3Tuple(z[n], name=self.name)
525 def toLatLon(self, LatLon=None, **LatLon_kwds):
526 '''Return (the approximate center of) this geohash cell
527 as an instance of the supplied C{LatLon} class.
529 @arg LatLon: Class to use (C{LatLon}) or C{None}.
530 @kwarg LatLon_kwds: Optional, additional B{C{LatLon}} keyword
531 arguments, ignored if C{B{LatLon} is None}.
533 @return: This geohash location (B{C{LatLon}}) or if C{B{LatLon}
534 is None}, a L{LatLon2Tuple}C{(lat, lon)}.
536 @raise TypeError: Invalid B{C{LatLon}} or B{C{LatLon_kwds}}.
537 '''
538 return self.latlon if LatLon is None else _xnamed(LatLon(
539 *self.latlon, **LatLon_kwds), self.name)
541 def vincentysTo(self, other, **radius_wrap):
542 '''Compute the distance between this and an other geohash using
543 the L{pygeodesy.vincentys} formula.
545 @arg other: The other geohash (L{Geohash}, C{LatLon} or C{str}).
546 @kwarg radius_wrap: Optional keyword arguments for function
547 L{pygeodesy.vincentys}.
549 @return: Distance (C{meter}, same units as B{C{radius}} or the
550 ellipsoid or datum axes).
552 @raise TypeError: The B{C{other}} is not a L{Geohash}, C{LatLon}
553 or C{str} or invalid B{C{radius}}.
554 '''
555 return self._distanceTo(_formy.vincentys, other, **radius_wrap)
557 @Property_RO
558 def E(self):
559 '''Get the cell East of this (L{Geohash}).
560 '''
561 return self.adjacent(_E_)
563 @Property_RO
564 def N(self):
565 '''Get the cell North of this (L{Geohash}).
566 '''
567 return self.adjacent(_N_)
569 @Property_RO
570 def NE(self):
571 '''Get the cell NorthEast of this (L{Geohash}).
572 '''
573 return self.N.E
575 @Property_RO
576 def NW(self):
577 '''Get the cell NorthWest of this (L{Geohash}).
578 '''
579 return self.N.W
581 @Property_RO
582 def S(self):
583 '''Get the cell South of this (L{Geohash}).
584 '''
585 return self.adjacent(_S_)
587 @Property_RO
588 def SE(self):
589 '''Get the cell SouthEast of this (L{Geohash}).
590 '''
591 return self.S.E
593 @Property_RO
594 def SW(self):
595 '''Get the cell SouthWest of this (L{Geohash}).
596 '''
597 return self.S.W
599 @Property_RO
600 def W(self):
601 '''Get the cell West of this (L{Geohash}).
602 '''
603 return self.adjacent(_W_)
606class Geohashed(object):
607 '''A cache of en- and decoded geohashes of one precision.
608 '''
609 _nn = None, # 1-tuple
611 def __init__(self, precision, ndigits=None):
612 '''New L{Geohashed} cache.
614 @arg precision: The geohash encoded length (C{int}, 1..12).
615 @kwarg ndigits: Optional number of digits to round C{lat}
616 and C{lon} to cache keys (C{int}, typically
617 C{B{ndigits}=B{precision}}) or C{None} for
618 no rounding.
619 '''
620 self._p = _2Precision(precision)
621 if ndigits is None:
622 self._ab2 = self._ab2float
623 else:
624 self._ab2 = self._ab2round
625 n = Int(ndigits=ndigits)
626 self._nn = n, n
627 self.clear()
629 def __len__(self):
630 '''Return the number of I{unigue} geohashes (C{int}).
631 '''
632 d = self._d
633 d = set(d.keys())
634 n = len(d)
635 for e in self._e.values():
636 e = set(e.values())
637 n += len(e - d)
638 return n
640 def _ab2(self, *ll): # overwritten
641 '''(INTERNAL) Make encoded keys C{a, b}.
642 '''
643 return ll
645 def _ab2float(self, *ll):
646 '''(INTERNAL) Make encoded keys C{a, b}.
647 '''
648 return map(float, ll)
650 def _ab2round(self, *ll):
651 '''(INTERNAL) Make encoded keys C{a, b}.
652 '''
653 return map(round, ll, self._nn)
655 def clear(self):
656 '''Clear the C{en-} and C{decoded} cache.
657 '''
658 self._e = {}
659 self._d = {}
661 def decoded(self, geohash, encoded=False):
662 '''Get and cache the C{(lat, lon)} for C{geohash}, see L{decode<pygeodesy.geohash.decode>}.
664 @kwarg encoded: If C{True}, cache the result as C{encoded}.
666 @return: The C{(lat, lon}) pair for C{geohash}.
667 '''
668 try:
669 ll = self._d[geohash]
670 except KeyError:
671 self._d[geohash] = ll = _GH.decode2(geohash)
672 if encoded:
673 a, b = self._ab2(*ll)
674 try:
675 _ = self._e[b][a]
676 except KeyError:
677 self._e.setdefault(b, {})[a] = geohash
678 return ll
680 def encoded(self, lat, lon, decoded=False):
681 '''Get and cache the C{geohash} for C{(lat, lon)}, see L{encode<pygeodesy.geohash.encode>}.
683 @kwarg decoded: If C{True}, cache the result as C{decoded}.
685 @return: The C{geohash} for pair C{(lat, lon}).
686 '''
687 lat, lon = ll = _2fll(lat, lon)
688 a, b = self._ab2(*ll)
689 try:
690 gh = self._e[b][a]
691 except KeyError:
692 gh = _GH.encode(lat, lon, self._p, 0)
693 self._e.setdefault(b, {})[a] = gh
694 if decoded and gh not in self._d:
695 self._d[gh] = ll
696 return gh
698 @property_RO
699 def len2(self):
700 '''Return 2-tuple C{(lencoded, ldecoded)} with the C{len}gths of the
701 C{en-} and C{decoded} cache.
702 '''
703 return sum(len(e) for e in self._e.values()), len(self._d)
705 @Property_RO
706 def ndigits(self):
707 '''Get the rounding (C{int} or C{None}).
708 '''
709 return self._nn[0]
711 @Property_RO
712 def precision(self):
713 '''Get the C{precision} (C{int}).
714 '''
715 return self._p
718class GeohashError(_ValueError):
719 '''Geohash encode, decode or other L{Geohash} issue.
720 '''
721 pass
724class Neighbors8Dict(_NamedDict):
725 '''8-Dict C{(N, NE, E, SE, S, SW, W, NW)} of L{Geohash}es,
726 providing key I{and} attribute access to the items.
727 '''
728 _Keys_ = (_N_, _NE_, _E_, _SE_, _S_, _SW_, _W_, _NW_)
730 def __init__(self, **kwds): # PYCHOK no *args
731 kwds = _xkwds(kwds, **_Neighbors8Defaults)
732 _NamedDict.__init__(self, **kwds) # name=...
735_Neighbors8Defaults = dict(zip(Neighbors8Dict._Keys_, (None,) *
736 len(Neighbors8Dict._Keys_))) # XXX frozendict
739class Resolutions2Tuple(_NamedTuple):
740 '''2-Tuple C{(res1, res2)} with the primary I{(longitudinal)} and
741 secondary I{(latitudinal)} resolution, both in C{degrees}.
742 '''
743 _Names_ = ('res1', 'res2')
744 _Units_ = ( Degrees_, Degrees_)
746 @property_RO
747 def lat(self):
748 '''Get the secondary, latitudinal resolution (C{degrees}).
749 '''
750 return self[1]
752 @property_RO
753 def lon(self):
754 '''Get the primary, longitudinal resolution (C{degrees}).
755 '''
756 return self[0]
759class Sizes3Tuple(_NamedTuple):
760 '''3-Tuple C{(height, width, radius)} with latitudinal C{height},
761 longitudinal C{width} and area C{radius}, all in C{meter}.
762 '''
763 _Names_ = (_height_, _width_, _radius_)
764 _Units_ = ( Meter, Meter, Meter)
767def bounds(geohash, LatLon=None, **LatLon_kwds):
768 '''Returns the lower-left SW and upper-right NE corners of a geohash.
770 @arg geohash: To be "bound" (L{Geohash}).
771 @kwarg LatLon: Optional class to return the bounds (C{LatLon}) or C{None}.
772 @kwarg LatLon_kwds: Optional, additional B{C{LatLon}} keyword arguments,
773 ignored if C{B{LatLon} is None}.
775 @return: A L{Bounds2Tuple}C{(latlonSW, latlonNE)}, each a B{C{LatLon}}
776 or if C{B{LatLon} is None}, a L{Bounds4Tuple}C{(latS, lonW,
777 latN, lonE)}.
779 @raise TypeError: The B{C{geohash}} is not a L{Geohash}, C{LatLon} or
780 C{str} or invalid B{C{LatLon}} or invalid B{C{LatLon_kwds}}.
782 @raise GeohashError: Invalid or C{null} B{C{geohash}}.
783 '''
784 swne = _GH.swne4(geohash)
785 return _2bounds(LatLon, LatLon_kwds, *swne,
786 name=nameof(geohash)) # _or_nameof=geohash
789def decode(geohash):
790 '''Decode a geohash to lat-/longitude of the (approximate
791 centre of) geohash cell to reasonable precision.
793 @arg geohash: To be decoded (L{Geohash}).
795 @return: 2-Tuple C{(latStr, lonStr)}, both C{str}.
797 @raise TypeError: The B{C{geohash}} is not a L{Geohash},
798 C{LatLon} or C{str}.
800 @raise GeohashError: Invalid or null B{C{geohash}}.
801 '''
802 # round to near centre without excessive precision to
803 # ⌊2-log10(Δ°)⌋ decimal places, strip trailing zeros
804 swne = _GH.swne4(geohash)
805 return _2latlon(*swne, fstr=_MODS.streprs.fstr)
808def decode2(geohash, LatLon=None, **LatLon_kwds):
809 '''Decode a geohash to lat-/longitude of the (approximate center
810 of) geohash cell to reasonable precision.
812 @arg geohash: To be decoded (L{Geohash}).
813 @kwarg LatLon: Optional class to return the location (C{LatLon})
814 or C{None}.
815 @kwarg LatLon_kwds: Optional, addtional B{C{LatLon}} keyword
816 arguments, ignored if C{B{LatLon} is None}.
818 @return: L{LatLon2Tuple}C{(lat, lon)}, both C{degrees} if
819 C{B{LatLon} is None}, otherwise a B{C{LatLon}} instance.
821 @raise TypeError: The B{C{geohash}} is not a L{Geohash},
822 C{LatLon} or C{str}.
824 @raise GeohashError: Invalid or null B{C{geohash}}.
825 '''
826 ll = _GH.decode2(geohash)
827 r = LatLon2Tuple(ll) if LatLon is None else \
828 LatLon( *ll, **LatLon_kwds)
829 return _xnamed(r, name__=decode2)
832@deprecated_function
833def decode_error(geohash):
834 '''DEPRECATED on 2024.07.28, use L{geohash.decode_error2}.'''
835 return decode_error2(geohash)
838def decode_error2(geohash):
839 '''Return the lat- and longitude decoding error for a geohash.
841 @arg geohash: To be decoded (L{Geohash}).
843 @return: A L{LatLon2Tuple}C{(lat, lon)} with the lat- and
844 longitudinal errors in (C{degrees}).
846 @raise TypeError: The B{C{geohash}} is not a L{Geohash},
847 C{LatLon} or C{str}.
849 @raise GeohashError: Invalid or null B{C{geohash}}.
850 '''
851 s, w, n, e = _GH.swne4(geohash)
852 return LatLon2Tuple((n - s) * _0_5, # lat error
853 (e - w) * _0_5) # lon error
856def distance_(geohash1, geohash2):
857 '''Estimate the distance between two geohash (from the cell sizes).
859 @arg geohash1: First geohash (L{Geohash}, C{LatLon} or C{str}).
860 @arg geohash2: Second geohash (L{Geohash}, C{LatLon} or C{str}).
862 @return: Approximate distance (C{meter}).
864 @raise TypeError: If B{C{geohash1}} or B{C{geohash2}} is not a
865 L{Geohash}, C{LatLon} or C{str}.
866 '''
867 return _2Geohash(geohash1).distanceTo(geohash2)
870@deprecated_function
871def distance1(geohash1, geohash2):
872 '''DEPRECATED, use L{geohash.distance_}.'''
873 return distance_(geohash1, geohash2)
876@deprecated_function
877def distance2(geohash1, geohash2):
878 '''DEPRECATED, use L{geohash.equirectangular4}.'''
879 return equirectangular4(geohash1, geohash2)
882@deprecated_function
883def distance3(geohash1, geohash2):
884 '''DEPRECATED, use L{geohash.haversine_}.'''
885 return haversine_(geohash1, geohash2)
888def encode(lat, lon, precision=None, eps=EPS):
889 '''Encode a lat-/longitude as a C{geohash}, either to the specified
890 precision or if not provided, to an inferred precision.
892 @arg lat: Latitude (C{degrees90}).
893 @arg lon: Longitude (C{degrees180}).
894 @kwarg precision: The desired geohash length (C{int} 1..12) or
895 C{None} or C{0} for inferred.
896 @kwarg eps: Optional inference tolerance (C{degrees}), ignored
897 if B{C{precision}} is not C{None} or C{0}.
899 @return: The C{geohash} (C{str}).
901 @raise GeohashError: Invalid B{C{lat}}, B{C{lon}} or B{C{precision}}.
902 '''
903 gh, _ = _GH.encode2(lat, lon, precision, eps)
904 return gh
907def equirectangular4(geohash1, geohash2, radius=R_M):
908 '''Approximate the distance between two geohashes using the
909 L{pygeodesy.equirectangular} formula.
911 @arg geohash1: First geohash (L{Geohash}, C{LatLon} or C{str}).
912 @arg geohash2: Second geohash (L{Geohash}, C{LatLon} or C{str}).
913 @kwarg radius: Mean earth radius (C{meter}) or C{None}, see method
914 L{Geohash.equirectangularTo}.
916 @return: Approximate distance (C{meter}, same units as B{C{radius}}),
917 see method L{Geohash.equirectangularTo}.
919 @raise TypeError: If B{C{geohash1}} or B{C{geohash2}} is not a
920 L{Geohash}, C{LatLon} or C{str}.
921 '''
922 return _2Geohash(geohash1).equirectangularTo(geohash2, radius=radius)
925def euclidean_(geohash1, geohash2, **radius_adjust_wrap):
926 '''Approximate the distance between two geohashes using the
927 L{pygeodesy.euclidean} formula.
929 @arg geohash1: First geohash (L{Geohash}, C{LatLon} or C{str}).
930 @arg geohash2: Second geohash (L{Geohash}, C{LatLon} or C{str}).
931 @kwarg radius_adjust_wrap: Optional keyword arguments for function
932 L{pygeodesy.euclidean}.
934 @return: Approximate distance (C{meter}, same units as B{C{radius}}).
936 @raise TypeError: If B{C{geohash1}} or B{C{geohash2}} is not a
937 L{Geohash}, C{LatLon} or C{str}.
938 '''
939 return _2Geohash(geohash1).euclideanTo(geohash2, **radius_adjust_wrap)
942def haversine_(geohash1, geohash2, **radius_wrap):
943 '''Compute the great-circle distance between two geohashes
944 using the L{pygeodesy.haversine} formula.
946 @arg geohash1: First geohash (L{Geohash}, C{LatLon} or C{str}).
947 @arg geohash2: Second geohash (L{Geohash}, C{LatLon} or C{str}).
948 @kwarg radius_wrap: Optional keyword arguments for function
949 L{pygeodesy.haversine}.
951 @return: Great-circle distance (C{meter}, same units as
952 B{C{radius}}).
954 @raise TypeError: If B{C{geohash1}} or B{C{geohash2}} is
955 not a L{Geohash}, C{LatLon} or C{str}.
956 '''
957 return _2Geohash(geohash1).haversineTo(geohash2, **radius_wrap)
960def neighbors(geohash):
961 '''Return the L{Geohash}es for all 8 adjacent cells.
963 @arg geohash: Cell for which neighbors are requested
964 (L{Geohash} or C{str}).
966 @return: A L{Neighbors8Dict}C{(N, NE, E, SE, S, SW, W, NW)}
967 of L{Geohash}es.
969 @raise TypeError: The B{C{geohash}} is not a L{Geohash},
970 C{LatLon} or C{str}.
971 '''
972 return _2Geohash(geohash).neighbors
975def precision(res1, res2=None):
976 '''Determine the L{Geohash} precisions to meet a or both given
977 (geographic) resolutions.
979 @arg res1: The required primary I{(longitudinal)} resolution
980 (C{degrees}).
981 @kwarg res2: Optional, required secondary I{(latitudinal)}
982 resolution (C{degrees}).
984 @return: The L{Geohash} precision or length (C{int}, 1..12).
986 @raise GeohashError: Invalid B{C{res1}} or B{C{res2}}.
988 @see: C++ class U{Geohash
989 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Geohash.html>}.
990 '''
991 r = Degrees_(res1=res1, low=_0_0, Error=GeohashError)
992 N = res2 is None
993 t = r, (r if N else Degrees_(res2=res2, low=_0_0, Error=GeohashError))
994 for p in range(1, _MaxPrec):
995 if resolution2(p, (None if N else p)) <= t:
996 return p
997 return _MaxPrec
1000def resolution2(prec1, prec2=None):
1001 '''Determine the (geographic) resolutions of given L{Geohash}
1002 precisions.
1004 @arg prec1: The given primary I{(longitudinal)} precision
1005 (C{int} 1..12).
1006 @kwarg prec2: Optional, secondary I{(latitudinal)} precision
1007 (C{int} 1..12).
1009 @return: L{Resolutions2Tuple}C{(res1, res2)} with the
1010 (geographic) resolutions C{degrees}, where C{res2
1011 B{is} res1} if no B{C{prec2}} is given.
1013 @raise GeohashError: Invalid B{C{prec1}} or B{C{prec2}}.
1015 @see: I{Karney}'s C++ class U{Geohash
1016 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Geohash.html>}.
1017 '''
1018 lon = _2res(_360_0, prec1=prec1)
1019 lat = lon if prec2 is None else \
1020 _2res(_180_0, prec2=prec2)
1021 return Resolutions2Tuple(lon, lat)
1024@deprecated_function
1025def sizes(geohash):
1026 '''DEPRECATED on 2024.07.28, use function L{pygeodesy.geohash.sizes3}.'''
1027 t = sizes3(geohash)
1028 return _GH._LatLon2Tuple(t.height, t.width, name=t.name)
1031def sizes3(geohash):
1032 '''Return the lat-, longitudinal and radial size of this L{Geohash} cell.
1034 @arg geohash: Cell for which size are required (L{Geohash} or C{str}).
1036 @return: A L{Sizes3Tuple}C{(height, width, radius)}, all C{meter}.
1038 @raise TypeError: The B{C{geohash}} is not a L{Geohash}, C{LatLon} or C{str}.
1039 '''
1040 return _2Geohash(geohash).sizes3
1043def vincentys_(geohash1, geohash2, **radius_wrap):
1044 '''Compute the distance between two geohashes using the
1045 L{pygeodesy.vincentys} formula.
1047 @arg geohash1: First geohash (L{Geohash}, C{LatLon} or C{str}).
1048 @arg geohash2: Second geohash (L{Geohash}, C{LatLon} or C{str}).
1049 @kwarg radius_wrap: Optional keyword arguments for function
1050 L{pygeodesy.vincentys}.
1052 @return: Distance (C{meter}, same units as B{C{radius}}).
1054 @raise TypeError: If B{C{geohash1}} or B{C{geohash2}} is not a
1055 L{Geohash}, C{LatLon} or C{str}.
1056 '''
1057 return _2Geohash(geohash1).vincentysTo(geohash2, **radius_wrap)
1060__all__ += _ALL_DOCS(bounds, # functions
1061 decode, decode2, decode_error2, distance_,
1062 encode, equirectangular4, euclidean_, haversine_,
1063 neighbors, precision, resolution2, sizes3, vincentys_,
1064 decode_error, sizes) # DEPRECATED
1066if __name__ == '__main__':
1068 from pygeodesy.internals import printf, _versions
1069 from timeit import timeit
1071 for f, p in (('encode', _MaxPrec), ('infer', None)):
1073 def _t(prec=p):
1074 i = 0
1075 for lat in range(-90, 90, 3):
1076 for lon in range(-180, 180, 7):
1077 _ = encode(lat, lon, prec)
1078 i += 1
1079 return i
1081 i = _t() # prime
1082 n = 10
1083 t = timeit(_t, number=n) / (i * n)
1084 printf('%s %.3f usec, %s', f, t * 1e6, _versions())
1086# % python3.12 -m pygeodesy.geohash
1087# encode 10.145 usec, pygeodesy 24.8.4 Python 3.12.4 64bit arm64 macOS 14.5
1088# infer 14.780 usec, pygeodesy 24.8.4 Python 3.12.4 64bit arm64 macOS 14.5
1089# or about 6.56 and 74.12 times faster than pygeodesy 24.7.24 and older:
1090# encode 66.524 usec, pygeodesy 24.7.24 Python 3.12.4 64bit arm64 macOS 14.5
1091# infer 1095.386 usec, pygeodesy 24.7.24 Python 3.12.4 64bit arm64 macOS 14.5
1093# **) MIT License
1094#
1095# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
1096#
1097# Permission is hereby granted, free of charge, to any person obtaining a
1098# copy of this software and associated documentation files (the "Software"),
1099# to deal in the Software without restriction, including without limitation
1100# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1101# and/or sell copies of the Software, and to permit persons to whom the
1102# Software is furnished to do so, subject to the following conditions:
1103#
1104# The above copyright notice and this permission notice shall be included
1105# in all copies or substantial portions of the Software.
1106#
1107# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1108# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1109# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1110# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1111# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1112# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1113# OTHER DEALINGS IN THE SOFTWARE.