Skip to main content
Glama

weighted_band_sum

Calculate a weighted sum of multi-band raster data using specified weights to produce a single-band output for geospatial analysis.

Instructions

Compute a weighted sum of all bands in a raster using specified weights.

Parameters:

  • source: Path to the input multi-band raster file.

  • weights: List of weights (must match number of bands and sum to 1).

  • destination: Path to save the output single-band raster.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sourceYes
weightsYes
destinationYes

Implementation Reference

  • The handler function that implements the core logic of weighted_band_sum: reads a multi-band raster, applies weights to each band, computes the sum, and writes the result to a new single-band raster file.
    def weighted_band_sum(
        source: str,
        weights: List[float],
        destination: str
    ) -> Dict[str, Any]:
        """
        Compute a weighted sum of all bands in a raster using specified weights.
    
        Parameters:
        - source:      Path to the input multi-band raster file.
        - weights:     List of weights (must match number of bands and sum to 1).
        - destination: Path to save the output single-band raster.
        """
        try:
            import os
            import numpy as np
            import rasterio
    
            src_path = os.path.expanduser(source.replace("`", ""))
            dst_path = os.path.expanduser(destination.replace("`", ""))
    
            with rasterio.open(src_path) as src:
                count = src.count
                if len(weights) != count:
                    raise ValueError(f"Number of weights ({len(weights)}) does not match number of bands ({count}).")
    
                if not np.isclose(sum(weights), 1.0, atol=1e-6):
                    raise ValueError("Sum of weights must be 1.0.")
    
                weighted = np.zeros((src.height, src.width), dtype="float32")
    
                for i in range(1, count + 1):
                    band = src.read(i).astype("float32")
                    weighted += weights[i - 1] * band
    
                profile = src.profile.copy()
                profile.update(dtype="float32", count=1)
    
            os.makedirs(os.path.dirname(dst_path) or ".", exist_ok=True)
    
            with rasterio.open(dst_path, "w", **profile) as dst:
                dst.write(weighted, 1)
    
            return {
                "status": "success",
                "destination": str(dst_path),
                "message": f"Weighted band sum computed and saved to '{dst_path}'."
            }
    
        except Exception as e:
            raise ValueError(f"Failed to compute weighted sum: {e}")
  • Resource function that lists 'weighted_band_sum' among available rasterio operations, indicating its registration in the MCP toolset.
    @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"
            ]
        }
  • src/gis_mcp/mcp.py:1-6 (registration)
    Creates the FastMCP instance 'gis_mcp' to which tools like weighted_band_sum are registered via decorators.
    # MCP imports using the new SDK patterns
    from fastmcp import FastMCP
    
    
    gis_mcp = FastMCP("GIS MCP")

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