API Reference#

This page contains the complete API documentation for M3S.

Base Classes#

Base classes and interfaces for spatial grids.

class m3s.base.GridCell(identifier: str, polygon: Polygon, precision: int)[source]#

Bases: object

Represents a single grid cell.

A GridCell contains an identifier, geometric polygon representation, and precision level for spatial indexing systems.

__init__(identifier: str, polygon: Polygon, precision: int)[source]#
identifier#
polygon#
precision#
property area_km2: float[source]#

Calculate the area of the grid cell in square kilometers.

Returns:

Area of the cell in square kilometers

Return type:

float

property id: str#

Alias for identifier.

Returns:

Cell identifier

Return type:

str

property bounds: tuple[float, float, float, float]#

Bounding box of the cell.

Returns:

(min_lon, min_lat, max_lon, max_lat)

Return type:

tuple[float, float, float, float]

property centroid: tuple[float, float]#

Centroid of the cell.

Returns:

(lat, lon) of centroid

Return type:

tuple[float, float]

property geometry: Polygon#

Alias for polygon.

Returns:

Cell polygon geometry

Return type:

Polygon

to_dict() dict[str, Any][source]#

Convert to dictionary.

Returns:

Dictionary with cell properties

Return type:

dict[str, Any]

to_geojson() dict[str, Any][source]#

Convert to GeoJSON feature.

Returns:

GeoJSON feature with geometry and properties

Return type:

dict[str, Any]

class m3s.base.BaseGrid(precision: int)[source]#

Bases: ABC

Abstract base class for all grid systems.

Provides common interface for spatial grid implementations including cell retrieval, neighbor finding, and polygon intersection operations.

__init__(precision: int)[source]#
abstractmethod get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the grid cell containing the given point.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

The grid cell containing the specified point

Return type:

GridCell

abstractmethod get_cell_from_identifier(identifier: str) GridCell[source]#

Get a grid cell from its identifier.

Parameters:

identifier (str) – The unique identifier for the grid cell

Returns:

The grid cell corresponding to the identifier

Return type:

GridCell

abstractmethod get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring cells of the given cell.

Parameters:

cell (GridCell) – The cell for which to find neighbors

Returns:

List of neighboring grid cells

Return type:

list[GridCell]

abstractmethod get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all grid cells within the given bounding box.

Parameters:
  • min_lat (float) – Minimum latitude of bounding box

  • min_lon (float) – Minimum longitude of bounding box

  • max_lat (float) – Maximum latitude of bounding box

  • max_lon (float) – Maximum longitude of bounding box

Returns:

List of grid cells that intersect the bounding box

Return type:

list[GridCell]

contains_point(polygon: Polygon, lat: float, lon: float) bool[source]#

Check if a point is contained within the polygon.

Parameters:
  • polygon (Polygon) – A shapely Polygon object

  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

True if the point is contained within the polygon

Return type:

bool

intersects(gdf: GeoDataFrame, target_crs: str = 'EPSG:4326', use_spatial_index: bool = False) GeoDataFrame[source]#

Get all grid cells that intersect with geometries in a GeoDataFrame.

Automatically handles CRS transformation to WGS84 (EPSG:4326) for grid operations, then transforms results back to the original CRS if different.

Parameters:
  • gdf (gpd.GeoDataFrame) – A GeoDataFrame containing geometries to intersect with grid cells

  • target_crs (str, optional) – Target CRS for grid operations (default: β€œEPSG:4326”)

  • use_spatial_index (bool, optional) – Use GeoPandas spatial index for intersection checks when available

Returns:

GeoDataFrame with grid cell identifiers, geometries, and original data

Return type:

gpd.GeoDataFrame

Grid Systems#

H3 Grid#

H3 (Uber’s Hexagonal Hierarchical Spatial Index) grid implementation.

class m3s.h3.H3Grid(precision: int | None = None, resolution: int | None = None)[source]#

Bases: BaseGrid

H3-based hexagonal spatial grid system.

Implements Uber’s H3 hexagonal hierarchical spatial indexing system, providing uniform hexagonal cells with consistent neighbor relationships.

__init__(precision: int | None = None, resolution: int | None = None)[source]#

Initialize H3Grid.

Parameters:
  • precision (int, optional) – H3 precision level (0-15), by default 7. This is the standardized parameter name across all grid systems.

  • resolution (int, optional) –

    Deprecated alias for precision. Use β€˜precision’ instead.

    Resolution scales:

    0 = ~4,250km edge length (continent scale) 1 = ~1,607km edge length 2 = ~606km edge length 3 = ~229km edge length (country scale) 4 = ~86km edge length 5 = ~33km edge length (state scale) 6 = ~12km edge length 7 = ~4.5km edge length (city scale) 8 = ~1.7km edge length 9 = ~650m edge length (neighborhood scale) 10 = ~240m edge length 11 = ~90m edge length (building scale) 12 = ~34m edge length 13 = ~13m edge length 14 = ~4.8m edge length (room scale) 15 = ~1.8m edge length (precise location)

Raises:

ValueError – If precision/resolution is not between 0 and 15

property resolution: int#

Alias for precision to match H3 terminology.

property area_km2: float#

Get the theoretical area of H3 cells at this resolution in square kilometers.

Returns:

Theoretical area in square kilometers for cells at this resolution

Return type:

float

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the H3 cell containing the given point.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

The H3 hexagonal cell containing the specified point

Return type:

GridCell

get_cell_from_identifier(identifier: str) GridCell[source]#

Get an H3 cell from its identifier.

Parameters:

identifier (str) – The H3 cell identifier (hexadecimal string)

Returns:

The H3 grid cell with hexagonal geometry

Return type:

GridCell

Raises:

ValueError – If the identifier is invalid

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring H3 cells (6 neighbors for hexagons).

Parameters:

cell (GridCell) – The H3 cell for which to find neighbors

Returns:

List of neighboring H3 cells (typically 6 for hexagons)

Return type:

list[GridCell]

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all H3 cells within the given bounding box.

Parameters:
  • min_lat (float) – Minimum latitude of bounding box

  • min_lon (float) – Minimum longitude of bounding box

  • max_lat (float) – Maximum latitude of bounding box

  • max_lon (float) – Maximum longitude of bounding box

Returns:

List of H3 cells that intersect the bounding box

Return type:

list[GridCell]

get_edge_length_km() float[source]#

Get the edge length of hexagons at current resolution in kilometers.

Returns:

Edge length in kilometers for the current H3 resolution

Return type:

float

get_hexagon_area_km2() float[source]#

Get the area of hexagons at current resolution in square kilometers.

Returns:

Hexagon area in square kilometers for the current H3 resolution

Return type:

float

get_children(cell: GridCell) list[GridCell][source]#

Get child cells at the next resolution level.

Parameters:

cell (GridCell) – The parent H3 cell

Returns:

List of child cells at resolution + 1 (typically 7 children)

Return type:

list[GridCell]

get_parent(cell: GridCell) GridCell[source]#

Get parent cell at the previous resolution level.

Parameters:

cell (GridCell) – The child H3 cell

Returns:

Parent cell at resolution - 1

Return type:

GridCell

get_resolution_info() dict[source]#

Get detailed information about the current resolution level.

Returns:

Dictionary containing resolution metrics including edge length, area, and relationship information

Return type:

dict

compact_cells(cells: list[GridCell]) list[GridCell][source]#

Compact a set of cells by replacing groups of children with their parents.

Useful for reducing the number of cells while maintaining coverage.

Parameters:

cells (list[GridCell]) – List of H3 cells to compact

Returns:

Compacted list with parent cells replacing complete sets of children

Return type:

list[GridCell]

uncompact_cells(cells: list[GridCell], target_resolution: int) list[GridCell][source]#

Uncompact cells to a target resolution, expanding parent cells to children.

Parameters:
  • cells (list[GridCell]) – List of H3 cells to uncompact

  • target_resolution (int) – Target resolution level for expansion

Returns:

Expanded list of cells at the target resolution

Return type:

list[GridCell]

Geohash Grid#

Geohash grid implementation.

class m3s.geohash.GeohashGrid(precision: int = 5)[source]#

Bases: BaseGrid

Geohash-based spatial grid system.

Implements the Geohash spatial indexing system using base-32 encoding to create hierarchical rectangular grid cells.

__init__(precision: int = 5)[source]#

Initialize GeohashGrid.

Parameters:

precision (int, optional) – Geohash precision level (1-12), by default 5. Higher values mean smaller cells.

Raises:

ValueError – If precision is not between 1 and 12

property area_km2: float#

Get the theoretical area of Geohash cells at this precision.

Returns:

Theoretical area in square kilometers for cells at this precision

Return type:

float

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the geohash cell containing the given point.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

The geohash grid cell containing the specified point

Return type:

GridCell

get_cell_from_identifier(identifier: str) GridCell[source]#

Get a geohash cell from its identifier.

Parameters:

identifier (str) – The geohash string identifier

Returns:

The geohash grid cell with rectangular geometry

Return type:

GridCell

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring geohash cells.

Parameters:

cell (GridCell) – The geohash cell for which to find neighbors

Returns:

List of neighboring geohash cells

Return type:

list[GridCell]

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all geohash cells within the given bounding box.

expand_cell(cell: GridCell) list[GridCell][source]#

Expand a geohash cell to higher precision cells contained within it.

Parameters:

cell – The cell to expand

Return type:

List of higher precision cells

MGRS Grid#

MGRS (Military Grid Reference System) grid implementation.

class m3s.mgrs.MGRSGrid(precision: int = 1)[source]#

Bases: BaseGrid

MGRS-based spatial grid system.

Implements the Military Grid Reference System (MGRS) for creating uniform square grid cells based on UTM projections.

__init__(precision: int = 1)[source]#

Initialize MGRSGrid.

Parameters:

precision (int, optional) –

MGRS precision level (0-5), by default 1.

Precision levels:

0 = 100km grid 1 = 10km grid 2 = 1km grid 3 = 100m grid 4 = 10m grid 5 = 1m grid

Raises:

ValueError – If precision is not between 0 and 5

property area_km2: float#

Get the theoretical area of MGRS cells at this precision in square kilometers.

Returns:

Theoretical area in square kilometers for cells at this precision

Return type:

float

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the MGRS cell containing the given point.

get_cell_from_identifier(identifier: str) GridCell[source]#

Get an MGRS cell from its identifier.

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring MGRS cells.

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all MGRS cells within the given bounding box.

Package Initialization#

M3S - Multi Spatial Subdivision System.

A unified Python package for working with hierarchical spatial grid systems, including grid conversion utilities, relationship analysis, and multi-resolution operations.

class m3s.BaseGrid(precision: int)[source]#

Bases: ABC

Abstract base class for all grid systems.

Provides common interface for spatial grid implementations including cell retrieval, neighbor finding, and polygon intersection operations.

__init__(precision: int)[source]#
abstractmethod get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the grid cell containing the given point.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

The grid cell containing the specified point

Return type:

GridCell

abstractmethod get_cell_from_identifier(identifier: str) GridCell[source]#

Get a grid cell from its identifier.

Parameters:

identifier (str) – The unique identifier for the grid cell

Returns:

The grid cell corresponding to the identifier

Return type:

GridCell

abstractmethod get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring cells of the given cell.

Parameters:

cell (GridCell) – The cell for which to find neighbors

Returns:

List of neighboring grid cells

Return type:

list[GridCell]

abstractmethod get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all grid cells within the given bounding box.

Parameters:
  • min_lat (float) – Minimum latitude of bounding box

  • min_lon (float) – Minimum longitude of bounding box

  • max_lat (float) – Maximum latitude of bounding box

  • max_lon (float) – Maximum longitude of bounding box

Returns:

