API Reference#

This page provides detailed documentation for all public functions and classes.

Main Coverage Functions#

Polygeohasher: A Python package for geohash-based polygon subdivision.

This package provides tools for downloading geometries and subdividing them using geohash for efficient spatial processing.

sigmap.polygeohasher.adaptive_geohash_coverage(country_geom, min_level, max_level, coverage_threshold=0.95, use_strtree=True, predicate='intersects', debug=False)[source]#

Generate adaptive geohash coverage with refinement at boundaries.

Parameters:
  • country_geom (MultiPolygon) – Country geometry

  • min_level (int) – Starting geohash level

  • max_level (int) – Maximum refinement level

  • coverage_threshold (float) – Threshold for considering a tile “fully covered” (0-1)

  • use_strtree (bool) – Use spatial index for performance

  • predicate (Literal['intersects', 'within', 'contains', 'overlaps', 'crosses', 'touches', 'covers', 'covered_by', 'contains_properly']) – Spatial predicate for filtering

  • debug (bool) – Enable debug logging

Returns:

tuple

  • geohash_dict: Dictionary with levels as keys

  • tiles_gdf: GeoDataFrame with all tiles and their levels

Return type:

tuple[dict[str, list], GeoDataFrame]

sigmap.polygeohasher.geohash_coverage(country_geom, level=1, use_strtree=True, predicate='intersects', debug=False)[source]#

Generate geohash coverage for a single level.

Parameters:
  • country_geom (MultiPolygon) – Country geometry

  • level (int) – Geohash level

  • use_strtree (bool) – Use spatial index for performance

  • predicate (Literal['intersects', 'within', 'contains', 'overlaps', 'crosses', 'touches', 'covers', 'covered_by', 'contains_properly']) – Spatial predicate for filtering

  • debug (bool) – Enable debug logging

Returns:

dict

Return type:

dict[str, list]

sigmap.polygeohasher.plot_geohash_coverage(country_geom, geohash_dict, tiles_gdf=None, style='adaptive', figsize=(12, 14), save_path=None, dpi=200, draw_bbox=True, draw_country=True, label_tiles=False, color_by_level=True, cmap='viridis', title=None, show_stats=True, alpha=0.6, edge_color='navy', edge_width=0.7, country_color='crimson', country_width=2.5, show_legend=True)[source]#

Universal plotting function for geohash coverage results.

Works with both adaptive_geohash_coverage and geohash_coverage outputs.

Parameters:
  • country_geom (MultiPolygon) – Country boundary geometry (MultiPolygon or Polygon)

  • geohash_dict (dict) – Dictionary with level as keys and list of geohashes as values Output from adaptive_geohash_coverage or geohash_coverage

  • tiles_gdf (Optional[GeoDataFrame]) – GeoDataFrame with ‘level’ column. If None, will be created from geohash_dict

  • style (Literal['adaptive', 'single']) – Visualization style: - ‘adaptive’: Color by level with legend (best for adaptive coverage) - ‘simple’: Single color (good for single-level coverage) - ‘heatmap’: Density-based coloring

  • figsize (Tuple[float, float]) – Figure size in inches

  • save_path (Optional[str]) – Path to save the figure

  • dpi (int) – Resolution for saved figure

  • draw_bbox (bool) – Draw bounding box around country

  • draw_country (bool) – Draw country boundary

  • label_tiles (bool) – Add geohash labels to tiles (only for ≤100 tiles)

  • color_by_level (bool) – Color tiles by geohash level (ignored if style=’simple’)

  • cmap (str) – Matplotlib colormap name

  • title (Optional[str]) – Custom title. If None, auto-generates title with stats

  • show_stats (bool) – Show statistics in title

  • alpha (float) – Tile transparency (0-1)

  • edge_color (str) – Tile edge color

  • edge_width (float) – Tile edge width

  • country_color (str) – Country boundary color

  • country_width (float) – Country boundary width

  • show_legend (bool) – Show legend for level colors

Returns:

  • fig (matplotlib.figure.Figure) – Figure object

  • ax (matplotlib.axes.Axes) – Axes object

sigmap.polygeohasher.quick_plot(country_geom, geohash_dict, tiles_gdf=None)[source]#

Quick plot with sensible defaults.

