1

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

3

4 u'''Geohash en-/decoding.

5

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

7 decode and inspect I{geohashes}.

8

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

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

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

12

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

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

15<https://PyPI.org/project/pygeohash>} and U{Geohash-Javascript

16<https://GitHub.com/DaveTroy/geohash-js>}.

17'''

18

19 from pygeodesy.basics import isodd, isstr, map2

20 from 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!

22 from pygeodesy.dms import parse3llh # parseDMS2

23 from pygeodesy.errors import _ValueError, _xkwds

24 from pygeodesy.fmath import favg

25# from pygeodesy import formy as _formy # _MODS

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

27 _S_, _SE_, _SW_, _W_

28 from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, _ALL_OTHER

29 from pygeodesy.named import _name__, _NamedDict, _NamedTuple, nameof, _xnamed

30 from pygeodesy.namedTuples import Bounds2Tuple, Bounds4Tuple, LatLon2Tuple, \

31 PhiLam2Tuple

32 from pygeodesy.props import deprecated_function, deprecated_method, \

33 deprecated_property_RO, Property_RO, property_RO

34 from pygeodesy.streprs import fstr

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

36 _xStrError

37

38 from math import fabs, ldexp, log10, radians

39

40__all__ = _ALL_LAZY.geohash

41__version__ = '24.05.23'

42

43

44 class _GH(object):

45 '''(INTERNAL) Lazily defined constants.

46 '''

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

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

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

50

51 @Property_RO

52 def Borders(self):

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

54

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

56

57 @Property_RO

58 def DecodedBase32(self): # inverse GeohashBase32 map

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

60

61 # Geohash-specific base32 map

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

63

64 @Property_RO

65 def Neighbors(self):

66 return self._4d('p0r21436x8zb9dcf5h7kjnmqesgutwvy',

67 'bc01fg45238967deuvhjyznpkmstqrwx',

68 '14365h7k9dcfesgujnmqp0r2twvyx8zb',

69 '238967debc01fg45kmstqrwxuvhjyznp')

70

71 @Property_RO

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

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

74 _t = _floatuple

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

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

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

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

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

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

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

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

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

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

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

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

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

88

89_GH = _GH() # PYCHOK singleton

90_MaxPrec = 12

91

92

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

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

95 '''

96 if LatLon is None:

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

98 else:

99 kwds = _xkwds(LatLon_kwds, **name)

100 r = Bounds2Tuple(LatLon(s, w, **kwds),

101 LatLon(n, e, **kwds), **name)

102 return r

103

104

105 def _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

112 def _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

120 def _2Geohash(geohash):

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

122 '''

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

124 Geohash(geohash)

125

126

127 def _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

142 class 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):

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 C{B{name}=NN} (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__(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):

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 C{B{name}=NN} (C{str}) otherwise this

195 cell's name, either extended with 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 = self._name__(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 (C{meter},

301 L{Ellipsoid}, L{Ellipsoid2}, L{Datum} or

302 L{a_f2Tuple}) or C{None}, see function

303 L{pygeodesy.equirectangular}.

304 @kwarg adjust_limit_wrap: Optional keyword arguments for function

305 L{pygeodesy.equirectangular4}, overriding defaults

306 C{B{adjust}=False, 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} or

313 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 m = self._formy

321 return m.equirectangular( *lls, radius=radius, **kwds) if radius else \

322 m.equirectangular4(*lls, **kwds).distance2

323

324 def euclideanTo(self, other, **radius_adjust_wrap):

325 '''Approximate the distance between this and an other geohash using

326 function L{pygeodesy.euclidean}.

327

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

329 @kwarg radius_adjust_wrap: Optional keyword arguments for function

330 L{pygeodesy.euclidean}.

331

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

333 ellipsoid or datum axes).

334

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

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

337 '''

338 return self._distanceTo(self._formy.euclidean, other, **radius_adjust_wrap)

339

340 @property_RO

341 def _formy(self):

342 '''(INTERNAL) Get the C{.formy} module, I{once}.

343 '''

344 Geohash._formy = f = _MODS.formy # overwrite property_RO

345 return f

346

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

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

349 the L{pygeodesy.haversine} formula.

350

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

352 @kwarg radius_wrap: Optional keyword arguments for function

353 L{pygeodesy.haversine}.

354

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

356 ellipsoid or datum axes).

357

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

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

360 '''

361 return self._distanceTo(self._formy.haversine, other, **radius_wrap)

362

363 @Property_RO

364 def latlon(self):

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

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

367 '''

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

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

370

371 @Property_RO

372 def neighbors(self):

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

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

375 '''

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

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

378 name=self.name)

379

380 @Property_RO

381 def philam(self):

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

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

384 '''

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

386

387 @Property_RO

388 def precision(self):

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

390 '''

391 return len(self)

392

393 @Property_RO

394 def sizes(self):

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

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

397 '''