List of grid cells that intersect the bounding box

Return type:

list[GridCell]

contains_point(polygon: Polygon, lat: float, lon: float) bool[source]#

Check if a point is contained within the polygon.

Parameters:
  • polygon (Polygon) – A shapely Polygon object

  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

True if the point is contained within the polygon

Return type:

bool

intersects(gdf: GeoDataFrame, target_crs: str = 'EPSG:4326', use_spatial_index: bool = False) GeoDataFrame[source]#

Get all grid cells that intersect with geometries in a GeoDataFrame.

Automatically handles CRS transformation to WGS84 (EPSG:4326) for grid operations, then transforms results back to the original CRS if different.

Parameters:
  • gdf (gpd.GeoDataFrame) – A GeoDataFrame containing geometries to intersect with grid cells

  • target_crs (str, optional) – Target CRS for grid operations (default: β€œEPSG:4326”)

  • use_spatial_index (bool, optional) – Use GeoPandas spatial index for intersection checks when available

Returns:

GeoDataFrame with grid cell identifiers, geometries, and original data

Return type:

gpd.GeoDataFrame

class m3s.GeohashGrid(precision: int = 5)[source]#

Bases: BaseGrid

Geohash-based spatial grid system.

Implements the Geohash spatial indexing system using base-32 encoding to create hierarchical rectangular grid cells.

__init__(precision: int = 5)[source]#

Initialize GeohashGrid.

Parameters:

precision (int, optional) – Geohash precision level (1-12), by default 5. Higher values mean smaller cells.

Raises:

ValueError – If precision is not between 1 and 12

property area_km2: float#

Get the theoretical area of Geohash cells at this precision.

Returns:

Theoretical area in square kilometers for cells at this precision

Return type:

float

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the geohash cell containing the given point.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

The geohash grid cell containing the specified point

Return type:

GridCell

get_cell_from_identifier(identifier: str) GridCell[source]#

Get a geohash cell from its identifier.

Parameters:

identifier (str) – The geohash string identifier

Returns:

The geohash grid cell with rectangular geometry

Return type:

GridCell

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring geohash cells.

Parameters:

cell (GridCell) – The geohash cell for which to find neighbors

Returns:

List of neighboring geohash cells

Return type:

list[GridCell]

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all geohash cells within the given bounding box.

expand_cell(cell: GridCell) list[GridCell][source]#

Expand a geohash cell to higher precision cells contained within it.

Parameters:

cell – The cell to expand

Return type:

List of higher precision cells

class m3s.MGRSGrid(precision: int = 1)[source]#

Bases: BaseGrid

MGRS-based spatial grid system.

Implements the Military Grid Reference System (MGRS) for creating uniform square grid cells based on UTM projections.

__init__(precision: int = 1)[source]#

Initialize MGRSGrid.

Parameters:

precision (int, optional) –

MGRS precision level (0-5), by default 1.

Precision levels:

0 = 100km grid 1 = 10km grid 2 = 1km grid 3 = 100m grid 4 = 10m grid 5 = 1m grid

Raises:

ValueError – If precision is not between 0 and 5

property area_km2: float#

Get the theoretical area of MGRS cells at this precision in square kilometers.

Returns:

Theoretical area in square kilometers for cells at this precision

Return type:

float

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the MGRS cell containing the given point.

get_cell_from_identifier(identifier: str) GridCell[source]#

Get an MGRS cell from its identifier.

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring MGRS cells.

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all MGRS cells within the given bounding box.

class m3s.H3Grid(precision: int | None = None, resolution: int | None = None)[source]#

Bases: BaseGrid

H3-based hexagonal spatial grid system.

Implements Uber’s H3 hexagonal hierarchical spatial indexing system, providing uniform hexagonal cells with consistent neighbor relationships.

__init__(precision: int | None = None, resolution: int | None = None)[source]#

Initialize H3Grid.

Parameters:
  • precision (int, optional) – H3 precision level (0-15), by default 7. This is the standardized parameter name across all grid systems.

  • resolution (int, optional) –

    Deprecated alias for precision. Use β€˜precision’ instead.

    Resolution scales:

    0 = ~4,250km edge length (continent scale) 1 = ~1,607km edge length 2 = ~606km edge length 3 = ~229km edge length (country scale) 4 = ~86km edge length 5 = ~33km edge length (state scale) 6 = ~12km edge length 7 = ~4.5km edge length (city scale) 8 = ~1.7km edge length 9 = ~650m edge length (neighborhood scale) 10 = ~240m edge length 11 = ~90m edge length (building scale) 12 = ~34m edge length 13 = ~13m edge length 14 = ~4.8m edge length (room scale) 15 = ~1.8m edge length (precise location)

Raises:

ValueError – If precision/resolution is not between 0 and 15

property resolution: int#

Alias for precision to match H3 terminology.

property area_km2: float#

Get the theoretical area of H3 cells at this resolution in square kilometers.

Returns:

Theoretical area in square kilometers for cells at this resolution

Return type:

float

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the H3 cell containing the given point.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

The H3 hexagonal cell containing the specified point

Return type:

GridCell

get_cell_from_identifier(identifier: str) GridCell[source]#

Get an H3 cell from its identifier.

Parameters:

identifier (str) – The H3 cell identifier (hexadecimal string)

Returns:

The H3 grid cell with hexagonal geometry

Return type:

GridCell

Raises:

ValueError – If the identifier is invalid

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring H3 cells (6 neighbors for hexagons).

Parameters:

cell (GridCell) – The H3 cell for which to find neighbors

Returns:

List of neighboring H3 cells (typically 6 for hexagons)

Return type:

list[GridCell]

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all H3 cells within the given bounding box.

Parameters:
  • min_lat (float) – Minimum latitude of bounding box

  • min_lon (float) – Minimum longitude of bounding box

  • max_lat (float) – Maximum latitude of bounding box

  • max_lon (float) – Maximum longitude of bounding box

Returns:

List of H3 cells that intersect the bounding box

Return type:

list[GridCell]

get_edge_length_km() float[source]#

Get the edge length of hexagons at current resolution in kilometers.

Returns:

Edge length in kilometers for the current H3 resolution

Return type:

float

get_hexagon_area_km2() float[source]#

Get the area of hexagons at current resolution in square kilometers.

Returns:

Hexagon area in square kilometers for the current H3 resolution

Return type:

float

get_children(cell: GridCell) list[GridCell][source]#

Get child cells at the next resolution level.

Parameters:

cell (GridCell) – The parent H3 cell

Returns:

List of child cells at resolution + 1 (typically 7 children)

Return type:

list[GridCell]

get_parent(cell: GridCell) GridCell[source]#

Get parent cell at the previous resolution level.

Parameters:

cell (GridCell) – The child H3 cell

Returns:

Parent cell at resolution - 1

Return type:

GridCell

get_resolution_info() dict[source]#

Get detailed information about the current resolution level.

Returns:

Dictionary containing resolution metrics including edge length, area, and relationship information

Return type:

dict

compact_cells(cells: list[GridCell]) list[GridCell][source]#

Compact a set of cells by replacing groups of children with their parents.

Useful for reducing the number of cells while maintaining coverage.

Parameters:

cells (list[GridCell]) – List of H3 cells to compact

Returns:

Compacted list with parent cells replacing complete sets of children

Return type:

list[GridCell]

uncompact_cells(cells: list[GridCell], target_resolution: int) list[GridCell][source]#

Uncompact cells to a target resolution, expanding parent cells to children.

Parameters:
  • cells (list[GridCell]) – List of H3 cells to uncompact

  • target_resolution (int) – Target resolution level for expansion

Returns:

Expanded list of cells at the target resolution

Return type:

list[GridCell]

class m3s.CSquaresGrid(precision: int = 3)[source]#

Bases: BaseGrid

C-squares-based spatial grid system.

Implements the Concise Spatial Query and Representation System (C-squares) for marine and environmental data referencing using a hierarchical decimal grid system.

__init__(precision: int = 3)[source]#

Initialize CSquaresGrid.

Parameters:

precision (int, optional) –

C-squares precision level (1-5), by default 3.

Precision levels:

1 = 10Β° x 10Β° cells (base level) 2 = 5Β° x 5Β° cells 3 = 1Β° x 1Β° cells 4 = 0.5Β° x 0.5Β° cells (30’ x 30’) 5 = 0.1Β° x 0.1Β° cells (6’ x 6’)

Raises:

ValueError – If precision is not between 1 and 5

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the C-squares cell containing the given point.

Parameters:
  • lat (float) – Latitude coordinate (-90 to 90)

  • lon (float) – Longitude coordinate (-180 to 180)

Returns:

The C-squares grid cell containing the specified point

Return type:

GridCell

Raises:

ValueError – If coordinates are out of valid range

get_cell_from_identifier(identifier: str) GridCell[source]#

Get a C-squares cell from its identifier.

Parameters:

identifier (str) – The C-squares identifier string

Returns:

The C-squares grid cell with rectangular geometry

Return type:

GridCell

Raises:

ValueError – If the identifier is invalid

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring C-squares cells.

Parameters:

cell (GridCell) – The C-squares cell for which to find neighbors

Returns:

List of neighboring C-squares cells (up to 8 neighbors)

Return type:

list[GridCell]

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all C-squares cells within the given bounding box.

Parameters:
  • min_lat (float) – Minimum latitude of bounding box

  • min_lon (float) – Minimum longitude of bounding box

  • max_lat (float) – Maximum latitude of bounding box

  • max_lon (float) – Maximum longitude of bounding box

Returns:

List of C-squares cells that intersect the bounding box

Return type:

list[GridCell]

get_precision_info() dict[source]#

Get detailed information about the current precision level.

Returns:

Dictionary containing precision metrics including cell size and coverage information

Return type:

dict

property area_km2: float#

Theoretical area of a C-squares cell at this precision in kmΒ².

Returns:

Theoretical area in square kilometers

Return type:

float

class m3s.GARSGrid(precision: int = 1)[source]#

Bases: BaseGrid

GARS (Global Area Reference System) spatial grid.

Implements the military/aviation grid system using a hierarchical coordinate system with longitude bands and latitude zones.

__init__(precision: int = 1)[source]#

Initialize GARSGrid.

Parameters:

precision (int, optional) –

GARS precision level (1-3), by default 1.

Precision levels:

1 = 30’ Γ— 30’ (0.5Β° Γ— 0.5Β°) - e.g., β€œ001AA” 2 = 15’ Γ— 15’ (0.25Β° Γ— 0.25Β°) - e.g., β€œ001AA1” 3 = 5’ Γ— 5’ (~0.083Β° Γ— 0.083Β°) - e.g., β€œ001AA19”

Raises:

ValueError – If precision is not between 1 and 3

property area_km2: float[source]#

Approximate area of a GARS cell at this precision in square kilometers.

Returns:

Approximate area in square kilometers

Return type:

float

encode(lat: float, lon: float) str[source]#

Encode a latitude/longitude into a GARS identifier.

Parameters:
  • lat (float) – Latitude coordinate (-90 to 90)

  • lon (float) – Longitude coordinate (-180 to 180)

Returns:

GARS identifier string

Return type:

str

decode(gars_id: str) tuple[source]#

Decode a GARS identifier into latitude/longitude bounds.

Parameters:

gars_id (str) – GARS identifier string

Returns:

(south, west, north, east) bounds

Return type:

tuple

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the grid cell containing the given point.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

The grid cell containing the specified point

Return type:

GridCell

get_cell_from_identifier(identifier: str) GridCell[source]#

Get a grid cell from its identifier.

Parameters:

identifier (str) – The GARS identifier string

Returns:

The grid cell corresponding to the identifier

Return type:

GridCell

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring cells of the given cell.

Parameters:

cell (GridCell) – The cell for which to find neighbors

Returns:

List of neighboring grid cells

Return type:

list[GridCell]

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all grid cells within the given bounding box.

Parameters:
  • min_lat (float) – Minimum latitude of bounding box

  • min_lon (float) – Minimum longitude of bounding box

  • max_lat (float) – Maximum latitude of bounding box

  • max_lon (float) – Maximum longitude of bounding box

Returns:

List of grid cells that intersect the bounding box

Return type:

list[GridCell]

class m3s.MaidenheadGrid(precision: int = 3)[source]#

Bases: BaseGrid

Maidenhead locator system spatial grid.

Implements the ham radio grid system using a hierarchical coordinate system with alternating letter/number pairs.

__init__(precision: int = 3)[source]#

Initialize MaidenheadGrid.

Parameters:

precision (int, optional) –

Maidenhead precision level (1-4), by default 3.

Precision levels:

1 = Field (20Β° Γ— 10Β°) - e.g., β€œJO” 2 = Square (2Β° Γ— 1Β°) - e.g., β€œJO62” 3 = Subsquare (5’ Γ— 2.5’) - e.g., β€œJO62KO” 4 = Extended square (12.5” Γ— 6.25”) - e.g., β€œJO62KO78”

Raises:

ValueError – If precision is not between 1 and 4

property area_km2: float[source]#

Approximate area of a Maidenhead cell at this precision in square kilometers.

Returns:

Approximate area in square kilometers

Return type:

float

encode(lat: float, lon: float) str[source]#

Encode a latitude/longitude into a Maidenhead locator.

Parameters:
  • lat (float) – Latitude coordinate (-90 to 90)

  • lon (float) – Longitude coordinate (-180 to 180)

Returns:

Maidenhead locator string

Return type:

str

decode(locator: str) tuple[source]#

Decode a Maidenhead locator into latitude/longitude bounds.

Parameters:

locator (str) – Maidenhead locator string

Returns:

(south, west, north, east) bounds

Return type:

tuple

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the grid cell containing the given point.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

The grid cell containing the specified point

Return type:

GridCell

get_cell_from_identifier(identifier: str) GridCell[source]#

Get a grid cell from its identifier.

Parameters:

identifier (str) – The Maidenhead locator string

Returns:

The grid cell corresponding to the identifier

Return type:

GridCell

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring cells of the given cell.

Parameters:

cell (GridCell) – The cell for which to find neighbors

Returns:

List of neighboring grid cells

Return type:

list[GridCell]

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all grid cells within the given bounding box.

Parameters:
  • min_lat (float) – Minimum latitude of bounding box

  • min_lon (float) – Minimum longitude of bounding box

  • max_lat (float) – Maximum latitude of bounding box

  • max_lon (float) – Maximum longitude of bounding box

Returns:

List of grid cells that intersect the bounding box

Return type:

list[GridCell]

class m3s.PlusCodeGrid(precision: int = 4)[source]#

Bases: BaseGrid

Plus codes (Open Location Code) spatial grid system.

Implements Google’s open-source alternative to addresses using a base-20 encoding system to create hierarchical grid cells.

ALPHABET = '23456789CFGHJMPQRVWX'#
BASE = 20#
GRID_SIZES = [20.0, 1.0, 0.05, 0.0025, 0.000125, 6.25e-06, 3.125e-07, 1.5625e-08]#
__init__(precision: int = 4)[source]#

Initialize PlusCodeGrid.

Parameters:

precision (int, optional) – Plus code precision level (1-7), by default 4. Higher values mean smaller cells.

Raises:

ValueError – If precision is not between 1 and 7

property area_km2: float[source]#

Approximate area of a Plus Code cell at this precision in square kilometers.

Returns:

Approximate area in square kilometers

Return type:

float

encode(lat: float, lon: float) str[source]#

Encode a latitude/longitude into a plus code.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

Plus code identifier

Return type:

str

decode(code: str) tuple[source]#

Decode a plus code into latitude/longitude bounds.

Parameters:

code (str) – Plus code identifier

Returns:

(south, west, north, east) bounds

Return type:

tuple

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the grid cell containing the given point.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

The grid cell containing the specified point

Return type:

GridCell

get_cell_from_identifier(identifier: str) GridCell[source]#

Get a grid cell from its identifier.

Parameters:

identifier (str) – The plus code identifier

Returns:

The grid cell corresponding to the identifier

Return type:

GridCell

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring cells of the given cell.

Parameters:

cell (GridCell) – The cell for which to find neighbors

Returns:

List of neighboring grid cells

Return type:

list[GridCell]

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all grid cells within the given bounding box.

Parameters:
  • min_lat (float) – Minimum latitude of bounding box

  • min_lon (float) – Minimum longitude of bounding box

  • max_lat (float) – Maximum latitude of bounding box

  • max_lon (float) – Maximum longitude of bounding box

Returns:

List of grid cells that intersect the bounding box

Return type:

list[GridCell]

class m3s.QuadkeyGrid(precision: int | None = None, level: int | None = None)[source]#

Bases: BaseGrid

Quadkey spatial grid implementation.

Based on Microsoft’s Bing Maps tile system, this grid uses a quadtree to hierarchically divide the world into square tiles. Each tile is identified by a quadkey string where each digit (0-3) represents the quadrant chosen at each level of the tree.

level#

Zoom level (precision) of the quadkey tiles (1-23)

Type:

int

__init__(precision: int | None = None, level: int | None = None)[source]#

Initialize Quadkey grid.

Parameters:
  • precision (int, optional) – Precision level for quadkey tiles (1-23). This is the standardized parameter name across all grid systems.

  • level (int, optional) – Deprecated alias for precision. Use β€˜precision’ instead.

property area_km2: float#

Get the theoretical area of Quadkey tiles at this level in square kilometers.

Returns:

Theoretical area in square kilometers for tiles at this level

Return type:

float

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the quadkey cell containing the given point.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

The grid cell containing the specified point

Return type:

GridCell

get_cell_from_identifier(identifier: str) GridCell[source]#

Get a grid cell from its quadkey identifier.

Parameters:

identifier (str) – The quadkey identifier

Returns:

The grid cell corresponding to the identifier

Return type:

GridCell

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring cells of the given cell.

Parameters:

cell (GridCell) – The cell for which to find neighbors

Returns:

List of neighboring grid cells (up to 8 neighbors)

Return type:

list[GridCell]

get_children(cell: GridCell) list[GridCell][source]#

Get child cells at the next zoom level.

Parameters:

cell (GridCell) – Parent cell

Returns:

List of 4 child cells

Return type:

list[GridCell]

get_parent(cell: GridCell) GridCell[source]#

Get parent cell at the previous zoom level.

Parameters:

cell (GridCell) – Child cell

Returns:

Parent cell

Return type:

GridCell

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all grid cells within the given bounding box.

Parameters:
  • min_lat (float) – Minimum latitude of bounding box

  • min_lon (float) – Minimum longitude of bounding box

  • max_lat (float) – Maximum latitude of bounding box

  • max_lon (float) – Maximum longitude of bounding box

Returns:

List of grid cells that intersect the bounding box

Return type:

list[GridCell]

get_quadkey_bounds(quadkey: str) tuple[float, float, float, float][source]#

Get the latitude/longitude bounds of a quadkey.

Parameters:

quadkey (str) – Quadkey identifier

Returns:

Bounds as (min_lat, min_lon, max_lat, max_lon)

Return type:

tuple

class m3s.S2Grid(precision: int | None = None, level: int | None = None)[source]#

Bases: BaseGrid

S2 spatial grid implementation.

Based on Google’s S2 geometry library, this grid provides hierarchical decomposition of the sphere into cells. S2 uses a cube-to-sphere projection and the Hilbert curve to create a spatial index with excellent locality properties.

level#

S2 cell level (0-30), where higher levels provide smaller cells

Type:

int

__init__(precision: int | None = None, level: int | None = None)[source]#

Initialize S2 grid.

Parameters:
  • precision (int, optional) – S2 cell precision level (0-30). This is the standardized parameter name across all grid systems.

  • level (int, optional) – Deprecated alias for precision. Use β€˜precision’ instead. Level 0: ~85,000 km edge length Level 10: ~1,300 km edge length Level 20: ~20 m edge length Level 30: ~1 cm edge length

property area_km2: float#

Get the theoretical area of S2 cells at this level in square kilometers.

Returns:

Theoretical area in square kilometers for cells at this level

Return type:

float

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the S2 cell containing the given point.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

The grid cell containing the specified point

Return type:

GridCell

get_cell_from_identifier(identifier: str) GridCell[source]#

Get a grid cell from its S2 cell token.

Parameters:

identifier (str) – The S2 cell token (hexadecimal string)

Returns:

The grid cell corresponding to the identifier

Return type:

GridCell

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring cells of the given cell.

Parameters:

cell (GridCell) – The cell for which to find neighbors

Returns:

List of neighboring grid cells

Return type:

list[GridCell]

get_children(cell: GridCell) list[GridCell][source]#

Get child cells at the next level.

Parameters:

cell (GridCell) – Parent cell

Returns:

List of 4 child cells

Return type:

list[GridCell]

get_parent(cell: GridCell) GridCell | None[source]#

Get parent cell at the previous level.

Parameters:

cell (GridCell) – Child cell

Returns:

Parent cell, or None if already at level 0

Return type:

GridCell | None

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all grid cells within the given bounding box.

Parameters:
  • min_lat (float) – Minimum latitude of bounding box

  • min_lon (float) – Minimum longitude of bounding box

  • max_lat (float) – Maximum latitude of bounding box

  • max_lon (float) – Maximum longitude of bounding box

Returns:

List of grid cells that intersect the bounding box

Return type:

list[GridCell]

get_covering_cells(polygon: Polygon, max_cells: int = 100) list[GridCell][source]#

Get S2 cells that cover the given polygon.

Parameters:
  • polygon (Polygon) – Shapely polygon to cover

  • max_cells (int) – Maximum number of cells to return

Returns:

List of cells covering the polygon

Return type:

list[GridCell]

class m3s.SlippyGrid(precision: int | None = None, zoom: int | None = None)[source]#

Bases: BaseGrid

Slippy Map Tiling grid implementation.

Based on the standard web map tile system used by OpenStreetMap, Google Maps, and other web mapping services. Uses Web Mercator projection (EPSG:3857) with 256Γ—256 pixel tiles organized in a z/x/y coordinate system.

zoom#

Zoom level (0-22), where higher levels provide smaller tiles

Type:

int

__init__(precision: int | None = None, zoom: int | None = None)[source]#

Initialize Slippy Map Tiling grid.

Parameters:
  • precision (int, optional) – Precision level (0-22). This is the standardized parameter name across all grid systems.

  • zoom (int, optional) – Deprecated alias for precision. Use β€˜precision’ instead. Zoom 0: 1 tile covering the world Zoom 1: 2Γ—2 = 4 tiles Zoom 10: 1024Γ—1024 = ~1M tiles (~40km tiles) Zoom 15: 32768Γ—32768 = ~1B tiles (~1.2km tiles) Zoom 18: 262144Γ—262144 tiles (~150m tiles)

property area_km2: float#

Get the theoretical area of Slippy Map tiles.

At this zoom level, returns the area in square kilometers.

Returns:

Theoretical area in square kilometers for tiles at this zoom level

Return type:

float

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the Slippy Map tile containing the given point.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

The tile containing the specified point

Return type:

GridCell

get_cell_from_identifier(identifier: str) GridCell[source]#

Get a tile from its z/x/y identifier.

Parameters:

identifier (str) – The tile identifier in β€œz/x/y” format

Returns:

The tile corresponding to the identifier

Return type:

GridCell

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring tiles of the given tile.

