### Install h3ronpy from source Source: https://h3ronpy.readthedocs.io/en/latest/_sources/installation Builds and installs the h3ronpy library from its source code repository. This method requires cloning the repository, having Rust installed, and using pip to install the package. It utilizes maturin for building the Rust components. ```shell git clone https://github.com/nmandery/h3ronpy.git cd h3ronpy pip install . ``` -------------------------------- ### Install h3ronpy using pip Source: https://h3ronpy.readthedocs.io/en/latest/_sources/installation Installs the h3ronpy Python package directly from the Python Package Index (PyPI). This is the most common and straightforward installation method. ```shell pip install h3ronpy ``` -------------------------------- ### Install h3ronpy from source Source: https://h3ronpy.readthedocs.io/en/latest/installation Installs h3ronpy by cloning the repository and building from source. This process requires Git, a recent Rust toolchain (installed via rustup), and pip. The Rust code is built using maturin. ```Shell git clone https://github.com/nmandery/h3ronpy.git cd h3ronpy pip install . ``` -------------------------------- ### Upgrade pip Source: https://h3ronpy.readthedocs.io/en/latest/_sources/installation Upgrades the pip package installer to the latest version. This is a prerequisite for building h3ronpy from source, ensuring compatibility with the build process. ```shell pip install --upgrade pip ``` -------------------------------- ### Install h3ronpy using pip Source: https://h3ronpy.readthedocs.io/en/latest/installation Installs the h3ronpy library using pip, the Python package installer. Ensure you have Python and pip installed. ```Shell pip install h3ronpy ``` -------------------------------- ### Aggregate Grid Disks with H3ronpy (Min) Source: https://h3ronpy.readthedocs.io/en/latest/usage/grid This example demonstrates how to aggregate hexagonal cells within a disk using `h3ronpy.grid_disk_aggregate_k()` to find the minimum value ('min') for cells within a k-radius. The results are plotted with a legend. ```Python from h3ronpy import grid_disk_aggregate_k cells_dataframe_to_geodataframe( pa.table(grid_disk_aggregate_k(cells, 9, "min")).to_pandas() ).plot(column="k", legend=True, legend_kwds={"label": "k", "orientation": "horizontal"},) ``` -------------------------------- ### Upgrade pip Source: https://h3ronpy.readthedocs.io/en/latest/installation Upgrades the pip package installer to the latest version. A recent version of pip (e.g., 23.1.2) is recommended for building from source. ```Shell pip install --upgrade pip ``` -------------------------------- ### Grid Disk Traversal with h3ronpy.grid_disk() Source: https://h3ronpy.readthedocs.io/en/latest/usage/index Demonstrates the usage of the `h3ronpy.grid_disk()` function for performing grid traversal. This function finds all H3 cells within a specified distance (k) from a starting H3 cell. ```Python import h3ronpy # Define a starting H3 cell and a radius (k) center_h3 = '8928308280fffff' # Example H3 cell radius_k = 2 # Get all H3 cells within the specified radius h3_disk = h3ronpy.grid_disk(center_h3, radius_k) print(f"Found {len(h3_disk)} H3 cells within k={radius_k} of {center_h3}.") # print(h3_disk) # Uncomment to see the list of H3 cells ``` -------------------------------- ### Aggregate Grid Disks with H3ronpy (Max) Source: https://h3ronpy.readthedocs.io/en/latest/usage/grid This example demonstrates how to aggregate hexagonal cells within a disk using `h3ronpy.grid_disk_aggregate_k()` to find the maximum value ('max') for cells within a k-radius. The results are plotted with a legend. ```Python from h3ronpy import grid_disk_aggregate_k cells_dataframe_to_geodataframe( pa.table(grid_disk_aggregate_k(cells, 9, "max")).to_pandas() ).plot(column="k", legend=True, legend_kwds={"label": "k", "orientation": "horizontal"},) ``` -------------------------------- ### Grid Disk Aggregation with h3ronpy.grid_disk_aggregate_k() Source: https://h3ronpy.readthedocs.io/en/latest/usage/index Explains and shows how to use `h3ronpy.grid_disk_aggregate_k()` for aggregating H3 cells within a specified distance (k). This function is useful for summarizing data over a region. ```Python import h3ronpy # Define a starting H3 cell and a radius (k) center_h3 = '8928308280fffff' # Example H3 cell radius_k = 3 # Aggregate H3 cells within the specified radius aggregated_h3 = h3ronpy.grid_disk_aggregate_k(center_h3, radius_k) print(f"Aggregated H3 cells within k={radius_k} of {center_h3}: {aggregated_h3}") ``` -------------------------------- ### Grid Disk Aggregates (Min) with h3ronpy.grid_disk_aggregate_k Source: https://h3ronpy.readthedocs.io/en/latest/_sources/usage/grid This example shows how to perform minimum aggregations on grid disks using `h3ronpy.grid_disk_aggregate_k`. It processes the aggregated data into a GeoDataFrame and plots it, including a legend for the 'k' values. ```python from h3ronpy import grid_disk_aggregate_k cells_dataframe_to_geodataframe( pa.table(grid_disk_aggregate_k(cells, 9, "min")).to_pandas() ).plot(column="k", legend=True, legend_kwds={"label": "k", "orientation": "horizontal"},) ``` -------------------------------- ### Convert Raster Data to H3 using H3ronpy Source: https://h3ronpy.readthedocs.io/en/latest/usage/index Demonstrates how to prepare a dataset using rasterio and then convert a raster numpy array to H3 cells using the H3ronpy library. This involves reading raster data and applying H3 indexing. ```Python import rasterio import h3ronpy import numpy as np # Load raster data (example) with rasterio.open('your_raster.tif') as src: image = src.read(1) # Read the first band transform = src.transform crs = src.crs # Convert numpy array to H3 cells # Assuming a resolution and appropriate coordinate transformation h3_cells = h3ronpy.raster.raster_to_h3(image, transform, resolution=5) print(f"Converted {len(h3_cells)} H3 cells from raster data.") ``` -------------------------------- ### Convert Single Geometries to H3 Cells using H3ronpy Source: https://h3ronpy.readthedocs.io/en/latest/usage/index Shows how to convert individual geometries (like points or polygons) into H3 cells. This is a fundamental operation for spatial indexing. ```Python import h3ronpy from shapely.geometry import Point, Polygon # Example: Convert a Point to an H3 cell point = Point(-74.0, 40.7) h3_cell_from_point = h3ronpy.point_to_h3(point.y, point.x, resolution=5) print(f"H3 cell for point: {h3_cell_from_point}") # Example: Convert a Polygon to H3 cells polygon = Polygon([(-74.0, 40.7), (-73.9, 40.7), (-73.9, 40.8), (-74.0, 40.8), (-74.0, 40.7)]) h3_cells_from_polygon = h3ronpy.polygon_to_h3(polygon, resolution=5) print(f"H3 cells for polygon: {len(h3_cells_from_polygon)}") ``` -------------------------------- ### H3ronpy Polygon Fill Modes Source: https://h3ronpy.readthedocs.io/en/latest/usage/index Explains and demonstrates different polygon fill modes available in H3ronpy for converting vector data. These modes control how polygons are represented on the H3 grid. ```Python import geopandas as gpd import h3ronpy # Load a GeoDataFrame with polygons geodataframe = gpd.read_file('your_polygons.shp') # Convert polygons to H3 cells using different fill modes # Example: 'center_only' mode h3_cells_center = h3ronpy.vector.polygon_to_h3(geodataframe, resolution=5, fill_mode='center_only') # Example: 'centroid' mode h3_cells_centroid = h3ronpy.vector.polygon_to_h3(geodataframe, resolution=5, fill_mode='centroid') # Example: 'all_inside' mode (default) h3_cells_all = h3ronpy.vector.polygon_to_h3(geodataframe, resolution=5, fill_mode='all_inside') print(f"Cells (center_only): {len(h3_cells_center)}") print(f"Cells (centroid): {len(h3_cells_centroid)}") print(f"Cells (all_inside): {len(h3_cells_all)}") ``` -------------------------------- ### Merge H3 Cells into Polygons using H3ronpy Source: https://h3ronpy.readthedocs.io/en/latest/usage/index Demonstrates how to merge smaller H3 cells into larger polygonal representations. This is useful for aggregation and simplifying spatial data. ```Python import h3ronpy import geopandas as gpd # Assume you have a list of H3 cells h3_cells = ['8928308280fffff', '8928308281fffff', '8928308282fffff'] # Example H3 cells # Merge H3 cells into polygons merged_polygons = h3ronpy.h3_set_to_multi_polygon(h3_cells, geo_json=True) # Convert the GeoJSON-like output to a GeoDataFrame merged_gdf = gpd.GeoDataFrame.from_features(merged_polygons) print(f"Merged {len(merged_gdf)} polygons from H3 cells.") ``` -------------------------------- ### Generate and Plot Grid Disks with H3ronpy Source: https://h3ronpy.readthedocs.io/en/latest/usage/grid This code generates hexagonal cells within a specified radius (disk) around existing cells using `h3ronpy.grid_disk()` and then visualizes these cells as a GeoDataFrame plot. It utilizes pandas and pyarrow for data manipulation. ```Python from h3ronpy import grid_disk cells_dataframe_to_geodataframe( pd.DataFrame({ DEFAULT_CELL_COLUMN_NAME: pa.array(grid_disk(cells, 9, flatten=True)).to_pandas()} ) ).plot() ``` -------------------------------- ### Convert H3 Cells to Raster using H3ronpy Source: https://h3ronpy.readthedocs.io/en/latest/usage/index Shows how to convert H3 cells back into a raster format. This is useful for visualizing H3 data or integrating it with other raster-based workflows. ```Python import h3ronpy import numpy as np import rasterio # Assume you have a list of H3 cells and a desired resolution h3_cells = ['8928308280fffff', '8928308281fffff'] # Example H3 cells resolution = 5 # Define output raster properties (e.g., bounds, resolution, CRS) # These would typically be derived from the original raster or desired output width, height = 100, 100 resolution_x, resolution_y = 0.1, 0.1 west, south, east, north = -10.0, -10.0, 10.0, 10.0 crs = 'EPSG:4326' transform = rasterio.transform.from_bounds(west, south, east, north, width, height) # Convert H3 cells to raster h3_raster = h3ronpy.h3_to_raster(h3_cells, resolution, transform, width, height) # Save the raster (example) with rasterio.open( 'output_raster.tif', 'w', driver='GTiff', height=height, width=width, count=1, dtype=h3_raster.dtype, crs=crs, transform=transform, ) as dst: dst.write(h3_raster, 1) print("H3 cells converted to raster and saved.") ``` -------------------------------- ### Create H3 Cells with NumPy and H3 Source: https://h3ronpy.readthedocs.io/en/latest/usage/grid This snippet demonstrates how to create hexagonal H3 cells using NumPy and the H3 library. It defines a few test cells based on latitude and longitude coordinates and resolution. ```Python import numpy as np import h3.api.numpy_int as h3 import pandas as pd import pyarrow as pa from h3ronpy.pandas.vector import cells_dataframe_to_geodataframe from h3ronpy import DEFAULT_CELL_COLUMN_NAME cells = np.array( [ h3.geo_to_h3(5.2, -5.2, 7), h3.geo_to_h3(5.3, -5.1, 7), ], dtype=np.uint64, ) ``` -------------------------------- ### Convert GeoDataFrame to H3 Cells using H3ronpy Source: https://h3ronpy.readthedocs.io/en/latest/usage/index Illustrates how to convert an entire GeoDataFrame, containing various geometries, into H3 cells. This function handles the complexities of mapping geometric shapes to the H3 grid system. ```Python import geopandas as gpd import h3ronpy # Load a GeoDataFrame (example) geodataframe = gpd.read_file('your_vector_data.shp') # Convert GeoDataFrame to H3 cells h3_cells = h3ronpy.vector.geodataframe_to_h3(geodataframe, resolution=5) print(f"Converted {len(h3_cells)} H3 cells from GeoDataFrame.") ``` -------------------------------- ### h3ronpy.version: Get Module Version Source: https://h3ronpy.readthedocs.io/en/latest/api/core Retrieves the current version of the h3ronpy module. This is a simple utility function with no parameters. ```Python h3ronpy.version() ``` -------------------------------- ### Create Test Cells with H3ronpy Source: https://h3ronpy.readthedocs.io/en/latest/_sources/usage/grid This snippet demonstrates how to create test H3 cells using the h3ronpy library. It imports necessary libraries like numpy, h3, pandas, and pyarrow, and defines a few sample cells based on geographic coordinates and resolution. ```python import numpy as np import h3.api.numpy_int as h3 import pandas as pd import pyarrow as pa from h3ronpy.pandas.vector import cells_dataframe_to_geodataframe from h3ronpy import DEFAULT_CELL_COLUMN_NAME cells = np.array( [ h3.geo_to_h3(5.2, -5.2, 7), h3.geo_to_h3(5.3, -5.1, 7), ], dtype=np.uint64, ) ``` -------------------------------- ### Get H3 Cell Resolution Source: https://h3ronpy.readthedocs.io/en/latest/api/core Generates a new array containing the resolution of each H3 cell from the input array. This function is useful for understanding the granularity of the H3 cells. ```Python h3ronpy.cells_resolution(_arr_) → Array ``` -------------------------------- ### Prepare Dataset using Rasterio Source: https://h3ronpy.readthedocs.io/en/latest/usage/raster Opens a GeoTIFF file using rasterio, reads specific color bands (green and blue), prints their color interpretation and shape, and displays the raster data using rasterio's show function. This step prepares the raster data for further processing. ```Python import rasterio from rasterio.plot import show src = rasterio.open(project_root / "data/europe-and-north-africa.tif") print(src.colorinterp) green = src.read(2) blue = src.read(3) print(green.shape) show(src) ``` -------------------------------- ### Get H3 Cell Resolution in Polars Source: https://h3ronpy.readthedocs.io/en/latest/api/polars Retrieves the resolution level of H3 cells stored in a Polars Series using the `cells_resolution` method. This function is part of the h3ronpy Polars integration. ```python # s.h3.cells_resolution() ``` -------------------------------- ### Grid Disk Aggregates (Max) with h3ronpy.grid_disk_aggregate_k Source: https://h3ronpy.readthedocs.io/en/latest/_sources/usage/grid This snippet demonstrates maximum aggregation on grid disks using `h3ronpy.grid_disk_aggregate_k`. Similar to the minimum aggregation, it converts the results to a GeoDataFrame and visualizes them with a legend. ```python from h3ronpy import grid_disk_aggregate_k cells_dataframe_to_geodataframe( pa.table(grid_disk_aggregate_k(cells, 9, "max")).to_pandas() ).plot(column="k", legend=True, legend_kwds={"label": "k", "orientation": "horizontal"},) ``` -------------------------------- ### Generate Grid Disks with h3ronpy.grid_disk Source: https://h3ronpy.readthedocs.io/en/latest/_sources/usage/grid This code snippet illustrates how to generate grid disks using the `h3ronpy.grid_disk` function. It takes a set of H3 cells and a resolution, then converts the resulting cells into a GeoDataFrame for plotting. ```python from h3ronpy import grid_disk cells_dataframe_to_geodataframe( pd.DataFrame({ DEFAULT_CELL_COLUMN_NAME: pa.array(grid_disk(cells, 9, flatten=True)).to_pandas()} ) ).plot() ``` -------------------------------- ### Prepare Raster Dataset with Rasterio Source: https://h3ronpy.readthedocs.io/en/latest/_sources/usage/raster This snippet demonstrates how to open a GeoTIFF file using rasterio, read specific color bands (green and blue), and print basic information like color interpretation and array shape. It serves as a prerequisite for image processing and H3 conversion. ```Python import rasterio from rasterio.plot import show # Assuming project_root is defined elsewhere # project_root = Path(os.environ["PROJECT_ROOT"]) src = rasterio.open(project_root / "data/europe-and-north-africa.tif") print(src.colorinterp) green = src.read(2) blue = src.read(3) print(green.shape) show(src) ``` -------------------------------- ### Get H3 Grid Disk Neighbors in Polars Source: https://h3ronpy.readthedocs.io/en/latest/api/polars Finds all H3 cells within a specified grid distance 'k' from the cells in a Polars Series using the `grid_disk` method. The `flatten` option can be used to return a flat list of neighbors. ```python # s.h3.grid_disk(k=2, flatten=True) ``` -------------------------------- ### Extend documentation of cells_parse Source: https://h3ronpy.readthedocs.io/en/latest/changelog Provides extended documentation for the `cells_parse` function. ```Python # Extend documentation of `cells_parse`. ``` -------------------------------- ### H3 Grid Traversal with h3ronpy Source: https://h3ronpy.readthedocs.io/en/latest/index This documentation focuses on grid traversal functionalities within h3ronpy, specifically using `h3ronpy.grid_disk()` for finding cells within a certain distance and `h3ronpy.grid_disk_aggregate_k()` for aggregated disk operations. ```python import h3ronpy # Example: Grid-disks with h3ronpy.grid_disk() # h3_cell = '8928308280fffff' # Example H3 cell # k_distance = 3 # cells_in_disk = h3ronpy.grid_disk(h3_cell, k_distance) # print(f"Cells within distance {k_distance} of {h3_cell}: {len(cells_in_disk)}") # Example: Grid-disk aggregates with h3ronpy.grid_disk_aggregate_k() # This function typically aggregates values within a grid disk # Example usage would depend on the data associated with H3 cells # aggregated_value = h3ronpy.grid_disk_aggregate_k(h3_cell, k_distance, aggregation_function) print("H3 grid traversal functions like grid_disk are available.") ``` -------------------------------- ### Parse and Grid Disk H3 Cells - Polars Expressions Source: https://h3ronpy.readthedocs.io/en/latest/_sources/api/polars Demonstrates parsing H3 cell strings, applying a grid disk operation, and aggregating results using Polars lazy evaluation. Requires 'polars' and 'h3ronpy.polars'. ```python import polars as pl # to register extension functions in the polars API import h3ronpy.polars df = pl.DataFrame({ "cell": ["8852dc41cbfffff", "8852dc41bbfffff"], "value": ["a", "b"] }) (df.lazy() .select([ pl.col("cell") .h3.cells_parse() .h3.grid_disk(2) .alias("disk"), pl.col("value") ]) .group_by("value") .agg([ pl.col("disk") .explode() .h3.cells_area_km2() .sum() ]) .collect() ) ``` -------------------------------- ### H3 Series Shortcuts Class for Polars Source: https://h3ronpy.readthedocs.io/en/latest/api/polars The `H3SeriesShortcuts` class in h3ronpy integrates H3 functionality directly into Polars Series. It mirrors the module's functions, providing methods for area calculation, resolution changes, string conversion, and more, all accessible via the `.h3` attribute of a Polars Series. ```python import polars as pl # Example of accessing a method (actual usage would involve a Series) # s = pl.Series('h3_cells', ['8852dc41cbfffff']) # s.h3.cells_parse() ``` -------------------------------- ### Parse, Grid Disk, and Convert H3 Cells - Polars Series Source: https://h3ronpy.readthedocs.io/en/latest/_sources/api/polars Shows parsing H3 cell strings, applying a grid disk operation, and converting the results back to strings using Polars Series. Requires 'polars' and 'h3ronpy.polars'. ```python import polars as pl # to register extension functions in the polars API import h3ronpy.polars cell_strings = (pl.Series("cells", ["8852dc41cbfffff"]) .h3.cells_parse() .h3.grid_disk(1) .explode() .sort() .h3.cells_to_string()) cell_strings ``` -------------------------------- ### Initialize plotting and load GeoDataFrame Source: https://h3ronpy.readthedocs.io/en/latest/usage/vector Sets up matplotlib for plotting and loads a GeoDataFrame containing world country data. It filters this data to select only the continent of Africa and prepares it for plotting. ```Python from matplotlib import pyplot from pathlib import Path import os # increase the plot size pyplot.rcParams['figure.dpi'] = 120 project_root = Path(os.environ["PROJECT_ROOT"]) ``` ```Python import geopandas as gpd world = gpd.read_file(project_root / "data/naturalearth_110m_admin_0_countries.fgb") africa = world[world["CONTINENT"] == "Africa"] africa.plot(column="NAME_EN") ``` -------------------------------- ### Core h3ronpy API Functions Source: https://h3ronpy.readthedocs.io/en/latest/index This section lists and describes core functions available in the h3ronpy library. It includes functions for cell manipulation (parsing, resolution, conversion), containment modes, edge operations, and utility functions like version checking. ```python # Example usage of core h3ronpy functions: # Area calculations # area_km2 = h3ronpy.cells_area_km2(resolution=7) # area_m2 = h3ronpy.cells_area_m2(resolution=7) # area_rads2 = h3ronpy.cells_area_rads2(resolution=7) # Cell manipulation # parsed_cell = h3ronpy.cells_parse('8928308280fffff') # resolution = h3ronpy.cells_resolution(parsed_cell) # local_ij = h3ronpy.cells_to_localij(parsed_cell) # string_cell = h3ronpy.cells_to_string(parsed_cell) # is_valid = h3ronpy.cells_valid(parsed_cell) # Resolution changes # changed_res = h3ronpy.change_resolution(parsed_cell, new_resolution=8) # changed_res_list = h3ronpy.change_resolution_list([parsed_cell], new_resolution=8) # changed_res_paired = h3ronpy.change_resolution_paired(parsed_cell, new_resolution=8) # Compaction and uncompaction # compacted_cells = h3ronpy.compact([parsed_cell, '89283082807ffff']) # uncompacted_cells = h3ronpy.uncompact(compacted_cells) # Version # version = h3ronpy.version() print("Core h3ronpy API functions are documented.") ``` -------------------------------- ### Polars expressions and series shortcuts Source: https://h3ronpy.readthedocs.io/en/latest/changelog Introduces Polars expressions and series shortcuts for enhanced data manipulation. ```Python # Polars expressions and series shortcuts. #33 ``` -------------------------------- ### Directly support GeoSeries in vector to H3 conversion Source: https://h3ronpy.readthedocs.io/en/latest/changelog Enables direct support for GeoSeries in vector to H3 conversion by automatically exchanging geometries using WKB. ```Python # Directly support GeoSeries in vector to H3 conversion by automatically exchanging geometries using WKB. #7 ``` -------------------------------- ### Convert single Shapely geometry to H3 cells Source: https://h3ronpy.readthedocs.io/en/latest/usage/vector Demonstrates converting a single Shapely geometry (Namibia's geometry) into H3 cells at resolution 3 using the `geometry_to_cells` function. ```Python from h3ronpy.vector import geometry_to_cells namibia_geom = namibia["geometry"].iloc[0] print(namibia_geom) geometry_to_cells(namibia_geom, 3) ``` -------------------------------- ### h3ronpy Polars Integration Source: https://h3ronpy.readthedocs.io/en/latest/index This section covers the integration of h3ronpy with the Polars DataFrame library. It highlights specific API extensions and functions that enable efficient H3 operations within Polars DataFrames. ```python # Conceptual example for h3ronpy with Polars # import polars as pl # import h3ronpy.polars as hpolars # Assuming 'df' is a Polars DataFrame with a geometry column or H3 indices # df = df.with_columns(hpolars.geodataframe_to_h3('geometry', resolution=8).alias('h3_index')) # h3_indices = df['h3_index'].unique() # h3_geometries = hpolars.h3_to_geodataframe(h3_indices) print("Polars integration and API extensions are available.") ``` -------------------------------- ### Convert Raster Data to H3 using h3ronpy Source: https://h3ronpy.readthedocs.io/en/latest/index This section details the process of converting raster data into H3 cells using the h3ronpy library. It involves preparing a dataset with rasterio and then converting a raster numpy array to H3, likely involving functions for spatial indexing and aggregation. ```python import h3ronpy import rasterio import numpy as np # Example: Prepare a dataset using rasterio first # Assuming 'raster_data.tif' is a GeoTIFF file with rasterio.open('raster_data.tif') as src: raster_array = src.read(1) # Read the first band transform = src.transform crs = src.crs # Example: Convert the raster numpy array to H3 # This is a conceptual example, actual implementation depends on h3ronpy's API # You would typically need to define the H3 resolution and map raster pixels to H3 cells # For instance, using h3ronpy.raster.raster_to_h3 (hypothetical function) # h3_cells = h3ronpy.raster.raster_to_h3(raster_array, transform, resolution=7) # Placeholder for actual conversion logic print("Raster data loaded and ready for H3 conversion.") ``` -------------------------------- ### Add change_resolution_list function Source: https://h3ronpy.readthedocs.io/en/latest/changelog Introduces the `change_resolution_list` function for batch resolution changes. ```Python # Add `change_resolution_list` #35. ``` -------------------------------- ### H3 Polars Series API Source: https://h3ronpy.readthedocs.io/en/latest/api/index Provides H3 Series shortcuts for direct application of H3 functions to Polars Series. This simplifies common geospatial tasks when working with H3 indexes in Polars. ```python import polars as pl from h3_polars import * # Example usage: s = pl.Series("h3_series", ['852a1000fffffff', '852a1000fffffff']) # Applying a Series shortcut areas = s.h3().cells_area_m2() print(areas) ``` -------------------------------- ### Add support for h3o containment mode 'covers' Source: https://h3ronpy.readthedocs.io/en/latest/changelog Adds support for the 'covers' containment mode from the h3o library. ```Python # Add support for the h3o containment mode “covers” ``` -------------------------------- ### Convert H3 Cells to Raster using h3ronpy Source: https://h3ronpy.readthedocs.io/en/latest/index This documentation covers the functionality for converting H3 cells back into a raster format. This process typically involves defining the output raster's properties (resolution, bounds, CRS) and mapping the H3 cell data onto the raster grid. ```python # Conceptual example for converting H3 cells to raster # This would involve functions like h3ronpy.raster.h3_to_raster (hypothetical) # You would need a list of H3 cells and desired raster parameters # h3_cells_list = [...] # List of H3 cell IDs # output_raster_path = 'output_raster.tif' # h3ronpy.raster.h3_to_raster(h3_cells_list, output_raster_path, resolution=7, crs='EPSG:4326') print("Functionality to convert H3 cells to raster is available.") ``` -------------------------------- ### Make GeoSeries-returning function visible in vector module Source: https://h3ronpy.readthedocs.io/en/latest/changelog Ensures the GeoSeries-returning function is correctly displayed within the `h3ronpy.pandas.vector` module. ```Python # Make the GeoSeries-returning function show up in the `h3ronpy.pandas.vector` module. ``` -------------------------------- ### Parse and Find H3 Grid Disk Neighbors in Polars Source: https://h3ronpy.readthedocs.io/en/latest/api/polars This snippet demonstrates how to parse H3 cell strings, find neighbors within a specified grid distance (k), and sort the results using h3ronpy's Polars integration. It showcases the chaining of H3 operations on a Polars Series. ```python import h3ronpy.polars import polars as pl cell_strings = (pl.Series("cells", ["8852dc41cbfffff"]) .h3.cells_parse() .h3.grid_disk(1) .explode() .sort() .h3.cells_to_string()) cell_strings ``` -------------------------------- ### Remove directededges_to_wkb_lines and directededges_to_lines Source: https://h3ronpy.readthedocs.io/en/latest/changelog Removes `directededges_to_wkb_lines` and `directededges_to_lines` functions, recommending the use of linestring-versions instead due to migration to official arrow-rs. ```Python # directededges_to_wkb_lines and directededges_to_lines have been removed. Use the linestring-versions instead. ``` -------------------------------- ### Image Processing for Vegetation Mask Source: https://h3ronpy.readthedocs.io/en/latest/usage/raster Performs image processing on raster data to create a vegetation mask and an ocean mask based on pixel values in the green and blue bands. It then applies these masks to create a 'vegetation' array, smooths it using a Gaussian filter, and categorizes the values into different classes representing vegetation types and no-data areas. Finally, it displays the processed vegetation data. ```Python vegetation_mask = (green < 250) & (blue < 50) ocean_mask = (green >= 6) & (green <= 14) & (blue >= 47) & (blue <= 54) vegetation_nodata_value = 0 vegetation = np.full(green.shape, 10, dtype="int8") vegetation[ocean_mask] = vegetation_nodata_value vegetation[vegetation_mask] = 20 # smooth a bit to remove single pixels vegetation = ndimage.gaussian_filter(vegetation, sigma=.7) vegetation[vegetation <= 5] = vegetation_nodata_value vegetation[(vegetation > 0) & (vegetation < 15)] = 1 vegetation[vegetation >= 15] = 2 vegetation[ocean_mask] = vegetation_nodata_value vegetation_plot_args = dict(cmap='Greens', vmin=0, vmax=2) pyplot.imshow(vegetation, **vegetation_plot_args) ``` -------------------------------- ### Polygon fill modes for H3 conversion Source: https://h3ronpy.readthedocs.io/en/latest/usage/vector Demonstrates different polygon fill modes for converting a 'Namibia' GeoDataFrame to H3 cells. The `containment_mode` argument controls how polygons are filled, affecting the resulting H3 cells. ```Python namibia = africa[africa["NAME_EN"] == "Namibia"] def fill_namibia(**kw): cell_ax = cells_dataframe_to_geodataframe(geodataframe_to_cells(namibia, 3, **kw)).plot() return namibia.plot(ax=cell_ax, facecolor=(0,0,0,0), edgecolor='black') fill_namibia() ``` ```Python fill_namibia(containment_mode=ContainmentMode.ContainsCentroid) ``` ```Python fill_namibia(containment_mode=ContainmentMode.ContainsBoundary) ``` ```Python fill_namibia(containment_mode=ContainmentMode.IntersectsBoundary) ``` ```Python fill_namibia(containment_mode=ContainmentMode.Covers) ``` -------------------------------- ### Compact H3 Cells in Polars Source: https://h3ronpy.readthedocs.io/en/latest/api/polars Compacts a set of H3 cells in a Polars Series into the smallest possible set of larger H3 cells using the `compact` method. The `mixed_resolutions` parameter allows for handling series with varying resolutions. ```python # s.h3.compact(mixed_resolutions=True) ``` -------------------------------- ### H3 Core Functions Source: https://h3ronpy.readthedocs.io/en/latest/api/index Provides access to core H3 geospatial indexing functions. These functions handle cell area calculations, parsing, resolution management, and data conversion between different H3 representations. ```python from h3 import * # Example usage: print(cells_area_km2(5)) print(cells_parse('852a1000fffffff')) print(version()) ``` -------------------------------- ### Convert GeoDataFrame to H3 cells Source: https://h3ronpy.readthedocs.io/en/latest/usage/vector Converts a GeoDataFrame of African countries into H3 cells at resolution 3. It then reconstructs a GeoDataFrame from these H3 cells and plots it, coloring by country name. ```Python from h3ronpy.pandas.vector import geodataframe_to_cells, cells_dataframe_to_geodataframe from h3ronpy import ContainmentMode df = geodataframe_to_cells(africa, 3) gdf = cells_dataframe_to_geodataframe(df) gdf.plot(column="NAME_EN") ``` -------------------------------- ### h3ronpy.grid_disk_distances: Calculate Distances in Grid Disk Source: https://h3ronpy.readthedocs.io/en/latest/api/core Calculates the distances of cells within a k-radius disk from a set of anchor cells. The `flatten` parameter controls the output format. Returns a RecordBatch with distance information. ```Python h3ronpy.grid_disk_distances(_cellarray_ , _k : int_, _flatten : bool = False_) ``` -------------------------------- ### h3ronpy.compact: Compact H3 Cells Source: https://h3ronpy.readthedocs.io/en/latest/api/core Compacts a given array of H3 cells. The function expects cells to be of the same resolution, but can handle mixed resolutions if the `mixed_resolutions` parameter is set to True, though this may slightly impact performance. It returns an array of compacted cells. ```Python h3ronpy.compact(_arr_ , _mixed_resolutions : bool = False_) ``` -------------------------------- ### Add cells_to_localij and localij_to_cells Functions Source: https://h3ronpy.readthedocs.io/en/latest/changelog Introduces new functions `cells_to_localij` and `localij_to_cells` for H3 index manipulation. ```Python # Add cells_to_localij and localij_to_cells functions. ``` -------------------------------- ### Convert H3 Cells to Raster Format Source: https://h3ronpy.readthedocs.io/en/latest/_sources/usage/raster This code demonstrates converting H3 cells back into a raster format. It reads H3 index and population data from a Parquet file, then uses `rasterize_cells` to generate a NumPy array and its corresponding affine transform. The resulting raster can be visualized using libraries like rasterio. ```Python import pandas as pd import pyarrow as pa from h3ronpy.pandas.raster import rasterize_cells from rasterio.plot import show # Assuming project_root is defined elsewhere # project_root = Path(os.environ["PROJECT_ROOT"]) df = pd.read_parquet(project_root / "data/population-841fa8bffffffff.parquet") size = 1000 nodata_value = -1 array, transform = rasterize_cells( pa.array(df["h3index"]), pa.array(df["pop_general"].astype("int32")), size, nodata_value=nodata_value ) show(array, cmap="viridis", transform=transform, contour=False) ``` -------------------------------- ### Parse directed edges and vertexes from utf8 strings Source: https://h3ronpy.readthedocs.io/en/latest/changelog Enables parsing of directed edges and vertexes directly from UTF8 strings. ```Python # Parse directed edges and vertexes from utf8 strings. ``` -------------------------------- ### h3ronpy.grid_disk: Generate Grid Disk Source: https://h3ronpy.readthedocs.io/en/latest/api/core Generates cells within a specified grid disk (k-ring) around a given set of cells. The `flatten` parameter determines whether the output is a flat array or retains hierarchical structure. Returns an array of cells within the disk. ```Python h3ronpy.grid_disk(_cellarray_ , _k : int_, _flatten : bool = False_) ``` -------------------------------- ### h3ronpy.grid_disk_aggregate_k: Aggregate Cells in Grid Disk Source: https://h3ronpy.readthedocs.io/en/latest/api/core Aggregates cells within a k-radius disk around given cells using a specified method. Supported aggregation methods are 'min' and 'max'. Returns a RecordBatch containing the aggregated results. ```Python h3ronpy.grid_disk_aggregate_k(_cellarray_ , _k : int_, _aggregation_method : str_) ``` -------------------------------- ### Image Processing for Vegetation Mask Source: https://h3ronpy.readthedocs.io/en/latest/_sources/usage/raster This code performs image processing on raster data to create a vegetation mask. It identifies vegetation and ocean areas based on color values and applies a Gaussian filter for smoothing. The processed data is then categorized into different values representing no data, vegetation, and other areas. ```Python from matplotlib import pyplot import numpy as np from scipy import ndimage # Assuming green, blue, and src are defined from previous steps # vegetation_nodata_value = 0 vegetation_mask = (green < 250) & (blue < 50) ocean_mask = (green >= 6) & (green <= 14) & (blue >= 47) & (blue <= 54) vegetation_nodata_value = 0 vegetation = np.full(green.shape, 10, dtype="int8") vegetation[ocean_mask] = vegetation_nodata_value vegetation[vegetation_mask] = 20 # smooth a bit to remove single pixels vegetation = ndimage.gaussian_filter(vegetation, sigma=.7) vegetation[vegetation <= 5] = vegetation_nodata_value vegetation[(vegetation > 0) & (vegetation < 15)] = 1 vegetation[vegetation >= 15] = 2 vegetation[ocean_mask] = vegetation_nodata_value vegetation_plot_args = dict(cmap='Greens', vmin=0, vmax=2) pyplot.imshow(vegetation, **vegetation_plot_args) # Display the processed vegetation array # print(vegetation) ``` -------------------------------- ### Add h3ronpy K-Ring Distance Functions Source: https://h3ronpy.readthedocs.io/en/latest/changelog This snippet announces the addition of `h3ronpy.op.kring_distances` and `h3ronpy.op.kring_distances_agg` functions. These functions are related to calculating distances within H3 grids. ```Python `h3ronpy.op.kring_distances` and `h3ronpy.op.kring_distances_agg` ``` -------------------------------- ### h3ronpy Pandas/GeoPandas Integration Source: https://h3ronpy.readthedocs.io/en/latest/index This section details the integration of h3ronpy with Pandas and GeoPandas DataFrames. It covers specific functions and modules designed to work seamlessly with these data manipulation libraries, including raster and vector modules. ```python # Conceptual example for h3ronpy with Pandas/GeoPandas # import pandas as pd # import geopandas as gpd # import h3ronpy.pandas as hpd # Assuming 'gdf' is a GeoDataFrame # gdf['h3_index'] = hpd.geopandas_to_h3(gdf, resolution=7) # h3_gdf = hpd.h3_to_geopandas(gdf['h3_index'].unique()) print("Pandas and GeoPandas integration is available.") ``` -------------------------------- ### Add h3ronpy Resolution Change Functions Source: https://h3ronpy.readthedocs.io/en/latest/changelog This snippet details the addition of new functions to the `h3ronpy.op` module: `change_resolution` and `change_resolution_paired`. These functions are likely used for modifying the resolution of H3 indexes. ```Python Add `h3ronpy.op.change_resolution` and `h3ronpy.op.change_resolution_paired` ``` -------------------------------- ### Import Libraries for Raster to H3 Conversion Source: https://h3ronpy.readthedocs.io/en/latest/usage/raster Imports necessary libraries for raster data processing and H3 integration, including matplotlib for plotting, rasterio for reading raster files, numpy for numerical operations, h3.api.numpy_int for H3 indexing, scipy.ndimage for image filtering, geopandas for geospatial data manipulation, and pathlib for path management. It also configures matplotlib for larger plot sizes. ```Python from matplotlib import pyplot import rasterio from rasterio.plot import show import numpy as np import h3.api.numpy_int as h3 from scipy import ndimage import geopandas as gpd from pathlib import Path import os # increase the plot size pyplot.rcParams['figure.dpi'] = 120 project_root = Path(os.environ["PROJECT_ROOT"]) ``` -------------------------------- ### h3ronpy.grid_ring_distances: Calculate Grid Ring Distances Source: https://h3ronpy.readthedocs.io/en/latest/api/core Computes distances for cells within specified minimum and maximum k-radius rings around anchor cells. The `flatten` parameter affects the output structure. Returns a RecordBatch containing distance data. ```Python h3ronpy.grid_ring_distances(_cellarray_ , _k_min : int_, _k_max : int_, _flatten : bool = False_) ``` -------------------------------- ### Polygon fill modes for H3 conversion Source: https://h3ronpy.readthedocs.io/en/latest/_sources/usage/vector Demonstrates different polygon fill modes when converting polygons to H3 cells. The `containment_mode` argument in `geodataframe_to_cells` controls how polygons are filled. Supported modes include `ContainsCentroid`, `ContainsBoundary`, `IntersectsBoundary`, and `Covers`. ```python from h3ronpy.pandas.vector import geodataframe_to_cells, cells_dataframe_to_geodataframe from h3ronpy import ContainmentMode def fill_namibia(**kw): cell_ax = cells_dataframe_to_geodataframe(geodataframe_to_cells(namibia, 3, **kw)).plot() return namibia.plot(ax=cell_ax, facecolor=(0,0,0,0), edgecolor='black') fill_namibia(containment_mode=ContainmentMode.ContainsCentroid) ``` ```python fill_namibia(containment_mode=ContainmentMode.ContainsBoundary) ``` ```python fill_namibia(containment_mode=ContainmentMode.IntersectsBoundary) ``` ```python fill_namibia(containment_mode=ContainmentMode.Covers) ``` -------------------------------- ### Deprecate h3ronpy Utility Function Source: https://h3ronpy.readthedocs.io/en/latest/changelog This snippet indicates the deprecation of `h3ronpy.util.h3index_column_to_geodataframe` in favor of `h3ronpy.util.dataframe_to_geodataframe`. This suggests a change in how H3 index columns are converted to GeoDataFrames. ```Python Deprecate `h3ronpy.util.h3index_column_to_geodataframe` in favor of `h3ronpy.util.dataframe_to_geodataframe`. ``` -------------------------------- ### Added coordinates_to_cells function Source: https://h3ronpy.readthedocs.io/en/latest/changelog Introduces the `coordinates_to_cells` function for converting coordinates to H3 cells. ```Python # Added `coordinates_to_cells` function. ``` -------------------------------- ### Warn about memory exhaustion in explode_table_include_null Source: https://h3ronpy.readthedocs.io/en/latest/changelog Adds a warning for potential memory exhaustion when encountering an ArrowIndexError in `explode_table_include_null` or `geodataframe_to_cells`. ```Python # Warn about possible memory exhaustion when encountering a ArrowIndexError in explode_table_include_null / geodataframe_to_cells. ```