CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-spyndex

Awesome Spectral Indices in Python - comprehensive library for computing spectral indices from remote sensing data

Overview
Eval results
Files

computation.mddocs/

Spectral Index Computation

Core functionality for computing single or multiple spectral indices from the Awesome Spectral Indices catalogue. The computation engine uses dynamic expression evaluation with overloaded operators to support multiple Python data types seamlessly.

Capabilities

Main Index Computation

Computes one or more spectral indices from the standardized catalogue. Automatically handles parameter validation, expression evaluation, and result formatting based on input data types.

def computeIndex(
    index: Union[str, List[str]],
    params: Optional[dict] = None,
    online: bool = False,
    returnOrigin: bool = True,
    coordinate: str = "index",
    **kwargs
) -> Any:
    """
    Computes one or more Spectral Indices from the Awesome Spectral Indices list.

    Parameters:
    - index: Index name or list of index names to compute
    - params: Dictionary of parameters/bands for computation (compatible with overloaded operators)
    - online: Whether to retrieve most recent index list from GitHub (default: False)
    - returnOrigin: Whether to return results in original data type format (default: True)
    - coordinate: Name of coordinate for xarray concatenation (default: "index")
    - **kwargs: Alternative parameter specification (ignored if params provided)

    Returns:
    Computed spectral indices with type depending on inputs:
    - Single index with numeric inputs: float
    - Multiple indices with numeric inputs: list[float]
    - NumPy arrays: numpy.ndarray
    - Pandas Series: pandas.DataFrame
    - Xarray DataArray: xarray.DataArray
    - Earth Engine Image: ee.Image
    - Earth Engine Number: ee.List
    - Dask Array: dask.Array
    - Dask DataFrame: dask.DataFrame
    """

Usage Examples:

import spyndex
import numpy as np
import pandas as pd
import xarray as xr

# Single index with numeric values
ndvi = spyndex.computeIndex("NDVI", params={"N": 0.643, "R": 0.175})
# Returns: 0.5721271393643031

# Multiple indices with keyword arguments
indices = spyndex.computeIndex(
    ["NDVI", "SAVI"],
    N=0.643,
    R=0.175,
    L=0.5
)
# Returns: [0.5721271393643031, 0.5326251896813354]

# NumPy arrays
nir = np.random.normal(0.67, 0.12, 10000)
red = np.random.normal(0.12, 0.05, 10000)
result = spyndex.computeIndex(
    ["NDVI", "GNDVI"],
    params={
        "N": nir,
        "R": red,
        "G": np.random.normal(0.34, 0.07, 10000)
    }
)
# Returns: numpy.ndarray with shape (2, 10000)

# Pandas DataFrame
df = pd.DataFrame({
    "Red": np.random.normal(0.12, 0.05, 1000),
    "NIR": np.random.normal(0.67, 0.12, 1000)
})
result = spyndex.computeIndex(
    "NDVI",
    params={
        "N": df["NIR"],
        "R": df["Red"]
    }
)
# Returns: pandas.Series

# Xarray DataArray
data = xr.DataArray(
    np.array([
        np.random.normal(0.1, 0.1, (100, 100)),  # Blue
        np.random.normal(0.3, 0.1, (100, 100)),  # Green  
        np.random.normal(0.1, 0.1, (100, 100)),  # Red
        np.random.normal(0.6, 0.1, (100, 100))   # NIR
    ]),
    dims=("band", "x", "y"),
    coords={"band": ["B", "G", "R", "N"]}
)
result = spyndex.computeIndex(
    ["NDVI", "SAVI"],
    params={
        "N": data.sel(band="N"),
        "R": data.sel(band="R"),
        "L": 0.5
    }
)
# Returns: xarray.DataArray with index dimension

Kernel Computation

Computes kernel functions used in kernel-based spectral indices. Supports linear, polynomial, and RBF (Radial Basis Function) kernels with configurable parameters.

def computeKernel(
    kernel: str,
    params: Optional[dict] = None,
    **kwargs
) -> Any:
    """
    Computes a kernel k(a,b) for kernel-based spectral indices.

    Parameters:
    - kernel: Kernel type ("linear", "poly", "RBF")  
    - params: Kernel parameters dictionary
      - For "linear": requires 'a' and 'b' (band values)
      - For "poly": requires 'a', 'b', 'p' (degree), 'c' (trade-off)
      - For "RBF": requires 'a', 'b', 'sigma' (length-scale)
    - **kwargs: Alternative parameter specification

    Returns:
    Computed kernel value (type matches input data)
    """

Kernel Formulas:

  • Linear: a * b
  • Polynomial: ((a * b) + c) ** p
  • RBF: exp((-1.0 * (a - b) ** 2.0) / (2.0 * sigma ** 2.0))

Usage Examples:

import spyndex
import numpy as np

# Linear kernel for kNDVI computation
knr_linear = spyndex.computeKernel(
    "linear",
    params={"a": 0.68, "b": 0.13}
)

# RBF kernel computation
knr_rbf = spyndex.computeKernel(
    "RBF",
    params={
        "a": 0.68,
        "b": 0.13,
        "sigma": (0.68 + 0.13) / 2
    }
)

# Use kernel in kNDVI index computation
kndvi = spyndex.computeIndex(
    "kNDVI",
    params={
        "kNN": 1.0,
        "kNR": knr_rbf
    }
)

# Polynomial kernel with arrays
nir = np.random.normal(0.67, 0.12, 1000)
red = np.random.normal(0.12, 0.05, 1000)

knr_poly = spyndex.computeKernel(
    "poly",
    params={
        "a": nir,
        "b": red,
        "p": 2.0,
        "c": spyndex.constants.c.default
    }
)
# Returns: numpy.ndarray with computed polynomial kernel values

Parameter Validation

All computation functions automatically validate required parameters:

  • Index validation: Checks if requested index exists in catalogue
  • Parameter completeness: Ensures all required bands/parameters are provided
  • Earth Engine compatibility: Automatically detects and handles Earth Engine objects

Data Type Handling

Return Type Logic

The returnOrigin parameter controls output formatting:

  • returnOrigin=True (default): Returns results in format matching input data type

    • Multiple indices are concatenated/stacked appropriately
    • Single index returns the computed value directly
  • returnOrigin=False: Always returns a list of computed values

    • Useful when you need consistent list output regardless of input type

Multi-Index Results

When computing multiple indices:

  • NumPy arrays: Stacked as numpy.ndarray with first dimension as index count
  • Pandas Series: Combined into pandas.DataFrame with index names as columns
  • Xarray DataArray: Concatenated along specified coordinate dimension
  • Earth Engine Image: Combined into multi-band ee.Image with index names as band names
  • Earth Engine Number: Returned as ee.List
  • Dask arrays: Stacked as dask.Array
  • Dask DataFrames: Concatenated with index names as columns

Online Index Retrieval

Setting online=True retrieves the most recent spectral indices directly from the Awesome Spectral Indices GitHub repository, ensuring access to newly added indices and formula updates. This requires an internet connection and may be slower than using the local catalogue.

Install with Tessl CLI

npx tessl i tessl/pypi-spyndex

docs

bands.md

catalogue.md

computation.md

constants.md

datasets.md

index.md

plotting.md

tile.json