Skip to main content
Glama

morans_i

Calculate spatial autocorrelation using Moran's I statistic to identify clustering patterns in geographic data from shapefiles.

Instructions

Compute Moran's I Global Autocorrelation Statistic.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
shapefile_pathYes
dependent_varNoLAND_USE
target_crsNoEPSG:4326
distance_thresholdNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The primary handler for the 'morans_i' tool. Loads a shapefile using geopandas, creates row-standardized distance-based spatial weights with libpysal, computes the global Moran's I statistic using esda.Moran (including simulated p-value and z-score), and returns structured JSON results with a data preview.
    @gis_mcp.tool()
    def morans_i(shapefile_path: str, dependent_var: str = "LAND_USE", target_crs: str = "EPSG:4326", distance_threshold: float = 100000) -> Dict[str, Any]:
        """Compute Moran's I Global Autocorrelation Statistic."""
        gdf, y, w, (threshold, unit), err = pysal_load_data(shapefile_path, dependent_var, target_crs, distance_threshold)
        if err:
            return {"status": "error", "message": err}
    
        import esda
        stat = esda.Moran(y, w)
        preview = gdf[['geometry', dependent_var]].head(5).assign(
            geometry=lambda df: df.geometry.apply(lambda g: g.wkt)
        ).to_dict(orient="records")
    
        return {
            "status": "success",
            "message": f"Moran's I completed successfully (threshold: {threshold} {unit})",
            "result": {
                "I": float(stat.I),
                "morans_i": float(stat.I),  # Also include as morans_i for test compatibility
                "p_value": float(stat.p_sim),
                "z_score": float(stat.z_sim),
                "data_preview": preview
            }
        }
  • Helper function called by morans_i (and other ESDA tools) to validate and load the shapefile as GeoDataFrame, reproject to target CRS, adjust distance threshold for geographic CRS, extract numeric dependent variable array, construct and row-standardize DistanceBand weights, and handle isolated observations (islands).
    def pysal_load_data(shapefile_path: str, dependent_var: str, target_crs: str, distance_threshold: float):
        """Common loader and weight creation for esda statistics."""
        if not os.path.exists(shapefile_path):
            return None, None, None, None, f"Shapefile not found: {shapefile_path}"
    
        gdf = gpd.read_file(shapefile_path)
        if dependent_var not in gdf.columns:
            return None, None, None, None, f"Dependent variable '{dependent_var}' not found in shapefile columns"
    
        gdf = gdf.to_crs(target_crs)
    
        effective_threshold = distance_threshold
        unit = "meters"
        if target_crs.upper() == "EPSG:4326":
            effective_threshold = distance_threshold / 111000
            unit = "degrees"
    
        y = gdf[dependent_var].values.astype(np.float64)
        import libpysal
        w = libpysal.weights.DistanceBand.from_dataframe(gdf, threshold=effective_threshold, binary=False)
        w.transform = 'r'
    
        for island in w.islands:
            w.weights[island] = [0] * len(w.weights[island])
            w.cardinalities[island] = 0
    
        return gdf, y, w, (effective_threshold, unit), None
  • Import block in main.py that loads pysal_functions.py, triggering registration of all @gis_mcp.tool()-decorated functions including morans_i via FastMCP decorators.
    from . import (
        geopandas_functions,
        shapely_functions,
        rasterio_functions,
        pyproj_functions,
        pysal_functions,
    )
  • MCP resource that lists available ESDA operations including 'morans_i', serving as a discovery/schema endpoint for clients to know the tool exists and its name.
    @gis_mcp.resource("gis://operations/esda")
    def get_spatial_operations() -> Dict[str, List[str]]:
        """List available spatial analysis operations. This is for esda library. They are using pysal library."""
        return {
            "operations": [
                "getis_ord_g",
                "morans_i",
                "gearys_c",
                "gamma_statistic",
                "moran_local",
                "getis_ord_g_local",
                "join_counts",
                "join_counts_local",
                "adbscan"
            ]
        }
Behavior1/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full burden but offers minimal behavioral insight. It doesn't disclose computational characteristics (e.g., performance with large datasets), output format (though an output schema exists), error conditions, or dependencies like requiring spatial weights. The description is purely functional without behavioral context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with zero wasted words. It front-loads the core purpose ('Compute Moran's I Global Autocorrelation Statistic') without unnecessary elaboration, making it easy to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (spatial statistics with 4 parameters) and lack of annotations, the description is incomplete. It doesn't cover parameter meanings, usage context, or behavioral traits, though the existence of an output schema mitigates the need to explain return values. For a specialized tool in a crowded sibling set, more guidance is warranted.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate but adds no parameter information. It doesn't explain what 'shapefile_path', 'dependent_var', 'target_crs', or 'distance_threshold' mean, their roles in Moran's I calculation, or typical values. This leaves parameters largely undocumented despite the schema defining them.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool computes 'Moran's I Global Autocorrelation Statistic,' which is a specific statistical operation in spatial analysis. It distinguishes from siblings like 'moran_local' (local autocorrelation) and other spatial statistics tools, though it doesn't explicitly mention spatial data or distinguish from non-statistical siblings like 'clip_raster_with_shapefile.'

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing spatial data with a dependent variable), compare it to siblings like 'gearys_c' or 'getis_ord_g' for other spatial autocorrelation measures, or indicate when global vs. local autocorrelation is appropriate.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/mahdin75/gis-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server