Parameters:
  • country_geom (MultiPolygon) – Country boundary geometry

  • geohash_dict (dict[str, list[str]]) – Dictionary with level as keys and list of geohashes as values

  • tiles_gdf (GeoDataFrame) – Optional GeoDataFrame with ‘level’ column

Returns:

  • fig (matplotlib.figure.Figure) – Figure object

  • ax (matplotlib.axes.Axes) – Axes object

sigmap.polygeohasher.download_gadm_country(iso3, level=0, cache_dir=None, force_download=False)[source]#

Download or load GADM country boundary data.

Return type:

GeoDataFrame

Parameters:#

iso3str

ISO3 country code (e.g., ‘FRA’, ‘USA’)

levelint

Administrative level (0 = country, 1 = states/regions, etc.)

cache_dirstr, optional

Directory to cache downloaded files. If None, uses temp directory.

force_downloadbool

If True, download even if a cached version exists

Returns:#

: gpd.GeoDataFrame : Country boundary in EPSG:4326

sigmap.polygeohasher.clear_gadm_temp_files(dirs=None, patterns=None, dry_run=False, verbose=False, extra_path_to_check=None)[source]#

Clear GADM temporary files from specified directories.

Parameters:
  • dirs (list or None, default None) – Directories to search. If None, uses temp directory

  • patterns (list or None, default None) – File patterns to match. If None, uses default GADM patterns

  • dry_run (bool, default False) – If True, only report files without deleting

  • verbose (bool, default False) – Enable verbose logging

  • extra_path_to_check (list) – Additional paths to check

Returns:

List of file paths (candidates if dry_run, removed if not)

Return type:

list

sigmap.polygeohasher.encode_geohash(lon, lat, L)[source]#

Encode longitude and latitude to geohash string.

Parameters:
  • lon (float) – Longitude in degrees [-180, 180]

  • lat (float) – Latitude in degrees [-90, 90]

  • L (int) – Desired geohash string length

Returns:

Geohash string of length L

Return type:

str

sigmap.polygeohasher.candidate_geohashes_covering_bbox(lon_min, lat_min, lon_max, lat_max, L)[source]#

Generate candidate geohashes that could intersect a bounding box.

Parameters:
  • lon_min (float) – Minimum longitude of bbox

  • lat_min (float) – Minimum latitude of bbox

  • lon_max (float) – Maximum longitude of bbox

  • lat_max (float) – Maximum latitude of bbox

  • L (int) – Geohash length

Returns:

List of tuples (geohash, lon, lat)

Return type:

list

sigmap.polygeohasher.geohash_to_polygon(gh)[source]#

Convert geohash to shapely box polygon.

Parameters:

gh (str) – Geohash string

Returns:

Box polygon representing the geohash cell

Return type:

shapely.geometry.Polygon

sigmap.polygeohasher.geohashes_to_gdf(geos, crs='EPSG:4326')[source]#

Convert geohashes to GeoDataFrame.

Parameters:
  • geos (list or str) – List of geohashes or tuples (geohash, lon, lat), or single geohash

  • crs (str, default 'EPSG:4326') – Coordinate reference system

Returns:

GeoDataFrame with geohash codes and polygon geometries

Return type:

gpd.GeoDataFrame

sigmap.polygeohasher.get_geohash_children(parent_geohash)[source]#

Generate all child geohashes for a given parent geohash.

Each parent geohash has exactly 32 children (one for each base32 character). Each child adds one character of precision.

Parameters:

parent_geohash (str) – Parent geohash string

Returns:

List of 32 child geohash strings

Return type:

list

sigmap.polygeohasher.geohashes_to_boxes(geohashes)[source]#

Convert geohash(es) to a dictionary mapping geohash strings to box polygons.

Parameters:

geohashes (str or list of str) – Single geohash string or list of geohash strings

Returns:

dict – {geohash: box_polygon, …}

Return type:

Dictionary mapping geohash string to shapely box polygon

Examples

>>> # Single geohash
>>> boxes = geohashes_to_boxes("u4pruyd")
>>> print(boxes)
{'u4pruyd': <Box polygon>}
>>> # Multiple geohashes
>>> boxes = geohashes_to_boxes(["u4pru", "u4prv", "u4prw"])
>>> print(len(boxes))
3
>>> # Access a specific box
>>> box_poly = boxes["u4pru"]
>>> print(box_poly.bounds)  # (lon_min, lat_min, lon_max, lat_max)
sigmap.polygeohasher.geohashes_to_multipolygon(geohashes_or_dict, dissolve=True)[source]#

