### Build and Install h3ronpy from Source Source: https://github.com/nmandery/h3ronpy/blob/main/h3ronpy/docs/source/installation.md Follow these steps to clone the repository, navigate into the directory, and install h3ronpy from its source code. This method requires a recent Rust installation and uses maturin for building. ```shell git clone https://github.com/nmandery/h3ronpy.git cd h3ronpy pip install . ``` -------------------------------- ### Install h3ronpy from PyPI Source: https://github.com/nmandery/h3ronpy/blob/main/h3ronpy/docs/source/installation.md Use this command to install the latest stable version of h3ronpy directly from the Python Package Index. ```shell pip install h3ronpy ``` -------------------------------- ### H3 Grid Disk and Compact Operations with Polars Source: https://context7.com/nmandery/h3ronpy/llms.txt Demonstrates using the h3ronpy Polars integration for grid disk operations and compacting H3 cells. Requires Polars and h3ronpy to be installed. ```python s = pl.Series("cells", [599686042433355775], dtype=pl.UInt64) disk = s.h3.grid_disk(k=2, flatten=True) compacted = s.h3.compact() ``` -------------------------------- ### Get h3ronpy Library Version Source: https://context7.com/nmandery/h3ronpy/llms.txt Retrieves the current version of the h3ronpy library. No specific setup is required beyond importing the library. ```python import h3ronpy print(h3ronpy.version()) ``` -------------------------------- ### Get H3 Grid Disk Distances Source: https://context7.com/nmandery/h3ronpy/llms.txt Returns a `RecordBatch` containing H3 cells and their respective ring distances from the origin. Ideal for distance-weighted spatial analyses. The output schema includes 'cell' and 'k' columns. ```python import h3ronpy import pyarrow as pa origin = h3ronpy.cells_parse(["8552dc63fffffff"]) result = h3ronpy.grid_disk_distances(origin, k=2) print(result.schema) # cell: uint64 # k: uint32 # Convert to pandas df = pa.RecordBatch.from_batches([result]).to_pandas() if False else \ {col: result.column(col).to_pylist() for col in result.schema.names} print(dict(list(df.items()))) ``` -------------------------------- ### Get Bounding Boxes for H3 Cells Source: https://context7.com/nmandery/h3ronpy/llms.txt Provides bounding box information for H3 cells. `cells_bounds()` returns a single tuple for the entire array, while `cells_bounds_arrays()` returns a RecordBatch with per-cell bounding boxes. ```python import h3ronpy.vector as hv import h3ronpy cells = h3ronpy.cells_parse(["8552dc63fffffff", "8928308280fffff"]) # Overall bounds bbox = hv.cells_bounds(cells) print(bbox) # (minx, miny, maxx, maxy) # Per-cell bounds table per_cell = hv.cells_bounds_arrays(cells) print(per_cell.schema) # minx: double, miny: double, maxx: double, maxy: double ``` -------------------------------- ### Convert H3 Cells to Centroid Coordinates Source: https://context7.com/nmandery/h3ronpy/llms.txt Returns a PyArrow RecordBatch containing `lat` and `lng` float64 columns for the centroid of each input H3 cell. This is useful for getting the geographic center of H3 cells. ```python import h3ronpy.vector as hv import h3ronpy cells = h3ronpy.cells_parse(["8552dc63fffffff"]) coords = hv.cells_to_coordinates(cells) print(coords.schema) # lat: double, lng: double print(coords.column("lat").to_pylist(), coords.column("lng").to_pylist()) ``` -------------------------------- ### Get H3 Grid Disk Neighbors Source: https://context7.com/nmandery/h3ronpy/llms.txt Retrieves all H3 cells within a specified grid distance `k` from an origin cell. Can return a list of lists or a flattened array. Useful for finding all cells within a certain radius. ```python import h3ronpy origin = h3ronpy.cells_parse(["8552dc63fffffff"]) # List array: each row contains the cells within k=2 disks = h3ronpy.grid_disk(origin, k=2, flatten=False) print(len(disks[0])) # 19 (1 + 6 + 12) # Flat array: all neighbor cells concatenated flat = h3ronpy.grid_disk(origin, k=2, flatten=True) print(len(flat)) # 19 ``` -------------------------------- ### Get H3 Cells within Specific Ring Distances Source: https://context7.com/nmandery/h3ronpy/llms.txt Retrieves H3 cells within a specified range of ring distances (`k_min` to `k_max`), excluding cells closer than `k_min`. Can return a flattened array. Useful for analyzing specific rings around a cell. ```python import h3ronpy cells = h3ronpy.cells_parse(["8552dc63fffffff"]) # Only cells at ring distance 2 and 3 (not 0 or 1) ring = h3ronpy.grid_ring_distances(cells, k_min=2, k_max=3, flatten=True) print(len(ring)) # 30 (12 at ring 2 + 18 at ring 3) ``` -------------------------------- ### Upgrade pip Source: https://github.com/nmandery/h3ronpy/blob/main/h3ronpy/docs/source/installation.md Ensure you have a recent version of pip, which is required for building from source. Version 23.1.2 or later is recommended. ```shell pip install --upgrade pip ``` -------------------------------- ### version() Source: https://context7.com/nmandery/h3ronpy/llms.txt Retrieves the current version of the h3ronpy library as a string. ```APIDOC ## version() ### Description Returns the current h3ronpy version as a string. ### Method `version()` ### Parameters None ### Returns - `string`: The library version. ``` -------------------------------- ### Compact and Uncompact H3 Cells Source: https://context7.com/nmandery/h3ronpy/llms.txt Demonstrates how to compact a set of H3 cells to their parent cells and then expand them back to a target resolution. Useful for reducing data size or preparing data for specific H3 operations. ```python import h3ronpy res5 = h3ronpy.cells_parse(["8552dc63fffffff"]) res7_children = h3ronpy.change_resolution(res5, 7) # 49 cells print(len(res7_children)) # 49 compacted = h3ronpy.compact(res7_children) print(len(compacted)) # 1 — all 49 children collapsed back to one res-5 parent # Expand back expanded = h3ronpy.uncompact(compacted, target_resolution=7) print(len(expanded)) # 49 ``` -------------------------------- ### compact() / uncompact() Source: https://context7.com/nmandery/h3ronpy/llms.txt Functions for H3 cell set compaction and expansion. `compact()` merges sets of same-resolution cells into their parent cells, while `uncompact()` expands cells back to a uniform target resolution. ```APIDOC ## compact() / uncompact() ### Description `compact()` merges sets of same-resolution cells into their parent cells wherever all children are present, reducing storage. `uncompact()` expands cells back to a uniform target resolution. ### Method `compact(cells: pyarrow.UInt64Array) -> pyarrow.UInt64Array` `uncompact(cells: pyarrow.UInt64Array, resolution: int) -> pyarrow.UInt64Array` ### Parameters #### `compact` Arguments - `cells` (pyarrow.UInt64Array): An Arrow array of H3 cell indexes to be compacted. #### `uncompact` Arguments - `cells` (pyarrow.UInt64Array): An Arrow array of H3 cell indexes to be uncompacted. - `resolution` (int): The target resolution to expand the cells to. ### Returns - `pyarrow.UInt64Array`: An Arrow array containing the compacted or uncompacted H3 cell indexes. ``` -------------------------------- ### H3Expr and H3SeriesShortcuts Source: https://context7.com/nmandery/h3ronpy/llms.txt Importing `h3ronpy.polars` registers an `h3` namespace on both `pl.Expr` and `pl.Series`, mirroring the core API for seamless polars pipeline integration. ```APIDOC ## H3Expr and H3SeriesShortcuts ### Description Importing `h3ronpy.polars` registers an `h3` namespace on both `pl.Expr` and `pl.Series`, mirroring the core API for seamless polars pipeline integration. ### Usage ```python import polars as pl import h3ronpy.polars # registers .h3 namespace df = pl.DataFrame({ "cell_str": ["8552dc63fffffff", "8928308280fffff", "INVALID"], }) result = df.with_columns([ pl.col("cell_str").h3.cells_parse(set_failing_to_invalid=True).alias("cell"), ]).with_columns([ pl.col("cell").h3.cells_resolution().alias("resolution"), pl.col("cell").h3.cells_area_km2().alias("area_km2"), pl.col("cell").h3.cells_valid().alias("is_valid"), ]).with_columns([ pl.col("cell").h3.change_resolution(7).alias("res7_children"), ]).with_columns([ pl.col("cell").h3.cells_to_string().alias("cell_hex"), ]) print(result) # ┌──────────────────┬──────────────────────┬────────────────┬────────────┬──────────┬───────────────────┬─────────────────┐ # │ cell_str ┆ cell ┆ resolution ┆ area_km2 ┆ is_valid ┆ res7_children ┆ cell_hex │ # ╞══════════════════╪══════════════════════╪════════════════╪════════════╪══════════╪═══════════════════╪═════════════════╡ # │ "8552dc63fffffff"┆ 1073741824000000000 ┆ 5 ┆ 1.6384 ┆ true ┆ 1073741824000000000 ┆ 8552dc63fffffff │ # │ "8928308280fffff"┆ 1073741824000000000 ┆ 7 ┆ 0.256 ┆ true ┆ 1073741824000000000 ┆ 8928308280fffff │ # │ "INVALID" ┆ null ┆ null ┆ null ┆ false ┆ null ┆ null │ # └──────────────────┴──────────────────────┴────────────────┴────────────┴──────────┴───────────────────┴─────────────────┘ ``` ``` -------------------------------- ### cells_to_wkb_points(), vertexes_to_wkb_points(), directededges_to_wkb_linestrings() Source: https://context7.com/nmandery/h3ronpy/llms.txt Convert H3 entities to their centroid points or edge linestrings as WKB. ```APIDOC ## cells_to_wkb_points() / vertexes_to_wkb_points() / directededges_to_wkb_linestrings() ### Description Convert H3 entities to their centroid points or edge linestrings as WKB. ### Parameters - **cells**: Arrow array - Required - An array of H3 cell indexes (for `cells_to_wkb_points`). ### Request Example ```python import h3ronpy.vector as hv import h3ronpy import shapely cells = h3ronpy.cells_parse(["8552dc63fffffff", "8928308280fffff"]) # Cell centroids as points points_wkb = hv.cells_to_wkb_points(cells) points = [shapely.from_wkb(w) for w in points_wkb.to_pylist()] print([(round(p.x, 4), round(p.y, 4)) for p in points]) # [(lng, lat), ...] ``` ### Response - **wkb_array**: Arrow array - An array of WKB-formatted points or linestrings. ``` -------------------------------- ### change_resolution_list() Source: https://context7.com/nmandery/h3ronpy/llms.txt Similar to `change_resolution()`, but returns a list array preserving alignment with the input array. ```APIDOC ## change_resolution_list() ### Description Same as `change_resolution()` but returns a **list array** whose length equals the input, so each output row corresponds to the same-position input cell. Useful for keeping data aligned when joining tables. ### Method `change_resolution_list(cells: pyarrow.UInt64Array, resolution: int) -> pyarrow.ListArray` ### Parameters #### Arguments - `cells` (pyarrow.UInt64Array): An Arrow array of H3 cell indexes. - `resolution` (int): The target resolution to change the cells to. ### Returns - `pyarrow.ListArray`: A list array where each element is a list of H3 cells at the target resolution, corresponding to the input cell. ``` -------------------------------- ### cells_to_wkb_polygons() Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts an array of H3 cell indexes to their hexagonal/pentagonal polygon boundaries in WKB format. Setting `link_cells=True` merges adjacent cells into combined polygons. ```APIDOC ## cells_to_wkb_polygons() ### Description Converts an array of H3 cell indexes to their hexagonal/pentagonal polygon boundaries in WKB format. Setting `link_cells=True` merges adjacent cells into combined polygons. ### Parameters - **cells**: Arrow array - Required - An array of H3 cell indexes. - **link_cells**: bool - Optional - Whether to merge adjacent cells into combined polygons. Defaults to `False`. ### Request Example ```python import h3ronpy.vector as hv import h3ronpy import shapely cells = h3ronpy.cells_parse(["8552dc63fffffff", "8552dc67fffffff"]) wkb_array = hv.cells_to_wkb_polygons(cells, link_cells=True) polygons = [shapely.from_wkb(wkb) for wkb in wkb_array.to_pylist() if wkb] print(polygons[0].geom_type) # "Polygon" print(polygons[0].bounds) # (lng_min, lat_min, lng_max, lat_max) ``` ### Response - **wkb_array**: Arrow array - An array of WKB-formatted polygons. ``` -------------------------------- ### cells_bounds() / cells_bounds_arrays() Source: https://context7.com/nmandery/h3ronpy/llms.txt `cells_bounds()` returns a single `(minx, miny, maxx, maxy)` tuple for the whole array. `cells_bounds_arrays()` returns per-cell bounding boxes as a `RecordBatch`. ```APIDOC ## cells_bounds() / cells_bounds_arrays() ### Description `cells_bounds()` returns a single `(minx, miny, maxx, maxy)` tuple for the whole array. `cells_bounds_arrays()` returns per-cell bounding boxes as a `RecordBatch`. ### Parameters - **cells**: Arrow array - Required - An array of H3 cell indexes. ### Request Example ```python import h3ronpy.vector as hv import h3ronpy cells = h3ronpy.cells_parse(["8552dc63fffffff", "8928308280fffff"]) # Overall bounds bbox = hv.cells_bounds(cells) print(bbox) # (minx, miny, maxx, maxy) # Per-cell bounds table per_cell = hv.cells_bounds_arrays(cells) print(per_cell.schema) # minx: double, miny: double, maxx: double, maxy: double ``` ### Response - **bbox**: tuple - A tuple representing the overall bounding box `(minx, miny, maxx, maxy)`. - **per_cell**: RecordBatch - A `RecordBatch` containing `minx`, `miny`, `maxx`, and `maxy` columns for each cell. ``` -------------------------------- ### Polars Namespace Extensions for H3 Operations Source: https://context7.com/nmandery/h3ronpy/llms.txt Imports h3ronpy.polars to register an 'h3' namespace on Polars Expressions and Series. This allows seamless integration of H3 functions within Polars data pipelines. Requires polars and h3ronpy.polars. ```python import polars as pl import h3ronpy.polars # registers .h3 namespace df = pl.DataFrame({ "cell_str": ["8552dc63fffffff", "8928308280fffff", "INVALID"], }) result = df.with_columns([ pl.col("cell_str").h3.cells_parse(set_failing_to_invalid=True).alias("cell"), ]).with_columns([ pl.col("cell").h3.cells_resolution().alias("resolution"), pl.col("cell").h3.cells_area_km2().alias("area_km2"), pl.col("cell").h3.cells_valid().alias("is_valid"), ]).with_columns([ pl.col("cell").h3.change_resolution(7).alias("res7_children"), ]).with_columns([ pl.col("cell").h3.cells_to_string().alias("cell_hex"), ]) print(result) ``` -------------------------------- ### Convert Local IJ Coordinates Back to H3 Cells Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts local IJ integer coordinates back to H3 cell indices, using a specified anchor cell. Requires providing 'i' and 'j' columns. Use `set_failing_to_invalid=True` for robust conversion. ```python import h3ronpy anchor_hex = "8552dc63fffffff" anchor_int = h3ronpy.cells_parse([anchor_hex]).to_pylist()[0] neighbours = h3ronpy.grid_disk(h3ronpy.cells_parse([anchor_hex]), k=1, flatten=True) ij = h3ronpy.cells_to_localij(neighbours, anchor=anchor_int, set_failing_to_invalid=True) # Back to cells recovered = h3ronpy.localij_to_cells( anchor=anchor_int, i=ij.column("i"), j=ij.column("j"), set_failing_to_invalid=True, ) ``` -------------------------------- ### change_resolution_paired() Source: https://context7.com/nmandery/h3ronpy/llms.txt Performs a resolution change and returns a two-column RecordBatch with 'cell_before' and 'cell_after' columns. ```APIDOC ## change_resolution_paired() ### Description Returns a two-column `RecordBatch` (`cell_before`, `cell_after`) useful for joining datasets at different resolutions via dataframe `merge`/`join`. ### Method `change_resolution_paired(cells: pyarrow.UInt64Array, resolution: int) -> pyarrow.RecordBatch` ### Parameters #### Arguments - `cells` (pyarrow.UInt64Array): An Arrow array of H3 cell indexes. - `resolution` (int): The target resolution to change the cells to. ### Returns - `pyarrow.RecordBatch`: A RecordBatch with two columns: `cell_before` and `cell_after`. ``` -------------------------------- ### Compact and Uncompact H3 Cell Sets Source: https://context7.com/nmandery/h3ronpy/llms.txt `compact()` merges sets of same-resolution cells into their parent cells if all children are present, reducing storage. `uncompact()` expands cells back to a uniform target resolution. ```python import h3ronpy ``` -------------------------------- ### Resolution Change with Before/After Columns Source: https://context7.com/nmandery/h3ronpy/llms.txt Generates a two-column `RecordBatch` containing the original and transformed H3 cells. This format is ideal for joining datasets that have been processed at different resolutions. ```python import h3ronpy import pyarrow as pa cells = h3ronpy.cells_parse(["8552dc63fffffff", "8552dc67fffffff"]) paired = h3ronpy.change_resolution_paired(cells, resolution=7) # Convert to pandas for inspection import pandas as pd df = pa.record_batch(paired).to_pandas() if hasattr(paired, "to_pandas") else paired.to_pydict() print(paired.schema) ``` -------------------------------- ### Convert H3 Cells to WKB Points and Edges Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts H3 cell indexes to WKB point representations of their centroids, or directed edges to WKB linestrings. This is useful for visualizing cell centers or boundaries. ```python import h3ronpy.vector as hv import h3ronpy import shapely cells = h3ronpy.cells_parse(["8552dc63fffffff", "8928308280fffff"]) # Cell centroids as points points_wkb = hv.cells_to_wkb_points(cells) points = [shapely.from_wkb(w) for w in points_wkb.to_pylist()] print([(round(p.x, 4), round(p.y, 4)) for p in points]) # [(lng, lat), ...] ``` -------------------------------- ### Aggregate K-Ring Distances for Multiple Origins Source: https://context7.com/nmandery/h3ronpy/llms.txt Computes the minimum or maximum ring distance for each neighbor cell across multiple origin cells. Requires specifying an `aggregation_method` ('min' or 'max'). Useful for finding the closest or furthest origin for each cell within a given radius. ```python import h3ronpy origins = h3ronpy.cells_parse(["8552dc63fffffff", "8552dc67fffffff"]) result = h3ronpy.grid_disk_aggregate_k(origins, k=3, aggregation_method="min") print(result.schema) # cell: uint64 # k: uint32 ``` -------------------------------- ### grid_disk_aggregate_k() Source: https://context7.com/nmandery/h3ronpy/llms.txt Computes the minimum or maximum ring distance for neighbor cells across multiple origin cells. ```APIDOC ## grid_disk_aggregate_k() ### Description Computes the minimum or maximum ring distance at which each neighbour cell appears across all origin cells. `aggregation_method` must be `"min"` or `"max"`. ### Method `h3ronpy.grid_disk_aggregate_k(origins, k, aggregation_method)` ### Parameters #### Path Parameters None #### Query Parameters - **origins** (array) - The origin H3 cell(s). - **k** (integer) - The maximum grid distance (k-ring). - **aggregation_method** (string) - Either 'min' or 'max'. ### Request Example ```python import h3ronpy origins = h3ronpy.cells_parse(["8552dc63fffffff", "8552dc67fffffff"]) result = h3ronpy.grid_disk_aggregate_k(origins, k=3, aggregation_method="min") print(result.schema) # cell: uint64 # k: uint32 ``` ### Response #### Success Response (200) - **result** (RecordBatch) - A RecordBatch with 'cell' and aggregated 'k' columns. ``` -------------------------------- ### grid_disk() Source: https://context7.com/nmandery/h3ronpy/llms.txt Returns all H3 cells within a specified grid distance (k-ring) of an origin cell. Can return a list array or a flattened array. ```APIDOC ## grid_disk() ### Description Returns all H3 cells within grid distance `k` of each input cell. Returns a list array by default; set `flatten=True` for a flat cell array. ### Method `h3ronpy.grid_disk(origin, k, flatten=False)` ### Parameters #### Path Parameters None #### Query Parameters - **origin** (array) - The origin H3 cell(s). - **k** (integer) - The grid distance (k-ring). - **flatten** (boolean) - If `True`, returns a flat array of cells. If `False`, returns a list array where each sub-array corresponds to a k-ring. ### Request Example ```python import h3ronpy origin = h3ronpy.cells_parse(["8552dc63fffffff"]) # List array: each row contains the cells within k=2 disks = h3ronpy.grid_disk(origin, k=2, flatten=False) print(len(disks[0])) # 19 (1 + 6 + 12) # Flat array: all neighbor cells concatenated flat = h3ronpy.grid_disk(origin, k=2, flatten=True) print(len(flat)) # 19 ``` ### Response #### Success Response (200) - **disks** (list of lists or array) - An array containing H3 cells within the specified k-ring. ``` -------------------------------- ### grid_disk_distances() Source: https://context7.com/nmandery/h3ronpy/llms.txt Returns a RecordBatch containing H3 cells and their respective grid distances from the origin cell. ```APIDOC ## grid_disk_distances() ### Description Returns a `RecordBatch` with columns `cell` and `k` (the ring distance), useful for distance-weighted spatial analyses. ### Method `h3ronpy.grid_disk_distances(origin, k)` ### Parameters #### Path Parameters None #### Query Parameters - **origin** (array) - The origin H3 cell(s). - **k** (integer) - The maximum grid distance (k-ring). ### Request Example ```python import h3ronpy origin = h3ronpy.cells_parse(["8552dc63fffffff"]) result = h3ronpy.grid_disk_distances(origin, k=2) print(result.schema) # cell: uint64 # k: uint32 # Convert to pandas import pyarrow as pa df = pa.RecordBatch.from_batches([result]).to_pandas() if False else \ {col: result.column(col).to_pylist() for col in result.schema.names} print(dict(list(df.items()))) ``` ### Response #### Success Response (200) - **result** (RecordBatch) - A RecordBatch with 'cell' and 'k' columns. ``` -------------------------------- ### wkb_to_cells() Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts a column of WKB-encoded geometries to H3 cells. Returns a list array (one entry per geometry) or a flat array when `flatten=True`. ```APIDOC ## wkb_to_cells() ### Description Converts a column of WKB-encoded geometries to H3 cells. Returns a list array (one entry per geometry) or a flat array when `flatten=True`. ### Parameters - **wkb_array**: Arrow array - Required - An Arrow array containing WKB-encoded geometries. - **resolution**: int - Required - The H3 resolution for the output cells. - **containment_mode**: ContainmentMode - Optional - Specifies how geometries should be contained within cells. Defaults to `ContainsCentroid`. - **compact**: bool - Optional - Whether to return compact sets of H3 cells. Defaults to `False`. - **flatten**: bool - Optional - If `True`, returns a flat array of cells. Defaults to `False`. ### Request Example ```python import h3ronpy.vector as hv from h3ronpy import ContainmentMode import pyarrow as pa import shapely, shapely.wkb geoms = [shapely.geometry.box(13.3, 52.4, 13.6, 52.6), shapely.geometry.box(11.5, 48.1, 11.7, 48.3)] wkb_array = pa.array([shapely.wkb.dumps(g) for g in geoms]) cells_list = hv.wkb_to_cells( wkb_array, resolution=7, containment_mode=ContainmentMode.Covers, compact=True, flatten=False, ) # cells_list[0] contains all cells for geoms[0] print([len(row) for row in cells_list.to_pylist()]) ``` ### Response - **cells**: Arrow array - An array of H3 cell indexes. Can be a list array or a flat array depending on the `flatten` parameter. ``` -------------------------------- ### change_resolution() Source: https://context7.com/nmandery/h3ronpy/llms.txt Changes all H3 cells in an array to a specified target resolution. Expands cells for higher resolutions and aggregates for lower resolutions. ```APIDOC ## change_resolution() ### Description Changes all cells in an array to the target resolution. Resolution increases expand each cell into all children; resolution decreases replace children with their parent. Invalid/empty values are omitted from the result. ### Method `change_resolution(cells: pyarrow.UInt64Array, resolution: int) -> pyarrow.UInt64Array` ### Parameters #### Arguments - `cells` (pyarrow.UInt64Array): An Arrow array of H3 cell indexes. - `resolution` (int): The target resolution to change the cells to. ### Returns - `pyarrow.UInt64Array`: An Arrow array containing the H3 cells at the target resolution. ``` -------------------------------- ### Convert H3 Cells to WKB Polygons Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts an array of H3 cell indexes to their WKB polygon boundaries. Setting `link_cells=True` merges adjacent cells into single polygons, simplifying the output. ```python import h3ronpy.vector as hv import h3ronpy import shapely cells = h3ronpy.cells_parse(["8552dc63fffffff", "8552dc67fffffff"]) wkb_array = hv.cells_to_wkb_polygons(cells, link_cells=True) polygons = [shapely.from_wkb(wkb) for wkb in wkb_array.to_pylist() if wkb] print(polygons[0].geom_type) # "Polygon" print(polygons[0].bounds) # (lng_min, lat_min, lng_max, lat_max) ``` -------------------------------- ### Polygon to H3 Cells Conversion with Containment Modes Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts a Shapely polygon to H3 cells using different containment modes. Requires h3ronpy, shapely, and optionally polars. ```python from h3ronpy import ContainmentMode import h3ronpy.vector as hv import shapely.geometry circle = shapely.geometry.Point(13.4, 52.5).buffer(0.2) # ContainsCentroid: a cell is included if its centroid is inside (default) cells_centroid = hv.geometry_to_cells(circle, 8, ContainmentMode.ContainsCentroid) # Covers: a cell is included if the geometry fully covers it cells_covers = hv.geometry_to_cells(circle, 8, ContainmentMode.Covers) # IntersectsBoundary: include all cells that intersect the boundary or interior cells_intersects = hv.geometry_to_cells(circle, 8, ContainmentMode.IntersectsBoundary) print(len(cells_centroid), len(cells_covers), len(cells_intersects)) ``` -------------------------------- ### Convert WKB Array to H3 Cells Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts a PyArrow array of WKB-encoded geometries to H3 cells. The `flatten=False` option returns a list array where each entry corresponds to the cells for a single input geometry. `Covers` mode is used for containment. ```python import h3ronpy.vector as hv from h3ronpy import ContainmentMode import pyarrow as pa import shapely, shapely.wkb geoms = [shapely.geometry.box(13.3, 52.4, 13.6, 52.6), shapely.geometry.box(11.5, 48.1, 11.7, 48.3)] wkb_array = pa.array([shapely.wkb.dumps(g) for g in geoms]) cells_list = hv.wkb_to_cells( wkb_array, resolution=7, containment_mode=ContainmentMode.Covers, compact=True, flatten=False, ) # cells_list[0] contains all cells for geoms[0] print([len(row) for row in cells_list.to_pylist()]) ``` -------------------------------- ### Convert H3 Cells Series to GeoSeries (Polygons/Points) Source: https://context7.com/nmandery/h3ronpy/llms.txt Directly converts a pandas Series of H3 cell integers to a GeoSeries of polygon or point geometries. The output is in EPSG:4326. Requires pandas and h3ronpy. ```python import pandas as pd import h3ronpy import h3ronpy.pandas.vector as hpv cells_series = pd.array( h3ronpy.cells_parse(["8552dc63fffffff", "8928308280fffff"]).to_pylist(), dtype="uint64", ) polygons = hpv.cells_to_polygons(pd.Series(cells_series)) print(polygons.crs) # EPSG:4326 print(polygons[0].area) # area in degrees² points = hpv.cells_to_points(pd.Series(cells_series)) print([(round(p.x, 4), round(p.y, 4)) for p in points]) ``` -------------------------------- ### cells_to_localij() / localij_to_cells() Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts H3 cells to and from local IJ coordinates relative to an anchor cell. ```APIDOC ## cells_to_localij() / localij_to_cells() ### Description Converts cells to local IJ integer coordinates relative to an anchor cell, and back. Useful for building local grid neighbourhoods. ### Method `h3ronpy.cells_to_localij(cells, anchor, set_failing_to_invalid=True)` `h3ronpy.localij_to_cells(anchor, i, j, set_failing_to_invalid=True)` ### Parameters #### Path Parameters None #### Query Parameters - **cells** (array) - The input H3 cells for `cells_to_localij`. - **anchor** (integer) - The anchor H3 cell. - **i** (array) - The 'i' component of local IJ coordinates for `localij_to_cells`. - **j** (array) - The 'j' component of local IJ coordinates for `localij_to_cells`. - **set_failing_to_invalid** (boolean) - If `True`, invalid conversions result in an invalid H3 index. ### Request Example ```python import h3ronpy anchor_hex = "8552dc63fffffff" anchor_int = h3ronpy.cells_parse([anchor_hex]).to_pylist()[0] neighbours = h3ronpy.grid_disk(h3ronpy.cells_parse([anchor_hex]), k=1, flatten=True) # To local IJ ij = h3ronpy.cells_to_localij(neighbours, anchor=anchor_int, set_failing_to_invalid=True) print(ij.schema) # i: int32, j: int32 # Back to cells recovered = h3ronpy.localij_to_cells( anchor=anchor_int, i=ij.column("i"), j=ij.column("j"), set_failing_to_invalid=True, ) ``` ### Response #### Success Response (200) - **ij** (RecordBatch) - A RecordBatch with 'i' and 'j' columns for `cells_to_localij`. - **recovered** (array) - An array of H3 cells for `localij_to_cells`. ``` -------------------------------- ### cells_to_polygons() / cells_to_points() Source: https://context7.com/nmandery/h3ronpy/llms.txt Directly convert a pandas Series of H3 cell integers to a GeoSeries of polygon or point geometries (EPSG:4326). ```APIDOC ## cells_to_polygons() / cells_to_points() ### Description Directly convert a pandas `Series` of H3 cell integers to a `GeoSeries` of polygon or point geometries (EPSG:4326). ### Usage ```python import pandas as pd import h3ronpy import h3ronpy.pandas.vector as hpv cells_series = pd.array( h3ronpy.cells_parse(["8552dc63fffffff", "8928308280fffff"]).to_pylist(), dtype="uint64", ) polygons = hpv.cells_to_polygons(pd.Series(cells_series)) print(polygons.crs) # EPSG:4326 print(polygons[0].area) # area in degrees² points = hpv.cells_to_points(pd.Series(cells_series)) print([(round(p.x, 4), round(p.y, 4)) for p in points]) ``` ``` -------------------------------- ### Parse H3 Cells from Strings Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts various string representations (hex, integer, coordinates) into H3 cell indexes. Use `set_failing_to_invalid=True` to handle unparsable entries gracefully by masking them instead of raising an error. ```python import h3ronpy # Mix of hex, integer-string and coordinate-triplet representations strings = ["8552dc63fffffff", "600436454824345599", "10.2,45.5,5"] cells = h3ronpy.cells_parse(strings, set_failing_to_invalid=True) print(cells) # # [599686042433355775, 600436454824345599, ...] # Round-trip back to hex strings print(h3ronpy.cells_to_string(cells)) ``` -------------------------------- ### Convert Raster NumPy Array to H3 Arrow Table Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts a 2D numpy array with an affine transform into an Arrow Table containing H3 cells and their corresponding values. Supports multi-threading and various numpy dtypes. Nodata values are excluded. Requires numpy, rasterio, and h3ronpy.raster. ```python import numpy as np import rasterio import h3ronpy.raster as hr with rasterio.open("europe-and-north-africa.tif") as src: data = src.read(1) # first band as 2D array transform = src.transform # rasterio Affine object h3_res = hr.nearest_h3_resolution(data.shape, transform) table = hr.raster_to_dataframe( data, transform=transform, h3_resolution=h3_res, nodata_value=0, compact=True, ) print(table.schema) # value: uint8 (or matching numpy dtype) # cell: uint64 print(table.num_rows) # number of non-nodata H3 cells ``` -------------------------------- ### coordinates_to_cells() Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts parallel arrays of latitude, longitude, and resolution values into H3 cell indexes. ```APIDOC ## coordinates_to_cells() ### Description Converts parallel arrays of latitude, longitude, and resolution values into H3 cell indexes. ### Parameters - **lats**: list[float] or Arrow array - Required - Array of latitudes. - **lngs**: list[float] or Arrow array - Required - Array of longitudes. - **resarray**: int or list[int] or Arrow array - Required - The H3 resolution(s) for the output cells. Can be a single integer for all points or an array for per-point resolution. ### Request Example ```python import h3ronpy.vector as hv lats = [52.52, 48.14, 40.71] lngs = [13.40, 11.58, -74.00] # Single resolution for all points cells = hv.coordinates_to_cells(lats, lngs, resarray=6) print(h3ronpy.cells_to_string(cells).to_pylist()) # ["862a1073fffffff", "862b8947fffffff", "862a100b7ffffff"] # Per-row resolution cells_mixed = hv.coordinates_to_cells(lats, lngs, resarray=[5, 6, 7]) ``` ### Response - **cells**: Arrow array - An array of H3 cell indexes. ``` -------------------------------- ### cells_to_coordinates() Source: https://context7.com/nmandery/h3ronpy/llms.txt Returns a `RecordBatch` with `lat` and `lng` float64 columns for each cell's centroid. ```APIDOC ## cells_to_coordinates() ### Description Returns a `RecordBatch` with `lat` and `lng` float64 columns for each cell's centroid. ### Parameters - **cells**: Arrow array - Required - An array of H3 cell indexes. ### Request Example ```python import h3ronpy.vector as hv import h3ronpy cells = h3ronpy.cells_parse(["8552dc63fffffff"]) coords = hv.cells_to_coordinates(cells) print(coords.schema) # lat: double, lng: double print(coords.column("lat").to_pylist(), coords.column("lng").to_pylist()) ``` ### Response - **coords**: RecordBatch - A `RecordBatch` containing `lat` and `lng` columns. ``` -------------------------------- ### rasterize_cells() Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts arrays of cells and values back to a 2D numpy array and an affine transform, suitable for writing with rasterio. ```APIDOC ## rasterize_cells() ### Description Converts arrays of cells and values back to a 2D numpy array and an affine transform, suitable for writing with rasterio. ### Usage ```python import numpy as np import rasterio import h3ronpy import h3ronpy.raster as hr cells = h3ronpy.cells_parse(["8552dc63fffffff", "8552dc67fffffff"]) import pyarrow as pa values = pa.array([100, 200], type=pa.uint8()) raster_array, transform = hr.rasterize_cells(cells, values, size=512, nodata_value=0) print(raster_array.shape) # (512, width_interpolated) print(raster_array.dtype) # uint8 with rasterio.open( "output.tif", "w", driver="GTiff", height=raster_array.shape[0], width=raster_array.shape[1], count=1, dtype=raster_array.dtype, crs="EPSG:4326", transform=transform, ) as dst: dst.write(raster_array, 1) ``` ``` -------------------------------- ### Convert H3 Cells to Raster NumPy Array Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts arrays of H3 cells and their values back into a 2D numpy array and an affine transform, suitable for writing with rasterio. Requires numpy, rasterio, h3ronpy, and h3ronpy.raster. ```python import numpy as np import rasterio import h3ronpy import h3ronpy.raster as hr cells = h3ronpy.cells_parse(["8552dc63fffffff", "8552dc67fffffff"]) import pyarrow as pa values = pa.array([100, 200], type=pa.uint8()) raster_array, transform = hr.rasterize_cells(cells, values, size=512, nodata_value=0) print(raster_array.shape) # (512, width_interpolated) print(raster_array.dtype) # uint8 with rasterio.open( "output.tif", "w", driver="GTiff", height=raster_array.shape[0], width=raster_array.shape[1], count=1, dtype=raster_array.dtype, crs="EPSG:4326", transform=transform, ) as dst: dst.write(raster_array, 1) ``` -------------------------------- ### grid_ring_distances() Source: https://context7.com/nmandery/h3ronpy/llms.txt Returns H3 cells within a specified range of ring distances (k_min to k_max), excluding inner rings. ```APIDOC ## grid_ring_distances() ### Description Returns only cells in ring distances `k_min` through `k_max` (inclusive), excluding the inner disk. ### Method `h3ronpy.grid_ring_distances(cells, k_min, k_max, flatten=True)` ### Parameters #### Path Parameters None #### Query Parameters - **cells** (array) - The input H3 cell(s). - **k_min** (integer) - The minimum ring distance. - **k_max** (integer) - The maximum ring distance. - **flatten** (boolean) - If `True`, returns a flat array of cells. If `False`, returns a list array. ### Request Example ```python import h3ronpy cells = h3ronpy.cells_parse(["8552dc63fffffff"]) # Only cells at ring distance 2 and 3 (not 0 or 1) ring = h3ronpy.grid_ring_distances(cells, k_min=2, k_max=3, flatten=True) print(len(ring)) # 30 (12 at ring 2 + 18 at ring 3) ``` ### Response #### Success Response (200) - **ring** (array) - An array containing H3 cells within the specified ring distance range. ``` -------------------------------- ### geodataframe_to_cells() Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts a `GeoDataFrame` to a `DataFrame` with H3 cell indexes. Each geometry is replaced by all cells that cover it; all other columns are duplicated (exploded) accordingly. Multi-threaded over available CPUs. ```APIDOC ## geodataframe_to_cells() ### Description Converts a `GeoDataFrame` to a `DataFrame` with H3 cell indexes. Each geometry is replaced by all cells that cover it; all other columns are duplicated (exploded) accordingly. Multi-threaded over available CPUs. ### Parameters - **gdf**: GeoDataFrame - Required - The input GeoDataFrame. - **resolution**: int - Required - The H3 resolution for the output cells. - **containment_mode**: ContainmentMode - Optional - Specifies how geometries should be contained within cells. Defaults to `ContainsCentroid`. - **compact**: bool - Optional - Whether to return compact sets of H3 cells. Defaults to `False`. ### Request Example ```python import geopandas as gpd import h3ronpy.pandas.vector as hpv from h3ronpy import ContainmentMode gdf = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres")) gdf = gdf[gdf["continent"] == "Europe"].to_crs("EPSG:4326") cells_df = hpv.geodataframe_to_cells( gdf, resolution=4, containment_mode=ContainmentMode.ContainsCentroid, compact=False, ) print(cells_df.head()) # pop_est continent name ... cell # 0 ... Europe Albania ... 613... # 1 ... Europe Albania ... 613... print(cells_df.dtypes) ``` ### Response - **cells_df**: DataFrame - A pandas DataFrame with H3 cell indexes and duplicated original columns. ``` -------------------------------- ### cells_resolution() Source: https://context7.com/nmandery/h3ronpy/llms.txt Extracts the H3 resolution level from input H3 cells. ```APIDOC ## cells_resolution() ### Description Returns a `UInt8` Arrow array containing the H3 resolution (0–15) of each input cell. ### Method `h3ronpy.cells_resolution(cells)` ### Parameters #### Path Parameters None #### Query Parameters - **cells** (array) - The input H3 cells. ### Request Example ```python import h3ronpy mixed = h3ronpy.cells_parse(["8552dc63fffffff", "8928308280fffff"]) resolutions = h3ronpy.cells_resolution(mixed) print(resolutions.to_pylist()) # [5, 9] ``` ### Response #### Success Response (200) - **resolutions** (UInt8 Array) - An array of H3 resolutions for each input cell. ``` -------------------------------- ### geometry_to_cells() Source: https://context7.com/nmandery/h3ronpy/llms.txt Converts any object implementing the Python `__geo_interface__` protocol (shapely, geojson, etc.) to an Arrow array of H3 cells. ```APIDOC ## geometry_to_cells() ### Description Converts any object implementing the Python `__geo_interface__` protocol (shapely, geojson, etc.) to an Arrow array of H3 cells. ### Parameters - **geometry**: object - Required - An object implementing the `__geo_interface__` protocol. - **resolution**: int - Required - The H3 resolution for the output cells. - **containment_mode**: ContainmentMode - Optional - Specifies how geometries should be contained within cells. Defaults to `ContainsCentroid`. - **compact**: bool - Optional - Whether to return compact sets of H3 cells. Defaults to `False`. ### Request Example ```python import h3ronpy.vector as hv from h3ronpy import ContainmentMode import shapely.geometry polygon = shapely.geometry.box(13.3, 52.4, 13.6, 52.6) # Berlin bounding box cells = hv.geometry_to_cells( polygon, resolution=8, containment_mode=ContainmentMode.ContainsCentroid, compact=False, ) print(len(cells)) # ~400 cells covering the bounding box print(cells[0]) # e.g. 613177553099276287 ``` ### Response - **cells**: Arrow array - An array of H3 cell indexes. ```