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[source]#
Calculate the area of the grid cell in square kilometers.
- Returns:
Area of the cell in square kilometers
- Return type:
- 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.
- 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
Grid Systems#
H3 Grid#
H3 (Uberβs Hexagonal Hierarchical Spatial Index) grid implementation.
- class m3s.h3.H3Grid(precision: int | None = None, resolution: int | None = None)[source]#
Bases:
BaseGridH3-based hexagonal spatial grid system.
Implements Uberβs H3 hexagonal hierarchical spatial indexing system, providing uniform hexagonal cells with consistent neighbor relationships.
- __init__(precision: int | None = None, resolution: int | None = None)[source]#
Initialize H3Grid.
- Parameters:
precision (int, optional) β H3 precision level (0-15), by default 7. This is the standardized parameter name across all grid systems.
resolution (int, optional) β
Deprecated alias for precision. Use βprecisionβ instead.
- Resolution scales:
0 = ~4,250km edge length (continent scale) 1 = ~1,607km edge length 2 = ~606km edge length 3 = ~229km edge length (country scale) 4 = ~86km edge length 5 = ~33km edge length (state scale) 6 = ~12km edge length 7 = ~4.5km edge length (city scale) 8 = ~1.7km edge length 9 = ~650m edge length (neighborhood scale) 10 = ~240m edge length 11 = ~90m edge length (building scale) 12 = ~34m edge length 13 = ~13m edge length 14 = ~4.8m edge length (room scale) 15 = ~1.8m edge length (precise location)
- Raises:
ValueError β If precision/resolution is not between 0 and 15
- property area_km2: float#
Get the theoretical area of H3 cells at this resolution in square kilometers.
- Returns:
Theoretical area in square kilometers for cells at this resolution
- Return type:
- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the H3 cell containing the given point.
- 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_neighbors(cell: GridCell) list[GridCell][source]#
Get neighboring H3 cells (6 neighbors for hexagons).
- get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#
Get all H3 cells within the given bounding box.
- Parameters:
- Returns:
List of H3 cells that intersect the bounding box
- Return type:
- 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_resolution_info() dict[source]#
Get detailed information about the current resolution level.
- Returns:
Dictionary containing resolution metrics including edge length, area, and relationship information
- Return type:
- 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.
Geohash Grid#
Geohash grid implementation.
- class m3s.geohash.GeohashGrid(precision: int = 5)[source]#
Bases:
BaseGridGeohash-based spatial grid system.
Implements the Geohash spatial indexing system using base-32 encoding to create hierarchical rectangular grid cells.
- __init__(precision: int = 5)[source]#
Initialize GeohashGrid.
- Parameters:
precision (int, optional) β Geohash precision level (1-12), by default 5. Higher values mean smaller cells.
- Raises:
ValueError β If precision is not between 1 and 12
- property area_km2: float#
Get the theoretical area of Geohash cells at this precision.
- Returns:
Theoretical area in square kilometers for cells at this precision
- Return type:
- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the geohash cell containing the given point.
MGRS Grid#
MGRS (Military Grid Reference System) grid implementation.
- class m3s.mgrs.MGRSGrid(precision: int = 1)[source]#
Bases:
BaseGridMGRS-based spatial grid system.
Implements the Military Grid Reference System (MGRS) for creating uniform square grid cells based on UTM projections.
- __init__(precision: int = 1)[source]#
Initialize MGRSGrid.
- Parameters:
precision (int, optional) β
MGRS precision level (0-5), by default 1.
- Precision levels:
0 = 100km grid 1 = 10km grid 2 = 1km grid 3 = 100m grid 4 = 10m grid 5 = 1m grid
- Raises:
ValueError β If precision is not between 0 and 5
- property area_km2: float#
Get the theoretical area of MGRS cells at this precision in square kilometers.
- Returns:
Theoretical area in square kilometers for cells at this precision
- Return type:
Package Initialization#
M3S - Multi Spatial Subdivision System.
A unified Python package for working with hierarchical spatial grid systems, including grid conversion utilities, relationship analysis, and multi-resolution operations.
- class m3s.BaseGrid(precision: int)[source]#
Bases:
ABCAbstract base class for all grid systems.
Provides common interface for spatial grid implementations including cell retrieval, neighbor finding, and polygon intersection operations.
- 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
- class m3s.GeohashGrid(precision: int = 5)[source]#
Bases:
BaseGridGeohash-based spatial grid system.
Implements the Geohash spatial indexing system using base-32 encoding to create hierarchical rectangular grid cells.
- __init__(precision: int = 5)[source]#
Initialize GeohashGrid.
- Parameters:
precision (int, optional) β Geohash precision level (1-12), by default 5. Higher values mean smaller cells.
- Raises:
ValueError β If precision is not between 1 and 12
- property area_km2: float#
Get the theoretical area of Geohash cells at this precision.
- Returns:
Theoretical area in square kilometers for cells at this precision
- Return type:
- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the geohash cell containing the given point.
- class m3s.MGRSGrid(precision: int = 1)[source]#
Bases:
BaseGridMGRS-based spatial grid system.
Implements the Military Grid Reference System (MGRS) for creating uniform square grid cells based on UTM projections.
- __init__(precision: int = 1)[source]#
Initialize MGRSGrid.
- Parameters:
precision (int, optional) β
MGRS precision level (0-5), by default 1.
- Precision levels:
0 = 100km grid 1 = 10km grid 2 = 1km grid 3 = 100m grid 4 = 10m grid 5 = 1m grid
- Raises:
ValueError β If precision is not between 0 and 5
- property area_km2: float#
Get the theoretical area of MGRS cells at this precision in square kilometers.
- Returns:
Theoretical area in square kilometers for cells at this precision
- Return type:
- class m3s.H3Grid(precision: int | None = None, resolution: int | None = None)[source]#
Bases:
BaseGridH3-based hexagonal spatial grid system.
Implements Uberβs H3 hexagonal hierarchical spatial indexing system, providing uniform hexagonal cells with consistent neighbor relationships.
- __init__(precision: int | None = None, resolution: int | None = None)[source]#
Initialize H3Grid.
- Parameters:
precision (int, optional) β H3 precision level (0-15), by default 7. This is the standardized parameter name across all grid systems.
resolution (int, optional) β
Deprecated alias for precision. Use βprecisionβ instead.
- Resolution scales:
0 = ~4,250km edge length (continent scale) 1 = ~1,607km edge length 2 = ~606km edge length 3 = ~229km edge length (country scale) 4 = ~86km edge length 5 = ~33km edge length (state scale) 6 = ~12km edge length 7 = ~4.5km edge length (city scale) 8 = ~1.7km edge length 9 = ~650m edge length (neighborhood scale) 10 = ~240m edge length 11 = ~90m edge length (building scale) 12 = ~34m edge length 13 = ~13m edge length 14 = ~4.8m edge length (room scale) 15 = ~1.8m edge length (precise location)
- Raises:
ValueError β If precision/resolution is not between 0 and 15
- property area_km2: float#
Get the theoretical area of H3 cells at this resolution in square kilometers.
- Returns:
Theoretical area in square kilometers for cells at this resolution
- Return type:
- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the H3 cell containing the given point.
- 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_neighbors(cell: GridCell) list[GridCell][source]#
Get neighboring H3 cells (6 neighbors for hexagons).
- get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#
Get all H3 cells within the given bounding box.
- Parameters:
- Returns:
List of H3 cells that intersect the bounding box
- Return type:
- 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_resolution_info() dict[source]#
Get detailed information about the current resolution level.
- Returns:
Dictionary containing resolution metrics including edge length, area, and relationship information
- Return type:
- 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.
- class m3s.CSquaresGrid(precision: int = 3)[source]#
Bases:
BaseGridC-squares-based spatial grid system.
Implements the Concise Spatial Query and Representation System (C-squares) for marine and environmental data referencing using a hierarchical decimal grid system.
- __init__(precision: int = 3)[source]#
Initialize CSquaresGrid.
- Parameters:
precision (int, optional) β
C-squares precision level (1-5), by default 3.
- Precision levels:
1 = 10Β° x 10Β° cells (base level) 2 = 5Β° x 5Β° cells 3 = 1Β° x 1Β° cells 4 = 0.5Β° x 0.5Β° cells (30β x 30β) 5 = 0.1Β° x 0.1Β° cells (6β x 6β)
- Raises:
ValueError β If precision is not between 1 and 5
- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the C-squares cell containing the given point.
- Parameters:
- 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_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#
Get all C-squares cells within the given bounding box.
- Parameters:
- Returns:
List of C-squares cells that intersect the bounding box
- Return type:
- class m3s.GARSGrid(precision: int = 1)[source]#
Bases:
BaseGridGARS (Global Area Reference System) spatial grid.
Implements the military/aviation grid system using a hierarchical coordinate system with longitude bands and latitude zones.
- __init__(precision: int = 1)[source]#
Initialize GARSGrid.
- Parameters:
precision (int, optional) β
GARS precision level (1-3), by default 1.
- Precision levels:
1 = 30β Γ 30β (0.5Β° Γ 0.5Β°) - e.g., β001AAβ 2 = 15β Γ 15β (0.25Β° Γ 0.25Β°) - e.g., β001AA1β 3 = 5β Γ 5β (~0.083Β° Γ 0.083Β°) - e.g., β001AA19β
- Raises:
ValueError β If precision is not between 1 and 3
- property area_km2: float[source]#
Approximate area of a GARS cell at this precision in square kilometers.
- Returns:
Approximate area in square kilometers
- Return type:
- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the grid cell containing the given point.
- class m3s.MaidenheadGrid(precision: int = 3)[source]#
Bases:
BaseGridMaidenhead locator system spatial grid.
Implements the ham radio grid system using a hierarchical coordinate system with alternating letter/number pairs.
- __init__(precision: int = 3)[source]#
Initialize MaidenheadGrid.
- Parameters:
precision (int, optional) β
Maidenhead precision level (1-4), by default 3.
- Precision levels:
1 = Field (20Β° Γ 10Β°) - e.g., βJOβ 2 = Square (2Β° Γ 1Β°) - e.g., βJO62β 3 = Subsquare (5β Γ 2.5β) - e.g., βJO62KOβ 4 = Extended square (12.5β Γ 6.25β) - e.g., βJO62KO78β
- Raises:
ValueError β If precision is not between 1 and 4
- property area_km2: float[source]#
Approximate area of a Maidenhead cell at this precision in square kilometers.
- Returns:
Approximate area in square kilometers
- Return type:
- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the grid cell containing the given point.
- class m3s.PlusCodeGrid(precision: int = 4)[source]#
Bases:
BaseGridPlus codes (Open Location Code) spatial grid system.
Implements Googleβs open-source alternative to addresses using a base-20 encoding system to create hierarchical grid cells.
- ALPHABET = '23456789CFGHJMPQRVWX'#
- BASE = 20#
- GRID_SIZES = [20.0, 1.0, 0.05, 0.0025, 0.000125, 6.25e-06, 3.125e-07, 1.5625e-08]#
- __init__(precision: int = 4)[source]#
Initialize PlusCodeGrid.
- Parameters:
precision (int, optional) β Plus code precision level (1-7), by default 4. Higher values mean smaller cells.
- Raises:
ValueError β If precision is not between 1 and 7
- property area_km2: float[source]#
Approximate area of a Plus Code cell at this precision in square kilometers.
- Returns:
Approximate area in square kilometers
- Return type:
- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the grid cell containing the given point.
- class m3s.QuadkeyGrid(precision: int | None = None, level: int | None = None)[source]#
Bases:
BaseGridQuadkey 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.
- property area_km2: float#
Get the theoretical area of Quadkey tiles at this level in square kilometers.
- Returns:
Theoretical area in square kilometers for tiles at this level
- Return type:
- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the quadkey cell containing the given point.
- get_cell_from_identifier(identifier: str) GridCell[source]#
Get a grid cell from its quadkey identifier.
- class m3s.S2Grid(precision: int | None = None, level: int | None = None)[source]#
Bases:
BaseGridS2 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.
- __init__(precision: int | None = None, level: int | None = None)[source]#
Initialize S2 grid.
- Parameters:
precision (int, optional) β S2 cell precision level (0-30). This is the standardized parameter name across all grid systems.
level (int, optional) β Deprecated alias for precision. Use βprecisionβ instead. Level 0: ~85,000 km edge length Level 10: ~1,300 km edge length Level 20: ~20 m edge length Level 30: ~1 cm edge length
- property area_km2: float#
Get the theoretical area of S2 cells at this level in square kilometers.
- Returns:
Theoretical area in square kilometers for cells at this level
- Return type:
- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the S2 cell containing the given point.
- 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:
- class m3s.SlippyGrid(precision: int | None = None, zoom: int | None = None)[source]#
Bases:
BaseGridSlippy 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.
- __init__(precision: int | None = None, zoom: int | None = None)[source]#
Initialize Slippy Map Tiling grid.
- Parameters:
precision (int, optional) β Precision level (0-22). This is the standardized parameter name across all grid systems.
zoom (int, optional) β Deprecated alias for precision. Use βprecisionβ instead. Zoom 0: 1 tile covering the world Zoom 1: 2Γ2 = 4 tiles Zoom 10: 1024Γ1024 = ~1M tiles (~40km tiles) Zoom 15: 32768Γ32768 = ~1B tiles (~1.2km tiles) Zoom 18: 262144Γ262144 tiles (~150m tiles)
- property area_km2: float#
Get the theoretical area of Slippy Map tiles.
At this zoom level, returns the area in square kilometers.
- Returns:
Theoretical area in square kilometers for tiles at this zoom level
- Return type:
- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the Slippy Map tile containing the given point.
- get_cells_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) list[GridCell][source]#
Get all tiles within the given bounding box.
- Parameters:
- Returns:
List of tiles that intersect the bounding box
- Return type:
- class m3s.What3WordsGrid(precision: int = 1)[source]#
Bases:
BaseGridWhat3Words-style spatial grid system.
Implements a 3-meter square grid system similar to What3Words. Each cell represents approximately a 3x3 meter square on the Earthβs surface.
Note: This implementation provides the grid structure. For actual What3Words integration with their word system, use the official What3Words API.
- __init__(precision: int = 1)[source]#
Initialize What3WordsGrid.
- Parameters:
precision (int, optional) β Grid precision level (1 only supported for 3m squares), by default 1
- Raises:
ValueError β If precision is not 1
- property area_km2: float#
Get the theoretical area of What3Words cells in square kilometers.
- Returns:
Theoretical area in square kilometers (approximately 0.000009 kmΒ²)
- Return type:
- get_cell_from_point(lat: float, lon: float) GridCell[source]#
Get the grid cell containing the given point.
- 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 12 grid systems through a unified interface.
Examples
Basic single-point query:
>>> result = (GridBuilder ... .for_system('h3') ... .with_precision(7) ... .at_point(40.7128, -74.0060) ... .execute()) >>> print(result.single.identifier)
Intelligent precision with neighbors:
>>> selector = PrecisionSelector('geohash') >>> rec = selector.for_use_case('neighborhood') >>> result = (GridBuilder ... .for_system('geohash') ... .with_auto_precision(rec) ... .at_point(40.7128, -74.0060) ... .find_neighbors() ... .execute()) >>> print(f"Cell + {len(result.many) - 1} neighbors")
Region query with filtering:
>>> result = (GridBuilder ... .for_system('s2') ... .with_precision(10) ... .in_bbox(40.7, -74.1, 40.8, -73.9) ... .filter(lambda cell: cell.area_km2 > 1.0) ... .execute()) >>> gdf = result.to_geodataframe()
Cross-grid conversion:
>>> result = (GridBuilder ... .for_system('geohash') ... .with_precision(5) ... .at_point(40.7128, -74.0060) ... .convert_to('h3', method='centroid') ... .execute())
- classmethod for_system(system: str) GridBuilder[source]#
Select grid system.
- Parameters:
system (str) β Grid system name: βgeohashβ, βh3β, βs2β, βquadkeyβ, βslippyβ, βmgrsβ, βcsquaresβ, βgarsβ, βmaidenheadβ, βpluscodeβ, βwhat3wordsβ, βgeohash_intβ
- Returns:
Builder instance for method chaining
- Return type:
- 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:
- 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:
- 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:
- at_point(latitude: float, longitude: float) GridBuilder[source]#
Query single point location.
- Parameters:
- Returns:
Builder instance for method chaining
- Return type:
- at_points(points: List[Tuple[float, float]] | ndarray) GridBuilder[source]#
Query multiple point locations (batch operation).
- in_bbox(min_latitude: float, min_longitude: float, max_latitude: float, max_longitude: float) GridBuilder[source]#
Query bounding box region.
- Parameters:
- Returns:
Builder instance for method chaining
- Return type:
- in_polygon(polygon: Polygon) GridBuilder[source]#
Query cells intersecting polygon.
- Parameters:
polygon (Polygon) β Shapely polygon geometry
- Returns:
Builder instance for method chaining
- Return type:
- 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:
- 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:
- 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:
- convert_to(target_system: str, method: str = 'centroid') GridBuilder[source]#
Convert cells to different grid system.
- Parameters:
- Returns:
Builder instance for method chaining
- Return type:
- 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:
- execute() GridQueryResult[source]#
Execute the operation pipeline.
- Returns:
Type-safe result container
- Return type:
- Raises:
ValueError β If grid system or precision not set, or if no operations specified
- class m3s.GridWrapper(grid_class: Type[BaseGrid], default_precision: int, precision_param_name: str = 'precision')[source]#
Bases:
objectSimplified wrapper 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, precision_param_name: str = 'precision')[source]#
Initialize grid wrapper.
- from_geometry(geometry: Tuple[float, float] | Tuple[float, float, float, float] | Point | Polygon | MultiPolygon | GeoDataFrame, precision: int | None = None) GridCell | GridCellCollection[source]#
Universal method accepting any geometry type.
- Parameters:
geometry (Union[tuple, Point, Polygon, MultiPolygon, GeoDataFrame]) β
Input geometry: - Tuple[float, float]: (lat, lon) point - Tuple[float, float, float, float]: (min_lat, min_lon, max_lat,
max_lon) bbox
shapely.Point: Point geometry
shapely.Polygon: Polygon geometry
shapely.MultiPolygon: MultiPolygon geometry
GeoDataFrame: GeoDataFrame with geometries
precision (Optional[int], optional) β Precision level (uses default if not specified). For optimal precision, call find_precision() first.
- Returns:
Single GridCell for point, GridCellCollection for area geometries
- Return type:
Union[GridCell, GridCellCollection]
Notes
- For large areas, explicitly finding precision first is recommended:
>>> precision = m3s.H3.find_precision(polygon, method='auto') >>> cells = m3s.H3.from_geometry(polygon, precision=precision)
- from_point(lat: float, lon: float, precision: int | None = None) GridCell[source]#
Get cell at point location.
- from_bbox(bounds: Tuple[float, float, float, float] | List[float], precision: int | None = None) GridCellCollection[source]#
Get cells in bounding box.
- Parameters:
bounds (Union[Tuple, List]) β (min_lat, min_lon, max_lat, max_lon) or [min_lat, min_lon, max_lat, max_lon]
precision (Optional[int], optional) β Precision level (uses default if not specified)
- Returns:
Collection of cells intersecting bbox
- Return type:
- 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:
- neighbors(cell: GridCell, depth: int = 1) GridCellCollection[source]#
Get neighbors of a cell.
- Parameters:
- Returns:
Collection of neighbor cells (including original cell)
- Return type:
- 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
- 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:
- 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]
- 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]
- 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:
- 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:
- 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:
- Raises:
ValueError β If grid wrapper not available
- to_h3(method: str = 'centroid') GridCellCollection[source]#
Convert to H3 grid system.
- to_geohash(method: str = 'centroid') GridCellCollection[source]#
Convert to Geohash grid system.
- to_mgrs(method: str = 'centroid') GridCellCollection[source]#
Convert to MGRS grid system.
- to_s2(method: str = 'centroid') GridCellCollection[source]#
Convert to S2 grid system.
- to_quadkey(method: str = 'centroid') GridCellCollection[source]#
Convert to Quadkey grid system.
- to_slippy(method: str = 'centroid') GridCellCollection[source]#
Convert to Slippy tile grid system.
- to_csquares(method: str = 'centroid') GridCellCollection[source]#
Convert to C-squares grid system.
- to_gars(method: str = 'centroid') GridCellCollection[source]#
Convert to GARS grid system.
- to_maidenhead(method: str = 'centroid') GridCellCollection[source]#
Convert to Maidenhead grid system.
- to_pluscode(method: str = 'centroid') GridCellCollection[source]#
Convert to Plus Code grid system.
- to_what3words(method: str = 'centroid') GridCellCollection[source]#
Convert to What3Words grid system.
- property total_area_km2: float#
Total area of all cells in square kilometers.
- Returns:
Sum of all cell areas
- Return type:
- __getitem__(idx: int | slice) GridCell | GridCellCollection[source]#
Get cell by index or slice.
- Parameters:
- Returns:
Single cell for int index, collection for slice
- Return type:
Union[GridCell, 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
- USE_CASE_AREAS = {'block': (0.01, 0.1), 'building': (0.001, 0.01), 'city': (100.0, 1000.0), 'country': (100000.0, 1000000.0), 'neighborhood': (1.0, 10.0), 'region': (10000.0, 100000.0)}#
- __init__(grid_wrapper: GridWrapper)[source]#
Initialize precision finder with grid wrapper.
- for_geometries(geometries: Polygon | MultiPolygon | GeoDataFrame | List[Polygon], method: str | int = 'auto') int[source]#
Find optimal precision for geometries.
- Parameters:
geometries (Union[Polygon, MultiPolygon, gpd.GeoDataFrame, List[Polygon]]) β Input geometries
method (Union[str, int], optional) β Selection method: - βautoβ: Minimize coverage variance (default, best quality) - βlessβ: Fewer, larger cells - βmoreβ: More, smaller cells - βbalancedβ: Balance coverage quality and cell count - int (e.g., 100): Target specific cell count
- Returns:
Optimal precision level
- Return type:
- for_area(target_km2: float, tolerance: float = 0.2) int[source]#
Find precision closest to target cell area.
- for_use_case(use_case: str) int[source]#
Find precision for predefined use case.
- Parameters:
use_case (str) β Use case name: βbuildingβ, βblockβ, βneighborhoodβ, βcityβ, βregionβ, or βcountryβ
- Returns:
Recommended precision for use case
- Return type:
- 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:
- 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:
- for_use_case(use_case: str, context: Dict | None = None) PrecisionRecommendation[source]#
Select precision based on curated use case preset.
- Parameters:
use_case (str) β Use case name: βglobalβ, βcontinentalβ, βcountryβ, βregionβ, βcityβ, βneighborhoodβ, βstreetβ, βbuildingβ, βroomβ
context (Optional[Dict], optional) β Additional context (e.g., {βlatitudeβ: 40.7} for polar adjustments)
- Returns:
Recommendation with high confidence (curated presets)
- Return type:
- 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:
- class m3s.PrecisionRecommendation(precision: int, confidence: float, explanation: str, actual_area_km2: float | None = None, actual_cell_count: int | None = None, edge_length_m: float | None = None, metadata: Dict | None = None)[source]#
Bases:
objectRecommendation for grid precision with confidence and explanation.
- actual_area_km2#
Actual cell area at recommended precision (for area-based selection)
- Type:
Optional[float]
- metadata#
Additional metadata about the recommendation
- Type:
Optional[Dict]
- class m3s.AreaCalculator(grid_system: str)[source]#
Bases:
objectPrecomputed area lookup tables for fast precision selection.
This class provides O(1) area lookups for all grid systems with optional latitude-based corrections for systems with significant distortion.
- AREA_TABLES = {'csquares': [2827433.39, 282743.34, 2827.43, 28.27, 0.28], 'gars': [155400.0, 6475.0, 269.8], 'geohash': [5003.771, 625.471, 78.184, 19.546, 2.443, 0.61, 0.152, 0.019, 0.0048, 0.0012, 0.0003, 7.4e-05], 'geohash_int': [5003.771, 625.471, 78.184, 19.546, 2.443, 0.61, 0.152, 0.019, 0.0048, 0.0012, 0.0003, 7.4e-05], 'h3': [4357449.416, 609788.441, 86801.78, 12392.264, 1770.323, 252.903, 36.129, 5.161, 0.737, 0.105, 0.015, 0.002, 0.0003, 5e-05, 7e-06, 1e-06], 'maidenhead': [2000000.0, 200000.0, 5000.0, 125.0, 3.125, 0.078], 'mgrs': [10000.0, 100.0, 1.0, 0.01, 0.0001, 1e-06], 'pluscode': [24900000.0, 2490000.0, 249000.0, 24900.0, 3113.0, 389.0, 48.6, 6.1, 0.76, 0.095], 'quadkey': [127516118.0, 31879029.5, 7969757.38, 1992439.34, 498109.84, 124527.46, 31131.86, 7782.97, 1945.74, 486.43, 121.61, 30.4, 7.6, 1.9, 0.47, 0.12, 0.03, 0.007, 0.002, 0.0005, 0.0001, 3e-05, 8e-06], 's2': [85011012.19, 21252753.05, 5313188.26, 1328297.07, 332074.27, 83018.57, 20754.64, 5188.66, 1297.17, 324.29, 81.07, 20.27, 5.07, 1.27, 0.32, 0.08, 0.02, 0.005, 0.001, 0.0003, 8e-05, 2e-05, 5e-06, 1e-06, 3.2e-07, 8e-08, 2e-08, 5e-09, 1e-09, 3.2e-10, 8e-11], 'slippy': [510072000.0, 127518000.0, 31879500.0, 7969875.0, 1992469.0, 498117.0, 124529.0, 31132.0, 7783.0, 1946.0, 486.5, 121.6, 30.4, 7.6, 1.9, 0.475, 0.119, 0.03, 0.007, 0.002, 0.0005], 'what3words': [9e-06]}#
- PRECISION_RANGES = {'csquares': (1, 5), 'gars': (1, 3), 'geohash': (1, 12), 'geohash_int': (1, 12), 'h3': (0, 15), 'maidenhead': (1, 6), 'mgrs': (1, 6), 'pluscode': (2, 15), 'quadkey': (1, 23), 's2': (0, 30), 'slippy': (0, 20), 'what3words': (1, 1)}#
- __init__(grid_system: str)[source]#
Initialize area calculator for specific grid system.
- Parameters:
grid_system (str) β Name of the grid system (e.g., βgeohashβ, βh3β, βs2β)
- get_area(precision: int, latitude: float | None = None) float[source]#
Get cell area at given precision with optional latitude correction.
- 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 | 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 | 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')
- 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(40.7128, -74.0060) >>> df = comparator.compare_coverage((40.7, -74.1, 40.8, -73.9))
- __init__(grid_configs: List[Tuple[str, int]])[source]#
Initialize comparator with grid system configurations.
- query_all(latitude: float, longitude: float) Dict[str, GridCell][source]#
Query same point across all configured grid systems.
- query_all_in_bbox(min_lat: float, min_lon: float, max_lat: float, max_lon: float) Dict[str, List[GridCell]][source]#
Query bounding box across all configured grid systems.
- 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(latitude: float, longitude: float) GeoDataFrame[source]#
Visualize how different grid systems cover the same point.
- 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.
- __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.
- 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
- 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[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#
Get CRS without loading full dataset.
- property bounds#
Get bounds without loading full dataset.
- chunks(chunk_size: int | None = None) Iterator[GeoDataFrame][source]#
Iterate over chunks of the GeoDataFrame.
- Parameters:
chunk_size (int | None, optional) β Size of chunks, uses instance default if None
- Yields:
gpd.GeoDataFrame β Chunks of the original GeoDataFrame
- sample(n: int = 1000) GeoDataFrame[source]#
Get a random sample without loading full dataset.
- Parameters:
n (int, optional) β Number of samples to return, by default 1000
- Returns:
Random sample of features
- Return type:
gpd.GeoDataFrame
- class m3s.StreamingGridProcessor(grid, memory_monitor: MemoryMonitor | None = None)[source]#
Bases:
objectMemory-efficient streaming processor for grid operations.
Processes large datasets in chunks while maintaining minimal memory footprint.
- __init__(grid, memory_monitor: MemoryMonitor | None = None)[source]#
Initialize streaming processor.
- Parameters:
grid (BaseGrid) β Grid system to use for processing
memory_monitor (MemoryMonitor | None, optional) β Memory monitor for optimization
- process_stream(data_source: LazyGeodataFrame, output_callback: Callable[[GeoDataFrame], None] | None = None, adaptive_chunking: bool = True) Iterator[GeoDataFrame][source]#
Process data stream with memory optimization.
- Parameters:
data_source (LazyGeodataFrame) β Lazy data source to process
output_callback (Callable[[gpd.GeoDataFrame], None] | None, optional) β Callback function for each processed chunk
adaptive_chunking (bool, optional) β Whether to adjust chunk size based on memory pressure
- Yields:
gpd.GeoDataFrame β Processed chunks
- m3s.optimize_geodataframe_memory(gdf: GeoDataFrame, categorical_threshold: int = 10) GeoDataFrame[source]#
Optimize GeoDataFrame memory usage through type conversion and categorization.
- Parameters:
gdf (gpd.GeoDataFrame) β Input GeoDataFrame to optimize
categorical_threshold (int, optional) β Maximum unique values for categorical conversion, by default 10
- Returns:
Memory-optimized GeoDataFrame
- Return type:
gpd.GeoDataFrame
- m3s.estimate_memory_usage(gdf: GeoDataFrame) dict[source]#
Estimate memory usage of a GeoDataFrame.
- Parameters:
gdf (gpd.GeoDataFrame) β GeoDataFrame to analyze
- Returns:
Memory usage breakdown by column
- Return type:
- 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 = {'csquares': <class 'm3s.csquares.CSquaresGrid'>, 'gars': <class 'm3s.gars.GARSGrid'>, 'geohash': <class 'm3s.geohash.GeohashGrid'>, 'h3': <class 'm3s.h3.H3Grid'>, 'maidenhead': <class 'm3s.maidenhead.MaidenheadGrid'>, 'mgrs': <class 'm3s.mgrs.MGRSGrid'>, 'pluscode': <class 'm3s.pluscode.PlusCodeGrid'>, 'quadkey': <class 'm3s.quadkey.QuadkeyGrid'>, 's2': <class 'm3s.s2.S2Grid'>, 'slippy': <class 'm3s.slippy.SlippyGrid'>, 'what3words': <class 'm3s.what3words.What3WordsGrid'>}#
- DEFAULT_PRECISIONS = {'csquares': 2, 'gars': 2, 'geohash': 5, 'h3': 7, 'maidenhead': 4, 'mgrs': 1, 'pluscode': 4, 'quadkey': 12, 's2': 10, 'slippy': 12, 'what3words': 1}#
- 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.
- Parameters:
- Returns:
List of converted cells
- Return type:
- create_conversion_table(source_system: str, target_system: str, bounds: tuple, source_precision: int | None = None, target_precision: int | None = None, method: str = 'centroid') DataFrame[source]#
Create a conversion table between two grid systems for a given area.
- Parameters:
source_system (str) β Source grid system name
target_system (str) β Target grid system name
bounds (tuple) β Bounding box as (min_lon, min_lat, max_lon, max_lat)
source_precision (int, optional) β Source precision
target_precision (int, optional) β Target precision
method (str) β Conversion method
- Returns:
Conversion table with mappings
- Return type:
pd.DataFrame
- m3s.convert_cell(cell: GridCell, target_system: str, **kwargs: Any) GridCell | list[GridCell][source]#
Convert a single grid cell to another system.
- m3s.convert_cells(cells: list[GridCell], target_system: str, **kwargs: Any) list[GridCell | list[GridCell]][source]#
Convert multiple grid cells to another system.
- m3s.get_equivalent_precision(source_system: str, source_precision: int, target_system: str) int[source]#
Find equivalent precision between grid systems.
- m3s.create_conversion_table(source_system: str, target_system: str, bounds: tuple, **kwargs: Any) DataFrame[source]#
Create a conversion table between two grid systems.
- 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.
- Parameters:
- Returns:
Primary spatial relationship
- Return type:
- 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 | 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.
- Parameters:
- 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
- class m3s.ResolutionLevel(level: int, precision: int, area_km2: float, cells: list[GridCell])[source]#
Bases:
objectRepresents a resolution level in a multi-resolution grid.
- m3s.create_multiresolution_grid(grid_system: BaseGrid, levels: list[int]) MultiResolutionGrid[source]#
Create a multi-resolution grid.