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#

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.

Uses GIS-native (lon, lat) / (x, y) axis order, consistent with bounds and the GridWrapper API.

Returns:

(lon, lat) 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]

area(unit: str = 'km2') float[source]#

Cell area in the requested unit.

Parameters:

unit (str, optional) – One of "km2" (default), "m2", "ha", "mi2".

Returns:

Area expressed in unit.

Return type:

float

Raises:

ValueError – If unit is not recognised.

explore(**kwargs: Any) Any[source]#

Render the cell on an interactive Leaflet map (GeoPandas.explore).

plot(**kwargs: Any) Any[source]#

Plot the cell with matplotlib (GeoPandas.plot).

m3s.base.cell_from_core(core_cell: tuple[str, list[list[float]], int]) GridCell[source]#

Build a GridCell from a shared-core (id, ring, precision) tuple.

The m3s_core bindings return scalar cells as (id, ring, precision) where ring is a closed [lon, lat] ring (GIS axis order, ADR 0001 §4). This wraps that contract once so every grid’s binding-backed methods stay thin.

m3s.base.cells_from_core_packed(packed: tuple[str, Any, Any, Any]) list[GridCell][source]#

Build GridCell objects from a shared-core columnar bulk result.

Bulk operations (cells_in_bbox, children, neighbors) return (ids, coords, offsets, precisions): newline-joined ids plus flat numpy arrays. Geometries are constructed vectorized through shapely.linearrings/polygons (GEOS C loop) — orders of magnitude faster than a per-cell Polygon(ring) Python loop on large results.

m3s.base.nominal_area_km2(grid: BaseGrid, latitude: float | None = None) float[source]#

Nominal cell area for grid at its precision.

With latitude=None (the default) this returns BaseGrid.area_km2 – the canonical nominal, which honours the exact equal-area overrides (a5, rhealpix, eaquad, s2) rather than re-sampling them. Passing an explicit latitude samples the real cell there for the true local area, used by precision selection over a concrete region (its centroid latitude).

Equal-area grids override area_km2 with a latitude-independent exact value, so even with an explicit latitude they return that value (which also avoids sampling a degenerate huge cell, e.g. an s2 level-0 face).

m3s.base.validate_lat_lon(lat: float, lon: float) None[source]#

Validate that a coordinate lies within valid WGS84 bounds.

Parameters:
  • lat (float) – Latitude coordinate

  • lon (float) – Longitude coordinate

Raises:

ValueError – If lat is outside [-90, 90] or lon is outside [-180, 180].

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.

Required interface (abstract): area_km2, get_cell_from_point, get_cell_from_identifier, get_neighbors, get_cells_in_bbox.

Optional hierarchy interface: get_children and get_parent are implemented by the hierarchical grids (H3, S2, Quadkey, Slippy, EAQuad, Geohash, PlusCode, CSquares); get_covering_cells by S2 and Slippy. The remaining grids (MGRS, GARS, Maidenhead) are not hierarchical, so operations that depend on the interface (GridCellCollection.refine/coarsen, the h3-style cell_to_children/cell_to_parent) raise NotImplementedError on them.

Per-grid precision metadata (MIN_PRECISION, MAX_PRECISION, DEFAULT_PRECISION) is the single source of truth for valid precision bounds and the API default. Concrete grids must set all three as class attributes, and each grid’s __init__ validator reads them, so the bounds and the validation can never drift. Consumers (GridWrapper, AreaCalculator, precision finders) derive ranges from these attributes rather than maintaining their own copies.

MIN_PRECISION: ClassVar[int]#
MAX_PRECISION: ClassVar[int]#
DEFAULT_PRECISION: ClassVar[int]#
GRID_NAME: ClassVar[str] = ''#
__init__(precision: int)[source]#
classmethod precision_range() tuple[int, int][source]#

Inclusive (min, max) valid precision for this grid system.

Returns:

(MIN_PRECISION, MAX_PRECISION) for the grid.

Return type:

tuple[int, int]

property area_km2: float#

Theoretical (nominal) area of a cell at this grid’s precision.

A single representative number derived from the shared core: the geodesic area of a reference cell sampled at the canonical latitude (NOMINAL_SAMPLE_LAT, 45°). This is the single source of nominal area across every grid — the former hand-maintained per-grid tables are gone (CONTEXT.md “Area model”). The value is cached per (grid, precision).

For the true area of a specific cell use GridCell.area_km2; for the local area at a given latitude use nominal_area_km2().

Equal-area grids (a5, rhealpix, eaquad) override this with their exact core/analytic value instead of sampling.

Returns:

Nominal area of a single cell in square kilometers.

Return type:

float

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

is_valid_identifier(identifier: str) bool[source]#

Whether identifier parses as a cell at this grid’s precision.

Parameters:

identifier (str) – Candidate cell identifier

Returns:

True if get_cell_from_identifier succeeds

Return type:

bool

identifier_to_precision(identifier: str) int | None[source]#

Native precision/level encoded in identifier, or None if unknown.

Backends whose identifier encodes its own precision should override this so the h3-style verb layer can resolve a cell directly. Returning None signals the caller to fall back to a validated precision sweep.

Parameters:

identifier (str) – Cell identifier

Returns:

Precision encoded in the identifier, or None if not derivable

Return type:

int | None

native_cell_center(identifier: str) tuple[float, float] | None[source]#

Exact (lat, lng) cell center, or None to use the polygon centroid.

Parameters:

identifier (str) – Cell identifier

Returns:

Exact center as (lat, lng), or None if no native center is available

Return type:

tuple[float, float] | None

native_cell_area(identifier: str, unit: str) float | None[source]#

