### Install polars_h3 Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/quickstart.ipynb Install the necessary libraries if they are not already present. Uncomment the line to run the installation. ```python # If needed, uncomment to install # !pip install polars polars_h3 h3 ``` -------------------------------- ### Install Benchmarking Dependencies Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/benchmarking.ipynb Installs necessary libraries for benchmarking, including h3pandas, duckdb, h3, pyarrow, and pandas. ```python # !uv pip install h3pandas duckdb h3 pyarrow pandas ``` -------------------------------- ### Install Polars and Polars-H3 Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/telematics.ipynb Installs the necessary libraries for data manipulation and H3 geospatial indexing. ```python # !pip install polars polars-h3 matplotlib folium ``` -------------------------------- ### Install Graphing Libraries Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/telematics.ipynb Installs Folium and Matplotlib, which are required for visualizing the telematics data using mapping and graphing functions. ```python # Make sure you have volume and mapplotlib installed to use the graphing functions # !uv pip install folium matplotlib ``` -------------------------------- ### Install polars-h3 Source: https://github.com/filimoa/polars-h3/blob/master/docs/index.md Install the polars-h3 library using pip. This command ensures you have the latest version for use with Polars. ```bash pip install polars-h3 ``` -------------------------------- ### get_pentagons Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/metrics.md Get the number of pentagons at a given resolution. This function is a placeholder and is not yet implemented. ```APIDOC ## `get_pentagons` ### Description Get the number of pentagons at a given resolution. ### Method plh3.get_pentagons ### Parameters #### Path Parameters - **resolution** (IntoExprColumn) - Required - H3 resolution level (`0` to `15`). ### Returns - **Expr** - Once implemented, it should return a Polars expression with the count of pentagonal cells at the specified resolution. _Note:_ This function is a placeholder that raises `NotImplementedError`. ``` -------------------------------- ### get_num_cells Source: https://github.com/filimoa/polars-h3/blob/master/README.md Get the total number of cells at a specified resolution. ```APIDOC ## get_num_cells ### Description Get the total number of cells at a specified resolution. ### Method Not specified (likely a function call in the Polars-H3 library) ### Endpoint Not applicable (library function) ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### cell_to_children_size Source: https://github.com/filimoa/polars-h3/blob/master/docs/index.md Get the number of child cells at a given resolution. ```APIDOC ## cell_to_children_size ### Description Get the number of child cells at a given resolution. ### Method Not specified (likely a function call in a library) ### Endpoint Not applicable (library function) ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### grid_path_cells Source: https://github.com/filimoa/polars-h3/blob/master/README.md Find a grid path to connect two cells. This function calculates a sequence of H3 cell IDs representing a path between a starting cell and an ending cell. ```APIDOC ## grid_path_cells ### Description Find a grid path to connect two cells. ### Parameters * **cell1** (string) - The starting H3 cell ID. * **cell2** (string) - The ending H3 cell ID. ### Returns * **array** - An array of H3 cell IDs representing the path between `cell1` and `cell2`. ``` -------------------------------- ### Get the number of children cells at a specific resolution Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/inspection.md Use `cell_to_children_size` to calculate the number of children cells for a given H3 cell at a specified resolution. This function requires the cell expression and the target resolution. ```python >>> df = pl.DataFrame({"h3_cell": [582692784209657855]}) >>> df.with_columns( ... num_children=plh3.cell_to_children_size("h3_cell", 2) ... ) shape: (1, 2) ┌─────────────────────┬──────────────┐ │ h3_cell │ num_children │ │ --- │ --- │ │ u64 │ u64 │ ╞═════════════════════╪══════════════╡ │ 582692784209657855 │ 7 │ └─────────────────────┴──────────────┘ ``` -------------------------------- ### Get Number of Cells at Resolution Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/metrics.md Retrieves the total count of H3 cells for a specific resolution. Use this to determine the number of unique cells at a given H3 level. ```python df = pl.DataFrame({"resolution": [5]}) df.with_columns( count=plh3.get_num_cells("resolution") ) ``` -------------------------------- ### Aggregate Time Spent in H3 Hexagons Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/telematics.ipynb Groups trip data by trip ID and H3 hexagon to calculate the maximum end time, minimum start time, and total elapsed seconds within each hexagon. Use this to summarize temporal data within spatial cells. ```python final_df = trips_with_time_spent_in_hex.group_by( ["trip_id", hex_col], maintain_order=True, ).agg( [ pl.col("end").max(), pl.col("start").min(), pl.col("elapsed_seconds").sum(), ], ) display(final_df.head()) ``` -------------------------------- ### Get center child H3 cell at a specific resolution Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/inspection.md Use `cell_to_center_child` to retrieve the center child H3 cell for a given cell at a specified resolution. This function requires the cell expression and the target resolution. ```python >>> df = pl.DataFrame({"h3_cell": [582692784209657855]}) >>> df.with_columns( ... center_child=plh3.cell_to_center_child("h3_cell", 2) ... ) shape: (1, 2) ┌─────────────────────┬─────────────────┐ │ h3_cell │ center_child │ │ --- │ --- │ │ u64 │ u64 │ ╞═════════════════════╪═════════════════╡ │ 582692784209657855 │ ... │ └─────────────────────┴─────────────────┘ ``` -------------------------------- ### Retrieve icosahedron faces for H3 cells Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/inspection.md Use `get_icosahedron_faces` to get the icosahedron faces intersected by an H3 cell. It accepts an H3 cell expression and returns a Polars expression with a list of intersected face indices. ```python >>> df = pl.DataFrame({ ... "h3_cell": [599686042433355775] ... }) >>> df.with_columns( ... faces=plh3.get_icosahedron_faces("h3_cell") ... ) shape: (1, 2) ┌─────────────────────┬─────────┐ │ h3_cell │ faces │ │ --- │ --- │ │ u64 │ list[i64]│ ╞═════════════════════╪═════════╡ │ 599686042433355775 │ [7] │ └─────────────────────┴─────────┘ ``` -------------------------------- ### Get Cell from Parent Position with Polars-H3 Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/inspection.md Obtain a child H3 cell at a given position index for a specified parent cell and resolution. Use this when you know the parent and the desired child's index and need to derive the child's H3 index. ```python >>> df = pl.DataFrame({ ... "parent": [582692784209657855], ... "pos": [0] ... }) >>> df.with_columns( ... child=plh3.child_pos_to_cell("parent", "pos", 2) ... ) shape: (1, 2) ┌─────────────────────┬──────────┐ │ parent │ child │ │ --- │ --- │ │ u64 │ u64 │ ╞═════════════════════╪══════════╡ │ 582692784209657855 │ ... │ └─────────────────────┴──────────┘ ``` -------------------------------- ### Get H3 Index Resolution Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/inspection.md Use this function to retrieve the resolution of H3 indices. It accepts columns containing H3 indices in UInt64, Int64, or Utf8 format and returns an integer resolution. ```python >>> df = pl.DataFrame({ ... "h3_cell": [599686042433355775] ... }) >>> df.with_columns( ... resolution=plh3.get_resolution("h3_cell") ... ) shape: (1, 2) ┌─────────────────────┬────────────┐ │ h3_cell │ resolution │ │ --- │ --- │ │ u64 │ i64 │ ╞═════════════════════╪════════════╡ │ 599686042433355775 │ 2 │ └─────────────────────┴────────────┘ ``` -------------------------------- ### Find Hexagons Traveled Across in Trips Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/telematics.ipynb This snippet processes trip data to identify all H3 hexagons a trip has traversed. It calculates the start and end times for each segment and uses `plh3.grid_path_cells` to find the path of hexagons between consecutive points within a defined time limit. ```python prev_hex_col = f"prev_{hex_col}" trips_with_hex = ( trips.with_columns(pl.col(hex_col).shift(1).over("trip_id").alias(prev_hex_col)) .filter(pl.col("elapsed_seconds") <= FIFTEEN_MINUTES) .rename({"timestamp": "end", hex_col: "end_hex", prev_hex_col: "start_hex"}) .with_columns( [ (pl.col("end") - pl.duration(seconds=pl.col("elapsed_seconds"))).alias( "start" ), plh3.grid_path_cells(pl.col("start_hex"), pl.col("end_hex")).alias("path"), ] ) .drop(["start_hex", "end_hex", "lat", "long"]) .sort(["trip_id", "start"]) .select( [ "user_id", "trip_id", "start", "end", "elapsed_seconds", "path", ] ) ) # we now hav a dataframe with hex display(trips_with_hex.head()) ``` -------------------------------- ### Benchmark Polars-H3 Extension Source: https://github.com/filimoa/polars-h3/blob/master/README.md Build the release version of the extension and run the benchmark CLI to test performance. Specify libraries, functions, iterations, and output file. ```bash # 1 – (build) compile the optimized Rust extension uv run maturin develop --release --uv # 2 – (run) execute the benchmark CLI uv run h3-bench \ --libraries plh3 duckdb h3_py \ --functions latlng_to_cell cell_to_parent \ --iterations 3 \ --fast-factor 4 \ --output results.json ``` -------------------------------- ### Import Libraries Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/quickstart.ipynb Import the Polars and polars_h3 libraries to begin using their functionalities. ```python import polars as pl import polars_h3 as plh3 ``` -------------------------------- ### Run Benchmarks in Notebook Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/benchmarking.ipynb Configures and runs benchmarks using the Benchmark engine. It iterates through results, printing function names and individual result details. ```python from collections import defaultdict import json import statistics from .. import benchmarks param_config = benchmarks.ParamConfig( resolution=9, grid_ring_distance=3, num_iterations=3, libraries=["plh3", "duckdb", "h3_py"], difficulty_to_num_rows={ "basic": 10_000_000, "medium": 10_000_000, "complex": 100_000, }, # functions=["grid_path"], # verbose=True, ) benchmark_engine = benchmarks.Benchmark(config=param_config) raw_results = benchmark_engine.run_all() prev_func = None for result in raw_results: if prev_func != result.name: print(f"\n{result.name}") prev_func = result.name print(result) ``` -------------------------------- ### edge_length Source: https://github.com/filimoa/polars-h3/blob/master/README.md Get the length of a directed edge ID. ```APIDOC ## edge_length ### Description Get the length of a directed edge ID. ### Method Not specified (likely a function call in the Polars-H3 library) ### Endpoint Not applicable (library function) ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### cell_area Source: https://github.com/filimoa/polars-h3/blob/master/docs/index.md Get the area of a specific H3 cell. ```APIDOC ## cell_area ### Description Get the area of a specific H3 cell. ### Method Not specified (likely a function call in a library) ### Endpoint Not applicable (library function) ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Download Sample Telematics Data Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/telematics.ipynb Downloads a sample Parquet file containing telematics data and sets up the sample-data directory. Ensure the directory is created before downloading. ```python import polars as pl import polars_h3 as plh3 !mkdir -p sample-data !wget https://sergey-filimonov.nyc3.cdn.digitaloceanspaces.com/polars-h3/sample-data/sample-telematics-data.parquet -O sample-data/sample-telematics-data.parquet ``` -------------------------------- ### Load Benchmark Results from JSON Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/benchmarking.ipynb Loads raw benchmark results from a JSON file. This is an alternative to running benchmarks directly within the notebook. ```python # of if you used the cli # import json # with open("../benchmarks/benchmarks-results.json", "r") as f: # raw_results = json.load(f) ``` -------------------------------- ### cell_to_parent Source: https://github.com/filimoa/polars-h3/blob/master/README.md Gets a coarser H3 cell for a given cell ID. ```APIDOC ## cell_to_parent ### Description Get coarser cell for a cell. ### Method Not specified (likely a function call within the library) ### Parameters - **cell_id** (UInt64) - The H3 cell ID. - **resolution** (int) - The desired coarser resolution. ### Response - **parent_cell_id** (UInt64) - The parent H3 cell ID at the specified resolution. ``` -------------------------------- ### child_pos_to_cell Source: https://github.com/filimoa/polars-h3/blob/master/docs/index.md Get the child cell at a given position index for a specified parent/resolution. ```APIDOC ## child_pos_to_cell ### Description Get the child cell at a given position index for a specified parent/resolution. ### Method Not specified (likely a function call in a library) ### Endpoint Not applicable (library function) ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Benchmark Results Summary Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/benchmarking.ipynb Displays the median and average performance multipliers for each library (polars-h3, duckdb, h3_py) based on the benchmark results. ```text Median: {'plh3': 1.0, 'duckdb': 4.69, 'h3_py': 30.93} Average: {'plh3': 1.04, 'duckdb': 6.97, 'h3_py': 33.55} ``` -------------------------------- ### cell_to_child_pos Source: https://github.com/filimoa/polars-h3/blob/master/docs/index.md Get the position index of a child cell within its parent hierarchy. ```APIDOC ## cell_to_child_pos ### Description Get the position index of a child cell within its parent hierarchy. ### Method Not specified (likely a function call in a library) ### Endpoint Not applicable (library function) ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### grid_disk Source: https://github.com/filimoa/polars-h3/blob/master/docs/index.md Produce a “filled disk” of cells within distance `k` of an origin cell. ```APIDOC ## grid_disk ### Description Produce a “filled disk” of cells within distance `k` of an origin cell. ### Method Not specified (likely a function call in a library) ### Endpoint Not applicable (library function) ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### get_pentagons Source: https://github.com/filimoa/polars-h3/blob/master/README.md Retrieve all pentagons at a specified resolution. ```APIDOC ## get_pentagons ### Description Retrieve all pentagons at a specified resolution. ### Method Not specified (likely a function call in the Polars-H3 library) ### Endpoint Not applicable (library function) ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Get H3 Cell Boundary Coordinates Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/indexing.md Use `cell_to_boundary` to get the polygon boundary coordinates of an H3 cell. The input must be an H3 cell index, and the output is a Polars expression returning a list of latitude and longitude pairs. This function will raise a `ComputeError` for null or invalid H3 cell indices. ```python >>> df = pl.DataFrame({ ... "cell": ["8a1fb464492ffff"] ... }) >>> df.select(plh3.cell_to_boundary("cell")) shape: (1, 1) ┌────────────────────────────────────┐ │ cell_to_boundary │ │ --- │ │ list[f64] │ ╞════════════════════════════════════╡ │ [[50.99, -76.05], [48.29, -81.91...│ └────────────────────────────────────┘ ``` -------------------------------- ### cell_to_children Source: https://github.com/filimoa/polars-h3/blob/master/README.md Gets finer H3 cells for a given cell ID at a specified resolution. ```APIDOC ## cell_to_children ### Description Get finer cells for a cell. ### Method Not specified (likely a function call within the library) ### Parameters - **cell_id** (UInt64) - The H3 cell ID. - **resolution** (int) - The desired finer resolution. ### Response - **children_cell_ids** (list of UInt64) - A list of H3 cell IDs at the specified finer resolution. ``` -------------------------------- ### Calculate Performance Multipliers Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/benchmarking.ipynb Processes raw benchmark results to calculate performance multipliers. It determines the fastest execution time for each function and computes how many times slower other libraries are. ```python by_name = defaultdict(list) for d in raw_results: by_name[d["name"]].append(d) multiples = [] for speeds in by_name.values(): fastest = min(v["seconds"] for v in speeds) for v in speeds: multiples.append((v["library"], v["seconds"] / fastest)) by_lib = defaultdict(list) for lib, mult in multiples: by_lib[lib].append(mult) median_by_lib = {lib: round(statistics.median(ms), 2) for lib, ms in by_lib.items()} avg_by_lib = {lib: round(sum(ms) / len(ms), 2) for lib, ms in by_lib.items()} print("Median:") print(median_by_lib) print("Average:") print(avg_by_lib) ``` -------------------------------- ### Convert H3 Cell to Directed Edges and Back Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/quickstart.ipynb Demonstrates how to find the directed edges originating from an H3 cell and then extract the origin and destination cells from those edges. ```python df_edges = df.with_columns(edges=plh3.origin_to_directed_edges("h3_cell")) df_edges_explored = df_edges.explode("edges").with_columns( origin=plh3.get_directed_edge_origin("edges"), destination=plh3.get_directed_edge_destination("edges"), ) df_edges_explored ``` -------------------------------- ### Load and Sample Telematics Data Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/telematics.ipynb Loads telematics data from a Parquet file into a Polars DataFrame and samples 15% of the data with a fixed seed for reproducibility. Displays the first 5 rows of the sampled data. ```python # Real world telematics data tends to be messy, so we're going to take a small fraction of the available data to work with. df = pl.read_parquet( "./sample-data/sample-telematics-data.parquet", ).sample(fraction=0.15, seed=42) df.head() ``` -------------------------------- ### cell_area Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/metrics.md Get the area of a specific H3 cell. This function calculates the area for a given H3 cell index and unit. ```APIDOC ## `cell_area` ### Description Get the area of a specific H3 cell. ### Method plh3.cell_area ### Parameters #### Path Parameters - **cell** (IntoExprColumn) - Required - H3 cell index (as `pl.UInt64`, `pl.Int64`, or `pl.Utf8`). #### Query Parameters - **unit** (Literal["km^2", "m^2"]) - Optional - Unit of the returned area. Defaults to square kilometers. ### Returns - **Expr** - A Polars expression returning the area of the H3 cell. _Note:_ This function calls into a plugin that is elementwise. For invalid inputs, a `ComputeError` may be raised. ``` -------------------------------- ### get_num_cells Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/metrics.md Get the total number of H3 cells at a given resolution. This function returns the count of unique cells for the specified resolution. ```APIDOC ## `get_num_cells` ### Description Get the total number of H3 cells at a given resolution. ### Method plh3.get_num_cells ### Parameters #### Path Parameters - **resolution** (IntoExprColumn) - Required - H3 resolution level (`0` to `15`). ### Returns - **Expr** - A Polars expression returning the number of unique cells at the given resolution. ### Request Example ```python df = pl.DataFrame({"resolution": [5]}) df.with_columns( count=plh3.get_num_cells("resolution") ) ``` ``` -------------------------------- ### Convert Between Integer and String H3 Representations Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/quickstart.ipynb Convert H3 cells between their 64-bit integer and hexadecimal string representations using `int_to_str` and `str_to_int`. The converted values are added as 'h3_str' and 'h3_int' columns. ```python df_int_str = df.with_columns( h3_str=plh3.int_to_str("h3_cell"), h3_int=plh3.str_to_int(plh3.int_to_str("h3_cell")), ) df_int_str ``` -------------------------------- ### average_hexagon_edge_length Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/metrics.md Get the average edge length of H3 hexagons at a specific resolution. This function calculates the average edge length based on the resolution and unit. ```APIDOC ## `average_hexagon_edge_length` ### Description Get the average edge length of H3 hexagons at a specific resolution. ### Method plh3.average_hexagon_edge_length ### Parameters #### Path Parameters - **resolution** (IntoExprColumn) - Required - H3 resolution level (`0` to `15`). #### Query Parameters - **unit** (Literal["km", "m"]) - Optional - Unit of the returned length. Defaults to kilometers. ### Returns - **Expr** - A Polars expression returning the average edge length for hexagons at the specified resolution. ### Request Example ```python df = pl.DataFrame({"resolution": [1]}) df.with_columns( length=plh3.average_hexagon_edge_length("resolution", "km") ) ``` ``` -------------------------------- ### Extract Destination Cell from Directed Edge Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/edge.md Use this function to get the destination H3 cell index from a directed edge index. It returns a Polars expression. ```python >>> df = pl.DataFrame({"edge": [1608492358964346879]}) >>> df.with_columns(destination=plh3.get_directed_edge_destination("edge")) shape: (1, 2) ┌─────────────────────┬─────────────────────┐ │ edge │ destination │ │ --- │ --- │ │ u64 │ u64 │ ╞═════════════════════╪═════════════════════╡ │ 1608492358964346879 │ 599686030622195711 │ └─────────────────────┴─────────────────────┘ ``` -------------------------------- ### Map Telematics Data to H3 Hexes and Visualize Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/telematics.ipynb Converts latitude and longitude from the telematics data into H3 cells of resolution 9. It then uses the H3 cell IDs to generate an outline map visualization of the data points. ```python # IMPORTANT: Notice all the gaps in the data - # There's no particular reason to use hexes to visualize the points, but it's a good exercise. plotting_df = df.with_columns( [plh3.latlng_to_cell(pl.col("lat"), pl.col("long"), 9).alias("hex9")] ) plh3.graphing.plot_hex_outlines(plotting_df, hex_id_col="hex9") ``` -------------------------------- ### Create a directed H3 edge from two neighboring cells Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/edge.md Use `cells_to_directed_edge` to create a directed H3 edge index from an origin and destination cell. Both cells must be neighbors for a valid edge to be created. ```python >>> df = pl.DataFrame({ ... "origin": [599686042433355775], ... "destination": [599686030622195711], ... }) >>> df.with_columns(edge=plh3.cells_to_directed_edge("origin", "destination")) shape: (1, 3) ┌─────────────────────┬─────────────────────┬─────────────────────┐ │ origin │ destination │ edge │ │ --- │ --- │ --- │ │ u64 │ u64 │ u64 │ ╞═════════════════════╪═════════════════════╪═════════════════════╡ │ 599686042433355775 │ 599686030622195711 │ 1608492358964346879 │ └─────────────────────┴─────────────────────┴─────────────────────┘ ``` -------------------------------- ### Get Average Hexagon Area Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/metrics.md Returns the average area of an H3 hexagon at a specified resolution. Useful for understanding spatial density at different H3 levels. ```python df = pl.DataFrame({"resolution": [5]}) df.with_columns( area=plh3.average_hexagon_area("resolution", "km^2") ) ``` -------------------------------- ### grid_disk Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/traversal.md Generates a filled-in disk of H3 cells within a specified grid distance 'k' from an origin cell. The function returns a Polars expression containing a list of H3 cells, including the origin cell itself. Similar to grid_ring, pentagonal distortion may lead to null items in the output list. ```APIDOC ## grid_disk ### Description Produce a “filled-in disk” of cells within grid distance `k` of the origin cell. ### Method Python Function ### Signature ```python plh3.grid_disk( cell: IntoExprColumn, k: int | IntoExprColumn ) -> pl.Expr ``` ### Parameters #### Arguments - **cell** (IntoExprColumn) - Required - H3 cell index (as `pl.UInt64`, `pl.Int64`, or `pl.Utf8`). - **k** (int | IntoExprColumn) - Required - The maximum distance from the origin. Must be non-negative. ### Returns - **Expr** - A Polars expression returning a list of H3 cells from distance 0 up to `k`. May contain `null` items if pentagonal distortion is encountered. ### Errors - `ValueError`: If `k < 0`. - `ComputeError`: If pentagonal distortion or invalid inputs prevent computation. ### Examples ```python df = pl.DataFrame({"input": [622054503267303423]}) df.select(plh3.grid_disk("input", 1)) ``` ```python df = pl.DataFrame({"input": [622054503267303423], "k": [1]}) df.select(plh3.grid_disk("input", "k")) ``` ``` -------------------------------- ### cell_to_children_size Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/inspection.md Gets the number of children cells at a specified resolution. It takes an H3 cell expression and a target resolution, returning a Polars expression with the count of children cells. ```APIDOC ## cell_to_children_size ### Description Get the number of children cells at a specified resolution. ### Parameters * **cell** (IntoExprColumn) - H3 cells (`pl.UInt64`, `pl.Int64`, or `pl.Utf8`). * **resolution** (HexResolution) - Target resolution (int in `[0, 15]`). ### Returns * **Expr** - A Polars expression returning the number of children cells. ### Example ```python df = pl.DataFrame({"h3_cell": [582692784209657855]}) df.with_columns( num_children=plh3.cell_to_children_size("h3_cell", 2) ) ``` ``` -------------------------------- ### Convert Lat/Lng to H3 Cell (Integer Output) Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/indexing.md Converts latitude and longitude columns to H3 cell indices with an unsigned 64-bit integer return type. Ensure input columns are Float64 and resolution is between 0 and 15. ```python >>> df = pl.DataFrame({ ... "lat": [37.7752702151959], ... "lng": [-122.418307270836] ... }) >>> df.with_columns( ... h3_cell=plh3.latlng_to_cell("lat", "lng", resolution=1, return_dtype=pl.UInt64) ... ) shape: (1, 3) ┌─────────┬──────────┬─────────────────────┐ │ lat │ lng │ h3_cell │ │ --- │ --- │ --- │ │ f64 │ f64 │ u64 │ ╞═════════╪══════════╪═════════════════════╡ │ 0.0 │ 0.0 │ 583031433791012863 │ └─────────┴──────────┴─────────────────────┘ ``` -------------------------------- ### Convert String H3 to Integer Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/inspection.md Convert string H3 indices to their unsigned 64-bit integer representation. Handles invalid strings by returning null. ```python >>> df = pl.DataFrame({ ... "h3_str": ["85283473fffffff", "invalid_index"] ... }) >>> df.with_columns( ... h3_int=plh3.str_to_int("h3_str") ... ) shape: (2, 2) ┌──────────────────┬─────────────────────┐ │ h3_str │ h3_int │ │ --- │ --- │ │ str │ u64 │ ╞══════════════════╪═════════════════════╡ │ 85283473fffffff │ 599686042433355775 │ │ invalid_index │ null │ └──────────────────┴─────────────────────┘ ``` -------------------------------- ### Get Children Cells with Polars-H3 Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/inspection.md Retrieve all children cells of an H3 cell at a specified resolution. Use this when you need to break down a larger H3 cell into its constituent smaller cells. ```python >>> df = pl.DataFrame({"h3_cell": [582692784209657855]}) >>> df.with_columns( ... children=plh3.cell_to_children("h3_cell", 2) ... ) shape: (1, 2) ┌─────────────────────┬───────────────────────────────────┐ │ h3_cell │ children │ │ --- │ --- │ │ u64 │ list[u64] │ ╞═════════════════════╪═══════════════════════════════════╡ │ 582692784209657855 │ [587192535546331135, ...] │ └─────────────────────┴───────────────────────────────────┘ ``` -------------------------------- ### compact_cells Source: https://github.com/filimoa/polars-h3/blob/master/docs/index.md Compact a set of H3 cells into a minimal covering set. ```APIDOC ## compact_cells ### Description Compact a set of H3 cells into a minimal covering set. ### Method Not specified (likely a function call in a library) ### Endpoint Not applicable (library function) ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Retrieve Geographic Boundary of a Directed Edge Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/edge.md Get the geographic boundary, represented as a list of [latitude, longitude] pairs, for a given directed H3 edge. This returns a Polars expression. ```python >>> df = pl.DataFrame({"edge": [1608492358964346879]}) >>> df.with_columns(boundary=plh3.directed_edge_to_boundary("edge")) shape: (1, 2) ┌─────────────────────┬───────────────────────────────┐ │ edge │ boundary │ │ --- │ --- │ │ u64 │ list[list[f64]] │ ╞═════════════════════╪═══════════════════════════════╡ │ 1608492358964346879 │ [[37.3457, -121.9763], … ] │ └─────────────────────┴───────────────────────────────┘ ``` -------------------------------- ### Generate H3 Cell Disk within Distance k Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/traversal.md Produce a filled disk of H3 cells within grid distance k from an origin cell. This function includes the origin cell and all cells up to the specified distance. The distance k can be an integer or a Polars expression. ```python >>> df = pl.DataFrame({"input": [622054503267303423]}) >>> df.select(plh3.grid_disk("input", 1)) shape: (1, 1) ┌───────────────────────────────────┐ │ grid_disk │ │ --- │ │ list[u64] │ ╞═══════════════════════════════════╡ │ [622054503267303423, 622054502770…]│ └───────────────────────────────────┘ ``` ```python >>> df = pl.DataFrame({"input": [622054503267303423], "k": [1]}) >>> df.select(plh3.grid_disk("input", "k")) shape: (1, 1) ┌───────────────────────────────────┐ │ grid_disk │ │ --- │ │ list[u64] │ ╞═══════════════════════════════════╡ │ [622054503267303423, 622054502770…]│ └───────────────────────────────────┘ ``` -------------------------------- ### Get Average Hexagon Edge Length Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/metrics.md Calculates the average edge length of H3 hexagons for a given resolution. This is useful for estimating the scale of hexagons at different H3 levels. ```python df = pl.DataFrame({"resolution": [1]}) df.with_columns( length=plh3.average_hexagon_edge_length("resolution", "km") ) ``` -------------------------------- ### Visualize Time Spent in H3 Hexagons Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/telematics.ipynb Plots hexagonal fills on a map, coloring each hexagon based on the 'elapsed_seconds' metric. This is useful for visualizing spatial distributions of time spent. ```python # Notice how there's no gaps and we can see the time spent in each hexagon. hex_map = plh3.graphing.plot_hex_fills( trips_with_time_spent_in_hex, hex_id_col=hex_col, metric_col="elapsed_seconds" ) display(hex_map) ``` -------------------------------- ### Extract Longitude from H3 Cell Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/indexing.md Use `cell_to_lng` to get the longitude from an H3 cell index. It accepts string or integer representations of H3 cells and returns a Float64 Polars expression. ```python >>> df = pl.DataFrame({ ... "h3_cell": ["85283473fffffff"] ... }) >>> df.with_columns( ... lat=plh3.cell_to_lat("h3_cell"), ... lng=plh3.cell_to_lng("h3_cell") ... ) shape: (1, 3) ┌──────────────────┬─────────────────┬───────────────────┐ │ h3_cell │ lat │ lng │ │ --- │ --- │ --- │ │ str │ f64 │ f64 │ ╞══════════════════╪═════════════════╪═══════════════════╡ │ 85283473fffffff │ 37.345793375368 │ -121.976375972551 │ └──────────────────┴─────────────────┴───────────────────┘ >>> # Works with integer representation too >>> df = pl.DataFrame({"h3_cell": [599686042433355775]}, schema={"h3_cell": pl.UInt64}) >>> df.with_columns( ... lat=plh3.cell_to_lat("h3_cell"), ... lng=plh3.cell_to_lng("h3_cell") ... ) shape: (1, 3) ┌─────────────────────┬─────────────────┬───────────────────┐ │ h3_cell │ lat │ lng │ │ --- │ --- │ --- │ │ u64 │ f64 │ f64 │ ╞═════════════════════╪═════════════════╪═══════════════════╡ │ 599686042433355775 │ 37.345793375368 │ -121.976375972551 │ └─────────────────────┴─────────────────┴───────────────────┘ ``` -------------------------------- ### Convert Integer H3 to String Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/inspection.md Convert integer H3 indices to their string representation. Handles invalid inputs by returning null. ```python >>> df = pl.DataFrame({ ... "h3_int": [599686042433355775, -1] ... }) >>> df.with_columns( ... h3_str=plh3.int_to_str("h3_int") ... ) shape: (2, 2) ┌─────────────────────┬──────────────────┐ │ h3_int │ h3_str │ │ --- │ --- │ │ u64 │ str │ ╞═════════════════════╪══════════════════╡ │ 599686042433355775 │ 85283473fffffff │ │ -1 │ null │ └─────────────────────┴──────────────────┘ ``` -------------------------------- ### Convert Lat/Lng to H3 Cell (String Output) Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/indexing.md Converts latitude and longitude columns to H3 cell indices with a string return type. Ensure input columns are Float64 and resolution is between 0 and 15. ```python >>> df = pl.DataFrame({ ... "lat": [37.7752702151959], ... "lng": [-122.418307270836] ... }) >>> df.with_columns( ... h3_cell=plh3.latlng_to_cell("lat", "lng", resolution=9, return_dtype=pl.Utf8) ... ) shape: (1, 3) ┌──────────────────┬────────────────────┬──────────────────┐ │ lat │ lng │ h3_cell │ │ --- │ --- │ --- │ │ f64 │ f64 │ str │ ╞══════════════════╪════════════════════╪══════════════════╡ │ 37.7752702151959 │ -122.418307270836 │ 8928308280fffff │ └──────────────────┴────────────────────┴──────────────────┘ ``` -------------------------------- ### List Directed Edges Originating from a Cell Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/edge.md Obtain a list of all directed H3 edges that start from a specified H3 cell. The result is a Polars expression returning a list of edge indices. ```python >>> df = pl.DataFrame({"h3_cell": [599686042433355775]}) >>> df.with_columns(edges=plh3.origin_to_directed_edges("h3_cell")) shape: (1, 2) ┌─────────────────────┬─────────────────────────────────┐ │ h3_cell │ edges │ │ --- │ --- │ │ u64 │ list[u64] │ ╞═════════════════════╪═════════════════════════════════╡ │ 599686042433355775 │ [1608492358964346879,…] │ └─────────────────────┴─────────────────────────────────┘ ``` -------------------------------- ### Get parent H3 cell at a specific resolution Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/inspection.md Use `cell_to_parent` to find the parent H3 cell for a given cell at a specified resolution. This function requires both the cell expression and the target resolution. ```python >>> df = pl.DataFrame({"h3_cell": [599686042433355775]}) >>> df.with_columns( ... parent=plh3.cell_to_parent("h3_cell", 1) ... ) shape: (1, 2) ┌─────────────────────┬─────────────────────┐ │ h3_cell │ parent │ │ --- │ --- │ │ u64 │ u64 │ ╞═════════════════════╪═════════════════════╡ │ 599686042433355775 │ 593686042413355775 │ └─────────────────────┴─────────────────────┘ ``` -------------------------------- ### plot_hex_outlines Source: https://github.com/filimoa/polars-h3/blob/master/docs/graphing.md Plots the outlines of H3 hexagons onto a Folium map. It can either add to an existing map or create a new one, with customizable outline colors and map sizes. ```APIDOC ## plot_hex_outlines ### Description Plots hexagon outlines on a Folium map. ### Method `plot_hex_outlines( df: pl.DataFrame, hex_id_col: str, map: Any | None = None, outline_color: str = "red", map_size: Literal["medium", "large"] = "medium", ) -> Any` ### Parameters #### Path Parameters - **df** (pl.DataFrame) - Required - A DataFrame that must contain a column of H3 cell IDs. - **hex_id_col** (str) - Required - Column name in `df` containing H3 cell IDs (hexagon identifiers). - **map** (Any | None) - Optional - An existing Folium map object on which to plot. If `None`, a new map is created. - **outline_color** (str) - Optional - Color used to outline the hexagons. Defaults to `"red"`. - **map_size** (`{"medium", "large"}`) - Optional - The size of the displayed map. `"medium"` sets width and height to 50%; `"large"` sets them to 100%. ### Returns - **Any** - A Folium map object with hexagon outlines added. ### Errors - `ValueError` : If the input DataFrame is empty. - `ImportError` : If `folium` is not installed. ``` -------------------------------- ### Check Validity and Resolution of H3 Cells Source: https://github.com/filimoa/polars-h3/blob/master/notebooks/quickstart.ipynb Use `is_valid_cell` to check if an H3 cell is valid and `get_resolution` to determine its resolution. Results are added as 'is_valid' and 'resolution' columns. ```python df_inspect = df.with_columns( is_valid=plh3.is_valid_cell("h3_cell"), resolution=plh3.get_resolution("h3_cell"), ) df_inspect ``` -------------------------------- ### local_ij_to_cell Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/indexing.md Converts local IJ coordinates back into an H3 cell index using a provided origin. This function takes the origin cell and the i, j coordinates as input. ```APIDOC ## `local_ij_to_cell` ### Description Convert local IJ coordinates back into an H3 cell index using a given origin. ### Method ```python plh3.local_ij_to_cell( origin: IntoExprColumn, i: IntoExprColumn, j: IntoExprColumn ) -> pl.Expr ``` ### Parameters #### Path Parameters - **origin** (IntoExprColumn) - Required - The H3 cell index defining the local IJ space. - **i** (IntoExprColumn) - Required - The local i-coordinate (row). - **j** (IntoExprColumn) - Required - The local j-coordinate (column). ### Returns - **Expr** - A Polars expression returning the corresponding H3 cell index. ### Errors - `ComputeError`: If null or invalid inputs are encountered, or the transformation cannot be performed. ``` -------------------------------- ### Get Origin-Destination Cells from Directed Edge Source: https://github.com/filimoa/polars-h3/blob/master/docs/api-reference/edge.md Retrieve the origin and destination cell indices from a directed H3 edge. This function returns a Polars expression that yields a list of two cell indices. ```python >>> df = pl.DataFrame({"edge": [1608492358964346879]}) >>> df.with_columns(cells=plh3.directed_edge_to_cells("edge")) shape: (1, 2) ┌─────────────────────┬─────────────────────┐ │ edge │ cells │ │ --- │ --- │ │ u64 │ list[u64] │ ╞═════════════════════╪═════════════════════╡ │ 1608492358964346879 │ [599686042433355775,… │ └─────────────────────┴─────────────────────┘ ```