Convert geohashes to a MultiPolygon by unioning all box polygons.

Parameters:
  • geohashes_or_dict (str, list of str, or dict) –

    • Single geohash string

    • List of geohash strings

    • Dictionary from geohashes_to_boxes() {geohash: box_polygon}

  • dissolve (bool, default True) – If True, dissolve overlapping/adjacent boxes into single polygons If False, keep as separate polygons in MultiPolygon

Returns:

MultiPolygon or Polygon – Returns Polygon if union results in single polygon, MultiPolygon if multiple disjoint regions

Return type:

Union of all geohash boxes

Examples

>>> # From list of geohashes
>>> geohashes = ["u4pru", "u4prv", "u4prw"]
>>> multi_poly = geohashes_to_multipolygon(geohashes)
>>> print(multi_poly.area)
>>> # From dictionary
>>> boxes = geohashes_to_boxes(geohashes)
>>> multi_poly = geohashes_to_multipolygon(boxes)
>>> # Without dissolving (keep separate)
>>> multi_poly = geohashes_to_multipolygon(geohashes, dissolve=False)
sigmap.polygeohasher.lonlat_res_for_length(L)[source]#

Calculate longitude and latitude resolution for given geohash length.

Parameters:

L (int) – Geohash string length

Returns:

(lon_res, lat_res) in degrees

Return type:

tuple

sigmap.polygeohasher.build_single_multipolygon(gdf)[source]#

Build a single MultiPolygon from a GeoDataFrame of geometries.

Converts all geometries in the GeoDataFrame into a single unified MultiPolygon. Handles invalid geometries, GeometryCollections, and mixed geometry types.

Parameters:

gdf (GeoDataFrame) – GeoDataFrame containing geometries to unite

Returns:

Unified MultiPolygon geometry

Return type:

MultiPolygon

sigmap.polygeohasher.adaptative_geohash_coverage.adaptive_geohash_coverage(country_geom, min_level, max_level, coverage_threshold=0.95, use_strtree=True, predicate='intersects', debug=False)[source]#

Generate adaptive geohash coverage with refinement at boundaries.

Parameters:
  • country_geom (MultiPolygon) – Country geometry

  • min_level (int) – Starting geohash level

  • max_level (int) – Maximum refinement level

  • coverage_threshold (float) – Threshold for considering a tile “fully covered” (0-1)

  • use_strtree (bool) – Use spatial index for performance

  • predicate (Literal['intersects', 'within', 'contains', 'overlaps', 'crosses', 'touches', 'covers', 'covered_by', 'contains_properly']) – Spatial predicate for filtering

  • debug (bool) – Enable debug logging

Returns:

tuple

  • geohash_dict: Dictionary with levels as keys

  • tiles_gdf: GeoDataFrame with all tiles and their levels

Return type:

tuple[dict[str, list], GeoDataFrame]

sigmap.polygeohasher.adaptative_geohash_coverage.geohash_coverage(country_geom, level=1, use_strtree=True, predicate='intersects', debug=False)[source]#

Generate geohash coverage for a single level.

Parameters:
  • country_geom (MultiPolygon) – Country geometry

  • level (int) – Geohash level

  • use_strtree (bool) – Use spatial index for performance

  • predicate (Literal['intersects', 'within', 'contains', 'overlaps', 'crosses', 'touches', 'covers', 'covered_by', 'contains_properly']) – Spatial predicate for filtering

  • debug (bool) – Enable debug logging

Returns:

dict

Return type:

dict[str, list]

Plotting Functions#

sigmap.polygeohasher.plot_geohash_coverage.plot_geohash_coverage(country_geom, geohash_dict, tiles_gdf=None, style='adaptive', figsize=(12, 14), save_path=None, dpi=200, draw_bbox=True, draw_country=True, label_tiles=False, color_by_level=True, cmap='viridis', title=None, show_stats=True, alpha=0.6, edge_color='navy', edge_width=0.7, country_color='crimson', country_width=2.5, show_legend=True)[source]#

Universal plotting function for geohash coverage results.