Parameters:

cell (GridCell) – The tile for which to find neighbors

Returns:

List of neighboring tiles (up to 8 neighbors)

Return type:

list[GridCell]

get_children(cell: GridCell) list[GridCell][source]#

Get child tiles at the next zoom level.

Parameters:

cell (GridCell) – Parent tile

Returns:

List of 4 child tiles

Return type:

list[GridCell]

get_parent(cell: GridCell) GridCell | None[source]#

Get parent tile at the previous zoom level.

Parameters:

cell (GridCell) – Child tile

Returns:

Parent tile, or None if already at zoom 0

Return type:

GridCell | None

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all tiles within the given bounding box.

Parameters:
  • min_lat (float) – Minimum latitude of bounding box

  • min_lon (float) – Minimum longitude of bounding box

  • max_lat (float) – Maximum latitude of bounding box

  • max_lon (float) – Maximum longitude of bounding box

Returns:

List of tiles that intersect the bounding box

Return type:

list[GridCell]

get_covering_cells(polygon: Polygon, max_cells: int = 100) list[GridCell][source]#

Get Slippy Map tiles that cover the given polygon.

Parameters:
  • polygon (Polygon) – Shapely polygon to cover

  • max_cells (int) – Maximum number of tiles to return

Returns:

List of tiles covering the polygon

Return type:

list[GridCell]

class m3s.What3WordsGrid(precision: int = 1)[source]#

Bases: BaseGrid

What3Words-style spatial grid system.

Implements a 3-meter square grid system similar to What3Words. Each cell represents approximately a 3x3 meter square on the Earth’s surface.

Note: This implementation provides the grid structure. For actual What3Words integration with their word system, use the official What3Words API.

__init__(precision: int = 1)[source]#

Initialize What3WordsGrid.

Parameters:

precision (int, optional) – Grid precision level (1 only supported for 3m squares), by default 1

Raises:

ValueError – If precision is not 1

property area_km2: float#

Get the theoretical area of What3Words cells in square kilometers.

Returns:

Theoretical area in square kilometers (approximately 0.000009 kmΒ²)

Return type:

float

get_cell_from_point(lat: float, lon: float) GridCell[source]#

Get the grid cell containing the given point.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Returns:

The grid cell containing the specified point

Return type:

GridCell

get_cell_from_identifier(identifier: str) GridCell[source]#

Get a grid cell from its identifier.

Parameters:

identifier (str) – The unique identifier for the grid cell

Returns:

The grid cell corresponding to the identifier

Return type:

GridCell

get_neighbors(cell: GridCell) list[GridCell][source]#

Get neighboring cells of the given cell.

Parameters:

cell (GridCell) – The cell for which to find neighbors

Returns:

List of neighboring grid cells (8 neighbors for square grid)

Return type:

list[GridCell]

get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#

Get all grid cells within the given bounding box.

Parameters:
  • min_lat (float) – Minimum latitude of bounding box

  • min_lon (float) – Minimum longitude of bounding box

  • max_lat (float) – Maximum latitude of bounding box

  • max_lon (float) – Maximum longitude of bounding box

Returns:

List of grid cells within the bounding box

Return type:

list[GridCell]

class m3s.GridBuilder[source]#

Bases: object

Fluent interface for building and executing grid queries.

Enables method chaining for common workflows, eliminating verbose multi-step operations. Supports all 12 grid systems through a unified interface.

Examples

Basic single-point query:

>>> result = (GridBuilder
...     .for_system('h3')
...     .with_precision(7)
...     .at_point(40.7128, -74.0060)
...     .execute())
>>> print(result.single.identifier)

Intelligent precision with neighbors:

>>> selector = PrecisionSelector('geohash')
>>> rec = selector.for_use_case('neighborhood')
>>> result = (GridBuilder
...     .for_system('geohash')
...     .with_auto_precision(rec)
...     .at_point(40.7128, -74.0060)
...     .find_neighbors()
...     .execute())
>>> print(f"Cell + {len(result.many) - 1} neighbors")

Region query with filtering:

>>> result = (GridBuilder
...     .for_system('s2')
...     .with_precision(10)
...     .in_bbox(40.7, -74.1, 40.8, -73.9)
...     .filter(lambda cell: cell.area_km2 > 1.0)
...     .execute())
>>> gdf = result.to_geodataframe()

Cross-grid conversion:

>>> result = (GridBuilder
...     .for_system('geohash')
...     .with_precision(5)
...     .at_point(40.7128, -74.0060)
...     .convert_to('h3', method='centroid')
...     .execute())
__init__() None[source]#

Initialize empty builder.

classmethod for_system(system: str) GridBuilder[source]#

Select grid system.

Parameters:

system (str) – Grid system name: β€˜geohash’, β€˜h3’, β€˜s2’, β€˜quadkey’, β€˜slippy’, β€˜mgrs’, β€˜csquares’, β€˜gars’, β€˜maidenhead’, β€˜pluscode’, β€˜what3words’, β€˜geohash_int’

Returns:

Builder instance for method chaining

Return type:

GridBuilder

with_precision(precision: int) GridBuilder[source]#

Set explicit precision level.

Parameters:

precision (int) – Precision level (valid range depends on grid system)

Returns:

Builder instance for method chaining

Return type:

GridBuilder

with_auto_precision(recommendation: PrecisionRecommendation | PrecisionSelector) GridBuilder[source]#

Use intelligent precision selection.

Parameters:

recommendation (Union[PrecisionRecommendation, PrecisionSelector]) – Either a recommendation from PrecisionSelector or a selector instance (will use for_use_case(β€˜city’) as default)

Returns:

Builder instance for method chaining

Return type:

GridBuilder

with_spatial_index(enabled: bool = True) GridBuilder[source]#

Enable spatial index usage for intersects operations.

Parameters:

enabled (bool, optional) – Use GeoPandas spatial index when available (default: True)

Returns:

Builder instance for method chaining

Return type:

GridBuilder

at_point(latitude: float, longitude: float) GridBuilder[source]#

Query single point location.

Parameters:
  • latitude (float) – Latitude in decimal degrees

  • longitude (float) – Longitude in decimal degrees

Returns:

Builder instance for method chaining

Return type:

GridBuilder

at_points(points: List[Tuple[float, float]] | ndarray) GridBuilder[source]#

Query multiple point locations (batch operation).

Parameters:

points (Union[List[Tuple[float, float]], np.ndarray]) – List of (latitude, longitude) tuples or Nx2 array

Returns:

Builder instance for method chaining

Return type:

GridBuilder

in_bbox(min_latitude: float, min_longitude: float, max_latitude: float, max_longitude: float) GridBuilder[source]#

Query bounding box region.

Parameters:
  • min_latitude (float) – Minimum latitude

  • min_longitude (float) – Minimum longitude

  • max_latitude (float) – Maximum latitude

  • max_longitude (float) – Maximum longitude

Returns:

Builder instance for method chaining

Return type:

GridBuilder

in_polygon(polygon: Polygon) GridBuilder[source]#

Query cells intersecting polygon.

Parameters:

polygon (Polygon) – Shapely polygon geometry

Returns:

Builder instance for method chaining

Return type:

GridBuilder

find_neighbors(depth: int = 1) GridBuilder[source]#

Find neighbors of query results.

Parameters:

depth (int, optional) – Neighbor ring depth (1 = immediate neighbors, 2 = neighbors + their neighbors, etc.)

Returns:

Builder instance for method chaining

Return type:

GridBuilder

with_children(child_precision: int | None = None) GridBuilder[source]#

Get children of query results at finer precision.

Parameters:

child_precision (Optional[int], optional) – Precision for children (default: current precision + 1)

Returns:

Builder instance for method chaining

Return type:

GridBuilder

with_parent(parent_precision: int | None = None) GridBuilder[source]#

Get parent of query results at coarser precision.

Parameters:

parent_precision (Optional[int], optional) – Precision for parent (default: current precision - 1)

Returns:

Builder instance for method chaining

Return type:

GridBuilder

convert_to(target_system: str, method: str = 'centroid') GridBuilder[source]#

Convert cells to different grid system.

Parameters:
  • target_system (str) – Target grid system name

  • method (str, optional) – Conversion method: β€˜centroid’, β€˜overlap’, or β€˜containment’ (default: β€˜centroid’)

Returns:

Builder instance for method chaining

Return type:

GridBuilder

filter(predicate: Callable[[GridCell], bool]) GridBuilder[source]#

Filter cells by predicate function.

Parameters:

predicate (Callable[[GridCell], bool]) – Function that returns True to keep cell, False to discard

Returns:

Builder instance for method chaining

Return type:

GridBuilder

limit(count: int) GridBuilder[source]#

Limit number of results.

Parameters:

count (int) – Maximum number of cells to return

Returns:

Builder instance for method chaining

Return type:

GridBuilder

execute() GridQueryResult[source]#

Execute the operation pipeline.

Returns:

Type-safe result container

Return type:

GridQueryResult

Raises:

ValueError – If grid system or precision not set, or if no operations specified

class m3s.GridWrapper(grid_class: Type[BaseGrid], default_precision: int, precision_param_name: str = 'precision')[source]#

Bases: object

Simplified wrapper providing easy access to grid systems.

Enables working with grids without requiring upfront precision selection, with intelligent defaults and auto-precision capabilities.

Parameters:
  • grid_class (Type[BaseGrid]) – Grid system class to wrap

  • default_precision (int) – Default precision when not specified

  • precision_param_name (str, optional) – Parameter name for precision (β€˜precision’, β€˜resolution’, β€˜level’, β€˜zoom’)

Examples

>>> # Direct usage without instantiation
>>> cell = m3s.Geohash.from_geometry((40.7, -74.0))
>>> cells = m3s.H3.from_geometry(polygon)
>>>
>>> # With specific precision
>>> cells = m3s.H3.with_precision(8).from_geometry(bbox)
>>>
>>> # Auto-precision selection
>>> precision = m3s.MGRS.find_precision(geometries, method='auto')
>>> cells = m3s.MGRS.from_geometry(geometries, precision=precision)
__init__(grid_class: Type[BaseGrid], default_precision: int, precision_param_name: str = 'precision')[source]#

Initialize grid wrapper.

from_geometry(geometry: Tuple[float, float] | Tuple[float, float, float, float] | Point | Polygon | MultiPolygon | GeoDataFrame, precision: int | None = None) GridCell | GridCellCollection[source]#

Universal method accepting any geometry type.

Parameters:
  • geometry (Union[tuple, Point, Polygon, MultiPolygon, GeoDataFrame]) –

    Input geometry: - Tuple[float, float]: (lat, lon) point - Tuple[float, float, float, float]: (min_lat, min_lon, max_lat,

    max_lon) bbox

    • shapely.Point: Point geometry

    • shapely.Polygon: Polygon geometry

    • shapely.MultiPolygon: MultiPolygon geometry

    • GeoDataFrame: GeoDataFrame with geometries

  • precision (Optional[int], optional) – Precision level (uses default if not specified). For optimal precision, call find_precision() first.

Returns:

Single GridCell for point, GridCellCollection for area geometries

Return type:

Union[GridCell, GridCellCollection]

Notes

For large areas, explicitly finding precision first is recommended:
>>> precision = m3s.H3.find_precision(polygon, method='auto')
>>> cells = m3s.H3.from_geometry(polygon, precision=precision)
from_point(lat: float, lon: float, precision: int | None = None) GridCell[source]#

Get cell at point location.

Parameters:
  • lat (float) – Latitude in decimal degrees

  • lon (float) – Longitude in decimal degrees

  • precision (Optional[int], optional) – Precision level (uses default if not specified)

Returns:

Grid cell containing the point

Return type:

GridCell

