focal_statistics
Calculate moving window statistics like mean, min, max, or standard deviation on raster data for spatial pattern analysis in GIS workflows.
Instructions
Compute focal (moving window) statistics on a raster. Args: raster_path: Path to the input raster. statistic: Statistic to compute ('mean', 'min', 'max', 'std'). size: Window size (odd integer). output_path: Optional path to save the result. Returns: Dictionary with status, message, and output path if saved.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| raster_path | Yes | ||
| statistic | Yes | ||
| size | No | ||
| output_path | No |
Implementation Reference
- The primary handler function for the 'focal_statistics' MCP tool. It computes focal statistics (mean, min, max, std) on raster data using a moving window via scipy.ndimage.generic_filter. The function is registered via the @gis_mcp.tool() decorator, which handles schema generation from type hints and docstring.@gis_mcp.tool() def focal_statistics(raster_path: str, statistic: str, size: int = 3, output_path: str = None) -> Dict[str, Any]: """ Compute focal (moving window) statistics on a raster. Args: raster_path: Path to the input raster. statistic: Statistic to compute ('mean', 'min', 'max', 'std'). size: Window size (odd integer). output_path: Optional path to save the result. Returns: Dictionary with status, message, and output path if saved. """ try: import rasterio import numpy as np from scipy.ndimage import generic_filter with rasterio.open(raster_path) as src: data = src.read(1) profile = src.profile.copy() func = None if statistic == "mean": func = np.mean elif statistic == "min": func = np.min elif statistic == "max": func = np.max elif statistic == "std": func = np.std else: raise ValueError(f"Unsupported statistic: {statistic}") filtered = generic_filter(data, func, size=size, mode='nearest') if output_path: output_path_resolved = resolve_path(output_path, relative_to_storage=True) output_path_resolved.parent.mkdir(parents=True, exist_ok=True) with rasterio.open(str(output_path_resolved), "w", **profile) as dst: dst.write(filtered, 1) output_path = str(output_path_resolved) return { "status": "success", "message": f"Focal {statistic} computed successfully.", "output_path": output_path } except Exception as e: logger.error(f"Error in focal_statistics: {str(e)}") return {"status": "error", "message": str(e)}
- src/gis_mcp/main.py:66-72 (registration)Imports the rasterio_functions module (among others), which triggers the execution of decorators like @gis_mcp.tool() on functions such as focal_statistics, thereby registering the tool with the FastMCP server instance.from . import ( geopandas_functions, shapely_functions, rasterio_functions, pyproj_functions, pysal_functions, )
- A resource endpoint that lists available rasterio operations, including 'focal_statistics', for tool discovery.@gis_mcp.resource("gis://operation/rasterio") def get_rasterio_operations() -> Dict[str, List[str]]: """List available rasterio operations.""" return { "operations": [ "metadata_raster", "get_raster_crs", "clip_raster_with_shapefile", "resample_raster", "reproject_raster", "weighted_band_sum", "concat_bands", "raster_algebra", "compute_ndvi", "raster_histogram", "tile_raster", "raster_band_statistics", "extract_band", "zonal_statistics", "reclassify_raster", "focal_statistics", "hillshade", "write_raster" ] }
- The function signature and docstring define the input schema (parameters with types and descriptions) and output schema for the tool, used by FastMCP for validation.def focal_statistics(raster_path: str, statistic: str, size: int = 3, output_path: str = None) -> Dict[str, Any]: """ Compute focal (moving window) statistics on a raster. Args: raster_path: Path to the input raster. statistic: Statistic to compute ('mean', 'min', 'max', 'std'). size: Window size (odd integer). output_path: Optional path to save the result. Returns: Dictionary with status, message, and output path if saved. """