or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-operations.mdcell-hierarchy.mdcore-cell-operations.mddirected-edges.mdgrid-navigation.mdindex.mdmeasurements.mdpolygon-operations.md

index.mddocs/

0

# H3

1

2

Python bindings for H3, a hierarchical hexagonal geospatial indexing system. H3 partitions the world into hexagonal cells at multiple resolution levels, enabling efficient spatial indexing and analysis for location-based applications.

3

4

## Package Information

5

6

- **Package Name**: h3

7

- **Language**: Python

8

- **Installation**: `pip install h3`

9

10

## Core Imports

11

12

```python

13

import h3

14

```

15

16

Alternative APIs with different data formats:

17

18

```python

19

import h3.api.basic_int as h3 # Integer H3 indices

20

import h3.api.numpy_int as h3 # NumPy optimization

21

import h3.api.memview_int as h3 # Memory view operations

22

```

23

24

For polygon operations:

25

26

```python

27

from h3 import LatLngPoly, LatLngMultiPoly

28

```

29

30

## Basic Usage

31

32

```python

33

import h3

34

35

# Convert coordinates to H3 cell

36

cell = h3.latlng_to_cell(37.7749, -122.4194, resolution=9)

37

print(cell) # '89283082e73ffff'

38

39

# Get cell center and boundary

40

lat, lng = h3.cell_to_latlng(cell)

41

boundary = h3.cell_to_boundary(cell)

42

43

# Find neighboring cells

44

neighbors = h3.grid_disk(cell, k=1)

45

print(f"Cell and neighbors: {len(neighbors)} cells")

46

47

# Polygon to cells conversion

48

from h3 import LatLngPoly

49

polygon = LatLngPoly([

50

(37.68, -122.54), (37.68, -122.34),

51

(37.82, -122.34), (37.82, -122.54)

52

])

53

cells = h3.h3shape_to_cells(polygon, resolution=6)

54

```

55

56

## Architecture

57

58

H3 organizes the world into hexagonal cells across 16 resolution levels (0-15):

59

- **Resolution 0**: ~4,250 km edge length (122 base cells)

60

- **Resolution 15**: ~0.5 m edge length (finest detail)

61

- **Hierarchy**: Each cell contains ~7 children at the next finer resolution

62

- **APIs**: Multiple interfaces (basic_str, basic_int, numpy_int, memview_int) with identical functions

63

64

## Capabilities

65

66

### Core Cell Operations

67

68

Essential cell creation, validation, and format conversion functions.

69

70

```python { .api }

71

def latlng_to_cell(lat: float, lng: float, res: int) -> str:

72

"""Convert lat/lng to H3 cell at specified resolution."""

73

74

def is_valid_cell(h: str) -> bool:

75

"""Check if H3 cell identifier is valid."""

76

77

def cell_to_latlng(h: str) -> tuple[float, float]:

78

"""Get center coordinates of H3 cell."""

79

80

def cell_to_boundary(h: str) -> tuple[tuple[float, float], ...]:

81

"""Get boundary vertices of H3 cell."""

82

83

def get_resolution(h: str) -> int:

84

"""Get resolution of H3 cell."""

85

86

def str_to_int(h: str) -> int:

87

"""Convert hex string to 64-bit integer."""

88

89

def int_to_str(x: int) -> str:

90

"""Convert 64-bit integer to hex string."""

91

92

def get_num_cells(res: int) -> int:

93

"""Get total number of cells at resolution."""

94

95

def versions() -> dict[str, str]:

96

"""Get Python and C library versions."""

97

98

def is_pentagon(h: str) -> bool:

99

"""Check if cell is pentagon."""

100

101

def get_base_cell_number(h: str) -> int:

102

"""Get base cell number (0-121)."""

103

104

def is_res_class_III(h: str) -> bool:

105

"""Check if cell has Class III orientation."""

106

```

107

108

[Core Cell Operations](core-cell-operations.md)

109

110

### Grid Navigation

111

112

Functions for navigating the hexagonal grid and finding neighboring cells.

113

114

```python { .api }

115

def grid_distance(h1: str, h2: str) -> int:

116

"""Calculate grid distance between cells."""

117

118

def grid_disk(h: str, k: int = 1) -> list[str]:

119

"""Get cells within distance k (filled disk)."""

120

121

def grid_ring(h: str, k: int = 1) -> list[str]:

122

"""Get cells at exactly distance k (hollow ring)."""

123

124

def grid_path_cells(start: str, end: str) -> list[str]:

125

"""Find path between cells."""

126

127

def are_neighbor_cells(h1: str, h2: str) -> bool:

128

"""Check if cells are neighbors."""

129

```