from_bbox(bounds: Tuple[float, float, float, float] | List[float], precision: int | None = None) GridCellCollection[source]#

Get cells in bounding box.

Parameters:
  • bounds (Union[Tuple, List]) – (min_lat, min_lon, max_lat, max_lon) or [min_lat, min_lon, max_lat, max_lon]

  • precision (Optional[int], optional) – Precision level (uses default if not specified)

Returns:

Collection of cells intersecting bbox

Return type:

GridCellCollection

from_polygon(geometry: Polygon | MultiPolygon | GeoDataFrame, precision: int | None = None) GridCellCollection[source]#

Get cells intersecting polygon(s).

Parameters:
  • geometry (Union[Polygon, MultiPolygon, GeoDataFrame]) – Polygon geometry or GeoDataFrame

  • precision (Optional[int], optional) – Precision level (uses default if not specified)

Returns:

Collection of cells intersecting geometry

Return type:

GridCellCollection

neighbors(cell: GridCell, depth: int = 1) GridCellCollection[source]#

Get neighbors of a cell.

Parameters:
  • cell (GridCell) – Cell to find neighbors for

  • depth (int, optional) – Neighbor ring depth (default: 1)

Returns:

Collection of neighbor cells (including original cell)

Return type:

GridCellCollection

from_id(identifier: str) GridCell[source]#

Get cell from identifier.

Parameters:

identifier (str) – Cell identifier

Returns:

Grid cell

Return type:

GridCell

Raises:

ValueError – If identifier invalid or precision cannot be determined

with_precision(precision: int) GridWrapper[source]#

Create wrapper with specific precision.

Parameters:

precision (int) – Precision level

Returns:

New wrapper instance with specified default precision

Return type:

GridWrapper

find_precision(geometries: Polygon | MultiPolygon | GeoDataFrame | List[Polygon], method: str | int = 'auto') int[source]#

Find optimal precision for geometries.

Parameters:
  • geometries (Union[Polygon, MultiPolygon, GeoDataFrame, List[Polygon]]) – Input geometries

  • method (Union[str, int], optional) – Selection method: - β€˜auto’: Minimize coverage variance (default) - β€˜less’: Fewer, larger cells - β€˜more’: More, smaller cells - β€˜balanced’: Balance coverage and count - int (e.g., 100): Target specific cell count

Returns:

Optimal precision level

Return type:

int

find_precision_for_area(target_km2: float, tolerance: float = 0.2) int[source]#

Find precision for target cell area.

Parameters:
  • target_km2 (float) – Target cell area in square kilometers

  • tolerance (float, optional) – Acceptable relative error (default: 0.2 = 20%)

Returns:

Precision with cell area closest to target

Return type:

int

find_precision_for_use_case(use_case: str) int[source]#

Find precision for use case.

Parameters:

use_case (str) – Use case: β€˜building’, β€˜block’, β€˜neighborhood’, β€˜city’, β€˜region’, or β€˜country’

Returns:

Recommended precision

Return type:

int

class m3s.GridCellCollection(cells: List[GridCell], grid_wrapper: Any | None = None)[source]#

Bases: object

Container for multiple grid cells with utility methods.

Provides convenient operations for collections of grid cells including conversion to various formats, filtering, hierarchical operations, and cross-grid conversions.

Parameters:
  • cells (List[GridCell]) – List of grid cells

  • grid_wrapper (Optional[Any]) – Reference to parent GridWrapper (for operations requiring grid context)

Examples

>>> cells = GridCellCollection([cell1, cell2, cell3])
>>> gdf = cells.to_gdf()
>>> ids = cells.to_ids()
>>> filtered = cells.filter(lambda c: c.area_km2 > 100)
__init__(cells: List[GridCell], grid_wrapper: Any | None = None)[source]#

Initialize collection with cells and optional grid wrapper.

to_gdf(include_utm: bool = False) GeoDataFrame[source]#

Convert to GeoDataFrame.

Parameters:

include_utm (bool, optional) – Include UTM zone information (default: False)

Returns:

GeoDataFrame with cell geometries and properties

Return type:

gpd.GeoDataFrame

to_ids() List[str][source]#

Get list of cell identifiers.

Returns:

List of cell identifiers

Return type:

List[str]

to_polygons() List[Polygon][source]#

Get list of cell polygons.

Returns:

List of Shapely polygons

Return type:

List[Polygon]

to_dict() Dict[str, Any][source]#

Convert to dictionary format.

Returns:

Dictionary with cells data

Return type:

Dict[str, Any]

filter(predicate: Callable[[GridCell], bool]) GridCellCollection[source]#

Filter cells by predicate function.

Parameters:

predicate (Callable[[GridCell], bool]) – Function that returns True to keep cell, False to discard

Returns:

New collection with filtered cells

Return type:

GridCellCollection

map(func: Callable[[GridCell], Any]) List[Any][source]#

Apply function to each cell.

Parameters:

func (Callable[[GridCell], Any]) – Function to apply to each cell

Returns:

List of function results

Return type:

List[Any]

refine(precision: int) GridCellCollection[source]#

Get children of all cells at higher precision.

Parameters:

precision (int) – Target precision for children (must be higher than current)

Returns:

New collection with child cells

Return type:

GridCellCollection

Raises:

ValueError – If grid wrapper not available or precision invalid

coarsen(precision: int) GridCellCollection[source]#

Get parents of all cells at lower precision.

Parameters:

precision (int) – Target precision for parents (must be lower than current)

Returns:

New collection with parent cells (duplicates removed)

Return type:

GridCellCollection

Raises:

ValueError – If grid wrapper not available or precision invalid

neighbors(depth: int = 1, unique: bool = True) GridCellCollection[source]#

Get neighbors of all cells.

Parameters:
  • depth (int, optional) – Neighbor ring depth (default: 1)

  • unique (bool, optional) – Remove duplicate neighbors (default: True)

Returns:

New collection with neighbor cells

Return type:

GridCellCollection

Raises:

ValueError – If grid wrapper not available

to_h3(method: str = 'centroid') GridCellCollection[source]#

Convert to H3 grid system.

to_geohash(method: str = 'centroid') GridCellCollection[source]#

Convert to Geohash grid system.

to_mgrs(method: str = 'centroid') GridCellCollection[source]#

Convert to MGRS grid system.

to_s2(method: str = 'centroid') GridCellCollection[source]#

Convert to S2 grid system.

to_quadkey(method: str = 'centroid') GridCellCollection[source]#

Convert to Quadkey grid system.

to_slippy(method: str = 'centroid') GridCellCollection[source]#

Convert to Slippy tile grid system.

to_csquares(method: str = 'centroid') GridCellCollection[source]#

Convert to C-squares grid system.

to_gars(method: str = 'centroid') GridCellCollection[source]#

Convert to GARS grid system.

to_maidenhead(method: str = 'centroid') GridCellCollection[source]#

Convert to Maidenhead grid system.

to_pluscode(method: str = 'centroid') GridCellCollection[source]#

Convert to Plus Code grid system.

to_what3words(method: str = 'centroid') GridCellCollection[source]#

Convert to What3Words grid system.

property total_area_km2: float#

Total area of all cells in square kilometers.

Returns:

Sum of all cell areas

Return type:

float

property bounds: Tuple[float, float, float, float]#

Bounding box of all cells.

Returns:

(min_lon, min_lat, max_lon, max_lat)

Return type:

Tuple[float, float, float, float]

__len__() int[source]#

Return number of cells.

__iter__() Iterator[GridCell][source]#

Iterate over cells.

__getitem__(idx: int | slice) GridCell | GridCellCollection[source]#

Get cell by index or slice.

Parameters:

idx (Union[int, slice]) – Index or slice

Returns:

Single cell for int index, collection for slice

Return type:

Union[GridCell, GridCellCollection]

__repr__() str[source]#

Return string representation.

class m3s.PrecisionFinder(grid_wrapper: GridWrapper)[source]#

Bases: object

Find optimal precision for geometries and use cases.

Provides intelligent precision selection based on coverage optimization, target cell counts, and predefined use cases.

Parameters:

grid_wrapper (GridWrapper) – Reference to parent grid wrapper

USE_CASE_AREAS = {'block': (0.01, 0.1), 'building': (0.001, 0.01), 'city': (100.0, 1000.0), 'country': (100000.0, 1000000.0), 'neighborhood': (1.0, 10.0), 'region': (10000.0, 100000.0)}#
__init__(grid_wrapper: GridWrapper)[source]#

Initialize precision finder with grid wrapper.

for_geometries(geometries: Polygon | MultiPolygon | GeoDataFrame | List[Polygon], method: str | int = 'auto') int[source]#

Find optimal precision for geometries.

Parameters:
  • geometries (Union[Polygon, MultiPolygon, gpd.GeoDataFrame, List[Polygon]]) – Input geometries

  • method (Union[str, int], optional) – Selection method: - β€˜auto’: Minimize coverage variance (default, best quality) - β€˜less’: Fewer, larger cells - β€˜more’: More, smaller cells - β€˜balanced’: Balance coverage quality and cell count - int (e.g., 100): Target specific cell count

Returns:

Optimal precision level

Return type:

int

for_area(target_km2: float, tolerance: float = 0.2) int[source]#

Find precision closest to target cell area.

Parameters:
  • target_km2 (float) – Target cell area in square kilometers

  • tolerance (float, optional) – Acceptable relative error (default: 0.2 = 20%)

Returns:

Precision with cell area closest to target

Return type:

int

for_use_case(use_case: str) int[source]#

Find precision for predefined use case.

Parameters:

use_case (str) – Use case name: β€˜building’, β€˜block’, β€˜neighborhood’, β€˜city’, β€˜region’, or β€˜country’

Returns:

Recommended precision for use case

Return type:

int

Raises:

ValueError – If use case not recognized

class m3s.PrecisionSelector(grid_system: str)[source]#

Bases: object

Intelligent precision selection for spatial grid systems.

Provides 5 strategies for selecting optimal precision: 1. Area-based: Target specific cell area 2. Count-based: Target cell count in region 3. Use-case based: Curated presets for common scenarios 4. Distance-based: Target edge length 5. Performance-based: Balance precision vs computation time

__init__(grid_system: str)[source]#

Initialize precision selector for specific grid system.

Parameters:

grid_system (str) – Name of the grid system (e.g., β€˜geohash’, β€˜h3’, β€˜s2’)

for_area(target_area_km2: float, tolerance: float = 0.3, latitude: float | None = None) PrecisionRecommendation[source]#

Select precision based on target cell area.

Parameters:
  • target_area_km2 (float) – Desired cell area in kmΒ²

  • tolerance (float, optional) – Acceptable deviation from target (default: 0.3 = 30%)

  • latitude (Optional[float], optional) – Latitude for distortion correction

Returns:

Recommendation with confidence and explanation

Return type:

PrecisionRecommendation

for_region_count(bounds: Tuple[float, float, float, float], target_count: int, tolerance: float = 0.3) PrecisionRecommendation[source]#

Select precision to achieve target cell count in region.

Parameters:
  • bounds (Tuple[float, float, float, float]) – Bounding box (min_lat, min_lon, max_lat, max_lon)

  • target_count (int) – Desired number of cells

  • tolerance (float, optional) – Acceptable deviation from target count (default: 0.3 = 30%)

Returns:

Recommendation with confidence and explanation

Return type:

PrecisionRecommendation

for_use_case(use_case: str, context: Dict | None = None) PrecisionRecommendation[source]#

Select precision based on curated use case preset.

Parameters:
  • use_case (str) – Use case name: β€˜global’, β€˜continental’, β€˜country’, β€˜region’, β€˜city’, β€˜neighborhood’, β€˜street’, β€˜building’, β€˜room’

  • context (Optional[Dict], optional) – Additional context (e.g., {β€˜latitude’: 40.7} for polar adjustments)

