Skip to main content
Glama

gamma_statistic

Calculate spatial autocorrelation using the Gamma statistic to analyze geographic patterns in shapefile data.

Instructions

Compute Gamma Statistic for spatial autocorrelation.

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 function for the 'gamma_statistic' tool. It is decorated with @gis_mcp.tool(), loads geospatial data, computes the Gamma spatial autocorrelation statistic using esda.Gamma, handles various attribute names for results, and returns a structured response with status, message, gamma value, p-value, and data preview.
    @gis_mcp.tool()
    def gamma_statistic(shapefile_path: str, dependent_var: str = "LAND_USE", target_crs: str = "EPSG:4326", distance_threshold: float = 100000) -> Dict[str, Any]:
        """Compute Gamma Statistic for spatial autocorrelation."""
        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.Gamma(y, w)
        preview = gdf[['geometry', dependent_var]].head(5).assign(
            geometry=lambda df: df.geometry.apply(lambda g: g.wkt)
        ).to_dict(orient="records")
    
        # Gamma statistic - check for available attributes
        gamma_val = None
        if hasattr(stat, "G"):
            gamma_val = float(stat.G)
        elif hasattr(stat, "gamma"):
            gamma_val = float(stat.gamma)
        elif hasattr(stat, "gamma_index"):
            gamma_val = float(stat.gamma_index)
        
        p_val = None
        if hasattr(stat, "p_value"):
            p_val = float(stat.p_value)
        elif hasattr(stat, "p_sim"):
            p_val = float(stat.p_sim)
        
        return {
            "status": "success",
            "message": f"Gamma Statistic completed successfully (threshold: {threshold} {unit})",
            "result": {
                "Gamma": gamma_val,
                "p_value": p_val,
                "data_preview": preview
            }
        }
  • Supporting helper function 'pysal_load_data' used by gamma_statistic and other PySAL tools. Loads GeoDataFrame, reprojects, creates row-standardized distance-based spatial weights, handles islands, and returns data, values, weights, and threshold info.
    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
  • Resource function listing available ESDA operations including 'gamma_statistic', serving as a discovery/registration point for the tool.
    @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"
            ]
        }
  • Import of pysal_functions module in main.py, which triggers the registration of all @gis_mcp.tool() decorated functions including gamma_statistic via FastMCP decorators.
    from . import (
        geopandas_functions,
        shapely_functions,
        rasterio_functions,
        pyproj_functions,
        pysal_functions,
    )
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions computation but doesn't describe what the tool returns, any performance considerations, or side effects. This is inadequate for a tool with an output schema, as it leaves key behavioral traits unspecified.

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 no wasted words. It is appropriately sized and front-loaded, making it easy to parse quickly.

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

Completeness3/5

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

Given the complexity of spatial analysis and the presence of an output schema, the description is minimally complete. However, with no annotations and 0% schema coverage, it lacks sufficient context about inputs and behavior, though the output schema mitigates some gaps.

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 by explaining parameters, but it adds no meaning beyond the schema. Parameters like shapefile_path, dependent_var, target_crs, and distance_threshold are undocumented in both schema and description, leaving their semantics unclear.

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

Purpose3/5

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

The description states the tool computes the Gamma Statistic for spatial autocorrelation, which is a clear purpose. However, it doesn't specify what the Gamma Statistic measures or how it differs from other spatial autocorrelation tools like morans_i or gearys_c among the siblings, making it somewhat vague in differentiation.

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?

No guidance is provided on when to use this tool versus alternatives like morans_i or gearys_c. The description lacks context about specific use cases or prerequisites, leaving the agent with no explicit usage instructions.

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