### Install h3-py using pip Source: https://github.com/uber/h3-py/blob/master/readme.md Installs the h3-py library from the Python Package Index (PyPI). This is the standard way to install Python packages. ```console pip install h3 ``` -------------------------------- ### Load and Display GeoDataFrame Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Loads a GeoDataFrame from a geodataset and displays it. This is a common starting point for geospatial operations with h3-py. ```Python import geopandas import h3 from exemplos import plot_df # Assuming plot_df is defined elsewhere from geodatasets import get_path df = geopandas.read_file(get_path('nybb')) print(df) ``` -------------------------------- ### Install Cython Source Files Source: https://github.com/uber/h3-py/blob/master/src/h3/_cy/CMakeLists.txt This section installs the .pyx and .pxd files into the project's destination directory. This is necessary for the Cython API to be accessible and for potential re-compilation or inspection. ```cmake install( FILES cells.pxd cells.pyx edges.pxd edges.pyx error_system.pyx h3lib.pxd latlng.pxd latlng.pyx memory.pxd memory.pyx util.pxd util.pyx vertex.pxd vertex.pyx DESTINATION ${SKBUILD_PROJECT_NAME}/_cy ) ``` -------------------------------- ### Create LatLngMultiPoly from LatLngPoly Objects Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Example of constructing a LatLngMultiPoly by combining multiple LatLngPoly objects. The string representation provides a summary of the polygons' structure (outer vertices and holes). ```Python poly1 = h3.LatLngPoly(outer, hole1, hole2) poly2 = h3.LatLngPoly( [(37.803, -122.408), (37.736, -122.491), (37.738, -122.380), (37.787, -122.39)], [(37.760, -122.441), (37.772, -122.427), (37.773, -122.404), (37.758, -122.401), (37.745, -122.428)] ) mpoly = h3.LatLngMultiPoly(poly1, poly2) print(poly1) print(poly2) print(mpoly) ``` -------------------------------- ### H3 API Performance Comparison Source: https://github.com/uber/h3-py/blob/master/docs/api_comparison.md Provides example code for comparing the performance of different h3-py APIs. It includes functions to compute H3 grid disks and convert results between integer and string representations. The code is designed to be used with various h3 library implementations. ```Python import h3 import h3.api.numpy_int def compute(h3_lib, N=100): h = h3_lib.latlng_to_cell(0, 0, 9) out = h3_lib.grid_disk(h, N) out = h3_lib.compact_cells(out) return out def compute_and_convert(h3_lib, N=100): out = compute(h3_lib, N) out = [h3.int_to_str(h) for h in out] return out ``` -------------------------------- ### Install h3-py using conda Source: https://github.com/uber/h3-py/blob/master/readme.md Installs the h3-py library using the conda package manager, typically from the conda-forge channel. This is useful for managing dependencies in scientific and data science environments. ```console conda config --add channels conda-forge conda install h3-py ``` -------------------------------- ### Create LatLngPoly with Correct Right-Hand Rule Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Example of creating a LatLngPoly object while adhering to the right-hand rule for outer loops and holes. This ensures correct rendering when using GeoJSON interfaces. ```Python # Respects right-hand rule poly = h3.LatLngPoly(outer, hole1, hole2) plot_shape_and_cells(poly, res=10) ``` -------------------------------- ### H3 Memoryview Integer API Source: https://github.com/uber/h3-py/blob/master/docs/api_comparison.md Demonstrates the use of the h3.api.memview_int API for H3 index operations. This API uses Python's memoryview objects for collections, offering dependency-free benefits. Examples show converting lat/lng to cell, generating a grid ring, and accessing individual elements. ```Python import h3.api.memview_int as h3 h = h3.latlng_to_cell(0, 0, 0) print(h) mv = h3.grid_ring(h, 1) print(mv) print(mv[0]) print(list(mv)) ``` -------------------------------- ### Get H3 Grid Ring (Integer API) Source: https://github.com/uber/h3-py/blob/master/docs/api_comparison.md Demonstrates fetching the hexagonal neighbors of an H3 cell using the integer API. The output is a set of H3 indices represented as Python integers. ```Python >>> h3.grid_ring(h, 1) {577973680303243263, 578044049047420927, 578677367745019903, 578782920861286399, 579169948954263551} ``` -------------------------------- ### Get h3-py and H3 Core Library Versions in Python Source: https://github.com/uber/h3-py/blob/master/readme.md Retrieves the version information for both the h3-py Python library and the underlying H3 C library. This is useful for ensuring compatibility and understanding feature sets. ```python import h3 h3.versions() ``` -------------------------------- ### Get H3 Grid Ring (String API) Source: https://github.com/uber/h3-py/blob/master/docs/api_comparison.md Illustrates retrieving the hexagonal neighbors (grid ring) of a given H3 cell using the string-based API. The output is a set of hexadecimal H3 index strings. ```Python >>> h3.grid_ring(h, 1) {'8055fffffffffff', '8059fffffffffff', '807dfffffffffff', '8083fffffffffff', '8099fffffffffff'} ``` -------------------------------- ### Get GeoJSON Representation of LatLngMultiPoly Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Accesses the `__geo_interface__` attribute of a LatLngMultiPoly to obtain its GeoJSON-like dictionary representation, useful for interoperability with other geospatial libraries. ```Python d = mpoly.__geo_interface__ d ``` -------------------------------- ### Get H3 Grid Ring (NumPy API) Source: https://github.com/uber/h3-py/blob/master/docs/api_comparison.md Shows how to obtain the hexagonal neighbors of an H3 cell using the NumPy API. The result is a NumPy ndarray of uint64 H3 indices. ```Python >>> h3.grid_ring(h, 1) array([578782920861286399, 578044049047420927, 577973680303243263, 578677367745019903, 579169948954263551], dtype=uint64) ``` -------------------------------- ### Get Number of Polygons in LatLngMultiPoly Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Demonstrates how to determine the number of individual LatLngPoly objects contained within a LatLngMultiPoly using the `len()` function. ```Python len(mpoly) ``` -------------------------------- ### Get Current CRS of GeoDataFrame Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Retrieves and prints the Coordinate Reference System (CRS) of a GeoDataFrame. This is crucial for ensuring data compatibility with H3 functions. ```Python import geopandas import h3 from geodatasets import get_path df = geopandas.read_file(get_path('nybb')) print(df.crs) ``` -------------------------------- ### Numpy Array vs. Asarray with H3 Memoryview Source: https://github.com/uber/h3-py/blob/master/docs/api_comparison.md Illustrates the behavior of numpy.array and numpy.asarray when used with h3.api.memview_int. numpy.array creates a copy, while numpy.asarray creates a view, affecting how modifications to the memoryview impact the numpy array. Examples show data modification and its consequences. ```Python import h3.api.memview_int as h3 import numpy as np h = h3.latlng_to_cell(0, 0, 0) mv = h3.grid_ring(h, 1) print(list(mv)) a = np.array(mv) mv[0] = 0 print(a) mv = h3.grid_ring(h, 1) a = np.asarray(mv) mv[0] = 0 print(a) ``` -------------------------------- ### H3 Geographic Coordinate Conversion Source: https://github.com/uber/h3-py/blob/master/docs/api_quick.md This group of functions handles the conversion between H3 cell indices and geographic coordinates (latitude and longitude). It also includes functions to get the area and edge length of hexagons, and to retrieve boundary coordinates. ```Python import h3 # Convert latitude/longitude to an H3 cell index h3.latlng_to_cell(37.7749, -122.4194, resolution=5) # Convert an H3 cell index to latitude/longitude h3.cell_to_latlng('8928308280fffff') # Get the approximate area of an H3 cell in square meters h3.cell_area(resolution=5, unit='km^2') # Get the approximate edge length of an H3 cell in meters h3.edge_length(resolution=5, unit='km') # Get the boundary coordinates of an H3 cell h3.cell_to_boundary('8928308280fffff') # Get the boundary coordinates of a directed edge h3.directed_edge_to_boundary(1234567890abcdef) # Calculate the great circle distance between two H3 cell centers h3.great_circle_distance('8928308280fffff', '8928308280fffff', unit='km') # Get the average hexagon area at a given resolution h3.average_hexagon_area(resolution=5, unit='km^2') # Get the average hexagon edge length at a given resolution h3.average_hexagon_edge_length(resolution=5, unit='km') ``` -------------------------------- ### Visualize Polygon and Cells at Different Resolutions Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Demonstrates visualizing a polygon and the H3 cells within it at various resolutions using a helper function. This helps in understanding how cell density changes with resolution. ```Python plot_shape_and_cells(poly, 7) ``` ```Python plot_shape_and_cells(poly, 9) ``` ```Python plot_shape_and_cells(poly, 10) ``` -------------------------------- ### Creating a LatLngPoly with an Outer Boundary Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Demonstrates how to create a `LatLngPoly` object using a list of latitude/longitude pairs that define its outer boundary. The created polygon can then be printed and visualized. ```Python outer = [ (37.804, -122.412), (37.778, -122.507), (37.733, -122.501) ] poly = h3.LatLngPoly(outer) print(poly) plot_shape(poly) ``` -------------------------------- ### Creating LatLngPoly from GeoJSON-like Data Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Shows how to create an `LatLngPoly` object from a GeoJSON-like dictionary or an object implementing `__geo_interface__` using the `h3.geo_to_h3shape()` function. ```Python h3.geo_to_h3shape(d) class MockGeo: def __init__(self, d): self.d = d @property def __geo_interface__(self): return self.d geo = MockGeo(d) h3.geo_to_h3shape(geo) ``` -------------------------------- ### Equivalence of H3Shape to Geo Interface Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Demonstrates the equivalence between `h3shape_to_geo(a)` and `a.__geo_interface__` for H3Shape objects. It also shows that `geo_to_h3shape(a)` is equivalent to `a` if `a` is an H3Shape. ```Python import h3 # Assuming 'a' is an H3Shape object # h3shape_to_geo(a) == a.__geo_interface__ # geo_to_h3shape(a) == a ``` -------------------------------- ### Release New Version of h3-py Source: https://github.com/uber/h3-py/blob/master/dev_notes.md Steps for releasing a new version of the h3-py library. This includes updating the changelog and version number, drafting a new release on GitHub, and ensuring GitHub Actions correctly builds and uploads wheels to PyPI. ```Shell git tag v3.7.2 git push origin --tags ``` -------------------------------- ### Creating a LatLngPoly with Outer Boundary and Multiple Holes Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Illustrates the creation of a `LatLngPoly` object that includes an outer boundary and multiple holes. Each hole is defined by its own list of latitude/longitude pairs. The polygon is then printed and visualized. ```Python hole2 = [ (37.771, -122.484), (37.761, -122.481), (37.758, -122.494), (37.769, -122.496), ] poly = h3.LatLngPoly(outer, hole1, hole2) print(poly) plot_shape(poly) ``` -------------------------------- ### Visualize H3 Cells Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Visualizes a set of H3 cells using a helper function. This allows for the graphical representation of the generated H3 cell data. ```Python import geopandas import h3 from exemplos import plot_cells # Assuming plot_cells is defined elsewhere from geodatasets import get_path df = geopandas.read_file(get_path('nybb')) df = df.to_crs(epsg=4326) geo = df.geometry[0] h3_cells = h3.geo_to_cells(geo, res=9) plot_cells(h3_cells) ``` -------------------------------- ### Define Cython Module Build Macro Source: https://github.com/uber/h3-py/blob/master/src/h3/_cy/CMakeLists.txt This macro defines the process for building a Cython extension module. It uses `add_custom_command` to invoke Cython to generate C code from a .pyx file, then uses `python_add_library` to create the Python module. It also sets C standard and links the 'h3' library. ```cmake macro(add_cython_file filename) add_custom_command( OUTPUT "${filename}.c" COMMENT "Making ${CMAKE_CURRENT_BINARY_DIR}/${filename}.c from ${CMAKE_CURRENT_SOURCE_DIR}/${filename}.pyx" COMMAND Python::Interpreter -m cython "${CMAKE_CURRENT_SOURCE_DIR}/${filename}.pyx" --output-file "${filename}.c" -I ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS "${filename}.pyx" VERBATIM) python_add_library(${filename} MODULE "${filename}.c" WITH_SOABI) set_property(TARGET ${filename} PROPERTY C_STANDARD 99) target_link_libraries(${filename} PRIVATE h3) install(TARGETS ${filename} LIBRARY DESTINATION ${SKBUILD_PROJECT_NAME}/_cy) endmacro() ``` -------------------------------- ### Visualize a Set of H3 Cells Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Uses a helper function to plot a collection of H3 cells, providing a visual representation of their spatial distribution. ```Python plot_cells(cells) ``` -------------------------------- ### LatLngPoly __geo_interface__ Representation Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Explains and displays the `__geo_interface__` representation of a `LatLngPoly` object, which follows the GeoJSON format. It highlights that points are in lng/lat order and the first vertex is repeated. ```Python d = poly.__geo_interface__ d print(poly.outer) print(poly.holes) ``` -------------------------------- ### Configure H3-Py Build with CMake Source: https://github.com/uber/h3-py/blob/master/CMakeLists.txt This CMake script sets up the build environment for the H3-Py project. It defines the minimum required CMake version, project name, and compiler settings for a release build. It also configures the inclusion of Python components and disables several optional build targets to optimize for a release build. ```cmake cmake_minimum_required(VERSION 3.15...3.26) project(${SKBUILD_PROJECT_NAME} LANGUAGES C) set(CMAKE_POSITION_INDEPENDENT_CODE ON) # Always make a release build set(CMAKE_BUILD_TYPE Release) find_package( Python COMPONENTS Interpreter Development.Module REQUIRED) # Avoid building tooling we won't need for release # See all options with `cmake -LA` in an `h3/build` directory, # or at https://h3geo.org/docs/next/core-library/compilation-options/ macro(turn_off option_name) set(${option_name} OFF CACHE BOOL "" FORCE) endmacro() turn_off(BUILD_ALLOC_TESTS) turn_off(BUILD_BENCHMARKS) turn_off(BUILD_FILTERS) turn_off(BUILD_FUZZERS) turn_off(BUILD_GENERATORS) turn_off(BUILD_TESTING) turn_off(ENABLE_COVERAGE) turn_off(ENABLE_DOCS) turn_off(ENABLE_FORMAT) turn_off(ENABLE_LIBFUZZER) turn_off(ENABLE_LINTING) # Build the core library as static set(BUILD_SHARED_LIBS OFF) add_subdirectory(src/h3lib) # Build the rest (other than the core library dependency) as shared set(BUILD_SHARED_LIBS ON) add_subdirectory(src/h3) # Include built h3api.h for Cython API install( FILES "${CMAKE_CURRENT_BINARY_DIR}/src/h3lib/src/h3lib/include/h3api.h" DESTINATION ${SKBUILD_PROJECT_NAME}/_cy) ``` -------------------------------- ### Visualize LatLngMultiPoly Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Renders a LatLngMultiPoly object using a plotting function, allowing visual inspection of the complex polygon structure. ```Python plot_shape(mpoly) ``` -------------------------------- ### Comparing LatLngPoly __geo_interface__ with h3.h3shape_to_geo Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Verifies that the `__geo_interface__` attribute of a `LatLngPoly` object is equivalent to the output of the `h3.h3shape_to_geo()` function when called with the same `LatLngPoly` object. ```Python poly.__geo_interface__ == h3.h3shape_to_geo(poly) ``` -------------------------------- ### Generate H3 Cells from a Set of Cells Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Demonstrates generating a set of H3 cells that form a grid ring around a central cell at a specified resolution. This is useful for neighborhood analysis. ```Python h = h3.latlng_to_cell(37.804, -122.412, res=9) cells = h3.grid_ring(h, 2) cells ``` -------------------------------- ### Creating a LatLngPoly with Outer Boundary and One Hole Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Shows how to create a `LatLngPoly` object with both an outer boundary and a single hole. The hole is defined by a separate list of latitude/longitude pairs. The resulting polygon is printed and plotted. ```Python hole1 = [ (37.782, -122.449), (37.779, -122.465), (37.788, -122.454), ] poly = h3.LatLngPoly(outer, hole1) print(poly) plot_shape(poly) ``` -------------------------------- ### Plotting Helper Functions for H3-py Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Defines several helper functions for visualizing H3 shapes and GeoPandas dataframes. These functions include plotting dataframes with basemaps, plotting individual H3 shapes, plotting sets of H3 cells, and plotting a shape alongside its corresponding H3 cells. ```Python import h3 import geopandas import geodatasets import contextily as cx import matplotlib.pyplot as plt def plot_df(df, column=None, ax=None): """Plot based on the `geometry` column of a GeoPandas dataframe""" df = df.copy() df = df.to_crs(epsg=3857) # web mercator if ax is None: _, ax = plt.subplots(figsize=(8,8)) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) df.plot( ax=ax, alpha=0.5, edgecolor='k', column=column, categorical=True, legend=True, legend_kwds={'loc': 'upper left'}, ) cx.add_basemap(ax, crs=df.crs, source=cx.providers.CartoDB.Positron) def plot_shape(shape, ax=None): df = geopandas.GeoDataFrame({'geometry': [shape]}, crs='EPSG:4326') plot_df(df, ax=ax) def plot_cells(cells, ax=None): shape = h3.cells_to_h3shape(cells) plot_shape(shape, ax=ax) def plot_shape_and_cells(shape, res=9): fig, axs = plt.subplots(1,2, figsize=(10,5), sharex=True, sharey=True) plot_shape(shape, ax=axs[0]) plot_cells(h3.h3shape_to_cells(shape, res), ax=axs[1]) fig.tight_layout() ``` -------------------------------- ### H3 Hierarchical Relationships Source: https://github.com/uber/h3-py/blob/master/docs/api_quick.md These functions allow navigation through the H3 hierarchy, enabling conversion between parent and child cells, finding center children, and compacting/uncompacting sets of cells. This is crucial for spatial aggregation and analysis. ```Python import h3 # Get the parent cell of a given H3 cell at a specified resolution h3.cell_to_parent('8928308280fffff', resolution=7) # Get all children cells of a given H3 cell at a specified resolution h3.cell_to_children('8928308280fffff', resolution=7) # Get the center child cell of a given H3 cell at a specified resolution h3.cell_to_center_child('8928308280fffff', resolution=7) # Get the number of children cells for a given H3 cell at a specified resolution h3.cell_to_children_size('8928308280fffff', resolution=7) # Get the position of a child cell within its parent's children h3.cell_to_child_pos('8928308280fffff') # Get the H3 cell corresponding to a parent and a child position h3.child_pos_to_cell('8928308280fffff', 10) # Compact a set of H3 cells into a smaller set of larger H3 cells h3.compact_cells(['8928308280fffff', '89283082807ffff']) # Uncompact a set of H3 cells to a specified resolution h3.uncompact_cells(['8928308280fffff'], resolution=7) ``` -------------------------------- ### h3-py Library Version Source: https://github.com/uber/h3-py/blob/master/docs/api_quick.md This function returns the current version of the h3-py library. It's useful for checking compatibility or reporting issues. ```Python import h3 # Get the version of the h3-py library h3.versions() ``` -------------------------------- ### Convert LatLngMultiPoly to H3 Cells Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Applies the `h3shape_to_cells` function to a LatLngMultiPoly to obtain the set of H3 cells that cover the multi-polygon area. The result can then be visualized. ```Python cells = h3.h3shape_to_cells(mpoly, res=9) plot_cells(cells) ``` -------------------------------- ### Create H3Shape from GeoJSON-like Object Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Converts a GeoJSON-like Python dictionary (implementing `__geo_interface__`) into an H3Shape object using the `h3.geo_to_h3shape()` function. ```Python geo = MockGeo(d) h3.geo_to_h3shape(geo) ``` -------------------------------- ### IJ-Indexing Functions Source: https://github.com/uber/h3-py/blob/master/docs/api_quick.md These functions relate to the IJ-indexing system, which provides a local coordinate system for hexagons. They allow conversion between H3 indices and local IJ coordinates, and retrieval of icosahedron faces. ```Python import h3 # Get the icosahedron faces that contain a given H3 cell h3.get_icosahedron_faces('8928308280fffff') # Convert an H3 cell index to local IJ coordinates h3.cell_to_local_ij('8928308280fffff') # Convert local IJ coordinates back to an H3 cell index h3.local_ij_to_cell('8928308280fffff', ij=(0, 0)) ``` -------------------------------- ### H3 Polygon Interface Conversion Source: https://github.com/uber/h3-py/blob/master/docs/api_quick.md This section covers functions for converting between H3 cell sets and polygon representations (H3Shape, LatLngPoly, LatLngMultiPoly). These are compatible with the GeoJSON-like __geo_interface__ protocol. ```Python import h3 # Convert an H3Shape object to geographic coordinates h3.h3shape_to_geo(h3_shape_object) # Convert geographic coordinates to an H3Shape object h3.geo_to_h3shape(geo_json_like_object) # Convert an H3Shape object to a set of H3 cells h3.h3shape_to_cells(h3_shape_object, resolution=5) # Convert a set of H3 cells to an H3Shape object h3.cells_to_h3shape(h3_cells_list) # Convert geographic coordinates to a set of H3 cells h3.geo_to_h3cells(geo_json_like_object, resolution=5) # Convert a set of H3 cells to geographic coordinates h3.cells_to_geo(h3_cells_list) ``` -------------------------------- ### Plot GeoDataFrame Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Visualizes a GeoDataFrame, optionally coloring by a specified column. This is useful for inspecting geospatial data. ```Python import geopandas import h3 from exemplos import plot_df # Assuming plot_df is defined elsewhere from geodatasets import get_path df = geopandas.read_file(get_path('nybb')) plot_df(df, column='BoroName') ``` -------------------------------- ### Convert Lat/Lng to H3 Cell (String API) Source: https://github.com/uber/h3-py/blob/master/docs/api_comparison.md Demonstrates converting latitude and longitude to an H3 cell index using the default string-based API. It shows the hexadecimal string representation of the H3 index. ```Python >>> import h3 >>> h = h3.latlng_to_cell(0, 0, 0) >>> h '8075fffffffffff' ``` -------------------------------- ### H3 Cell Grid Relationships Source: https://github.com/uber/h3-py/blob/master/docs/api_quick.md These functions provide tools for exploring spatial relationships between H3 cells, including finding cells within a certain distance (grid ring or disk), calculating grid distances, and checking for adjacency. They are fundamental for neighborhood analysis. ```Python import h3 # Get cells in a grid ring around a central cell h3.grid_ring('8928308280fffff', k=1) # Get cells in a grid disk around a central cell h3.grid_disk('8928308280fffff', k=1) # Calculate the grid distance between two H3 cells h3.grid_distance('8928308280fffff', '89283082807ffff') # Check if two H3 cells are neighbors h3.are_neighbor_cells('8928308280fffff', '89283082807ffff') # Get the sequence of H3 cells forming a path between two cells h3.grid_path_cells('8928308280fffff', '89283082807ffff') ``` -------------------------------- ### Update H3 Submodule Source: https://github.com/uber/h3-py/blob/master/dev_notes.md Instructions for updating the H3 C library submodule within the h3-py project. This involves navigating to the submodule directory, checking out a specific branch or tag, and then staging and committing the changes in the main repository. ```Shell cd src/h3lib git checkout master git pull cd .. git add h3lib git commit ... ``` ```Shell cd src/h3lib git checkout v3.7.1 # or whatever version tag you'd like cd .. git add h3lib git commit ... ``` -------------------------------- ### Additional Polygon Conversion Functions Source: https://github.com/uber/h3-py/blob/master/docs/api_quick.md These functions provide alternative ways to convert polygons to H3 cells, including experimental versions that might offer different performance characteristics or algorithms. ```Python import h3 # Convert a polygon to a set of H3 cells (standard) h3.polygon_to_cells(geo_json_like_object, resolution=5) # Convert a polygon to a set of H3 cells (experimental) h3.polygon_to_cells_experimental(geo_json_like_object, resolution=5) # Convert an H3Shape object to a set of H3 cells (experimental) h3.h3shape_to_cells_experimental(h3_shape_object, resolution=5) ``` -------------------------------- ### Visualize GeoDataFrame with H3 Shapes Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Visualizes a GeoDataFrame where the geometry column has been updated with H3Shape objects. The `plot_df` function handles the conversion of H3Shapes to Shapely geometries for display. ```Python import geopandas import h3 from exemplos import plot_df # Assuming plot_df is defined elsewhere from geodatasets import get_path df = geopandas.read_file(get_path('nybb')) df = df.to_crs(epsg=4326) cell_column = df.geometry.apply(lambda x: h3.geo_to_cells(x, res=8)) shape_column = cell_column.apply(h3.cells_to_h3shape) df.geometry = shape_column plot_df(df, column='BoroName') ``` -------------------------------- ### Iterate Through LatLngPoly Objects in LatLngMultiPoly Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Shows how to iterate through each LatLngPoly object within a LatLngMultiPoly, allowing access to individual polygons for processing or analysis. ```Python for p in mpoly: print(p) ``` ```Python list(mpoly) ``` -------------------------------- ### Convert H3 Cells to GeoJSON Dictionary Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Converts a set of H3 cells directly into a GeoJSON-formatted dictionary representation, simplifying the process of exporting cell data for use in other systems. ```Python str(h3.cells_to_geo(cells))[:200] ``` -------------------------------- ### H3 Edge Functions Source: https://github.com/uber/h3-py/blob/master/docs/api_quick.md This set of functions deals with directed edges in the H3 system. It allows conversion between cell pairs and directed edges, and retrieval of the origin and destination cells of an edge, as well as all edges originating from a cell. ```Python import h3 # Create a directed edge from two H3 cells h3.cells_to_directed_edge('8928308280fffff', '89283082807ffff') # Get the origin and destination cells from a directed edge h3.directed_edge_to_cells(1234567890abcdef) # Get the origin cell of a directed edge h3.get_directed_edge_origin(1234567890abcdef) # Get the destination cell of a directed edge h3.get_directed_edge_destination(1234567890abcdef) # Get all directed edges originating from a given H3 cell h3.origin_to_directed_edges('8928308280fffff') ``` -------------------------------- ### H3 Cell Properties Retrieval Source: https://github.com/uber/h3-py/blob/master/docs/api_quick.md These functions retrieve properties of H3 cells, including the set of resolution 0 cells, pentagons, the total number of cells at a given resolution, and the base cell number for a given H3 index. They are essential for understanding the H3 grid structure. ```Python import h3 # Get all resolution 0 cells h3.get_res0_cells() # Get all pentagons at a given resolution h3.get_pentagons(resolution=5) # Get the total number of cells at a given resolution h3.get_num_cells(resolution=5) # Get the resolution of a given H3 cell index h3.get_resolution('8928308280fffff') # Get the base cell number for a given H3 cell index h3.get_base_cell_number('8928308280fffff') ``` -------------------------------- ### Reset H3 Submodule Source: https://github.com/uber/h3-py/blob/master/dev_notes.md Commands to reset the H3 C library submodule. This is useful when switching between h3-py branches that use different versions of the submodule. ```Shell git submodule deinit -f . git submodule update --init ``` -------------------------------- ### Create LatLngPoly with Reversed Hole (Right-Hand Rule Ignored) Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Demonstrates creating a LatLngPoly where a hole's vertex order is reversed, violating the right-hand rule. The conversion to H3 cells still functions correctly, but visualization might be affected. ```Python # Does not respect right-hand-rule; second hole is reversed # Conversion to cells still works, tho! poly = h3.LatLngPoly(outer, hole1[::-1], hole2) plot_shape_and_cells(poly, res=10) ``` -------------------------------- ### Convert Lat/Lng to H3 Cell (Integer API) Source: https://github.com/uber/h3-py/blob/master/docs/api_comparison.md Shows the conversion of latitude and longitude to an H3 cell index using the integer-based API. The H3 index is represented as a Python integer. ```Python >>> import h3.api.basic_int as h3 >>> h = h3.latlng_to_cell(0, 0, 0) >>> h 578536630256664575 ``` -------------------------------- ### H3 Cell Identification Functions Source: https://github.com/uber/h3-py/blob/master/docs/api_quick.md These functions are used to identify properties of H3 cells, such as validity, whether they are pentagons, or if they belong to a specific resolution class. They are part of the core H3 indexing functionality. ```Python import h3 # Check if a cell index is valid h3.is_valid_cell('8928308280fffff') # Check if a cell index is a pentagon h3.is_pentagon('8009fffffffffff') # Check if a cell index is a resolution class III cell h3.is_res_class_III('8928308280fffff') # Check if a directed edge is valid h3.is_valid_directed_edge('8928308280fffff') # Check if a vertex is valid h3.is_valid_vertex('8928308280fffff') ``` -------------------------------- ### Convert Lat/Lng to H3 Cell (NumPy API) Source: https://github.com/uber/h3-py/blob/master/docs/api_comparison.md Illustrates converting latitude and longitude to an H3 cell index using the NumPy-based API. The H3 index is returned as a NumPy uint64. ```Python >>> import h3.api.numpy_int as h3 >>> h = h3.latlng_to_cell(0, 0, 0) >>> h 578536630256664575 ``` -------------------------------- ### Convert H3 Cells to H3Shape Objects Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Converts sets of H3 cells into H3Shape objects (LatLngPoly or LatLngMultiPoly). These objects are compatible with the `__geo_interface__` and can be directly used in GeoPandas. ```Python import geopandas import h3 from geodatasets import get_path df = geopandas.read_file(get_path('nybb')) df = df.to_crs(epsg=4326) cell_column = df.geometry.apply(lambda x: h3.geo_to_cells(x, res=8)) shape_column = cell_column.apply(h3.cells_to_h3shape) print(shape_column) ``` -------------------------------- ### Accessing LatLngPoly Coordinates Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Demonstrates how to access the coordinates of a `LatLngPoly` object. The `outer` attribute provides the list of points for the outer boundary, and the `holes` attribute provides a list of lists for each hole. ```Python poly = h3.LatLngPoly(outer, hole1, hole2) poly poly.outer poly.holes ``` -------------------------------- ### Create LatLngPoly with Reversed Outer Loop and Hole Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Shows creating a LatLngPoly with both the outer loop and a hole having reversed vertex order, thus not respecting the right-hand rule. Cell conversion remains functional. ```Python # Does not respect right-hand-rule; outer loop and second hole are both reversed # Conversion to cells still works, tho! poly = h3.LatLngPoly(outer[::-1], hole1[::-1], hole2) plot_shape_and_cells(poly, res=10) ``` -------------------------------- ### H3 Index Representation Conversion Source: https://github.com/uber/h3-py/blob/master/docs/api_quick.md These functions facilitate the conversion between integer and string representations of H3 cell indices. This is useful for storing or transmitting H3 indices in different formats. ```Python import h3 # Convert an H3 index from integer to string format h3.int_to_str(611401343336337407) # Convert an H3 index from string to integer format h3.str_to_int('8928308280fffff') ``` -------------------------------- ### Convert Geo to H3 Cells Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Converts a geographic shape (like a Shapely Polygon or MultiPolygon) into a set of H3 cells at a specified resolution. Requires the input geo object to implement the `__geo_interface__`. ```Python import geopandas import h3 from geodatasets import get_path df = geopandas.read_file(get_path('nybb')) df = df.to_crs(epsg=4326) geo = df.geometry[0] h3_cells = h3.geo_to_cells(geo, res=6) print(h3_cells) ``` -------------------------------- ### Convert H3 Cells to H3Shape Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Converts a set of H3 cells into an H3Shape object (either LatLngPoly or LatLngMultiPoly), which can then be used for further geospatial operations or conversions. ```Python h3.cells_to_h3shape(cells) ``` -------------------------------- ### Apply geo_to_cells to GeoDataFrame Column Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Applies the `h3.geo_to_cells` function to each geometry in a GeoDataFrame's geometry column, generating a new column containing sets of H3 cells for each feature. ```Python import geopandas import h3 from geodatasets import get_path df = geopandas.read_file(get_path('nybb')) df = df.to_crs(epsg=4326) cell_column = df.geometry.apply(lambda x: h3.geo_to_cells(x, res=8)) print(cell_column) ``` -------------------------------- ### H3 Vertex Functions Source: https://github.com/uber/h3-py/blob/master/docs/api_quick.md These functions relate to the vertices of H3 cells. They allow conversion between cells and their vertices, and retrieval of the geographic coordinates of a vertex. ```Python import h3 # Get a specific vertex of an H3 cell h3.cell_to_vertex('8928308280fffff', vertex_index=0) # Get all vertices of an H3 cell h3.cell_to_vertexes('8928308280fffff') # Get the geographic coordinates of an H3 vertex h3.vertex_to_latlng(1234567890abcdef) ``` -------------------------------- ### Access Geometry of GeoDataFrame Row Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Accesses and prints the geometry object (e.g., Shapely Polygon or MultiPolygon) of a specific row in a GeoDataFrame. ```Python import geopandas import h3 from geodatasets import get_path df = geopandas.read_file(get_path('nybb')) print(df.geometry[0]) ``` -------------------------------- ### Convert Latitude/Longitude to H3 Cell ID in Python Source: https://github.com/uber/h3-py/blob/master/readme.md Demonstrates how to use the h3-py library to convert a given latitude and longitude to its corresponding H3 hexagonal cell identifier at a specified resolution. This is a core functionality for geospatial indexing. ```python import h3 lat, lng = 37.769377, -122.388903 resolution = 9 h3.latlng_to_cell(lat, lng, resolution) ``` -------------------------------- ### Convert GeoDataFrame CRS to WGS84 Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Converts a GeoDataFrame to the WGS84 coordinate system (EPSG:4326), which uses latitude and longitude. This is a necessary step before applying H3 functions that expect lat/lon input. ```Python import geopandas import h3 from geodatasets import get_path df = geopandas.read_file(get_path('nybb')) df = df.to_crs(epsg=4326) print(df.crs) ``` -------------------------------- ### Assign H3Shape Column to GeoDataFrame Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb Assigns a column of H3Shape objects back to the geometry column of a GeoDataFrame. GeoPandas automatically converts these H3Shape objects to Shapely geometries via `__geo_interface__` for plotting and other operations. ```Python import geopandas import h3 from geodatasets import get_path df = geopandas.read_file(get_path('nybb')) df = df.to_crs(epsg=4326) cell_column = df.geometry.apply(lambda x: h3.geo_to_cells(x, res=8)) shape_column = cell_column.apply(h3.cells_to_h3shape) df.geometry = shape_column print(df.geometry) print(type(df.geometry[0])) ``` -------------------------------- ### Convert Polygon to H3 Cells Source: https://github.com/uber/h3-py/blob/master/docs/polygon_tutorial.ipynb This function retrieves all H3 cells whose centroids fall within a given LatLngPoly. It requires the polygon object and the desired resolution. ```Python h3.h3shape_to_cells(poly, res=7) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.