Exact cell area in unit, or None to use the projected polygon area.

Parameters:
  • identifier (str) – Cell identifier

  • unit (str) – Area unit (‘km^2’, ‘m^2’, or ‘rads^2’)

Returns:

Exact area, or None if no native area is available

Return type:

float | None

native_compact(identifiers: list[str]) list[str] | None[source]#

Natively compact a same-precision id set, or None if unsupported.

Returns:

Mixed-precision compacted ids, or None to use the generic path

Return type:

list[str] | None

native_uncompact(identifiers: list[str], res: int) list[str] | None[source]#

Natively expand a compacted id set to res, or None if unsupported.

Returns:

Ids at res, or None to use the generic path

Return type:

list[str] | None

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

Bases: BaseGrid

Base for grids whose interface delegates to the shared Rust core.

A concrete grid sets KEY (its m3s_core function prefix, e.g. "gh" for geohash); the four common operations resolve the matching m3s_core.{KEY}_{op} function and wrap its (id, ring, precision) result via cell_from_core(). This holds the core-call contract in one place instead of repeating it across every grid.

A grid overrides one of these methods only when it adds behaviour beyond the bare delegation – coordinate validation, error re-wrapping, result caching, or non-core geometry (e.g. point-sampled / lattice bounding boxes). The hierarchy interface (get_children / get_parent) is not defined here because its edge semantics differ per grid (some raise at the coarsest level, some return None or the cell itself), so each hierarchical grid keeps its own.

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

Get the cell containing (lat, lon) via the shared core.

get_cell_from_identifier(identifier: str) GridCell[source]#

Get the cell for identifier via the shared core.

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

Get cell’s neighbours via the shared core.

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

Get the cells intersecting the bounding box via the shared core.

Grid Systems#

H3 Grid#

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

class m3s.h3.H3Grid(precision: int = 7)[source]#

Bases: CoreBackedGrid

H3-based hexagonal spatial grid system.

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

KEY: ClassVar[str] = 'h3'#
GRID_NAME: ClassVar[str] = 'H3'#
MIN_PRECISION: ClassVar[int] = 0#
MAX_PRECISION: ClassVar[int] = 15#
DEFAULT_PRECISION: ClassVar[int] = 7#
__init__(precision: int = 7)[source]#

Initialize H3Grid.

Parameters:

precision (int, optional) –

H3 precision level (0-15), by default 7.

Precision 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 is not between 0 and 15

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_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), or an empty list if already at the finest resolution (15).

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

Raises:

ValueError – If the cell is already at the coarsest resolution (0).

get_resolution_info() dict[str, Any][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]

is_valid_identifier(identifier: str) bool[source]#

Validate a cell id via h3.is_valid_cell.

identifier_to_precision(identifier: str) int | None[source]#

Resolution encoded in an H3 id via h3.get_resolution.

native_cell_center(identifier: str) tuple[float, float] | None[source]#

Exact cell center via h3.cell_to_latlng (returns (lat, lng)).

native_cell_area(identifier: str, unit: str) float | None[source]#

Exact spherical cell area via h3.cell_area.

native_compact(identifiers: list[str]) list[str] | None[source]#

Compact via h3.compact_cells.

native_uncompact(identifiers: list[str], res: int) list[str] | None[source]#

Uncompact via h3.uncompact_cells.

Geohash Grid#

Geohash grid implementation.

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

Bases: CoreBackedGrid

Geohash-based spatial grid system.

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

KEY: ClassVar[str] = 'gh'#
GRID_NAME: ClassVar[str] = 'Geohash'#
MIN_PRECISION: ClassVar[int] = 1#
MAX_PRECISION: ClassVar[int] = 12#
DEFAULT_PRECISION: ClassVar[int] = 5#
__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

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_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_children(cell: GridCell) list[GridCell][source]#

Get the 32 child cells one precision level finer.

Geohash is natively hierarchical: a child is the parent identifier with one more base-32 character appended, and the 32 children exactly tile the parent.

Parameters:

cell (GridCell) – Parent cell.

Returns:

The 32 children, or an empty list if already at the finest precision (12).

Return type:

list[GridCell]

get_parent(cell: GridCell) GridCell[source]#

Get the parent cell one precision level coarser.

Parameters:

cell (GridCell) – Child cell.

Returns:

The parent cell (identifier with the last character dropped).

Return type:

GridCell

Raises:

ValueError – If the cell is already at the coarsest precision (1).

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

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

Thin wrapper over get_children() that returns the cell unchanged when it is already at the finest precision.

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 = 3)[source]#

Bases: CoreBackedGrid

MGRS-based spatial grid system.

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

KEY: ClassVar[str] = 'mgrs'#
GRID_NAME: ClassVar[str] = 'MGRS'#
MIN_PRECISION: ClassVar[int] = 0#
MAX_PRECISION: ClassVar[int] = 5#
DEFAULT_PRECISION: ClassVar[int] = 3#
__init__(precision: int = 3)[source]#

Initialize MGRSGrid.

Parameters:

precision (int, optional) –

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

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

get_cell_from_identifier(identifier: str) GridCell[source]#

Get an MGRS cell from its identifier.

identifier_to_precision(identifier: str) int | None[source]#

Decode MGRS precision from the digit count in the identifier.

MGRS precision is the number of digits per easting/northing component: 31UDQ524117 has six numeric digits (three each) → precision 3. Returns None if the identifier is not a recognisable MGRS reference.

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.

The default entry point is the grid-singleton API, which uses GIS-native (lon, lat) coordinate order:

import m3s
cell = m3s.H3.from_geometry((-74.0060, 40.7128))   # (lon, lat)
cells = m3s.H3.from_geometry(polygon)

The *Grid classes and the advanced GridBuilder / PrecisionSelector / MultiGridComparator tools are also available for lower-level and multi-grid work.

m3s.grid(name: str, precision: int | None = None) GridWrapper[source]

Look up a grid system by name.

Enables dynamic / config-driven access without importing each singleton:

g = m3s.grid("h3", precision=7)
cells = g.from_geometry(polygon)
Parameters:
  • name (str) – Grid system name (case-insensitive), e.g. "h3". See grids().

  • precision (int, optional) – If given, return a wrapper bound to this precision.

Returns:

The grid singleton (or a precision-bound copy when precision is set).

Return type:

GridWrapper

Raises:

ValueError – If name is not a known grid system.

m3s.grids() list[str][source]

Sorted names of the available grid systems (for use with grid()).

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.

Required interface (abstract): area_km2, get_cell_from_point, get_cell_from_identifier, get_neighbors, get_cells_in_bbox.

Optional hierarchy interface: get_children and get_parent are implemented by the hierarchical grids (H3, S2, Quadkey, Slippy, EAQuad, Geohash, PlusCode, CSquares); get_covering_cells by S2 and Slippy. The remaining grids (MGRS, GARS, Maidenhead) are not hierarchical, so operations that depend on the interface (GridCellCollection.refine/coarsen, the h3-style cell_to_children/cell_to_parent) raise NotImplementedError on them.

Per-grid precision metadata (MIN_PRECISION, MAX_PRECISION, DEFAULT_PRECISION) is the single source of truth for valid precision bounds and the API default. Concrete grids must set all three as class attributes, and each grid’s __init__ validator reads them, so the bounds and the validation can never drift. Consumers (GridWrapper, AreaCalculator, precision finders) derive ranges from these attributes rather than maintaining their own copies.

MIN_PRECISION: ClassVar[int]
MAX_PRECISION: ClassVar[int]
DEFAULT_PRECISION: ClassVar[int]
GRID_NAME: ClassVar[str] = ''
__init__(precision: int)[source]
classmethod precision_range() tuple[int, int][source]

Inclusive (min, max) valid precision for this grid system.

Returns:

(MIN_PRECISION, MAX_PRECISION) for the grid.

Return type:

tuple[int, int]

property area_km2: float

Theoretical (nominal) area of a cell at this grid’s precision.

A single representative number derived from the shared core: the geodesic area of a reference cell sampled at the canonical latitude (NOMINAL_SAMPLE_LAT, 45°). This is the single source of nominal area across every grid — the former hand-maintained per-grid tables are gone (CONTEXT.md “Area model”). The value is cached per (grid, precision).

For the true area of a specific cell use GridCell.area_km2; for the local area at a given latitude use nominal_area_km2().

Equal-area grids (a5, rhealpix, eaquad) override this with their exact core/analytic value instead of sampling.

Returns:

Nominal area of a single cell in square kilometers.

Return type:

float

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

is_valid_identifier(identifier: str) bool[source]

Whether identifier parses as a cell at this grid’s precision.

Parameters:

identifier (str) – Candidate cell identifier

Returns:

True if get_cell_from_identifier succeeds

Return type:

bool

identifier_to_precision(identifier: str) int | None[source]

Native precision/level encoded in identifier, or None if unknown.

Backends whose identifier encodes its own precision should override this so the h3-style verb layer can resolve a cell directly. Returning None signals the caller to fall back to a validated precision sweep.

Parameters:

identifier (str) – Cell identifier

Returns:

Precision encoded in the identifier, or None if not derivable

Return type:

int | None

native_cell_center(identifier: str) tuple[float, float] | None[source]

Exact (lat, lng) cell center, or None to use the polygon centroid.

Parameters:

identifier (str) – Cell identifier

Returns:

Exact center as (lat, lng), or None if no native center is available

Return type:

tuple[float, float] | None

native_cell_area(identifier: str, unit: str) float | None[source]

Exact cell area in unit, or None to use the projected polygon area.

Parameters:
  • identifier (str) – Cell identifier

  • unit (str) – Area unit (‘km^2’, ‘m^2’, or ‘rads^2’)

Returns:

Exact area, or None if no native area is available

Return type:

float | None

native_compact(identifiers: list[str]) list[str] | None[source]

Natively compact a same-precision id set, or None if unsupported.

Returns:

Mixed-precision compacted ids, or None to use the generic path

Return type:

list[str] | None

native_uncompact(identifiers: list[str], res: int) list[str] | None[source]

Natively expand a compacted id set to res, or None if unsupported.

Returns:

Ids at res, or None to use the generic path

Return type:

list[str] | None

class m3s.A5Grid(precision: int = 8)[source]

Bases: CoreBackedGrid

A5 pentagonal grid system.

Global, equal-area pentagonal DGGS backed by the pya5 library, with exact hierarchical containment (aperture-4 above resolution 1).

precision

Resolution level (0-30). Higher precision means smaller cells: resolution 0 has 12 cells (one per dodecahedron face), resolution 30 cells are smaller than 30 mm^2.

Type:

int

KEY: ClassVar[str] = 'a5'
GRID_NAME: ClassVar[str] = 'A5'
MIN_PRECISION: ClassVar[int] = 0
MAX_PRECISION: ClassVar[int] = 30
DEFAULT_PRECISION: ClassVar[int] = 8
__init__(precision: int = 8)[source]

Initialize A5Grid.

Parameters:

precision (int, optional) – Resolution level (0-30), by default 8 (~520 km^2 cells).