Returns:

Recommendation with high confidence (curated presets)

Return type:

PrecisionRecommendation

for_distance(edge_length_m: float, tolerance: float = 0.3, latitude: float | None = None) PrecisionRecommendation[source]#

Select precision based on target edge length.

Parameters:
  • edge_length_m (float) – Desired edge length in meters

  • tolerance (float, optional) – Acceptable deviation from target (default: 0.3 = 30%)

  • latitude (Optional[float], optional) – Latitude for distortion correction

Returns:

Recommendation with confidence and explanation

Return type:

PrecisionRecommendation

for_performance(operation_type: str, time_budget_ms: float, region_size_km2: float) PrecisionRecommendation[source]#

Select precision balancing detail vs computation time.

Parameters:
  • operation_type (str) – Type of operation: β€˜point_query’, β€˜neighbor’, β€˜intersect’, β€˜contains’, β€˜conversion’, β€˜aggregate’

  • time_budget_ms (float) – Maximum acceptable computation time in milliseconds

  • region_size_km2 (float) – Size of region being processed

Returns:

Recommendation balancing precision vs performance

Return type:

PrecisionRecommendation

class m3s.PrecisionRecommendation(precision: int, confidence: float, explanation: str, actual_area_km2: float | None = None, actual_cell_count: int | None = None, edge_length_m: float | None = None, metadata: Dict | None = None)[source]#

Bases: object

Recommendation for grid precision with confidence and explanation.

precision#

Recommended precision/resolution level

Type:

int

confidence#

Confidence score (0.0 to 1.0) indicating recommendation quality

Type:

float

explanation#

Human-readable explanation of the recommendation

Type:

str

actual_area_km2#

Actual cell area at recommended precision (for area-based selection)

Type:

Optional[float]

actual_cell_count#

Actual cell count in region (for count-based selection)

Type:

Optional[int]

edge_length_m#

Estimated edge length in meters (for distance-based selection)

Type:

Optional[float]

metadata#

Additional metadata about the recommendation

Type:

Optional[Dict]

precision: int#
confidence: float#
explanation: str#
actual_area_km2: float | None = None#
actual_cell_count: int | None = None#
edge_length_m: float | None = None#
metadata: Dict | None = None#
__post_init__()[source]#

Validate confidence is in valid range.

__init__(precision: int, confidence: float, explanation: str, actual_area_km2: float | None = None, actual_cell_count: int | None = None, edge_length_m: float | None = None, metadata: Dict | None = None) None#
class m3s.AreaCalculator(grid_system: str)[source]#

Bases: object

Precomputed area lookup tables for fast precision selection.

This class provides O(1) area lookups for all grid systems with optional latitude-based corrections for systems with significant distortion.

AREA_TABLES = {'csquares': [2827433.39, 282743.34, 2827.43, 28.27, 0.28], 'gars': [155400.0, 6475.0, 269.8], 'geohash': [5003.771, 625.471, 78.184, 19.546, 2.443, 0.61, 0.152, 0.019, 0.0048, 0.0012, 0.0003, 7.4e-05], 'geohash_int': [5003.771, 625.471, 78.184, 19.546, 2.443, 0.61, 0.152, 0.019, 0.0048, 0.0012, 0.0003, 7.4e-05], 'h3': [4357449.416, 609788.441, 86801.78, 12392.264, 1770.323, 252.903, 36.129, 5.161, 0.737, 0.105, 0.015, 0.002, 0.0003, 5e-05, 7e-06, 1e-06], 'maidenhead': [2000000.0, 200000.0, 5000.0, 125.0, 3.125, 0.078], 'mgrs': [10000.0, 100.0, 1.0, 0.01, 0.0001, 1e-06], 'pluscode': [24900000.0, 2490000.0, 249000.0, 24900.0, 3113.0, 389.0, 48.6, 6.1, 0.76, 0.095], 'quadkey': [127516118.0, 31879029.5, 7969757.38, 1992439.34, 498109.84, 124527.46, 31131.86, 7782.97, 1945.74, 486.43, 121.61, 30.4, 7.6, 1.9, 0.47, 0.12, 0.03, 0.007, 0.002, 0.0005, 0.0001, 3e-05, 8e-06], 's2': [85011012.19, 21252753.05, 5313188.26, 1328297.07, 332074.27, 83018.57, 20754.64, 5188.66, 1297.17, 324.29, 81.07, 20.27, 5.07, 1.27, 0.32, 0.08, 0.02, 0.005, 0.001, 0.0003, 8e-05, 2e-05, 5e-06, 1e-06, 3.2e-07, 8e-08, 2e-08, 5e-09, 1e-09, 3.2e-10, 8e-11], 'slippy': [510072000.0, 127518000.0, 31879500.0, 7969875.0, 1992469.0, 498117.0, 124529.0, 31132.0, 7783.0, 1946.0, 486.5, 121.6, 30.4, 7.6, 1.9, 0.475, 0.119, 0.03, 0.007, 0.002, 0.0005], 'what3words': [9e-06]}#
PRECISION_RANGES = {'csquares': (1, 5), 'gars': (1, 3), 'geohash': (1, 12), 'geohash_int': (1, 12), 'h3': (0, 15), 'maidenhead': (1, 6), 'mgrs': (1, 6), 'pluscode': (2, 15), 'quadkey': (1, 23), 's2': (0, 30), 'slippy': (0, 20), 'what3words': (1, 1)}#
__init__(grid_system: str)[source]#

Initialize area calculator for specific grid system.

Parameters:

grid_system (str) – Name of the grid system (e.g., β€˜geohash’, β€˜h3’, β€˜s2’)

get_area(precision: int, latitude: float | None = None) float[source]#

Get cell area at given precision with optional latitude correction.

Parameters:
  • precision (int) – Precision level

  • latitude (Optional[float]) – Latitude for distortion correction (used for Geohash, MGRS)

Returns:

Cell area in kmΒ²

Return type:

float

find_precision_for_area(target_area_km2: float, latitude: float | None = None) int[source]#

Find precision level closest to target area using binary search.

Parameters:
  • target_area_km2 (float) – Desired cell area in kmΒ²

  • latitude (Optional[float]) – Latitude for distortion correction

Returns:

Precision level with area closest to target

Return type:

int

class m3s.PerformanceProfiler[source]#

Bases: object

Empirical performance estimates for grid operations.

Provides timing estimates based on cell counts and operation types to support performance-based precision selection.

OPERATION_COSTS = {'aggregate': 0.02, 'contains': 0.05, 'conversion': 0.5, 'intersect': 0.1, 'neighbor': 0.01, 'point_query': 0.001}#
BASE_OVERHEAD = {'aggregate': 3.0, 'contains': 2.0, 'conversion': 10.0, 'intersect': 5.0, 'neighbor': 1.0, 'point_query': 0.5}#
estimate_operation_time(operation_type: str, cell_count: int, grid_system: str) float[source]#

Estimate operation time in milliseconds.

Parameters:
  • operation_type (str) – Type of operation (β€˜point_query’, β€˜neighbor’, β€˜intersect’, etc.)

  • cell_count (int) – Number of cells involved in operation

  • grid_system (str) – Grid system name (some systems are faster than others)

Returns:

Estimated time in milliseconds

Return type:

float

class m3s.GridQueryResult(cells: GridCell | List[GridCell], metadata: dict | None = None)[source]#

Bases: object

Type-safe container for grid query results.

Provides explicit accessors for single vs multiple cell results, eliminating ambiguity and enabling better type checking.

Examples

>>> result = builder.at_point(40.7, -74.0).execute()
>>> cell = result.single  # Get single cell or raise error
>>> cells = result.many  # Get list of cells (may be empty)
>>> gdf = result.to_geodataframe()  # Convert to GeoPandas
__init__(cells: GridCell | List[GridCell], metadata: dict | None = None)[source]#

Initialize result container.

Parameters:
  • cells (Union[GridCell, List[GridCell]]) – Single cell or list of cells

  • metadata (Optional[dict], optional) – Additional metadata about the query

property single: GridCell#

Get single cell result.

Returns:

The single cell result

Return type:

GridCell

Raises:

ValueError – If result contains zero or multiple cells

property many: List[GridCell]#

Get list of all cells.

Returns:

List of all cells (may be empty)

Return type:

List[GridCell]

first() GridCell | None[source]#

Get first cell or None if empty.

Returns:

First cell or None

Return type:

Optional[GridCell]

is_empty() bool[source]#

Check if result is empty.

Returns:

True if result contains no cells

Return type:

bool

__len__() int[source]#

Return number of cells in result.

__iter__()[source]#

Iterate over cells.

__getitem__(idx)[source]#

Access cell by index.

to_geodataframe() GeoDataFrame[source]#

Convert result to GeoPandas GeoDataFrame.

Returns:

GeoDataFrame with one row per cell, including geometry and attributes

Return type:

gpd.GeoDataFrame

Examples

>>> result = builder.in_bbox(40.7, -74.1, 40.8, -73.9).execute()
>>> gdf = result.to_geodataframe()
>>> print(gdf.columns)
Index(['identifier', 'precision', 'area_km2', 'utm_zone', 'geometry'],
      dtype='object')
to_dataframe() DataFrame[source]#

Convert result to pandas DataFrame (without geometry).

Returns:

DataFrame with cell attributes (no geometry column)

Return type:

pd.DataFrame

__repr__() str[source]#

Return string representation.

__str__() str[source]#

Return human-readable string.

class m3s.MultiGridComparator(grid_configs: List[Tuple[str, int]])[source]#

Bases: object

Compare and analyze multiple grid systems simultaneously.

Provides utilities for querying the same location across different grid systems, comparing coverage characteristics, and analyzing precision equivalence.

Examples

>>> comparator = MultiGridComparator([
...     ('geohash', 5),
...     ('h3', 7),
...     ('s2', 10)
... ])
>>> results = comparator.query_all(40.7128, -74.0060)
>>> df = comparator.compare_coverage((40.7, -74.1, 40.8, -73.9))
__init__(grid_configs: List[Tuple[str, int]])[source]#

Initialize comparator with grid system configurations.

Parameters:

grid_configs (List[Tuple[str, int]]) – List of (grid_system, precision) tuples to compare

query_all(latitude: float, longitude: float) Dict[str, GridCell][source]#

Query same point across all configured grid systems.

Parameters:
  • latitude (float) – Latitude in decimal degrees

  • longitude (float) – Longitude in decimal degrees

Returns:

Map of grid_system -> GridCell at that location

Return type:

Dict[str, GridCell]

query_all_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) Dict[str, List[GridCell]][source]#

Query bounding box across all configured grid systems.

Parameters:
  • min_lat (float) – Minimum latitude

  • min_lon (float) – Minimum longitude

  • max_lat (float) – Maximum latitude

  • max_lon (float) – Maximum longitude

Returns:

Map of grid_system -> list of cells in bbox

Return type:

Dict[str, List[GridCell]]

compare_coverage(bounds: Tuple[float, float, float, float]) DataFrame[source]#

Compare coverage characteristics across grid systems for a region.

Parameters:

bounds (Tuple[float, float, float, float]) – Bounding box (min_lat, min_lon, max_lat, max_lon)

Returns:

Comparison table with columns: system, precision, cell_count, total_area_km2, avg_cell_size_km2, coverage_efficiency

Return type:

pd.DataFrame

analyze_precision_equivalence() DataFrame[source]#

Analyze area-based precision equivalence across all systems.

Returns:

Table showing which precisions are approximately equivalent across grid systems based on average cell area

Return type:

pd.DataFrame

compare_point_coverage(latitude: float, longitude: float) GeoDataFrame[source]#

Visualize how different grid systems cover the same point.