130

131

[Grid Navigation](grid-navigation.md)

132

133

### Cell Hierarchy

134

135

Operations for working with H3's multi-resolution hierarchy.

136

137

```python { .api }

138

def cell_to_parent(h: str, res: int = None) -> str:

139

"""Get parent cell at coarser resolution."""

140

141

def cell_to_children(h: str, res: int = None) -> list[str]:

142

"""Get child cells at finer resolution."""

143

144

def cell_to_children_size(h: str, res: int = None) -> int:

145

"""Get count of child cells."""

146

147

def cell_to_child_pos(child: str, res_parent: int) -> int:

148

"""Get child position index."""

149

150

def child_pos_to_cell(parent: str, res_child: int, child_pos: int) -> str:

151

"""Get child from position index."""

152

153

def cell_to_center_child(h: str, res: int = None) -> str:

154

"""Get center child at finer resolution."""

155

156

def compact_cells(cells: list[str]) -> list[str]:

157

"""Compact cells by combining children into parents."""

158

159

def uncompact_cells(cells: list[str], res: int) -> list[str]:

160

"""Expand cells to uniform resolution."""

161

```

162

163

[Cell Hierarchy](cell-hierarchy.md)

164

165

### Polygon Operations

166

167

Convert between H3 cells and geographic polygons.

168

169

```python { .api }

170

def h3shape_to_cells(h3shape: H3Shape, res: int) -> list[str]:

171

"""Convert shape to H3 cells."""

172

173

def polygon_to_cells(h3shape: H3Shape, res: int) -> list[str]:

174

"""Alias for h3shape_to_cells."""

175

176

def h3shape_to_cells_experimental(h3shape: H3Shape, res: int, contain: str = 'center') -> list[str]:

177

"""Experimental shape to cells with containment modes."""

178

179

def polygon_to_cells_experimental(h3shape: H3Shape, res: int, contain: str = 'center') -> list[str]:

180

"""Experimental alias for h3shape_to_cells_experimental."""

181

182

def cells_to_h3shape(cells: list[str], tight: bool = True) -> H3Shape:

183

"""Convert cells to shape."""

184

185

def geo_to_cells(geo: dict, res: int) -> list[str]:

186

"""Convert GeoJSON to cells."""

187

188

def cells_to_geo(cells: list[str], tight: bool = True) -> dict:

189

"""Convert cells to GeoJSON."""

190

```

191

192

[Polygon Operations](polygon-operations.md)

193

194

### Directed Edges

195

196

Operations for working with edges between adjacent cells.

197

198

```python { .api }

199

def cells_to_directed_edge(origin: str, destination: str) -> str:

200

"""Create directed edge between cells."""

201

202

def is_valid_directed_edge(edge: str) -> bool:

203

"""Check if edge identifier is valid."""

204

205

def directed_edge_to_cells(e: str) -> tuple[str, str]:

206

"""Get origin and destination from edge."""

207

208

def get_directed_edge_origin(e: str) -> str:

209

"""Get origin cell from edge."""

210

211

def get_directed_edge_destination(e: str) -> str:

212

"""Get destination cell from edge."""

213

214

def origin_to_directed_edges(origin: str) -> list[str]:

215

"""Get all edges from origin cell."""

216

217

def directed_edge_to_boundary(edge: str) -> tuple[tuple[float, float], ...]:

218

"""Get boundary points of edge."""

219

```

220

221

[Directed Edges](directed-edges.md)

222

223

### Measurements

224

225

Calculate areas, lengths, and distances with multiple unit support.

226

227

```python { .api }

228

def cell_area(h: str, unit: str = 'km^2') -> float:

229

"""Calculate area of specific cell."""

230

231

def edge_length(e: str, unit: str = 'km') -> float:

232

"""Calculate length of specific edge."""

233

234

def great_circle_distance(latlng1: tuple[float, float], latlng2: tuple[float, float], unit: str = 'km') -> float:

235

"""Calculate spherical distance between points."""

236

237

def average_hexagon_area(res: int, unit: str = 'km^2') -> float:

238

"""Get average hexagon area at resolution."""

239

240

def average_hexagon_edge_length(res: int, unit: str = 'km') -> float:

241

"""Get average hexagon edge length at resolution."""

242

```

243

244

[Measurements](measurements.md)

245

246

### Advanced Operations

247

248