Raises:

ValueError – If precision is not between 0 and 30.

property area_km2: float

Exact area of a cell at this precision in km^2.

A5 is equal-area, so every cell at a given resolution has the same ground area. The value comes straight from the shared core’s authalic, ellipsoid-aware a5_cell_area_m2 (the same a5 crate pya5 wraps) – exact, not the geodesic-sampled nominal the base class would compute.

Returns:

Cell area in square kilometres.

Return type:

float

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

Get the A5 cell containing the given point.

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

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

Returns:

The cell containing the point at this grid’s precision.

Return type:

GridCell

Raises:

ValueError – If coordinates are out of valid range.

get_cell_from_identifier(identifier: str) GridCell[source]

Get an A5 cell from its identifier.

Parameters:

identifier (str) – Hexadecimal cell id (e.g. "63c20e0000000000").

Returns:

The corresponding grid cell.

Return type:

GridCell

Raises:

ValueError – If the identifier is not a valid A5 hexadecimal cell id.

get_parent(cell: GridCell) GridCell[source]

Get the parent cell (one resolution coarser).

Parameters:

cell (GridCell) – Child cell.

Returns:

The parent cell that contains cell.

Return type:

GridCell

Raises:

ValueError – If the cell is already at resolution 0 (no parent).

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

Get the child cells (one resolution finer) that tile this cell.

Parameters:

cell (GridCell) – Parent cell.

Returns:

The children (5 below resolution 1, 4 above), or an empty list if already at the finest resolution (30).

Return type:

list[GridCell]

identifier_to_precision(identifier: str) int | None[source]

Native precision encoded in the identifier, or None if invalid.

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

Bases: CoreBackedGrid

Geohash-based spatial grid system.

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

KEY: ClassVar[str] = 'gh'
GRID_NAME: ClassVar[str] = 'Geohash'
MIN_PRECISION: ClassVar[int] = 1
MAX_PRECISION: ClassVar[int] = 12
DEFAULT_PRECISION: ClassVar[int] = 5
__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

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_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_children(cell: GridCell) list[GridCell][source]

Get the 32 child cells one precision level finer.

Geohash is natively hierarchical: a child is the parent identifier with one more base-32 character appended, and the 32 children exactly tile the parent.

Parameters:

cell (GridCell) – Parent cell.

Returns:

The 32 children, or an empty list if already at the finest precision (12).

Return type:

list[GridCell]

get_parent(cell: GridCell) GridCell[source]

Get the parent cell one precision level coarser.

Parameters:

cell (GridCell) – Child cell.

Returns:

The parent cell (identifier with the last character dropped).

Return type:

GridCell

Raises:

ValueError – If the cell is already at the coarsest precision (1).

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

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

Thin wrapper over get_children() that returns the cell unchanged when it is already at the finest precision.

Parameters:

cell – The cell to expand

Return type:

List of higher precision cells

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

Bases: CoreBackedGrid

MGRS-based spatial grid system.

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

KEY: ClassVar[str] = 'mgrs'
GRID_NAME: ClassVar[str] = 'MGRS'
MIN_PRECISION: ClassVar[int] = 0
MAX_PRECISION: ClassVar[int] = 5
DEFAULT_PRECISION: ClassVar[int] = 3
__init__(precision: int = 3)[source]

Initialize MGRSGrid.

Parameters:

precision (int, optional) –

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

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

get_cell_from_identifier(identifier: str) GridCell[source]

Get an MGRS cell from its identifier.

identifier_to_precision(identifier: str) int | None[source]

Decode MGRS precision from the digit count in the identifier.

MGRS precision is the number of digits per easting/northing component: 31UDQ524117 has six numeric digits (three each) → precision 3. Returns None if the identifier is not a recognisable MGRS reference.

class m3s.H3Grid(precision: int = 7)[source]

Bases: CoreBackedGrid

H3-based hexagonal spatial grid system.

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

KEY: ClassVar[str] = 'h3'
GRID_NAME: ClassVar[str] = 'H3'
MIN_PRECISION: ClassVar[int] = 0
MAX_PRECISION: ClassVar[int] = 15
DEFAULT_PRECISION: ClassVar[int] = 7
__init__(precision: int = 7)[source]

Initialize H3Grid.

Parameters:

precision (int, optional) –

H3 precision level (0-15), by default 7.

Precision 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 is not between 0 and 15

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_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), or an empty list if already at the finest resolution (15).

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

Raises:

ValueError – If the cell is already at the coarsest resolution (0).

get_resolution_info() dict[str, Any][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]

is_valid_identifier(identifier: str) bool[source]

Validate a cell id via h3.is_valid_cell.

identifier_to_precision(identifier: str) int | None[source]

Resolution encoded in an H3 id via h3.get_resolution.

native_cell_center(identifier: str) tuple[float, float] | None[source]

Exact cell center via h3.cell_to_latlng (returns (lat, lng)).

native_cell_area(identifier: str, unit: str) float | None[source]

Exact spherical cell area via h3.cell_area.

native_compact(identifiers: list[str]) list[str] | None[source]

Compact via h3.compact_cells.

native_uncompact(identifiers: list[str], res: int) list[str] | None[source]

Uncompact via h3.uncompact_cells.

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

Bases: CoreBackedGrid

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.

KEY: ClassVar[str] = 'cs'
GRID_NAME: ClassVar[str] = 'C-squares'
MIN_PRECISION: ClassVar[int] = 1
MAX_PRECISION: ClassVar[int] = 5
DEFAULT_PRECISION: ClassVar[int] = 5
__init__(precision: int = 5)[source]

Initialize CSquaresGrid.

