Skip to main content
Glama

distance_band_weights

Create spatial weights for point data based on distance thresholds to analyze spatial relationships in GIS applications.

Instructions

Create a distance-based spatial weights (W) object from point data.

  • data_path: path to point shapefile or GeoPackage

  • threshold: distance threshold for neighbors (in CRS units, e.g., meters)

  • binary: True for binary weights, False for inverse distance weights

  • id_field: optional attribute name to use as observation IDs

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
data_pathYes
thresholdYes
binaryNo
id_fieldNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The primary handler function implementing the 'distance_band_weights' tool. It loads point data from a shapefile, extracts coordinates, creates a libpysal DistanceBand weights object based on the given threshold and binary option, computes statistics and previews, ensures JSON serialization compatibility by converting numpy types, and returns structured results including weights_info for test compatibility.
    def distance_band_weights(
        data_path: str,
        threshold: float,
        binary: bool = True,
        id_field: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Create a distance-based spatial weights (W) object from point data.
    
        - data_path: path to point shapefile or GeoPackage
        - threshold: distance threshold for neighbors (in CRS units, e.g., meters)
        - binary: True for binary weights, False for inverse distance weights
        - id_field: optional attribute name to use as observation IDs
        """
        try:
            if not os.path.exists(data_path):
                return {"status": "error", "message": f"Data file not found: {data_path}"}
    
            gdf = gpd.read_file(data_path)
    
            if gdf.empty:
                return {"status": "error", "message": "Input file contains no features"}
    
            # Extract coordinates
            coords = [(geom.x, geom.y) for geom in gdf.geometry]
    
            # Create DistanceBand weights
            import libpysal
            if id_field and id_field in gdf.columns:
                ids = gdf[id_field].tolist()
                w = libpysal.weights.DistanceBand(coords, threshold=threshold, binary=binary, ids=ids)
            else:
                w = libpysal.weights.DistanceBand(coords, threshold=threshold, binary=binary)
    
            ids = w.id_order
            neighbor_counts = [w.cardinalities[i] for i in ids]
            islands = list(w.islands) if hasattr(w, "islands") else []
    
            # Previews - convert to native Python types immediately
            preview_ids = ids[:5]
            neighbors_preview = {}
            weights_preview = {}
            for i in preview_ids:
                # Convert neighbor IDs and weights to native Python types
                neighbors = w.neighbors.get(i, [])
                weights_list = w.weights.get(i, [])
                neighbors_preview[i] = [int(n) if isinstance(n, (np.integer, np.int32, np.int64)) else n for n in neighbors]
                weights_preview[i] = [float(w_val) if isinstance(w_val, (np.floating, np.float32, np.float64)) else (int(w_val) if isinstance(w_val, (np.integer, np.int32, np.int64)) else w_val) for w_val in weights_list]
    
            result = {
                "n": int(w.n),
                "id_count": int(len(ids)),
                "threshold": float(threshold),
                "binary": bool(binary),
                "id_field": id_field,
                "neighbors_stats": {
                    "min": int(min(neighbor_counts)) if neighbor_counts else 0,
                    "max": int(max(neighbor_counts)) if neighbor_counts else 0,
                    "mean": float(np.mean(neighbor_counts)) if neighbor_counts else 0.0,
                },
                "islands": [int(i) if isinstance(i, (np.integer, np.int32, np.int64)) else i for i in islands],
                "neighbors_preview": neighbors_preview,
                "weights_preview": weights_preview,
            }
    
            # Convert numpy types to native Python types for serialization (recursive)
            def convert_numpy_types(obj):
                """Recursively convert numpy types to native Python types."""
                if obj is None:
                    return None
                if isinstance(obj, dict):
                    return {k: convert_numpy_types(v) for k, v in obj.items()}
                elif isinstance(obj, (list, tuple)):
                    return [convert_numpy_types(item) for item in obj]
                elif isinstance(obj, (np.integer, np.int32, np.int64, np.int8, np.int16)):
                    return int(obj)
                elif isinstance(obj, (np.floating, np.float32, np.float64, np.float16)):
                    return float(obj)
                elif isinstance(obj, np.ndarray):
                    return obj.tolist()
                elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes)):
                    # Handle other iterable types
                    return [convert_numpy_types(item) for item in obj]
                else:
                    return obj
            
            result = convert_numpy_types(result)
    
            return {
                "status": "success",
                "message": "DistanceBand spatial weights constructed successfully",
                "result": result,
                "weights_info": result,  # Also include as weights_info for test compatibility
            }
    
        except Exception as e:
            logger.error(f"Error creating DistanceBand weights: {str(e)}")
            return {"status": "error", "message": f"Failed to create DistanceBand weights: {str(e)}"}
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It states the tool creates a spatial weights object but doesn't disclose behavioral traits such as whether it modifies input data, requires specific file permissions, handles errors, or has performance considerations. The description is minimal and lacks context on what the output entails or how it might be used downstream.

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 front-loaded with the core purpose in the first sentence, followed by a bulleted list of parameters. Every sentence earns its place by directly explaining the tool or its inputs, with zero waste or redundancy. It's appropriately sized for a tool with four parameters.

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 tool's complexity (spatial analysis with multiple parameters) and the presence of an output schema, the description is minimally adequate. It covers the purpose and parameters but lacks behavioral context, usage guidelines, and output details. With no annotations and 0% schema coverage, it should do more to explain the tool's role and behavior in the broader context of sibling tools.

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

Parameters4/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. It adds meaningful semantics for all four parameters: 'data_path' as a path to point shapefile or GeoPackage, 'threshold' as distance threshold in CRS units, 'binary' for weight type, and 'id_field' as optional observation IDs. This clarifies each parameter's role beyond the bare schema, though it could provide more detail on formats or units.

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's purpose: 'Create a distance-based spatial weights (W) object from point data.' It specifies the verb ('create'), resource ('spatial weights object'), and data source ('point data'). However, it doesn't explicitly differentiate from sibling tools like 'knn_weights' or 'weights_from_shapefile', which likely serve similar spatial weights purposes.

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 sibling tools like 'knn_weights' (for k-nearest neighbors) or 'weights_from_shapefile' (which might handle different input formats), nor does it specify prerequisites or typical use cases beyond the basic function.

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