398 z = _GH.Sizes

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

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

401

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

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

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

405

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

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

408 keyword arguments, ignored if

409 C{B{LatLon} is None}.

410

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

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

413 is C{None}.

414

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

416 '''

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

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

419

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

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

422 the L{pygeodesy.vincentys} formula.

423

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

425 @kwarg radius_wrap: Optional keyword arguments for function

426 L{pygeodesy.vincentys}.

427

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

429 ellipsoid or datum axes).

430

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

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

433 '''

434 return self._distanceTo(self._formy.vincentys, other, **radius_wrap)

435

436 @Property_RO

437 def N(self):

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

439 '''

440 return self.adjacent(_N_)

441

442 @Property_RO

443 def S(self):

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

445 '''

446 return self.adjacent(_S_)

447

448 @Property_RO

449 def E(self):

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

451 '''

452 return self.adjacent(_E_)

453

454 @Property_RO

455 def W(self):

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

457 '''

458 return self.adjacent(_W_)

459

460 @Property_RO

461 def NE(self):

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

463 '''

464 return self.N.E

465

466 @Property_RO

467 def NW(self):

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

469 '''

470 return self.N.W

471

472 @Property_RO

473 def SE(self):

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

475 '''

476 return self.S.E

477

478 @Property_RO

479 def SW(self):

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

481 '''

482 return self.S.W

483

484

485 class GeohashError(_ValueError):

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

487 '''

488 pass

489

490

491 class Neighbors8Dict(_NamedDict):

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

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

494 '''

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

496

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

498 kwds = _xkwds(kwds, **_Neighbors8Defaults)

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

500

501

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

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

504

505

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

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

508

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

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

511 or C{None}.

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

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

514

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

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

517 lonW, latN, lonE)}.

518

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

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

521 B{C{LatLon_kwds}}.

522

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

524 '''

525 gh = _2Geohash(geohash)

526 if len(gh) < 1:

527 raise GeohashError(geohash=geohash)

528

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

530 try:

531 d, _avg = True, favg

532 for c in gh.lower():

533 i = _GH.DecodedBase32[c]

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

535 if d: # longitude

536 a = _avg(w, e)

537 if (i & m):

538 w = a

539 else:

540 e = a

541 else: # latitude

542 a = _avg(s, n)

543 if (i & m):

544 s = a

545 else:

546 n = a

547 d = not d

548 except KeyError:

549 raise GeohashError(geohash=geohash)

550

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

552 name=nameof(geohash)) # _or_nameof=geohash

553

554

555 def _bounds3(geohash):

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

557 '''

558 b = bounds(geohash)

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

560

561

562 def decode(geohash):

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

564 centre of) geohash cell to reasonable precision.

565

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

567

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

569

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

571 C{LatLon} or C{str}.

572

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

574 '''

575 b, h, w = _bounds3(geohash)

576 lat, lon = _2center(b)

577

578 # round to near centre without excessive precision to

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

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

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

582

583

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

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

586 of) geohash cell to reasonable precision.

587

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

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

590 or C{None}.

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

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

593

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

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

596

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

598 C{LatLon} or C{str}.

599

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

601 '''

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

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

604 return _xnamed(r, name__=decode2)

605

606

607 def decode_error(geohash):

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

609 this geohash.

610

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

612

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

614 longitudinal errors in (C{degrees}).

615

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

617 C{LatLon} or C{str}.

618

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

620 '''

621 _, h, w = _bounds3(geohash)

622 return LatLon2Tuple(h * _0_5, # Height error

623 w * _0_5) # Width error

624

625

626 def distance_(geohash1, geohash2):

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

628

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

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

631

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

633

634 @raise TypeError: If B{C{geohash1}} or B{C{geohash2}} is not a

635 L{Geohash}, C{LatLon} or C{str}.

636 '''

637 return _2Geohash(geohash1).distanceTo(geohash2)

638

639

640@deprecated_function

641 def distance1(geohash1, geohash2):

642 '''DEPRECATED, use L{geohash.distance_}.'''

643 return distance_(geohash1, geohash2)

644

645

646@deprecated_function

647 def distance2(geohash1, geohash2):

648 '''DEPRECATED, use L{geohash.equirectangular4}.'''

649 return equirectangular4(geohash1, geohash2)

650

651

652@deprecated_function

653 def distance3(geohash1, geohash2):

654 '''DEPRECATED, use L{geohash.haversine_}.'''

655 return haversine_(geohash1, geohash2)

656

657

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

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

660 precision or if not provided, to an automatically evaluated

661 precision.

662

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

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

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

666 1..12).

667

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

669

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