Parameters:

precision (int, optional) –

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

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_children(cell: GridCell) list[GridCell][source]

Get the child cells one precision level finer.

C-squares nest exactly, but the aperture varies by level (10 deg -> 5 deg is 2x2, 5 deg -> 1 deg is 5x5, etc.). Children are produced by re-encoding each finer-cell centre, so identifiers stay canonical and the per-level aperture is handled automatically.

Parameters:

cell (GridCell) – Parent cell.

Returns:

The child cells, or an empty list if already at the finest precision.

Return type:

list[GridCell]

get_parent(cell: GridCell) GridCell[source]

Get the parent cell one precision level coarser.

Parameters:

cell (GridCell) – Child cell.

Returns:

The parent cell that contains cell.

Return type:

GridCell

Raises:

ValueError – If the cell is already at the coarsest precision.

get_precision_info() dict[str, Any][source]

Get detailed information about the current precision level.

Returns:

Dictionary containing precision metrics including cell size and coverage information

Return type:

dict

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

Bases: CoreBackedGrid

GARS (Global Area Reference System) spatial grid.

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

KEY: ClassVar[str] = 'gars'
GRID_NAME: ClassVar[str] = 'GARS'
MIN_PRECISION: ClassVar[int] = 1
MAX_PRECISION: ClassVar[int] = 3
DEFAULT_PRECISION: ClassVar[int] = 2
__init__(precision: int = 2)[source]

Initialize GARSGrid.

Parameters:

precision (int, optional) –

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

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

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[float, float, float, float][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

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

Bases: CoreBackedGrid

Maidenhead locator system spatial grid.

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

KEY: ClassVar[str] = 'mh'
GRID_NAME: ClassVar[str] = 'Maidenhead'
MIN_PRECISION: ClassVar[int] = 1
MAX_PRECISION: ClassVar[int] = 4
DEFAULT_PRECISION: ClassVar[int] = 4
__init__(precision: int = 4)[source]

Initialize MaidenheadGrid.

Parameters:

precision (int, optional) –

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

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

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[float, float, float, float][source]

Decode a Maidenhead locator into latitude/longitude bounds.

Parameters:

locator (str) – Maidenhead locator string

Returns:

(south, west, north, east) bounds

Return type:

tuple

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

Bases: CoreBackedGrid

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.

KEY: ClassVar[str] = 'pc'
GRID_NAME: ClassVar[str] = 'Plus code'
MIN_PRECISION: ClassVar[int] = 1
MAX_PRECISION: ClassVar[int] = 7
DEFAULT_PRECISION: ClassVar[int] = 5
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 = 5)[source]

Initialize PlusCodeGrid.

Parameters:

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

Raises:

ValueError – If precision is not between 1 and 7

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[float, float, float, float][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_children(cell: GridCell) list[GridCell][source]

Get the child cells one precision level finer.

Plus Codes nest exactly: each level subdivides a cell into BASE x BASE (20 x 20 = 400) children that tile it. Children are produced by re-encoding each sub-cell centre at the finer precision, so identifiers are always canonical.

Parameters:

cell (GridCell) – Parent cell.

Returns:

The child cells, or an empty list if already at the finest precision.

Return type:

list[GridCell]

get_parent(cell: GridCell) GridCell[source]

Get the parent cell one precision level coarser.

Parameters:

cell (GridCell) – Child cell.

Returns:

The parent cell that contains cell.

Return type:

GridCell

Raises:

ValueError – If the cell is already at the coarsest precision.

class m3s.QuadkeyGrid(precision: int = 12)[source]

Bases: CoreBackedGrid

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.

precision

Precision (zoom) level of the quadkey tiles (1-23)

Type:

int

KEY: ClassVar[str] = 'qk'
GRID_NAME: ClassVar[str] = 'Quadkey'
MIN_PRECISION: ClassVar[int] = 1
MAX_PRECISION: ClassVar[int] = 23
DEFAULT_PRECISION: ClassVar[int] = 12
__init__(precision: int = 12)[source]

Initialize Quadkey grid.

Parameters:

precision (int, optional) – Precision level for quadkey tiles (1-23), by default 12.

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_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_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 = 10)[source]

Bases: CoreBackedGrid

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.

precision

S2 cell precision (0-30), where higher values provide smaller cells

Type:

int

KEY: ClassVar[str] = 's2'
GRID_NAME: ClassVar[str] = 'S2'
MIN_PRECISION: ClassVar[int] = 0
MAX_PRECISION: ClassVar[int] = 30
DEFAULT_PRECISION: ClassVar[int] = 10
__init__(precision: int = 10)[source]

Initialize S2 grid.

Parameters:

precision (int, optional) – S2 cell precision level (0-30), by default 10. Precision 0: ~85,000 km edge length Precision 10: ~1,300 km edge length Precision 20: ~20 m edge length Precision 30: ~1 cm edge length

property area_km2: float

Nominal area of an S2 cell at this level in km^2.

S2 cells are approximately equal-area by construction, so the nominal size is analytic — Earth’s surface split across 6 * 4 ** level cells. Used instead of geodesic sampling because a level-0 S2 cell spans a sixth of the planet, where sampling a single ring degenerates.

Returns:

Nominal cell area in square kilometres.

Return type:

float

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_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[source]

Get parent cell at the previous level.

Parameters:

cell (GridCell) – Child cell

Returns:

Parent cell

Return type:

GridCell

Raises:

ValueError – If the cell is already at the coarsest level (0).

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]

Notes