Parameters:
  • latitude (float) – Latitude in decimal degrees

  • longitude (float) – Longitude in decimal degrees

Returns:

GeoDataFrame with one row per grid system showing cell geometries

Return type:

gpd.GeoDataFrame

get_summary_statistics() DataFrame[source]#

Get summary statistics for all configured grid systems.

Returns:

Summary statistics including avg cell area, precision range, etc.

Return type:

pd.DataFrame

find_optimal_precision_for_area(target_area_km2: float) DataFrame[source]#

Find optimal precision in each grid system for target area.

Parameters:

target_area_km2 (float) – Target cell area in kmΒ²

Returns:

Recommendations for each grid system

Return type:

pd.DataFrame

visualize_coverage(bounds: Tuple[float, float, float, float], max_cells_per_system: int = 100) GeoDataFrame[source]#

Create visualization-ready GeoDataFrame showing all grid coverages.

Parameters:
  • bounds (Tuple[float, float, float, float]) – Bounding box (min_lat, min_lon, max_lat, max_lon)

  • max_cells_per_system (int, optional) – Limit cells per system to avoid overwhelming visualizations

Returns:

GeoDataFrame with all cells from all systems

Return type:

gpd.GeoDataFrame

__repr__() str[source]#

Return string representation.

class m3s.ParallelConfig(n_workers: int | None = None, chunk_size: int = 10000, optimize_memory: bool = True, adaptive_chunking: bool = True)[source]#

Bases: object

Configuration for parallel processing operations.

__init__(n_workers: int | None = None, chunk_size: int = 10000, optimize_memory: bool = True, adaptive_chunking: bool = True)[source]#
class m3s.ParallelGridEngine(config: ParallelConfig | None = None)[source]#

Bases: object

Parallel processing engine for spatial grid operations.

Threading-only implementation for moderate-size workloads.

__init__(config: ParallelConfig | None = None)[source]#
intersect_parallel(grid: BaseGrid, gdf: GeoDataFrame, chunk_size: int | None = None) GeoDataFrame[source]#

Perform parallel grid intersection on GeoDataFrame.

Parameters:
  • grid (BaseGrid) – Grid system to use for intersection

  • gdf (gpd.GeoDataFrame) – Input GeoDataFrame

  • chunk_size (int | None, optional) – Size of chunks for parallel processing

Returns:

Results of grid intersection

Return type:

gpd.GeoDataFrame

stream_process(data_stream: Iterator[GeoDataFrame], processor: StreamProcessor, output_callback: Callable[[GeoDataFrame], None] | None = None) GeoDataFrame[source]#

Process streaming geospatial data.

Parameters:
  • data_stream (Iterator[gpd.GeoDataFrame]) – Stream of GeoDataFrame chunks

  • processor (StreamProcessor) – Processor to apply to each chunk

  • output_callback (Callable[[gpd.GeoDataFrame], None] | None, optional) – Callback function called with each processed chunk

Returns:

Combined results from all chunks

Return type:

gpd.GeoDataFrame

batch_intersect_multiple_grids(grids: list[BaseGrid], gdf: GeoDataFrame, grid_names: list[str] | None = None) dict[str, GeoDataFrame][source]#

Intersect GeoDataFrame with multiple grid systems in parallel.

Parameters:
  • grids (list[BaseGrid]) – List of grid systems

  • gdf (gpd.GeoDataFrame) – Input GeoDataFrame

  • grid_names (list[str] | None, optional) – Names for each grid system

Returns:

Results keyed by grid name

Return type:

dict[str, gpd.GeoDataFrame]

get_performance_stats() dict[str, Any][source]#

Get basic performance statistics.

m3s.parallel_intersect(grid: BaseGrid, gdf: GeoDataFrame, config: ParallelConfig | None = None, chunk_size: int | None = None) GeoDataFrame[source]#

Return a convenience wrapper for parallel intersection.

m3s.stream_grid_processing(grid: BaseGrid, data_stream: Iterator[GeoDataFrame], config: ParallelConfig | None = None, output_callback: Callable[[GeoDataFrame], None] | None = None) GeoDataFrame[source]#

Return a convenience wrapper for stream processing.

m3s.create_data_stream(gdf: GeoDataFrame, chunk_size: int = 10000) Iterator[GeoDataFrame][source]#

Create a streaming iterator from a GeoDataFrame.

Parameters:
  • gdf (gpd.GeoDataFrame) – Input GeoDataFrame

  • chunk_size (int) – Size of each chunk

Yields:

gpd.GeoDataFrame – Chunks of the input GeoDataFrame

m3s.create_file_stream(file_paths: list[str], chunk_size: int | None = None) Iterator[GeoDataFrame][source]#

Create a streaming iterator from multiple geospatial files.

Parameters:
  • file_paths (list[str]) – List of file paths to read

  • chunk_size (int | None, optional) – If provided, split large files into chunks

Yields:

gpd.GeoDataFrame – GeoDataFrames loaded from files

class m3s.MemoryMonitor(warn_threshold: float = 0.8, critical_threshold: float = 0.9)[source]#

Bases: object

Monitor and manage memory usage during spatial operations.

__init__(warn_threshold: float = 0.8, critical_threshold: float = 0.9)[source]#

Initialize memory monitor.

Parameters:
  • warn_threshold (float, optional) – Memory usage threshold (0-1) to trigger warning, by default 0.8

  • critical_threshold (float, optional) – Memory usage threshold (0-1) to trigger critical action, by default 0.9

get_memory_usage() dict[source]#

Get current memory usage statistics.

Returns:

Memory usage information including RSS, VMS, and percentage

Return type:

dict

check_memory_pressure() str[source]#

Check current memory pressure level.

Returns:

Memory pressure level: β€˜low’, β€˜medium’, β€˜high’, or β€˜critical’

Return type:

str

suggest_chunk_size(base_chunk_size: int = 10000) int[source]#

Suggest optimal chunk size based on current memory usage.

Parameters:

base_chunk_size (int, optional) – Base chunk size to adjust, by default 10000

Returns:

Recommended chunk size

Return type:

int

class m3s.LazyGeodataFrame(file_path: str | None = None, gdf: GeoDataFrame | None = None, chunk_size: int = 10000)[source]#

Bases: object

Lazy-loading wrapper for GeoDataFrame to minimize memory usage.

Only loads data chunks when needed and releases them after processing.

__init__(file_path: str | None = None, gdf: GeoDataFrame | None = None, chunk_size: int = 10000)[source]#

Initialize lazy GeoDataFrame.

Parameters:
  • file_path (str | None, optional) – Path to geospatial file to load lazily

  • gdf (gpd.GeoDataFrame | None, optional) – Existing GeoDataFrame to wrap

  • chunk_size (int, optional) – Size of chunks for processing, by default 10000

__len__() int[source]#

Get total number of features.

property crs#

Get CRS without loading full dataset.

property bounds#

Get bounds without loading full dataset.

chunks(chunk_size: int | None = None) Iterator[GeoDataFrame][source]#

Iterate over chunks of the GeoDataFrame.

Parameters:

chunk_size (int | None, optional) – Size of chunks, uses instance default if None

Yields:

gpd.GeoDataFrame – Chunks of the original GeoDataFrame

sample(n: int = 1000) GeoDataFrame[source]#

Get a random sample without loading full dataset.

Parameters:

n (int, optional) – Number of samples to return, by default 1000

Returns:

Random sample of features

Return type:

gpd.GeoDataFrame

class m3s.StreamingGridProcessor(grid, memory_monitor: MemoryMonitor | None = None)[source]#

Bases: object

Memory-efficient streaming processor for grid operations.

Processes large datasets in chunks while maintaining minimal memory footprint.

__init__(grid, memory_monitor: MemoryMonitor | None = None)[source]#

Initialize streaming processor.

Parameters:
  • grid (BaseGrid) – Grid system to use for processing

  • memory_monitor (MemoryMonitor | None, optional) – Memory monitor for optimization

process_stream(data_source: LazyGeodataFrame, output_callback: Callable[[GeoDataFrame], None] | None = None, adaptive_chunking: bool = True) Iterator[GeoDataFrame][source]#

Process data stream with memory optimization.

Parameters:
  • data_source (LazyGeodataFrame) – Lazy data source to process

  • output_callback (Callable[[gpd.GeoDataFrame], None] | None, optional) – Callback function for each processed chunk

  • adaptive_chunking (bool, optional) – Whether to adjust chunk size based on memory pressure

Yields:

gpd.GeoDataFrame – Processed chunks

get_processing_stats() dict[source]#

Get processing statistics.

Returns:

Processing statistics including memory usage

Return type:

dict

m3s.optimize_geodataframe_memory(gdf: GeoDataFrame, categorical_threshold: int = 10) GeoDataFrame[source]#

Optimize GeoDataFrame memory usage through type conversion and categorization.

Parameters:
  • gdf (gpd.GeoDataFrame) – Input GeoDataFrame to optimize

  • categorical_threshold (int, optional) – Maximum unique values for categorical conversion, by default 10

Returns:

Memory-optimized GeoDataFrame

Return type:

gpd.GeoDataFrame

m3s.estimate_memory_usage(gdf: GeoDataFrame) dict[source]#

Estimate memory usage of a GeoDataFrame.

Parameters:

gdf (gpd.GeoDataFrame) – GeoDataFrame to analyze

Returns:

Memory usage breakdown by column

Return type:

dict

class m3s.GridConverter[source]#

Bases: object

Utility class for converting between different grid systems.

Provides methods to convert grid cells from one system to another, find equivalent cells, and perform batch conversions.

GRID_SYSTEMS = {'csquares': <class 'm3s.csquares.CSquaresGrid'>, 'gars': <class 'm3s.gars.GARSGrid'>, 'geohash': <class 'm3s.geohash.GeohashGrid'>, 'h3': <class 'm3s.h3.H3Grid'>, 'maidenhead': <class 'm3s.maidenhead.MaidenheadGrid'>, 'mgrs': <class 'm3s.mgrs.MGRSGrid'>, 'pluscode': <class 'm3s.pluscode.PlusCodeGrid'>, 'quadkey': <class 'm3s.quadkey.QuadkeyGrid'>, 's2': <class 'm3s.s2.S2Grid'>, 'slippy': <class 'm3s.slippy.SlippyGrid'>, 'what3words': <class 'm3s.what3words.What3WordsGrid'>}#
DEFAULT_PRECISIONS = {'csquares': 2, 'gars': 2, 'geohash': 5, 'h3': 7, 'maidenhead': 4, 'mgrs': 1, 'pluscode': 4, 'quadkey': 12, 's2': 10, 'slippy': 12, 'what3words': 1}#
__init__() None[source]#
convert_cell(cell: GridCell, target_system: str, target_precision: int | None = None, method: str = 'centroid') GridCell | list[GridCell][source]#

Convert a grid cell to another grid system.

Parameters:
  • cell (GridCell) – Source grid cell to convert

  • target_system (str) – Target grid system name

  • target_precision (int, optional) – Target precision, uses default if None

  • method (str, optional) – Conversion method: β€˜centroid’, β€˜overlap’, or β€˜contains’

Returns:

Converted grid cell(s)

Return type:

GridCell or list[GridCell]

convert_cells_batch(cells: list[GridCell], target_system: str, target_precision: int | None = None, method: str = 'centroid') list[GridCell | list[GridCell]][source]#

Convert multiple grid cells to another system.

Parameters:
  • cells (list[GridCell]) – Source grid cells to convert

  • target_system (str) – Target grid system name

  • target_precision (int, optional) – Target precision, uses default if None

  • method (str) – Conversion method

Returns:

List of converted cells

Return type:

list[GridCell | list[GridCell]]