Works with both adaptive_geohash_coverage and geohash_coverage outputs.

Parameters:
  • country_geom (MultiPolygon) – Country boundary geometry (MultiPolygon or Polygon)

  • geohash_dict (dict) – Dictionary with level as keys and list of geohashes as values Output from adaptive_geohash_coverage or geohash_coverage

  • tiles_gdf (Optional[GeoDataFrame]) – GeoDataFrame with ‘level’ column. If None, will be created from geohash_dict

  • style (Literal['adaptive', 'single']) – Visualization style: - ‘adaptive’: Color by level with legend (best for adaptive coverage) - ‘simple’: Single color (good for single-level coverage) - ‘heatmap’: Density-based coloring

  • figsize (Tuple[float, float]) – Figure size in inches

  • save_path (Optional[str]) – Path to save the figure

  • dpi (int) – Resolution for saved figure

  • draw_bbox (bool) – Draw bounding box around country

  • draw_country (bool) – Draw country boundary

  • label_tiles (bool) – Add geohash labels to tiles (only for ≤100 tiles)

  • color_by_level (bool) – Color tiles by geohash level (ignored if style=’simple’)

  • cmap (str) – Matplotlib colormap name

  • title (Optional[str]) – Custom title. If None, auto-generates title with stats

  • show_stats (bool) – Show statistics in title

  • alpha (float) – Tile transparency (0-1)

  • edge_color (str) – Tile edge color

  • edge_width (float) – Tile edge width

  • country_color (str) – Country boundary color

  • country_width (float) – Country boundary width

  • show_legend (bool) – Show legend for level colors

Returns:

  • fig (matplotlib.figure.Figure) – Figure object

  • ax (matplotlib.axes.Axes) – Axes object

sigmap.polygeohasher.plot_geohash_coverage.quick_plot(country_geom, geohash_dict, tiles_gdf=None)[source]#

Quick plot with sensible defaults.

Parameters:
  • country_geom (MultiPolygon) – Country boundary geometry

  • geohash_dict (dict[str, list[str]]) – Dictionary with level as keys and list of geohashes as values

  • tiles_gdf (GeoDataFrame) – Optional GeoDataFrame with ‘level’ column

Returns:

  • fig (matplotlib.figure.Figure) – Figure object

  • ax (matplotlib.axes.Axes) – Axes object

GADM Download Utilities#

sigmap.polygeohasher.utils.gadm_download.download_gadm_country(iso3, level=0, cache_dir=None, force_download=False)[source]#

Download or load GADM country boundary data.

Return type:

GeoDataFrame

Parameters:#

iso3str

ISO3 country code (e.g., ‘FRA’, ‘USA’)

levelint

Administrative level (0 = country, 1 = states/regions, etc.)

cache_dirstr, optional

Directory to cache downloaded files. If None, uses temp directory.

force_downloadbool

If True, download even if a cached version exists

Returns:#

: gpd.GeoDataFrame : Country boundary in EPSG:4326

sigmap.polygeohasher.utils.gadm_download.clear_gadm_temp_files(dirs=None, patterns=None, dry_run=False, verbose=False, extra_path_to_check=None)[source]#

Clear GADM temporary files from specified directories.

Parameters:
  • dirs (list or None, default None) – Directories to search. If None, uses temp directory

  • patterns (list or None, default None) – File patterns to match. If None, uses default GADM patterns

  • dry_run (bool, default False) – If True, only report files without deleting

  • verbose (bool, default False) – Enable verbose logging

  • extra_path_to_check (list) – Additional paths to check

Returns:

List of file paths (candidates if dry_run, removed if not)

Return type:

list

Geohash Utilities#

sigmap.polygeohasher.utils.geohash.encode_geohash(lon, lat, L)[source]#

Encode longitude and latitude to geohash string.

Parameters:
  • lon (float) – Longitude in degrees [-180, 180]

  • lat (float) – Latitude in degrees [-90, 90]

  • L (int) – Desired geohash string length

Returns:

Geohash string of length L

Return type:

str

sigmap.polygeohasher.utils.geohash.candidate_geohashes_covering_bbox(lon_min, lat_min, lon_max, lat_max, L)[source]#

Generate candidate geohashes that could intersect a bounding box.

