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:
objectRepresents a single grid cell.
A GridCell contains an identifier, geometric polygon representation, and precision level for spatial indexing systems.
- 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:
- property centroid: tuple[float, float]#
Centroid of the cell.
Uses GIS-native (lon, lat) / (x, y) axis order, consistent with
boundsand theGridWrapperAPI.
- 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:
- Raises:
ValueError – If
unitis not recognised.
- m3s.base.cell_from_core(core_cell: tuple[str, list[list[float]], int]) GridCell[source]#
Build a
GridCellfrom a shared-core(id, ring, precision)tuple.The
m3s_corebindings return scalar cells as(id, ring, precision)whereringis 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
GridCellobjects 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 throughshapely.linearrings/polygons(GEOS C loop) — orders of magnitude faster than a per-cellPolygon(ring)Python loop on large results.
- m3s.base.nominal_area_km2(grid: BaseGrid, latitude: float | None = None) float[source]#
Nominal cell area for
gridat its precision.With
latitude=None(the default) this returnsBaseGrid.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_km2with 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:
- Raises:
ValueError – If
latis outside [-90, 90] orlonis outside [-180, 180].
- class m3s.base.BaseGrid(precision: int)[source]#
Bases:
ABCAbstract 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_childrenandget_parentare implemented by the hierarchical grids (H3, S2, Quadkey, Slippy, EAQuad, Geohash, PlusCode, CSquares);get_covering_cellsby S2 and Slippy. The remaining grids (MGRS, GARS, Maidenhead) are not hierarchical, so operations that depend on the interface (GridCellCollection.refine/coarsen, the h3-stylecell_to_children/cell_to_parent) raiseNotImplementedErroron 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.- classmethod precision_range() tuple[int, int][source]#
Inclusive
(min, max)valid precision for this grid system.
- 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 usenominal_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:
- abstractmethod get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the grid cell containing the given point.
- abstractmethod get_cell_from_identifier(identifier: str) GridCell[source]#
Get a grid cell from its identifier.
- abstractmethod get_neighbors(cell: GridCell) list[GridCell][source]#
Get neighboring cells of the given cell.
- 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:
- Returns:
List of grid cells that intersect the bounding box
- Return type:
- contains_point(polygon: Polygon, lat: float, lon: float) bool[source]#
Check if a point is contained within the polygon.
- 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:
- Returns:
GeoDataFrame with grid cell identifiers, geometries, and original data
- Return type:
gpd.GeoDataFrame
- is_valid_identifier(identifier: str) bool[source]#
Whether
identifierparses as a cell at this grid’s precision.
- 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.
- native_cell_center(identifier: str) tuple[float, float] | None[source]#
Exact
(lat, lng)cell center, or None to use the polygon centroid.
- native_cell_area(identifier: str, unit: str) float | None[source]#
Exact cell area in
unit, or None to use the projected polygon area.
- class m3s.base.CoreBackedGrid(precision: int)[source]#
Bases:
BaseGridBase for grids whose interface delegates to the shared Rust core.
A concrete grid sets
KEY(itsm3s_corefunction prefix, e.g."gh"for geohash); the four common operations resolve the matchingm3s_core.{KEY}_{op}function and wrap its(id, ring, precision)result viacell_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 returnNoneor the cell itself), so each hierarchical grid keeps its own.- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the cell containing
(lat, lon)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:
CoreBackedGridH3-based hexagonal spatial grid system.
Implements Uber’s H3 hexagonal hierarchical spatial indexing system, providing uniform hexagonal cells with consistent neighbor relationships.
- __init__(precision: int = 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:
- 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:
- 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:
- 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:
- 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:
- 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.
- uncompact_cells(cells: list[GridCell], target_resolution: int) list[GridCell][source]#
Uncompact cells to a target resolution, expanding parent cells to children.
- 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)).
Geohash Grid#
Geohash grid implementation.
- class m3s.geohash.GeohashGrid(precision: int = 5)[source]#
Bases:
CoreBackedGridGeohash-based spatial grid system.
Implements the Geohash spatial indexing system using base-32 encoding to create hierarchical rectangular grid cells.
- __init__(precision: int = 5)[source]#
Initialize GeohashGrid.
- Parameters:
precision (int, optional) – Geohash precision level (1-12), by default 5. Higher values mean smaller cells.
- Raises:
ValueError – If precision is not between 1 and 12
- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the geohash cell containing the given point.
- 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.
- 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:
- 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:
CoreBackedGridMGRS-based spatial grid system.
Implements the Military Grid Reference System (MGRS) for creating uniform square grid cells based on UTM projections.
- __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
- 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:
31UDQ524117has 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:
- Returns:
The grid singleton (or a precision-bound copy when
precisionis set).- Return type:
GridWrapper
- Raises:
ValueError – If
nameis not a known grid system.
- class m3s.BaseGrid(precision: int)[source]
Bases:
ABCAbstract 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_childrenandget_parentare implemented by the hierarchical grids (H3, S2, Quadkey, Slippy, EAQuad, Geohash, PlusCode, CSquares);get_covering_cellsby S2 and Slippy. The remaining grids (MGRS, GARS, Maidenhead) are not hierarchical, so operations that depend on the interface (GridCellCollection.refine/coarsen, the h3-stylecell_to_children/cell_to_parent) raiseNotImplementedErroron 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.- classmethod precision_range() tuple[int, int][source]
Inclusive
(min, max)valid precision for this grid system.
- 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 usenominal_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:
- abstractmethod get_cell_from_point(lat: float, lon: float) GridCell[source]
Get the grid cell containing the given point.
- abstractmethod get_cell_from_identifier(identifier: str) GridCell[source]
Get a grid cell from its identifier.
- abstractmethod get_neighbors(cell: GridCell) list[GridCell][source]
Get neighboring cells of the given cell.
- 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:
- Returns:
List of grid cells that intersect the bounding box
- Return type:
- contains_point(polygon: Polygon, lat: float, lon: float) bool[source]
Check if a point is contained within the polygon.
- 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:
- Returns:
GeoDataFrame with grid cell identifiers, geometries, and original data
- Return type:
gpd.GeoDataFrame
- is_valid_identifier(identifier: str) bool[source]
Whether
identifierparses as a cell at this grid’s precision.
- 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.
- native_cell_center(identifier: str) tuple[float, float] | None[source]
Exact
(lat, lng)cell center, or None to use the polygon centroid.
- native_cell_area(identifier: str, unit: str) float | None[source]
Exact cell area in
unit, or None to use the projected polygon area.
- class m3s.A5Grid(precision: int = 8)[source]
Bases:
CoreBackedGridA5 pentagonal grid system.
Global, equal-area pentagonal DGGS backed by the
pya5library, 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:
- __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 cratepya5wraps) – exact, not the geodesic-sampled nominal the base class would compute.- Returns:
Cell area in square kilometres.
- Return type:
- get_cell_from_point(lat: float, lon: float) GridCell[source]
Get the A5 cell containing the given point.
- Parameters:
- Returns:
The cell containing the point at this grid’s precision.
- Return type:
- 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:
- 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:
- Raises:
ValueError – If the cell is already at resolution 0 (no parent).
- class m3s.GeohashGrid(precision: int = 5)[source]
Bases:
CoreBackedGridGeohash-based spatial grid system.
Implements the Geohash spatial indexing system using base-32 encoding to create hierarchical rectangular grid cells.
- __init__(precision: int = 5)[source]
Initialize GeohashGrid.
- Parameters:
precision (int, optional) – Geohash precision level (1-12), by default 5. Higher values mean smaller cells.
- Raises:
ValueError – If precision is not between 1 and 12
- get_cell_from_point(lat: float, lon: float) GridCell[source]
Get the geohash cell containing the given point.
- 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.
- 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:
- 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:
CoreBackedGridMGRS-based spatial grid system.
Implements the Military Grid Reference System (MGRS) for creating uniform square grid cells based on UTM projections.
- __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
- 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:
31UDQ524117has 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:
CoreBackedGridH3-based hexagonal spatial grid system.
Implements Uber’s H3 hexagonal hierarchical spatial indexing system, providing uniform hexagonal cells with consistent neighbor relationships.
- __init__(precision: int = 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:
- 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:
- 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:
- 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:
- 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:
- 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.
- uncompact_cells(cells: list[GridCell], target_resolution: int) list[GridCell][source]
Uncompact cells to a target resolution, expanding parent cells to children.
- 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)).
- class m3s.CSquaresGrid(precision: int = 5)[source]
Bases:
CoreBackedGridC-squares-based spatial grid system.
Implements the Concise Spatial Query and Representation System (C-squares) for marine and environmental data referencing using a hierarchical decimal grid system.
- __init__(precision: int = 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:
- Returns:
The C-squares grid cell containing the specified point
- Return type:
- 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:
- 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.
- 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:
- Raises:
ValueError – If the cell is already at the coarsest precision.
- class m3s.GARSGrid(precision: int = 2)[source]
Bases:
CoreBackedGridGARS (Global Area Reference System) spatial grid.
Implements the military/aviation grid system using a hierarchical coordinate system with longitude bands and latitude zones.
- __init__(precision: int = 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
- class m3s.MaidenheadGrid(precision: int = 4)[source]
Bases:
CoreBackedGridMaidenhead locator system spatial grid.
Implements the ham radio grid system using a hierarchical coordinate system with alternating letter/number pairs.
- __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
- class m3s.PlusCodeGrid(precision: int = 5)[source]
Bases:
CoreBackedGridPlus codes (Open Location Code) spatial grid system.
Implements Google’s open-source alternative to addresses using a base-20 encoding system to create hierarchical grid cells.
- ALPHABET = '23456789CFGHJMPQRVWX'
- BASE = 20
- GRID_SIZES = [20.0, 1.0, 0.05, 0.0025, 0.000125, 6.25e-06, 3.125e-07, 1.5625e-08]
- __init__(precision: int = 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
- decode(code: str) tuple[float, float, float, float][source]
Decode a plus code into latitude/longitude bounds.
- 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.
- class m3s.QuadkeyGrid(precision: int = 12)[source]
Bases:
CoreBackedGridQuadkey 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:
- __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.
- class m3s.S2Grid(precision: int = 10)[source]
Bases:
CoreBackedGridS2 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:
- __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 ** levelcells. 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:
- get_parent(cell: GridCell) GridCell[source]
Get parent cell at the previous level.
- Parameters:
cell (GridCell) – Child cell
- Returns:
Parent cell
- Return type:
- 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:
- Returns:
List of cells covering the polygon
- Return type:
Notes
Takes the level-
precisioncells of the polygon’s bounding box (from the shared core’ss2_cells_in_bbox) and keeps those that actually intersect the polygon, capped atmax_cells. This replaces the formers2sphere.RegionCovererpath; the result is the set of cells covering the polygon at this precision.
- class m3s.SlippyGrid(precision: int = 12)[source]
Bases:
CoreBackedGridSlippy 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:
- __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_parent(cell: GridCell) GridCell[source]
Get parent tile at the previous zoom level.
- Parameters:
cell (GridCell) – Child tile
- Returns:
Parent tile
- Return type:
- Raises:
ValueError – If the tile is already at the coarsest zoom level (0).
- class m3s.EAQuadGrid(precision: int = 4)[source]
Bases:
CoreBackedGridEA-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:
- __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; usenative_cell_area()for an individual cell’s exact clipped area.)- Returns:
Nominal area in square kilometres.
- Return type:
- 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:
- 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:
- Returns:
The cell containing the point at this grid’s precision.
- Return type:
- 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:
- Raises:
ValueError – If the cell is already at the coarsest level (1024 km).
- class m3s.RHEALPixGrid(precision: int = 5)[source]
Bases:
CoreBackedGridrHEALPix 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:
- __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 ** resolutionwithR_Athe 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:
- native_cell_area(identifier: str, unit: str) float | None[source]
Exact cell area in
unit(equal-area: identical for every cell).- Parameters:
- 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:
- Returns:
The cell containing the point at this grid’s precision.
- Return type:
- 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:
- Raises:
ValueError – If the cell is already a resolution 0 face.
- class m3s.GridBuilder[source]
Bases:
objectFluent 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())
- 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.
- at_points(points: List[Tuple[float, float]] | ndarray) GridBuilder[source]
Query multiple point locations (batch operation).
- 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.
- 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.
- filter(predicate: Callable[[GridCell], bool]) GridBuilder[source]
Filter cells by predicate function.
- 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:
H3VerbsMixinWrapper providing easy access to grid systems.
Enables working with grids without requiring upfront precision selection, with intelligent defaults and auto-precision capabilities.
- Parameters:
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.
- 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, sogrid.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:
- Returns:
Collection of neighbor cells (the origin cell is included only when
include_selfis True)- Return type:
GridCellCollection
- from_id(identifier: str) GridCell[source]
Get cell from identifier.
- Parameters:
identifier (str) – Cell identifier
- Returns:
Grid cell
- Return type:
- 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/neighborswork).- 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:
- class m3s.GridCellCollection(cells: List[GridCell], grid_wrapper: Any | None = None)[source]
Bases:
objectContainer 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:
- Returns:
The path written to.
- Return type:
- 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 ofto_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.
- 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
Polygonif 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:
- Returns:
New collection with neighbor cells
- Return type:
GridCellCollection
- Raises:
ValueError – If grid wrapper not available
- to_maidenhead(method: str = 'centroid') GridCellCollection[source]
Convert to Maidenhead grid system.
- property total_area_km2: float
Total area of all cells in square kilometers.
- Returns:
Sum of all cell areas
- Return type:
- __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
- class m3s.PrecisionFinder(grid_wrapper: GridWrapper)[source]
Bases:
objectFind 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:
- 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).
- 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:
- Raises:
ValueError – If use case not recognized
- class m3s.PrecisionSelector(grid_system: str)[source]
Bases:
objectIntelligent 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:
- 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:
- 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:
- Returns:
Recommendation with confidence and explanation
- 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:
objectRecommendation for grid precision with confidence and explanation.
- precision
Recommended precision/resolution level
- Type:
- confidence
Confidence score (0.0 to 1.0) indicating recommendation quality
- Type:
- explanation
Human-readable explanation of the recommendation
- Type:
- 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
- class m3s.AreaCalculator(grid_system: str)[source]
Bases:
objectNominal 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 fromGrid.area_km2. Each sampled(grid, precision)value is cached, so after first touch it is effectively an O(1) lookup. Passing alatitudesamples 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()andGrid.area_km2.
- get_area(precision: int, latitude: float | None = None) float[source]
Nominal cell area at
precision, optionally sampled atlatitude.
- class m3s.PerformanceProfiler[source]
Bases:
objectEmpirical 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}
- class m3s.GridQueryResult(cells: GridCell | List[GridCell], metadata: dict[str, Any] | None = None)[source]
Bases:
objectType-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.
- property single: GridCell
Get single cell result.
- Returns:
The single cell result
- Return type:
- 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:
- 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
- class m3s.MultiGridComparator(grid_configs: List[Tuple[str, int]])[source]
Bases:
objectCompare 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.
- 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.
- 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.
- compare_coverage(bounds: Tuple[float, float, float, float]) DataFrame[source]
Compare coverage characteristics across grid systems for a region.
- 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.
- 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
- class m3s.ParallelConfig(n_workers: int | None = None, chunk_size: int = 10000, optimize_memory: bool = True, adaptive_chunking: bool = True)[source]
Bases:
objectConfiguration for parallel processing operations.
- class m3s.ParallelGridEngine(config: ParallelConfig | None = None)[source]
Bases:
objectParallel processing engine for spatial grid operations.
Threading-only implementation for moderate-size workloads.
- intersect_parallel(grid: BaseGrid, gdf: GeoDataFrame, chunk_size: int | None = None) GeoDataFrame[source]
Perform parallel grid intersection on 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.
- 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.
- class m3s.MemoryMonitor(warn_threshold: float = 0.8, critical_threshold: float = 0.9)[source]
Bases:
objectMonitor and manage memory usage during spatial operations.
- __init__(warn_threshold: float = 0.8, critical_threshold: float = 0.9)[source]
Initialize memory monitor.
- get_memory_usage() dict[str, float][source]
Get current memory usage statistics.
- Returns:
Memory usage information including RSS, VMS, and percentage
- Return type:
- class m3s.LazyGeodataFrame(file_path: str | None = None, gdf: GeoDataFrame | None = None, chunk_size: int = 10000)[source]
Bases:
objectLazy-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.
- 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:
objectMemory-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
- 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:
- class m3s.GridConverter[source]
Bases:
objectUtility 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}
- 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:
- Returns:
Converted grid cell(s)
- Return type:
- 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.
- 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:
- 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.
- 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:
objectAnalyzer 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.
- get_all_relationships(cell1: GridCell, cell2: GridCell) dict[str, bool][source]
Get all spatial relationships between two grid cells.
- is_adjacent(cell1: GridCell, cell2: GridCell) bool[source]
Check if two grid cells are adjacent (share an edge or vertex).
- find_contained_cells(container: GridCell, cells: list[GridCell]) list[GridCell][source]
Find all cells that are contained within a container cell.
- find_overlapping_cells(target: GridCell, cells: list[GridCell]) list[GridCell][source]
Find all cells that overlap with a target cell.
- find_adjacent_cells(target: GridCell, cells: list[GridCell]) list[GridCell][source]
Find all cells that are adjacent to a target cell.
- create_relationship_matrix(cells: list[GridCell]) DataFrame[source]
Create a relationship matrix for a collection of cells.
- create_adjacency_matrix(cells: list[GridCell]) DataFrame[source]
Create an adjacency matrix for a collection of cells.
- get_topology_statistics(cells: list[GridCell]) dict[str, int | float][source]
Calculate topological statistics for a collection of cells.
- find_clusters(cells: list[GridCell], min_cluster_size: int = 2) list[list[GridCell]][source]
Find clusters of connected (adjacent) cells.
- class m3s.RelationshipType(*values)[source]
Bases:
EnumEnumeration 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.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:
objectMulti-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.
- 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:
- Returns:
Dictionary mapping resolution levels to cell lists
- Return type:
- get_hierarchical_cells(point: Point, max_levels: int | None = None) dict[int, GridCell][source]
Get cells containing a point at all resolution levels.
- get_parent_child_relationships(bounds: tuple[float, float, float, float]) dict[str, list[str]][source]
Analyze parent-child relationships between resolution levels.
- 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.
- analyze_scale_transitions(bounds: tuple[float, float, float, float]) DataFrame[source]
Analyze how data transitions between different scale levels.
- aggregate_to_level(data: GeoDataFrame, target_level: int, aggregation_func: str = 'sum') GeoDataFrame[source]
Aggregate data from finer to coarser resolution level.
- get_resolution_statistics() DataFrame[source]
Get statistics about all resolution levels.
- Returns:
Statistics for each resolution level
- Return type:
pd.DataFrame
- class m3s.ResolutionLevel(level: int, precision: int, area_km2: float, cells: list[GridCell])[source]
Bases:
objectRepresents a resolution level in a multi-resolution grid.
- level
Resolution level identifier
- Type:
- precision
Grid precision/resolution parameter
- Type:
- area_km2
Typical cell area at this level
- Type:
- level: int
- precision: int
- area_km2: float
- m3s.create_multiresolution_grid(grid_system: BaseGrid, levels: list[int]) MultiResolutionGrid[source]
Create a multi-resolution grid.