671 '''

672 lat, lon = _2fll(lat, lon)

673

674 if precision is None:

675 # Infer precision by refining geohash until

676 # it matches precision of supplied lat/lon.

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

678 gh = encode(lat, lon, p)

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

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

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

682 return gh

683 p = _MaxPrec

684 else:

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

686

687 b = i = 0

688 d, gh = True, []

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

690

691 _avg = favg

692 while p > 0:

693 i += i

694 if d: # bisect longitude

695 m = _avg(e, w)

696 if lon < m:

697 e = m

698 else:

699 w = m

700 i += 1

701 else: # bisect latitude

702 m = _avg(n, s)

703 if lat < m:

704 n = m

705 else:

706 s = m

707 i += 1

708 d = not d

709

710 b += 1

711 if b == 5:

712 # 5 bits gives a character:

713 # append it and start over

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

715 b = i = 0

716 p -= 1

717

718 return NN.join(gh)

719

720

721 def equirectangular4(geohash1, geohash2, radius=R_M):

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

723 L{pygeodesy.equirectangular} formula.

724

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

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

727 @kwarg radius: Mean earth radius (C{meter}) or C{None}, see method

728 L{Geohash.equirectangularTo}.

729

730 @return: Approximate distance (C{meter}, same units as B{C{radius}}),

731 see method L{Geohash.equirectangularTo}.

732

733 @raise TypeError: If B{C{geohash1}} or B{C{geohash2}} is not a

734 L{Geohash}, C{LatLon} or C{str}.

735 '''

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

737

738

739 def euclidean_(geohash1, geohash2, **radius_adjust_wrap):

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

741 L{pygeodesy.euclidean} formula.

742

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

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

745 @kwarg radius_adjust_wrap: Optional keyword arguments for function

746 L{pygeodesy.euclidean}.

747

748 @return: Approximate distance (C{meter}, same units as B{C{radius}}).

749

750 @raise TypeError: If B{C{geohash1}} or B{C{geohash2}} is not a

751 L{Geohash}, C{LatLon} or C{str}.

752 '''

753 return _2Geohash(geohash1).euclideanTo(geohash2, **radius_adjust_wrap)

754

755

756 def haversine_(geohash1, geohash2, **radius_wrap):

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

758 using the L{pygeodesy.haversine} formula.

759

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

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

762 @kwarg radius_wrap: Optional keyword arguments for function

763 L{pygeodesy.haversine}.

764

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

766 B{C{radius}}).

767

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

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

770 '''

771 return _2Geohash(geohash1).haversineTo(geohash2, **radius_wrap)

772

773

774 def neighbors(geohash):

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

776

777 @arg geohash: Cell for which neighbors are requested

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

779

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

781 of L{Geohash}es.

782

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

784 C{LatLon} or C{str}.

785 '''

786 return _2Geohash(geohash).neighbors

787

788

789 def precision(res1, res2=None):

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

791 (geographic) resolutions.

792

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

794 (C{degrees}).

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

796 resolution (C{degrees}).

797

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

799

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

801

802 @see: C++ class U{Geohash

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

804 '''

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

806 if res2 is None:

807 t = r, r

808 for p in range(1, _MaxPrec):

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

810 return p

811

812 else:

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

814 for p in range(1, _MaxPrec):

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

816 return p

817

818 return _MaxPrec

819

820

821 class Resolutions2Tuple(_NamedTuple):

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

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

824 '''

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

826 _Units_ = ( Degrees_, Degrees_)

827

828

829 def resolution2(prec1, prec2=None):

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

831 precisions.

832

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

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

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

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

837

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

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

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

841

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

843

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

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

846 '''

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

848

849 if prec1:

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

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

852

853 if prec2:

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

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

856

857 return Resolutions2Tuple(res1, res2)

858

859

860 def sizes(geohash):

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

862

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

864 C{str}).

865

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

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

868

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

870 C{LatLon} or C{str}.

871 '''

872 return _2Geohash(geohash).sizes

873

874

875 def vincentys_(geohash1, geohash2, **radius_wrap):

876 '''Compute the distance between two geohashes using the

877 L{pygeodesy.vincentys} formula.

878

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

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

881 @kwarg radius_wrap: Optional keyword arguments for function

882 L{pygeodesy.vincentys}.

883

884 @return: Distance (C{meter}, same units as B{C{radius}}).

885

886 @raise TypeError: If B{C{geohash1}} or B{C{geohash2}} is not a

887 L{Geohash}, C{LatLon} or C{str}.

888 '''

889 return _2Geohash(geohash1).vincentysTo(geohash2, **radius_wrap)

890

891

892__all__ += _ALL_OTHER(bounds, # functions

893 decode, decode2, decode_error, distance_,

894 encode, equirectangular4, euclidean_, haversine_,

895 neighbors, precision, resolution2, sizes, vincentys_)

896

897# **) MIT License

898#

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

900#

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

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

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

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

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

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

907#

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

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

910#

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

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

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

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

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

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

917# OTHER DEALINGS IN THE SOFTWARE.