Takes the level-precision cells of the polygon’s bounding box (from the shared core’s s2_cells_in_bbox) and keeps those that actually intersect the polygon, capped at max_cells. This replaces the former s2sphere.RegionCoverer path; the result is the set of cells covering the polygon at this precision.

class m3s.SlippyGrid(precision: int = 12)[source]

Bases: CoreBackedGrid

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.

precision

Precision (zoom) level (0-22), where higher values provide smaller tiles

Type:

int

KEY: ClassVar[str] = 'sl'
GRID_NAME: ClassVar[str] = 'Slippy'
MIN_PRECISION: ClassVar[int] = 0
MAX_PRECISION: ClassVar[int] = 22
DEFAULT_PRECISION: ClassVar[int] = 12
__init__(precision: int = 12)[source]

Initialize Slippy Map Tiling grid.

Parameters:

precision (int, optional) – Precision (zoom) level (0-22), by default 12. Precision 0: 1 tile covering the world Precision 1: 2×2 = 4 tiles Precision 10: 1024×1024 = ~1M tiles (~40km tiles) Precision 15: 32768×32768 = ~1B tiles (~1.2km tiles) Precision 18: 262144×262144 tiles (~150m tiles)

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_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[source]

Get parent tile at the previous zoom level.

Parameters:

cell (GridCell) – Child tile

Returns:

Parent tile

Return type:

GridCell

Raises:

ValueError – If the tile is already at the coarsest zoom level (0).

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.EAQuadGrid(precision: int = 4)[source]

Bases: CoreBackedGrid

EA-Quad (Equal-Area Quadtree) grid system.

Global square quadtree grid on an equal-area projection (EPSG:6933) with power-of-two cell edges and exact hierarchical containment.

precision

Precision level (0-20). Higher precision means smaller cells. size_km == 2 ** (10 - precision) so precision 0 = 1024 km, precision 10 = 1 km and precision 20 ~ 0.98 m.

Type:

int

KEY: ClassVar[str] = 'eaq'
GRID_NAME: ClassVar[str] = 'EA-Quad'
MIN_PRECISION: ClassVar[int] = 0
MAX_PRECISION: ClassVar[int] = 20
DEFAULT_PRECISION: ClassVar[int] = 4
__init__(precision: int = 4)[source]

Initialize EAQuadGrid.

Parameters:

precision (int, optional) –

Precision level (0-20), by default 4 (64 km cells).

precision

cell edge

0

1024 km

4

64 km

10

1 km

14

62.5 m

20

~0.98 m

Raises:

ValueError – If precision is not between 0 and 20.

property size_km: float

Cell edge length in kilometres at this grid’s precision.

property area_km2: float

Exact nominal area of a cell at this precision in km^2.

EPSG:6933 is an equal-area projection, so the nominal cell area is analytic and constant worldwide: size_km ** 2 – exact, not the geodesic-sampled value the base class would compute. (The easternmost/northernmost cells are clipped to the projection domain and are physically smaller; use native_cell_area() for an individual cell’s exact clipped area.)

Returns:

Nominal area in square kilometres.

Return type:

float

native_cell_area(identifier: str, unit: str) float | None[source]

Exact ground area of a cell, accounting for domain clipping.

The projection is equal-area, so a cell’s true ground area equals its projected rectangle’s area after clipping to the EPSG:6933 domain – analytic, with no polygon involved. Interior cells report the nominal size_km ** 2; the easternmost/northernmost (and polar) cells report their physically smaller clipped area.

Parameters:
  • identifier (str) – Cell identifier (hex token).

  • unit (str) – Area unit: 'km^2', 'm^2' or 'rads^2'.

Returns:

Exact area in unit, or None for an unknown unit.

Return type:

float | None

Raises:

ValueError – If the identifier is invalid.

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

Get the EA-Quad cell containing the given point.

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

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

Returns:

The cell containing the point at this grid’s precision.

Return type:

GridCell

Raises:

ValueError – If coordinates are out of valid range.

get_parent(cell: GridCell) GridCell[source]

Get the parent cell (one level coarser, double the edge length).

Parameters:

cell (GridCell) – Child cell.

Returns:

The parent cell that exactly contains cell.

Return type:

GridCell

Raises:

ValueError – If the cell is already at the coarsest level (1024 km).

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

Get the 4 child cells (one level finer) that exactly tile this cell.

Parameters:

cell (GridCell) – Parent cell.

Returns:

The 4 children, or an empty list if already at the finest level (~0.98 m).

Return type:

list[GridCell]

identifier_to_precision(identifier: str) int | None[source]

Native precision encoded in the identifier, or None if invalid.

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

Bases: CoreBackedGrid

rHEALPix equal-area DGGS grid system.

Global aperture-9 quadtree on the rHEALPix projection (WGS84 ellipsoid, N_side = 3, polar squares at position 0) with exact hierarchical containment, equal-area cells and bounded shape distortion.

precision

Resolution level (0-15). Higher precision means smaller cells: resolution 0 has 6 cells (one per face), and each resolution divides the cell area by 9.

Type:

int

KEY: ClassVar[str] = 'rhp'
GRID_NAME: ClassVar[str] = 'rHEALPix'
MIN_PRECISION: ClassVar[int] = 0
MAX_PRECISION: ClassVar[int] = 15
DEFAULT_PRECISION: ClassVar[int] = 5
__init__(precision: int = 5)[source]

Initialize RHEALPixGrid.

Parameters:

precision (int, optional) –

Resolution level (0-15), by default 5 (~1440 km^2, ~38 km cells).

precision

cell area

0

~85 M km^2

3

~116,600 km^2

5

~1,440 km^2

10

~0.024 km^2

15

~6.2 m^2

Raises:

ValueError – If precision is not between 0 and 15.

property area_km2: float

Exact area of a cell at this resolution in km^2.

rHEALPix is equal-area, so every cell at a given resolution has the same ground area: (2*pi/3) * R_A^2 / 9 ** resolution with R_A the WGS84 authalic radius. Taken straight from the shared core (rhp_cell_area_km2) – exact, not the geodesic-sampled nominal the base class would compute.

Returns:

Cell area in square kilometres.

Return type:

float

native_cell_area(identifier: str, unit: str) float | None[source]

Exact cell area in unit (equal-area: identical for every cell).

Parameters:
  • identifier (str) – Cell identifier (SUID).

  • unit (str) – Area unit: 'km^2', 'm^2' or 'rads^2'.

Returns:

Exact area in unit, or None for an unknown unit.

Return type:

float | None

Raises:

ValueError – If the identifier is invalid.

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

Get the rHEALPix cell containing the given point.

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

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

Returns:

The cell containing the point at this grid’s precision.

Return type:

GridCell

Raises:

ValueError – If coordinates are out of valid range.

get_parent(cell: GridCell) GridCell[source]

Get the parent cell (one resolution coarser; drop the last digit).

Parameters:

cell (GridCell) – Child cell.

Returns:

The parent cell that exactly contains cell.

Return type:

GridCell

Raises:

ValueError – If the cell is already a resolution 0 face.

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

Get the 9 child cells (one resolution finer) that exactly tile this cell.

Parameters:

cell (GridCell) – Parent cell.

Returns:

The 9 children, or an empty list if already at the finest resolution (15).

Return type:

list[GridCell]

identifier_to_precision(identifier: str) int | None[source]

Native resolution encoded in the identifier, or None if invalid.

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 10 grid systems through a unified interface.

Examples

Basic single-point query:

>>> result = (GridBuilder
...     .for_system('h3')
...     .with_precision(7)
...     .at_point(-74.0060, 40.7128)
...     .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(-74.0060, 40.7128)
...     .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(-74.1, 40.7, -73.9, 40.8)
...     .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(-74.0060, 40.7128)
...     .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’, ‘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(longitude: float, latitude: float) GridBuilder[source]

Query single point location.

Uses GIS-native (lon, lat) / (x, y) argument order.

Parameters:
  • longitude (float) – Longitude in decimal degrees

  • latitude (float) – Latitude 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 (longitude, latitude) tuples or Nx2 array, GIS-native order

Returns:

Builder instance for method chaining

Return type:

GridBuilder

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

Query bounding box region.

Uses GIS-native (min_lon, min_lat, max_lon, max_lat) argument order.

Parameters:
  • min_longitude (float) – Minimum longitude

  • min_latitude (float) – Minimum latitude

  • max_longitude (float) – Maximum longitude

  • max_latitude (float) – Maximum latitude

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 | None = None)[source]

Bases: H3VerbsMixin

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, optional) – Default precision when not specified. Defaults to the grid class’s DEFAULT_PRECISION.

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 | None = None)[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.

Uses GIS-native (lon, lat) / (x, y) axis order for tuples, consistent with shapely, geopandas and pyproj.

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

    Input geometry:

    • Tuple[float, float]: (lon, lat) point

    • Tuple[float, float, float, float]: (min_lon, min_lat, max_lon, max_lat) 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 a point, GridCellCollection for area geometries. A 2-tuple is treated as a point, a 4-tuple as a bbox.

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(lon: float, lat: float, precision: int | None = None) GridCell[source]

Get cell at point location.

Uses GIS-native (lon, lat) / (x, y) axis order, consistent with shapely, geopandas and pyproj.

Parameters:
  • lon (float) – Longitude in decimal degrees

  • lat (float) – Latitude 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_lon, min_lat, max_lon, max_lat), GIS-native axis order. Matches GridCell.bounds / GridCellCollection.bounds, so grid.from_bbox(collection.bounds) round-trips correctly.

  • 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, include_self: bool = True) GridCellCollection[source]

Get neighbors of a cell.

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

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

  • include_self (bool, optional) – Include the origin cell in the result (default: True)

Returns:

Collection of neighbor cells (the origin cell is included only when include_self is True)

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

from_ids(identifiers: List[str]) GridCellCollection[source]

Build a collection from a list of cell identifiers.

Inverse of GridCellCollection.ids / GridCellCollection.to_ids(), so a saved identifier list round-trips into a wrapper-aware collection.

Parameters:

identifiers (List[str]) – Cell identifiers belonging to this grid system.

Returns:

Resolved cells (wrapper-aware, so refine/neighbors work).

Return type:

GridCellCollection

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: ‘global’, ‘continental’, ‘country’, ‘region’, ‘city’, ‘neighborhood’, ‘street’, ‘building’, or ‘room’

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]

to_geojson() Dict[str, Any][source]

Convert to a GeoJSON FeatureCollection.

Returns:

GeoJSON FeatureCollection with one feature per cell.

Return type:

Dict[str, Any]

save(path: str, driver: str | None = None, **kwargs: Any) str[source]

Write the cells to a vector file (GeoJSON, GeoPackage, Shapefile, …).

Parameters:
  • path (str) – Output path. The driver is inferred from the extension when driver is not given (.geojson → GeoJSON, .gpkg → GPKG, .shp → ESRI Shapefile).

  • driver (str, optional) – Explicit OGR driver name, overriding extension inference.

  • **kwargs – Forwarded to GeoDataFrame.to_file.

Returns:

The path written to.

Return type:

str

explore(**kwargs: Any) Any[source]

Render the cells on an interactive Leaflet map.