Specialized functions including local coordinates, vertices, and system introspection.

249

250

```python { .api }

251

def cell_to_local_ij(origin: str, h: str) -> tuple[int, int]:

252

"""Convert cell to local (i,j) coordinates."""

253

254

def local_ij_to_cell(origin: str, i: int, j: int) -> str:

255

"""Convert local coordinates to cell."""

256

257

def cell_to_vertex(h: str, vertex_num: int) -> str:

258

"""Get specific vertex of cell."""

259

260

def cell_to_vertexes(h: str) -> list[str]:

261

"""Get all vertices of cell."""

262

263

def vertex_to_latlng(v: str) -> tuple[float, float]:

264

"""Get coordinates of vertex."""

265

266

def is_valid_vertex(v: str) -> bool:

267

"""Check if vertex identifier is valid."""

268

269

def get_pentagons(res: int) -> list[str]:

270

"""Get all pentagon cells at resolution."""

271

272

def get_res0_cells() -> list[str]:

273

"""Get all base cells (resolution 0)."""

274

275

def get_icosahedron_faces(h: str) -> set[int]:

276

"""Get icosahedron faces intersecting cell."""

277

```

278

279

[Advanced Operations](advanced-operations.md)

280

281

## H3Shape Classes

282

283

```python { .api }

284

class H3Shape:

285

"""Abstract base class for geographic shapes."""

286

287

class LatLngPoly(H3Shape):

288

"""Polygon with optional holes."""

289

def __init__(self, outer: list[tuple[float, float]], *holes: list[tuple[float, float]]):

290

"""Create polygon from outer boundary and optional holes."""

291

292

@property

293

def outer(self) -> tuple[tuple[float, float], ...]

294

295

@property

296

def holes(self) -> tuple[tuple[tuple[float, float], ...], ...]

297

298

class LatLngMultiPoly(H3Shape):

299

"""Collection of multiple polygons."""

300

def __init__(self, *polys: LatLngPoly):

301

"""Create multipolygon from LatLngPoly objects."""

302

303

@property

304

def polys(self) -> tuple[LatLngPoly, ...]

305

```

306

307

## Shape Utilities

308

309

```python { .api }

310

def geo_to_h3shape(geo: dict) -> H3Shape:

311

"""Convert GeoJSON to H3Shape."""

312

313

def h3shape_to_geo(h3shape: H3Shape) -> dict:

314

"""Convert H3Shape to GeoJSON."""

315

```

316

317

## Error Handling

318

319

```python { .api }

320

class H3BaseException(Exception):

321

"""Base class for all H3 exceptions."""

322

323

class H3ValueError(H3BaseException):

324

"""Invalid input values."""

325

326

class H3DomainError(H3BaseException):

327

"""Input outside valid domain."""

328

329

class H3LatLngDomainError(H3DomainError):

330

"""Latitude/longitude outside valid range."""

331

332

class H3ResDomainError(H3DomainError):

333

"""Resolution outside valid range (0-15)."""

334

335

class H3CellInvalidError(H3BaseException):

336

"""Invalid H3 cell identifier."""

337

338

class H3DirEdgeInvalidError(H3BaseException):

339

"""Invalid H3 directed edge identifier."""

340

341

class H3UndirEdgeInvalidError(H3BaseException):

342

"""Invalid H3 undirected edge identifier."""

343

344

class H3VertexInvalidError(H3BaseException):

345

"""Invalid H3 vertex identifier."""

346

347

class H3PentagonError(H3BaseException):

348

"""Pentagon-related errors."""

349

350

class H3DuplicateInputError(H3BaseException):

351

"""Duplicate input error."""

352

353

class H3NotNeighborsError(H3BaseException):

354

"""Cells are not neighbors when required."""

355

356

class H3ResMismatchError(H3BaseException):

357

"""Resolution mismatch between cells."""

358

359

class H3GridNavigationError(H3BaseException):

360

"""Grid navigation operation failed."""

361

362

class H3MemoryError(H3BaseException):

363

"""Memory-related errors."""

364

365

class H3MemoryAllocError(H3MemoryError):

366

"""Memory allocation error."""

367

368

class H3MemoryBoundsError(H3MemoryError):

369

"""Memory bounds error."""

370

371

class H3OptionInvalidError(H3BaseException):

372

"""Invalid option error."""

373

374

class H3FailedError(H3BaseException):

375

"""General operation failure."""

376

377

class UnknownH3ErrorCode(H3BaseException):

378

"""Unknown H3 error code."""

379

```