Parameters:
  • lon_min (float) – Minimum longitude of bbox

  • lat_min (float) – Minimum latitude of bbox

  • lon_max (float) – Maximum longitude of bbox

  • lat_max (float) – Maximum latitude of bbox

  • L (int) – Geohash length

Returns:

List of tuples (geohash, lon, lat)

Return type:

list

sigmap.polygeohasher.utils.geohash.geohash_to_polygon(gh)[source]#

Convert geohash to shapely box polygon.

Parameters:

gh (str) – Geohash string

Returns:

Box polygon representing the geohash cell

Return type:

shapely.geometry.Polygon

sigmap.polygeohasher.utils.geohash.geohashes_to_gdf(geos, crs='EPSG:4326')[source]#

Convert geohashes to GeoDataFrame.

Parameters:
  • geos (list or str) – List of geohashes or tuples (geohash, lon, lat), or single geohash

  • crs (str, default 'EPSG:4326') – Coordinate reference system

Returns:

GeoDataFrame with geohash codes and polygon geometries

Return type:

gpd.GeoDataFrame

sigmap.polygeohasher.utils.geohash.get_geohash_children(parent_geohash)[source]#

Generate all child geohashes for a given parent geohash.

Each parent geohash has exactly 32 children (one for each base32 character). Each child adds one character of precision.

Parameters:

parent_geohash (str) – Parent geohash string

Returns:

List of 32 child geohash strings

Return type:

list

sigmap.polygeohasher.utils.geohash.geohashes_to_boxes(geohashes)[source]#

Convert geohash(es) to a dictionary mapping geohash strings to box polygons.

Parameters:

geohashes (str or list of str) – Single geohash string or list of geohash strings

Returns:

dict – {geohash: box_polygon, …}

Return type:

Dictionary mapping geohash string to shapely box polygon

Examples

>>> # Single geohash
>>> boxes = geohashes_to_boxes("u4pruyd")
>>> print(boxes)
{'u4pruyd': <Box polygon>}
>>> # Multiple geohashes
>>> boxes = geohashes_to_boxes(["u4pru", "u4prv", "u4prw"])
>>> print(len(boxes))
3
>>> # Access a specific box
>>> box_poly = boxes["u4pru"]
>>> print(box_poly.bounds)  # (lon_min, lat_min, lon_max, lat_max)
sigmap.polygeohasher.utils.geohash.geohashes_to_multipolygon(geohashes_or_dict, dissolve=True)[source]#

Convert geohashes to a MultiPolygon by unioning all box polygons.

Parameters:
  • geohashes_or_dict (str, list of str, or dict) –

    • Single geohash string

    • List of geohash strings

    • Dictionary from geohashes_to_boxes() {geohash: box_polygon}

  • dissolve (bool, default True) – If True, dissolve overlapping/adjacent boxes into single polygons If False, keep as separate polygons in MultiPolygon

Returns:

MultiPolygon or Polygon – Returns Polygon if union results in single polygon, MultiPolygon if multiple disjoint regions

Return type:

Union of all geohash boxes

Examples

>>> # From list of geohashes
>>> geohashes = ["u4pru", "u4prv", "u4prw"]
>>> multi_poly = geohashes_to_multipolygon(geohashes)
>>> print(multi_poly.area)
>>> # From dictionary
>>> boxes = geohashes_to_boxes(geohashes)
>>> multi_poly = geohashes_to_multipolygon(boxes)
>>> # Without dissolving (keep separate)
>>> multi_poly = geohashes_to_multipolygon(geohashes, dissolve=False)
sigmap.polygeohasher.utils.geohash.lonlat_res_for_length(L)[source]#

Calculate longitude and latitude resolution for given geohash length.

Parameters:

L (int) – Geohash string length

Returns:

(lon_res, lat_res) in degrees

Return type:

tuple

Polygon Utilities#

sigmap.polygeohasher.utils.polygons.build_single_multipolygon(gdf)[source]#

Build a single MultiPolygon from a GeoDataFrame of geometries.

Converts all geometries in the GeoDataFrame into a single unified MultiPolygon. Handles invalid geometries, GeometryCollections, and mixed geometry types.

Parameters:

gdf (GeoDataFrame) – GeoDataFrame containing geometries to unite

Returns:

Unified MultiPolygon geometry

Return type:

MultiPolygon