Thin delegate to GeoDataFrame.explore (folium). Any keyword arguments (column, tooltip, tiles, …) are forwarded.

Returns:

Interactive map of the cells.

Return type:

folium.Map

plot(**kwargs: Any) Any[source]

Plot the cells with matplotlib.

Thin delegate to GeoDataFrame.plot; all keyword arguments are forwarded. Reproject the result of to_gdf() yourself if you need a basemap-aligned CRS (e.g. EPSG:3857).

Returns:

The axes drawn on.

Return type:

matplotlib.axes.Axes

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]

unique() GridCellCollection[source]

Drop duplicate cells (by identifier), preserving order.

Returns:

New collection without duplicate cells.

Return type:

GridCellCollection

dissolve() BaseGeometry[source]

Merge all cell polygons into a single geometry.

Useful for the outer boundary of a covered region.

Returns:

Union of all cell polygons (empty Polygon if no cells).

Return type:

shapely.geometry.base.BaseGeometry

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.

property ids: List[str]

List of cell identifiers (alias for to_ids()).

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.

__add__(other: GridCellCollection) GridCellCollection[source]

Merge two collections, dropping duplicate cells (by identifier).

Returns:

Combined, de-duplicated collection. Keeps this collection’s grid wrapper when both share one.

Return type:

GridCellCollection

__contains__(item: object) bool[source]

Membership test by GridCell or identifier string.

__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

__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.

Delegates to the shared PrecisionSelector (single area source).

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 a predefined use case.

Delegates to the shared PrecisionSelector, whose per-grid curated presets are the single use-case table.

Parameters:

use_case (str) – Use case name: ‘global’, ‘continental’, ‘country’, ‘region’, ‘city’, ‘neighborhood’, ‘street’, ‘building’, or ‘room’.

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[str, Any] | 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[str, Any] | 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[str, Any] | None = None
__post_init__() None[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[str, Any] | None = None) None
class m3s.AreaCalculator(grid_system: str)[source]

Bases: object

Nominal cell-area lookups for precision selection.

Areas come from the shared core via geodesic sampling (m3s.base.nominal_area_km2()) — the single source of nominal area, so this can never drift from Grid.area_km2. Each sampled (grid, precision) value is cached, so after first touch it is effectively an O(1) lookup. Passing a latitude samples the cell there for the true local area (used by region-based selection); omitting it uses the canonical 45° nominal.

The valid precision range comes from the grid class (MIN_PRECISION/MAX_PRECISION), the single source of truth.

__init__(grid_system: str)[source]

Initialize area calculator for a specific grid system.

Parameters:

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

property area_table: list[float]

Nominal area (km²) at each precision in range, sampled at canonical 45°.

Derived on demand from the per-precision sampled areas (each cached), so it stays consistent with get_area() and Grid.area_km2.

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

Nominal cell area at precision, optionally sampled at latitude.

Parameters:
  • precision (int) – Precision level.

  • latitude (Optional[float]) – Latitude to sample at, for the true local area. Defaults to the canonical nominal latitude (45°).

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[str, Any] | 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[str, Any] | 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__() Iterator[GridCell][source]

Iterate over cells.

__getitem__(idx: int | slice) GridCell | List[GridCell][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(-74.0060, 40.7128)
>>> df = comparator.compare_coverage((-74.1, 40.7, -73.9, 40.8))
__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(longitude: float, latitude: float) Dict[str, GridCell][source]

Query same point across all configured grid systems.

Uses GIS-native (lon, lat) argument order.

Parameters:
  • longitude (float) – Longitude in decimal degrees

  • latitude (float) – Latitude in decimal degrees

Returns:

Map of grid_system -> GridCell at that location

Return type:

Dict[str, GridCell]

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

Query bounding box across all configured grid systems.

Uses GIS-native (min_lon, min_lat, max_lon, max_lat) argument order.

Parameters:
  • min_lon (float) – Minimum longitude

  • min_lat (float) – Minimum latitude

  • max_lon (float) – Maximum longitude

  • max_lat (float) – Maximum latitude

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_lon, min_lat, max_lon, max_lat), GIS-native order

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(longitude: float, latitude: float) GeoDataFrame[source]

Visualize how different grid systems cover the same point.

Uses GIS-native (lon, lat) argument order.

Parameters:
  • longitude (float) – Longitude in decimal degrees

  • latitude (float) – Latitude 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_lon, min_lat, max_lon, max_lat), GIS-native order

  • 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[str, float][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: Any

Get CRS without loading full dataset.

property bounds: Any

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: Any, 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: Any, 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[str, Any][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[str, float][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: dict[str, type[BaseGrid]] = {'a5': <class 'm3s.a5.A5Grid'>, 'csquares': <class 'm3s.csquares.CSquaresGrid'>, 'eaquad': <class 'm3s.eaquad.EAQuadGrid'>, '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'>, 'rhealpix': <class 'm3s.rhealpix.RHEALPixGrid'>, 's2': <class 'm3s.s2.S2Grid'>, 'slippy': <class 'm3s.slippy.SlippyGrid'>}
DEFAULT_PRECISIONS = {'a5': 9, 'csquares': 2, 'eaquad': 4, 'gars': 2, 'geohash': 5, 'h3': 7, 'maidenhead': 4, 'mgrs': 1, 'pluscode': 4, 'quadkey': 12, 'rhealpix': 5, 's2': 10, 'slippy': 12}
__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[float, float, float, float], 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[float, float, float, float], **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:
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:
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:
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[[...], Any] | 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[[...], Any] | None = None) GeoDataFrame[source]

Create an adaptive resolution grid.