create_conversion_table(source_system: str, target_system: str, bounds: tuple, source_precision: int | None = None, target_precision: int | None = None, method: str = 'centroid') DataFrame[source]#

Create a conversion table between two grid systems for a given area.

Parameters:
  • source_system (str) – Source grid system name

  • target_system (str) – Target grid system name

  • bounds (tuple) – Bounding box as (min_lon, min_lat, max_lon, max_lat)

  • source_precision (int, optional) – Source precision

  • target_precision (int, optional) – Target precision

  • method (str) – Conversion method

Returns:

Conversion table with mappings

Return type:

pd.DataFrame

get_equivalent_precision(source_system: str, source_precision: int, target_system: str) int[source]#

Find equivalent precision in target system based on cell area.

Parameters:
  • source_system (str) – Source grid system name

  • source_precision (int) – Source precision level

  • target_system (str) – Target grid system name

Returns:

Equivalent precision in target system

Return type:

int

get_system_info() DataFrame[source]#

Get information about all available grid systems.

Returns:

DataFrame with system information

Return type:

pd.DataFrame

m3s.convert_cell(cell: GridCell, target_system: str, **kwargs: Any) GridCell | list[GridCell][source]#

Convert a single grid cell to another system.

m3s.convert_cells(cells: list[GridCell], target_system: str, **kwargs: Any) list[GridCell | list[GridCell]][source]#

Convert multiple grid cells to another system.

m3s.get_equivalent_precision(source_system: str, source_precision: int, target_system: str) int[source]#

Find equivalent precision between grid systems.

m3s.create_conversion_table(source_system: str, target_system: str, bounds: tuple, **kwargs: Any) DataFrame[source]#

Create a conversion table between two grid systems.

m3s.list_grid_systems() DataFrame[source]#

List all available grid systems with information.

class m3s.GridRelationshipAnalyzer(tolerance: float = 1e-09)[source]#

Bases: object

Analyzer for spatial relationships between grid cells.

Provides methods to determine various spatial relationships between individual cells, cell collections, and across different grid systems.

__init__(tolerance: float = 1e-09)[source]#

Initialize the relationship analyzer.

Parameters:

tolerance (float, optional) – Geometric tolerance for spatial operations, by default 1e-9

analyze_relationship(cell1: GridCell, cell2: GridCell) RelationshipType[source]#

Analyze the primary spatial relationship between two grid cells.

Parameters:
  • cell1 (GridCell) – First grid cell

  • cell2 (GridCell) – Second grid cell

Returns:

Primary spatial relationship

Return type:

RelationshipType

get_all_relationships(cell1: GridCell, cell2: GridCell) dict[str, bool][source]#

Get all spatial relationships between two grid cells.

Parameters:
  • cell1 (GridCell) – First grid cell

  • cell2 (GridCell) – Second grid cell

Returns:

Dictionary mapping relationship names to boolean values

Return type:

dict[str, bool]

is_adjacent(cell1: GridCell, cell2: GridCell) bool[source]#

Check if two grid cells are adjacent (share an edge or vertex).

Parameters:
  • cell1 (GridCell) – First grid cell

  • cell2 (GridCell) – Second grid cell

Returns:

True if cells are adjacent

Return type:

bool

find_contained_cells(container: GridCell, cells: list[GridCell]) list[GridCell][source]#

Find all cells that are contained within a container cell.

Parameters:
Returns:

List of contained cells

Return type:

list[GridCell]

find_overlapping_cells(target: GridCell, cells: list[GridCell]) list[GridCell][source]#

Find all cells that overlap with a target cell.

Parameters:
Returns:

List of overlapping cells

Return type:

list[GridCell]

find_adjacent_cells(target: GridCell, cells: list[GridCell]) list[GridCell][source]#

Find all cells that are adjacent to a target cell.

Parameters:
Returns:

List of adjacent cells

Return type:

list[GridCell]

create_relationship_matrix(cells: list[GridCell]) DataFrame[source]#

Create a relationship matrix for a collection of cells.

Parameters:

cells (list[GridCell]) – List of grid cells

Returns:

Matrix showing relationships between all cell pairs

Return type:

pd.DataFrame

create_adjacency_matrix(cells: list[GridCell]) DataFrame[source]#

Create an adjacency matrix for a collection of cells.

Parameters:

cells (list[GridCell]) – List of grid cells

Returns:

Binary adjacency matrix

Return type:

pd.DataFrame

get_topology_statistics(cells: list[GridCell]) dict[str, int | float][source]#

Calculate topological statistics for a collection of cells.

Parameters:

cells (list[GridCell]) – List of grid cells

Returns:

Dictionary of topology statistics

Return type:

dict[str, int | float]

find_clusters(cells: list[GridCell], min_cluster_size: int = 2) list[list[GridCell]][source]#

Find clusters of connected (adjacent) cells.

Parameters:
  • cells (list[GridCell]) – List of grid cells

  • min_cluster_size (int, optional) – Minimum cluster size, by default 2

Returns:

List of cell clusters

Return type:

list[list[GridCell]]

analyze_grid_coverage(cells: list[GridCell], bounds: tuple[float, float, float, float] | None = None) dict[str, float][source]#

Analyze how well cells cover a given area.

Parameters:
  • cells (list[GridCell]) – List of grid cells

  • bounds (tuple[float, float, float, float] | None, optional) – Bounding box as (min_lon, min_lat, max_lon, max_lat) If None, uses cells’ bounding box

Returns:

Coverage statistics

Return type:

dict[str, float]

class m3s.RelationshipType(*values)[source]#

Bases: Enum

Enumeration of spatial relationship types.

CONTAINS = 'contains'#
WITHIN = 'within'#
OVERLAPS = 'overlaps'#
TOUCHES = 'touches'#
ADJACENT = 'adjacent'#
DISJOINT = 'disjoint'#
INTERSECTS = 'intersects'#
EQUALS = 'equals'#
m3s.analyze_relationship(cell1: GridCell, cell2: GridCell) RelationshipType[source]#

Analyze the primary spatial relationship between two cells.

m3s.is_adjacent(cell1: GridCell, cell2: GridCell) bool[source]#

Check if two cells are adjacent.

m3s.find_contained_cells(container: GridCell, cells: list[GridCell]) list[GridCell][source]#

Find cells contained within a container cell.

m3s.find_overlapping_cells(target: GridCell, cells: list[GridCell]) list[GridCell][source]#

Find cells that overlap with a target cell.

m3s.find_adjacent_cells(target: GridCell, cells: list[GridCell]) list[GridCell][source]#

Find cells adjacent to a target cell.

m3s.create_relationship_matrix(cells: list[GridCell]) DataFrame[source]#

Create a relationship matrix for a collection of cells.

m3s.create_adjacency_matrix(cells: list[GridCell]) DataFrame[source]#

Create an adjacency matrix for a collection of cells.

m3s.find_cell_clusters(cells: list[GridCell], min_cluster_size: int = 2) list[list[GridCell]][source]#

Find clusters of connected cells.

m3s.analyze_coverage(cells: list[GridCell], bounds: tuple[float, float, float, float] | None = None) dict[str, float][source]#

Analyze how well cells cover a given area.

class m3s.MultiResolutionGrid(grid_system: BaseGrid, resolution_levels: list[int])[source]#

Bases: object

Multi-resolution grid supporting hierarchical operations.

Supports hierarchical operations across different detail levels. Enables analysis and operations that span multiple resolution levels, including adaptive gridding and level-of-detail processing.

__init__(grid_system: BaseGrid, resolution_levels: list[int])[source]#

Initialize multi-resolution grid.

Parameters:
  • grid_system (BaseGrid) – Base grid system to use

  • resolution_levels (list[int]) – List of precision/resolution levels to support

populate_region(bounds: tuple[float, float, float, float], adaptive: bool = False, density_threshold: float | None = None) dict[int, list[GridCell]][source]#

Populate all resolution levels with cells for a given region.

Parameters:
  • bounds (tuple[float, float, float, float]) – Bounding box as (min_lon, min_lat, max_lon, max_lat)

  • adaptive (bool, optional) – Whether to use adaptive resolution selection, by default False

  • density_threshold (float | None, optional) – Density threshold for adaptive gridding, by default None

Returns:

Dictionary mapping resolution levels to cell lists

Return type:

dict[int, list[GridCell]]

get_hierarchical_cells(point: Point, max_levels: int | None = None) dict[int, GridCell][source]#

Get cells containing a point at all resolution levels.

Parameters:
  • point (Point) – Point to query

  • max_levels (int | None, optional) – Maximum number of levels to return

Returns:

Dictionary mapping resolution levels to cells

Return type:

dict[int, GridCell]

get_parent_child_relationships(bounds: tuple[float, float, float, float]) dict[str, list[str]][source]#

Analyze parent-child relationships between resolution levels.

Parameters:

bounds (tuple[float, float, float, float]) – Bounding box to analyze

Returns:

Dictionary mapping parent cell IDs to lists of child cell IDs

Return type:

dict[str, list[str]]

create_level_of_detail_view(bounds: tuple[float, float, float, float], detail_function: Callable | None = None) GeoDataFrame[source]#

Create a level-of-detail view with adaptive resolution selection.

Parameters:
  • bounds (tuple[float, float, float, float]) – Bounding box

  • detail_function (Callable | None, optional) – Function to determine appropriate detail level for each area

Returns:

GeoDataFrame with adaptive resolution cells

Return type:

gpd.GeoDataFrame

analyze_scale_transitions(bounds: tuple[float, float, float, float]) DataFrame[source]#

Analyze how data transitions between different scale levels.

Parameters:

bounds (tuple[float, float, float, float]) – Bounding box to analyze

Returns:

Analysis of scale transitions

Return type:

pd.DataFrame

aggregate_to_level(data: GeoDataFrame, target_level: int, aggregation_func: str = 'sum') GeoDataFrame[source]#

Aggregate data from finer to coarser resolution level.

Parameters:
  • data (gpd.GeoDataFrame) – Input data with grid cells

  • target_level (int) – Target resolution level index

  • aggregation_func (str, optional) – Aggregation function (β€˜sum’, β€˜mean’, β€˜max’, β€˜min’), by default β€˜sum’

Returns:

Aggregated data

Return type:

gpd.GeoDataFrame

get_resolution_statistics() DataFrame[source]#

Get statistics about all resolution levels.

Returns:

Statistics for each resolution level

Return type:

pd.DataFrame

create_quad_tree_structure(bounds: tuple[float, float, float, float], max_depth: int | None = None) dict[str, Any][source]#

Create a quad-tree-like hierarchical structure.

Parameters:
Returns:

Hierarchical tree structure

Return type:

dict[str, Any]

class m3s.ResolutionLevel(level: int, precision: int, area_km2: float, cells: list[GridCell])[source]#

Bases: object

Represents a resolution level in a multi-resolution grid.

level#

Resolution level identifier

Type:

int

precision#

Grid precision/resolution parameter

Type:

int

area_km2#

Typical cell area at this level

Type:

float

cells#

Grid cells at this resolution level

Type:

list[GridCell]

level: int#
precision: int#
area_km2: float#
cells: list[GridCell]#
__init__(level: int, precision: int, area_km2: float, cells: list[GridCell]) None#
m3s.create_multiresolution_grid(grid_system: BaseGrid, levels: list[int]) MultiResolutionGrid[source]#

Create a multi-resolution grid.

m3s.get_hierarchical_cells(grid: MultiResolutionGrid, point: Point, max_levels: int | None = None) dict[int, GridCell][source]#

Get cells containing a point at all resolution levels.

m3s.create_adaptive_grid(grid_system: BaseGrid, bounds: tuple[float, float, float, float], levels: list[int], detail_function: Callable | None = None) GeoDataFrame[source]#

Create an adaptive resolution grid.