Package {GeoIndexR}


Title: Computation of Spectral and Geospatial Indices from Multispectral Raster Data
Version: 0.1.0
Description: A unified, fast, and extensible framework for calculating spectral and geospatial indices from multispectral raster datasets (e.g., NDVI - Normalized Difference Vegetation Index, NDWI - Normalized Difference Water Index, MNDWI - Modified Normalized Difference Water Index, NDBI - Normalized Difference Built-up Index, SAVI - Soil Adjusted Vegetation Index, EVI - Enhanced Vegetation Index, GNDVI - Green Normalized Difference Vegetation Index, NDMI - Normalized Difference Moisture Index, BSI - Bare Soil Index). Designed around 'terra' 'SpatRaster' objects, it supports multi-band rasters, automatic band resolution, sensor presets (Sentinel-2, Landsat-8/9), customizable index parameters, vectorized computations, and comprehensive validation. Methods based on Rouse et al. (1973) , McFeeters (1996) <doi:10.1080/01431169608948714>, Xu (2006) <doi:10.1080/01431160600589179>, Zha et al. (2003) <doi:10.1016/S0034-4257(03)00087-7>, Huete (1988) <doi:10.1016/0034-4257(88)90106-X>, Gitelson et al. (1996) <doi:10.1016/S0034-4257(96)00072-7>, Wilson and Sader (2002) <doi:10.1016/S0034-4257(01)00318-2>, and Rikimaru et al. (2002).
License: MIT + file LICENSE
URL: https://github.com/sowsalim01/GeoIndexR
BugReports: https://github.com/sowsalim01/GeoIndexR/issues
Depends: R (≥ 3.5.0)
Imports: graphics, stats, terra (≥ 1.7-0)
Suggests: covr, knitr, rmarkdown, testthat (≥ 3.0.0)
Config/testthat/edition: 3
Encoding: UTF-8
VignetteBuilder: knitr
Config/roxygen2/version: 8.1.0
NeedsCompilation: no
Packaged: 2026-09-29 15:41:45 UTC; hp
Author: Mamadou Sow [aut, cre]
Maintainer: Mamadou Sow <sowsalim01@gmail.com>
Repository: CRAN
Date/Publication: 2026-10-10 10:40:07 UTC

GeoIndexR: Computation of Spectral and Geospatial Indices from Multispectral Raster Data

Description

A unified, fast, and extensible framework for calculating spectral and geospatial indices from multispectral raster datasets (e.g., NDVI - Normalized Difference Vegetation Index, NDWI - Normalized Difference Water Index, MNDWI - Modified Normalized Difference Water Index, NDBI - Normalized Difference Built-up Index, SAVI - Soil Adjusted Vegetation Index, EVI - Enhanced Vegetation Index, GNDVI - Green Normalized Difference Vegetation Index, NDMI - Normalized Difference Moisture Index, BSI - Bare Soil Index). Designed around 'terra' 'SpatRaster' objects, it supports multi-band rasters, automatic band resolution, sensor presets (Sentinel-2, Landsat-8/9), customizable index parameters, vectorized computations, and comprehensive validation. Methods based on Rouse et al. (1973), McFeeters (1996) doi:10.1080/01431169608948714, Xu (2006) doi:10.1080/01431160600589179, Zha et al. (2003) doi:10.1016/S0034-4257(03)00087-7, Huete (1988) doi:10.1016/0034-4257(88)90106-X, Gitelson et al. (1996) doi:10.1016/S0034-4257(96)00072-7, Wilson and Sader (2002) doi:10.1016/S0034-4257(01)00318-2, and Rikimaru et al. (2002).

Author(s)

Maintainer: Mamadou Sow sowsalim01@gmail.com

Authors:

See Also

Useful links:


Formula Engine for Custom Spectral Indices

Description

Provides secure parsing, syntax tree validation, and vectorized evaluation of mathematical expressions on multispectral raster layers and numeric values.

Usage

ALLOWED_OPERATORS

Sensor Band Mapping Presets

Description

Provides standard band name mappings for commonly used multispectral sensors and generic naming conventions.

Usage

band_mapping(
  sensor = c("generic", "sentinel2", "s2", "landsat8", "landsat9", "l8", "l9",
    "landsat7", "landsat5", "tm", "etm")
)

Arguments

sensor

Character string specifying the sensor preset. Supported options:

  • "generic": Common names (blue, green, red, nir, swir, swir1, swir2, rededge).

  • "sentinel2" or "s2": Sentinel-2 MSI bands (B02, B03, B04, B08, B11, B12, etc.).

  • "landsat8" / "landsat9" or "l8" / "l9": Landsat 8/9 OLI bands (B1 to B7).

  • "landsat7" / "landsat5" or "etm" / "tm": Landsat 4-7 TM/ETM+ bands (B1 to B7).

Defaults to "generic".

Value

A named character vector where names represent standardized spectral band roles (e.g., "nir", "red") and values represent corresponding band or layer names for the selected sensor.

Examples

# Generic mapping
band_mapping("generic")

# Sentinel-2 band mapping
band_mapping("sentinel2")

# Landsat 8/9 band mapping
band_mapping("landsat8")


Calculate Atmospherically Resistant Vegetation Index (ARVI)

Description

Computes the Atmospherically Resistant Vegetation Index (ARVI), which uses the difference between blue and red bands to reduce atmospheric aerosol effects on red reflectance.

Usage

calc_arvi(nir, red, blue, gamma = 1)

Arguments

nir

Near-infrared band (terra::SpatRaster or numeric).

red

Red band (terra::SpatRaster or numeric).

blue

Blue band (terra::SpatRaster or numeric).

gamma

Aerosol resistance coefficient. Defaults to 1.0.

Details

ARVI = \frac{NIR - RB}{NIR + RB}

where RB = RED - \gamma \times (BLUE - RED).

Value

A terra::SpatRaster (named "ARVI") or numeric vector with index values.

References

Kaufman, Y. J., & Tanre, D. (1992). Atmospherically resistant vegetation index (ARVI) for EOS-MODIS. IEEE TGRS, 30(2), 261-270.

See Also

calc_ndvi, calc_evi, geo_index

Examples

calc_arvi(nir = 0.7, red = 0.2, blue = 0.1)


Calculate Automated Water Extraction Index (AWEI)

Description

Computes the Automated Water Extraction Index (AWEI) to extract surface water while suppressing shadow artifacts and dark impervious surfaces.

Usage

calc_awei(green, nir, swir1, swir2)

Arguments

green

Green band (terra::SpatRaster or numeric).

nir

Near-infrared band (terra::SpatRaster or numeric).

swir1

SWIR 1 band (terra::SpatRaster or numeric).

swir2

SWIR 2 band (terra::SpatRaster or numeric).

Details

AWEI = 4 \times (GREEN - SWIR1) - (0.25 \times NIR + 2.75 \times SWIR2)

Value

A terra::SpatRaster (named "AWEI") or numeric vector with index values.

References

Feyisa, G. L., Meilby, H., Fensholt, R., & Proud, S. R. (2014). Automated Water Extraction Index: A new technique for surface water mapping using Landsat imagery. Remote Sensing of Environment, 140, 23-35.

See Also

calc_ndwi, calc_mndwi, geo_index

Examples

calc_awei(green = 0.5, nir = 0.2, swir1 = 0.1, swir2 = 0.05)


Calculate Bare Soil Index (BSI)

Description

Computes the Bare Soil Index (BSI), combining blue, red, NIR, and SWIR bands to distinguish bare soils from vegetation and impervious land.

Usage

calc_bsi(swir1, red, nir, blue)

Arguments

swir1

Short-wave infrared 1 band (terra::SpatRaster or numeric).

red

Red band (terra::SpatRaster or numeric).

nir

Near-infrared band (terra::SpatRaster or numeric).

blue

Blue band (terra::SpatRaster or numeric).

Details

BSI = \frac{(SWIR1 + RED) - (NIR + BLUE)}{(SWIR1 + RED) + (NIR + BLUE)}

Value

A terra::SpatRaster (named "BSI") or numeric vector with index values.

References

Rikimaru, A., Roy, P. S., & Miyatake, S. (2002). Tropical forest cover density mapping. Tropical Ecology, 43(1), 39-47.

See Also

geo_index

Examples

calc_bsi(swir1 = 0.5, red = 0.4, nir = 0.2, blue = 0.1)


Calculate Enhanced Vegetation Index (EVI)

Description

Computes the Enhanced Vegetation Index (EVI), optimizing the vegetation signal with improved sensitivity in high biomass regions and reduced atmospheric aerosol influences.

Usage

calc_evi(nir, red, blue, G = 2.5, C1 = 6, C2 = 7.5, L = 1)

Arguments

nir

Near-infrared band (terra::SpatRaster or numeric).

red

Red band (terra::SpatRaster or numeric).

blue

Blue band (terra::SpatRaster or numeric).

G

Gain factor. Defaults to 2.5.

C1

Atmospheric resistance coefficient for red. Defaults to 6.0.

C2

Atmospheric resistance coefficient for blue. Defaults to 7.5.

L

Canopy background adjustment. Defaults to 1.0.

Details

EVI = G \times \frac{NIR - RED}{NIR + C1 \times RED - C2 \times BLUE + L}

Description & Purpose: EVI was developed to enhance the vegetation signal in dense canopies where NDVI saturates, while reducing canopy background noise and aerosol scattering using the blue band.

Important - Reflectance Scale: EVI constants (G = 2.5, C1 = 6.0, C2 = 7.5, L = 1.0) were calibrated for physical surface reflectance in [0, 1]. If your input data are stored in raw integer Digital Numbers (e.g., Sentinel-2 L2A [0, 10000]), divide the inputs by 10000 or use geo_index(..., scale_factor = 10000).

Value

A terra::SpatRaster (named "EVI") or numeric vector with index values.

References

Liu, H. Q., & Huete, A. (1995). A feedback based modification of the NDVI to minimize canopy background and atmospheric noise. IEEE TGRS, 33(2), 457-465.

See Also

geo_index, calc_ndvi, calc_savi

Examples

# Numeric example with surface reflectance values in [0, 1]
calc_evi(nir = 0.50, red = 0.20, blue = 0.10)

# Raster example
img <- get_example_data()
evi_rast <- calc_evi(nir = img[["nir"]], red = img[["red"]], blue = img[["blue"]])
print(evi_rast)


Calculate Green Normalized Difference Vegetation Index (GNDVI)

Description

Computes the Green Normalized Difference Vegetation Index (GNDVI) from near-infrared (nir) and green (green) bands.

Usage

calc_gndvi(nir, green)

Arguments

nir

Near-infrared band (terra::SpatRaster or numeric).

green

Green band (terra::SpatRaster or numeric).

Details

GNDVI = \frac{NIR - GREEN}{NIR + GREEN}

Description & Purpose: GNDVI is more sensitive to chlorophyll variations than standard NDVI, especially in mid-to-high biomass stages and dense crops.

Value

A terra::SpatRaster (named "GNDVI") or numeric vector with index values.

References

Gitelson, A. A., Kaufman, Y. J., & Merzlyak, M. N. (1996). Use of a green channel in remote sensing of global vegetation from EOS-MODIS. Remote Sensing of Environment, 58(3), 289-298.

See Also

calc_ndvi, geo_index

Examples

calc_gndvi(nir = 0.8, green = 0.2)


Calculate Index-Based Built-Up Index (IBI)

Description

Computes the Index-Based Built-Up Index (IBI) by synthesizing NDBI, SAVI, and MNDWI.

Usage

calc_ibi(swir1, nir, red, green, L = 0.5)

Arguments

swir1

Short-wave infrared 1 band (terra::SpatRaster or numeric).

nir

Near-infrared band (terra::SpatRaster or numeric).

red

Red band (terra::SpatRaster or numeric).

green

Green band (terra::SpatRaster or numeric).

L

Soil adjustment factor for internal SAVI. Defaults to 0.5.

Value

A terra::SpatRaster (named "IBI") or numeric vector with index values.

References

Xu, H. (2007). Extraction of urban built-up land features from Landsat imagery using a new index-based approach. International Journal of Remote Sensing, 29(14), 4267-4283.

See Also

calc_ndbi, geo_index

Examples

calc_ibi(swir1 = 0.4, nir = 0.3, red = 0.2, green = 0.1)


Dispatch and Calculate a Named Index

Description

Dynamically invokes the calculation function for any registered index by name.

Usage

calc_index(index, ...)

Arguments

index

Character string specifying index name (e.g., "NDVI", "SAVI").

...

Named band arguments (e.g., nir = ..., red = ...) and optional index parameters (such as L = 0.5).

Value

A SpatRaster or numeric vector.

Examples

calc_index("NDVI", nir = 0.8, red = 0.2)
calc_index("SAVI", nir = 0.8, red = 0.2, L = 0.5)


Calculate Modified Normalized Difference Water Index (MNDWI)

Description

Computes Xu's Modified Normalized Difference Water Index (MNDWI), substituting SWIR1 for NIR to enhance open water features in urban landscapes.

Usage

calc_mndwi(green, swir1)

Arguments

green

Green band (terra::SpatRaster or numeric).

swir1

Short-wave infrared 1 band (terra::SpatRaster or numeric).

Details

MNDWI = \frac{GREEN - SWIR1}{GREEN + SWIR1}

Description & Purpose: Standard NDWI can produce false water detections on built-up and impervious surfaces. MNDWI suppresses built-up noise significantly because urban land has high SWIR reflectance.

Value

A terra::SpatRaster (named "MNDWI") or numeric vector with index values.

References

Xu, H. (2006). Modification of normalised difference water index (NDWI) to enhance open water features in remotely sensed imagery. IJRS, 27(14), 3025-3033.

See Also

calc_ndwi, calc_awei, geo_index

Examples

calc_mndwi(green = 0.7, swir1 = 0.1)


Calculate Modified Soil Adjusted Vegetation Index 2 (MSAVI)

Description

Computes the Modified Soil Adjusted Vegetation Index 2 (MSAVI2), which eliminates the need for manually finding or specifying a soil adjustment factor L.

Usage

calc_msavi(nir, red)

Arguments

nir

Near-infrared band (terra::SpatRaster or numeric).

red

Red band (terra::SpatRaster or numeric).

Details

MSAVI = \frac{2 \times NIR + 1 - \sqrt{(2 \times NIR + 1)^2 - 8 \times (NIR - RED)}}{2}

Description & Purpose: MSAVI simplifies SAVI by calculating an inductive soil adjustment factor mathematically, providing high sensitivity in sparse vegetation without requiring empirical soil line parameters.

Value

A terra::SpatRaster (named "MSAVI") or numeric vector with index values.

References

Qi, J., Chehbouni, A., Huete, A. R., Kerr, Y. H., & Sorooshian, S. (1994). A modified soil adjusted vegetation index. Remote Sensing of Environment, 48(2), 119-126.

See Also

calc_savi, calc_osavi, geo_index

Examples

# Numeric scalar calculation
calc_msavi(nir = 0.7, red = 0.2)

# Raster layer calculation
img <- get_example_data()
msavi_rast <- calc_msavi(nir = img[["nir"]], red = img[["red"]])
print(msavi_rast)


Calculate Moisture Stress Index (MSI)

Description

Computes the Moisture Stress Index (MSI) from SWIR1 and NIR bands.

Usage

calc_msi(swir1, nir)

Arguments

swir1

Short-wave infrared 1 band (terra::SpatRaster or numeric).

nir

Near-infrared band (terra::SpatRaster or numeric).

Details

MSI = \frac{SWIR1}{NIR}

Value

A terra::SpatRaster (named "MSI") or numeric vector with index values.

References

Rock, B. N., Vogelmann, J. E., Williams, D. L., & Vogelmann, A. F. (1986). Remote detection of forest damage. BioScience, 36(7), 439-445.

See Also

calc_ndmi, geo_index

Examples

calc_msi(swir1 = 0.4, nir = 0.8)


Calculate Normalized Difference Built-up Index (NDBI)

Description

Computes the Normalized Difference Built-up Index (NDBI) for mapping urban and impervious surfaces.

Usage

calc_ndbi(swir1, nir)

Arguments

swir1

Short-wave infrared 1 band (terra::SpatRaster or numeric).

nir

Near-infrared band (terra::SpatRaster or numeric).

Details

NDBI = \frac{SWIR1 - NIR}{SWIR1 + NIR}

Value

A terra::SpatRaster (named "NDBI") or numeric vector with index values.

References

Zha, Y., Gao, J., & Ni, S. (2003). Use of normalized difference built-up index in automatically mapping urban areas from TM imagery. IJRS, 24(3), 583-594.

See Also

calc_ibi, geo_index

Examples

calc_ndbi(swir1 = 0.6, nir = 0.3)


Calculate Normalized Difference Moisture Index (NDMI)

Description

Computes the Normalized Difference Moisture Index (NDMI) to assess vegetation canopy liquid water content.

Usage

calc_ndmi(nir, swir1)

Arguments

nir

Near-infrared band (terra::SpatRaster or numeric).

swir1

Short-wave infrared 1 band (terra::SpatRaster or numeric).

Details

NDMI = \frac{NIR - SWIR1}{NIR + SWIR1}

Value

A terra::SpatRaster (named "NDMI") or numeric vector with index values.

References

Gao, B. C. (1996). NDWI—A normalized difference water index for remote sensing of vegetation liquid water from space. Remote Sensing of Environment, 58(3), 257-266.

See Also

calc_msi, geo_index

Examples

calc_ndmi(nir = 0.7, swir1 = 0.3)


Calculate Normalized Difference Snow Index (NDSI)

Description

Computes the Normalized Difference Snow Index (NDSI) for mapping snow and ice cover.

Usage

calc_ndsi(green, swir1)

Arguments

green

Green band (terra::SpatRaster or numeric).

swir1

Short-wave infrared 1 band (terra::SpatRaster or numeric).

Details

NDSI = \frac{GREEN - SWIR1}{GREEN + SWIR1}

Value

A terra::SpatRaster (named "NDSI") or numeric vector with index values.

References

Hall, D. K., Riggs, G. A., & Salomonson, V. V. (1995). Development of methods for mapping global snow cover using moderate resolution imaging spectroradiometer data. Remote Sensing of Environment, 54(2), 127-140.

See Also

geo_index

Examples

calc_ndsi(green = 0.8, swir1 = 0.2)


Calculate Normalized Difference Vegetation Index (NDVI)

Description

Computes the Normalized Difference Vegetation Index (NDVI) directly from near-infrared (nir) and red (red) bands or numeric vectors.

Usage

calc_ndvi(nir, red)

Arguments

nir

Near-infrared band (terra::SpatRaster or numeric vector/matrix).

red

Red band (terra::SpatRaster or numeric vector/matrix).

Details

NDVI = \frac{NIR - RED}{NIR + RED}

Description & Purpose: NDVI is the most widely used remote sensing index for monitoring vegetation greenness, photosynthetic activity, and canopy vigor. Chlorophyll pigments in green leaves absorb red light strongly, while the spongy mesophyll structure scatters near-infrared light.

Direct Band Usage vs geo_index(): While geo_index(image, "NDVI") handles multi-band raster extraction and band mapping automatically, calc_ndvi() is a direct, lower-level computation function that works on:

Value Range & Interpretation:

Value

A single-layer terra::SpatRaster (with layer name "NDVI") or a numeric vector matching input dimensions.

References

Rouse, J. W., Haas, R. H., Schell, J. A., & Deering, D. W. (1974). Monitoring the vernal advancement and retrogradation (Green wave effect) of natural vegetation. NASA/GSFC Type III Final Report, Greenbelt, MD.

See Also

geo_index, calc_savi, calc_evi, index_registry

Examples

library(terra)

# --- Example 1: Direct calculation on numeric values ---
calc_ndvi(nir = 0.8, red = 0.2)

# Vectorized computation on numeric vectors:
nirs <- c(0.8, 0.5, 0.1, 0.02)
reds <- c(0.1, 0.3, 0.1, 0.05)
calc_ndvi(nir = nirs, red = reds)

# --- Example 2: Calculation on extracted SpatRaster layers ---
img <- get_example_data()
ndvi_rast <- calc_ndvi(nir = img[["nir"]], red = img[["red"]])
print(ndvi_rast)


Calculate Normalized Difference Water Index (NDWI)

Description

Computes McFeeters' Normalized Difference Water Index (NDWI) for delineating open water bodies.

Usage

calc_ndwi(green, nir)

Arguments

green

Green band (terra::SpatRaster or numeric).

nir

Near-infrared band (terra::SpatRaster or numeric).

Details

NDWI = \frac{GREEN - NIR}{GREEN + NIR}

Description & Purpose: NDWI maximizes the reflectance of water in the green wavelength while minimizing the low reflectance of water in the NIR wavelength.

Interpretation:

Value

A terra::SpatRaster (named "NDWI") or numeric vector with index values.

References

McFeeters, S. K. (1996). The use of the Normalized Difference Water Index (NDWI) in the delineation of open water features. International Journal of Remote Sensing, 17(7), 1425-1432.

See Also

calc_mndwi, calc_awei, geo_index

Examples

calc_ndwi(green = 0.6, nir = 0.2)

img <- get_example_data()
ndwi_rast <- calc_ndwi(green = img[["green"]], nir = img[["nir"]])
print(ndwi_rast)


Calculate Optimized Soil-Adjusted Vegetation Index (OSAVI)

Description

Computes the Optimized Soil-Adjusted Vegetation Index (OSAVI) with a standard optimal adjustment parameter theta = 0.16.

Usage

calc_osavi(nir, red, theta = 0.16)

Arguments

nir

Near-infrared band (terra::SpatRaster or numeric).

red

Red band (terra::SpatRaster or numeric).

theta

Canopy background adjustment factor. Defaults to 0.16.

Details

OSAVI = \frac{NIR - RED}{NIR + RED + \theta} \times (1 + \theta)

Description & Purpose: OSAVI is an optimization of SAVI that fixes theta = 0.16, which was found to provide optimal suppression of soil background variation across a broad range of agricultural canopies.

Value

A terra::SpatRaster (named "OSAVI") or numeric vector with index values.

References

Rondeaux, G., Steven, M., & Baret, F. (1996). Optimization of soil-adjusted vegetation indices. Remote Sensing of Environment, 55(2), 95-107.

See Also

calc_savi, calc_msavi, geo_index

Examples

calc_osavi(nir = 0.7, red = 0.2)

img <- get_example_data()
osavi_rast <- calc_osavi(nir = img[["nir"]], red = img[["red"]])
print(osavi_rast)


Calculate Soil Adjusted Vegetation Index (SAVI)

Description

Computes the Soil Adjusted Vegetation Index (SAVI) to minimize soil brightness and background influences, using a canopy background adjustment factor L.

Usage

calc_savi(nir, red, L = 0.5)

Arguments

nir

Near-infrared band (terra::SpatRaster or numeric).

red

Red band (terra::SpatRaster or numeric).

L

Soil adjustment factor. Defaults to 0.5.

Details

SAVI = \frac{NIR - RED}{NIR + RED + L} \times (1 + L)

Description & Purpose: In arid, semi-arid, or sparsely vegetated regions, exposed soil background alters red and NIR reflectance, distorting standard vegetation indices like NDVI. SAVI introduces a soil line calibration constant L that stabilizes the index.

Parameter L:

Value

A terra::SpatRaster (named "SAVI") or numeric vector with index values.

References

Huete, A. R. (1988). A soil-adjusted vegetation index (SAVI). Remote Sensing of Environment, 25(3), 295-309.

See Also

geo_index, calc_osavi, calc_msavi, calc_ndvi

Examples

# Numeric scalar calculation
calc_savi(nir = 0.7, red = 0.2, L = 0.5)

# Raster layer calculation
img <- get_example_data()
savi_rast <- calc_savi(nir = img[["nir"]], red = img[["red"]], L = 0.5)
print(savi_rast)


Check that an object is numeric or SpatRaster

Description

Check that an object is numeric or SpatRaster

Usage

check_numeric_or_raster(x, arg_name = "band")

Arguments

x

Object to check.

arg_name

Name of argument.

Value

Invisible TRUE if valid; throws error otherwise.


Check that an object is a SpatRaster

Description

Check that an object is a SpatRaster

Usage

check_raster(x, arg_name = "image")

Arguments

x

Object to check.

arg_name

Name of the argument in the calling function.

Value

Invisible TRUE if valid; throws an error otherwise.


Check Spatial Compatibility Across Raster Bands

Description

Validates that a list of terra::SpatRaster objects share identical geometry, CRS, and dimensions before computing pixel-wise operations.

Usage

check_spatial_compatibility(band_list)

Arguments

band_list

Named list of SpatRaster or numeric objects.

Value

Invisible TRUE if all raster inputs are compatible.


Safely Evaluate Formula on Bands and Parameters

Description

Evaluates a validated AST expression in a controlled, isolated environment containing only the raster/numeric bands, supplied parameters, and safe mathematical operators.

Usage

evaluate_custom_formula(
  parsed_expr,
  band_layers,
  params = list(),
  denominator_tolerance = 1e-06
)

Arguments

parsed_expr

Parsed language expression.

band_layers

Named list of SpatRaster or numeric band values.

params

Named list of numeric parameter constants.

denominator_tolerance

Tolerance for near-zero denominators. Defaults to 1e-6.

Value

A SpatRaster or numeric result.


Compute a Spectral Index from Multispectral Raster Data

Description

Calculates a specified spectral or geospatial index from a terra::SpatRaster object or a raster file path. Band names are automatically resolved using heuristic matching, sensor presets, or explicit user mapping.

Usage

geo_index(image, index, bands = NULL, scale_factor = NULL, sensor = NULL, ...)

Arguments

image

A terra::SpatRaster object or a character string specifying the file path to a raster image on disk.

index

Character string specifying the index to compute (case-insensitive, e.g., "NDVI", "SAVI", "EVI", "NDWI", etc.). See list_indices or index_registry for supported indices.

bands

Optional named vector or list specifying custom band mapping (e.g., c(nir = "B08", red = "B04") or c(nir = 4, red = 3)).

scale_factor

Optional numeric scaling divisor (e.g., 10000 for Sentinel-2 L2A or Landsat surface reflectance) to convert integer Digital Numbers into physical reflectance [0, 1].

sensor

Optional character string specifying a sensor preset for automatic band name resolution (e.g., "sentinel2", "landsat8", "landsat9").

...

Additional parameters passed to the index calculation function (e.g., soil adjustment factor L for SAVI, or gain factor G for EVI).

Value

A single-layer terra::SpatRaster object containing the computed index values, with layer name set to the uppercase index code, preserving all original spatial properties (CRS, resolution, extent, dimensions).

Examples

img <- get_example_data()

# 1. Compute NDVI
ndvi <- geo_index(img, "NDVI")
print(ndvi)

# 2. Compute SAVI with custom parameter
savi <- geo_index(img, "SAVI", L = 0.5)

# 3. Compute EVI with scale factor for raw DN values
evi <- geo_index(img, "EVI", scale_factor = 1)


Compute All Eligible Spectral Indices Automatically

Description

Automatically detects which spectral indices can be computed given the available bands in a terra::SpatRaster image (or raster file path) and calculates all of them.

Usage

geo_index_all(
  image,
  bands = NULL,
  scale_factor = NULL,
  sensor = NULL,
  quiet = FALSE,
  ...
)

Arguments

image

A terra::SpatRaster object or raster file path containing multispectral bands.

bands

Optional named vector or list specifying custom band mapping.

scale_factor

Optional numeric scaling divisor (e.g. 10000).

sensor

Optional character string specifying a sensor preset.

quiet

Logical. If FALSE (default), outputs an informative message listing which indices were detected and computed.

...

Additional parameters passed to index calculation functions.

Value

A multi-layer terra::SpatRaster containing all computable indices as individual layers.

Examples

img <- get_example_data()

# Compute all supported indices compatible with img bands
all_idx <- geo_index_all(img)
names(all_idx)


Compute a Custom Spectral or Geospatial Index

Description

Computes a custom spectral or geospatial index from a raster image or numeric inputs using a user-defined mathematical formula. The formula is securely parsed, validated against an AST whitelist of safe mathematical functions and operators, and evaluated vectorially with terra.

Usage

geo_index_custom(
  image,
  formula,
  bands = NULL,
  params = list(),
  name = "CustomIndex",
  scale_factor = NULL,
  denominator_tolerance = 1e-06,
  sensor = NULL,
  ...
)

Arguments

image

A terra::SpatRaster object or a character string specifying the file path to a raster image on disk.

formula

Character string specifying the mathematical expression to compute (e.g., "(nir - red) / (nir + red)" or "G * (nir - red) / (nir + C1 * red - C2 * blue + L)").

bands

Optional named vector or list specifying custom band mapping (e.g., c(nir = 4, red = 3) or c(nir = "B08", red = "B04")).

params

Optional named list of numeric parameter constants used in the formula (e.g., list(G = 2.5, C1 = 6.0, C2 = 7.5, L = 1.0)).

name

Character string specifying the name of the output index layer. Defaults to "CustomIndex".

scale_factor

Optional numeric scaling divisor (e.g., 10000 for Sentinel-2 or Landsat surface reflectance products) applied to input bands before evaluating the formula.

denominator_tolerance

Numeric threshold for near-zero denominators. Divisions where the absolute denominator is smaller than this value are safely converted to NA. Defaults to 1e-6.

sensor

Optional character string specifying a sensor preset for automatic band name resolution (e.g., "sentinel2", "landsat8").

...

Additional named numeric constants passed directly to the formula evaluation.

Value

A single-layer terra::SpatRaster (or numeric object) containing the computed custom index values, preserving all original spatial properties.

Examples

img <- get_example_data()

# 1. Simple custom ratio index
custom_ratio <- geo_index_custom(
  img,
  formula = "(nir - red) / (nir + red)",
  bands = c(red = "red", nir = "nir"),
  name = "CustomNDVI"
)
print(custom_ratio)

# 2. Custom parameterized index
custom_evi <- geo_index_custom(
  img,
  formula = "G * (nir - red) / (nir + C1 * red - C2 * blue + L)",
  bands = c(blue = "blue", red = "red", nir = "nir"),
  params = list(G = 2.5, C1 = 6.0, C2 = 7.5, L = 1.0),
  name = "CustomEVI"
)
print(custom_evi)


Compute Multiple Spectral Indices from Multispectral Raster Data

Description

Computes a collection of spectral indices from a multispectral terra::SpatRaster or raster file path and returns the results stacked into a multi-layer SpatRaster.

Usage

geo_indices(
  image,
  indices,
  bands = NULL,
  scale_factor = NULL,
  sensor = NULL,
  ...
)

Arguments

image

A terra::SpatRaster object or file path containing multispectral bands.

indices

Character vector of index codes to compute (e.g., c("NDVI", "NDWI", "NDBI", "NDMI")).

bands

Optional named vector or list specifying custom band mapping.

scale_factor

Optional numeric scaling divisor (e.g. 10000).

sensor

Optional character string specifying a sensor preset.

...

Additional parameters passed to index calculation functions.

Value

A multi-layer terra::SpatRaster where each layer corresponds to one computed index, named accordingly.

Examples

img <- get_example_data()

# Compute NDVI, NDWI and MNDWI simultaneously
stack <- geo_indices(img, c("NDVI", "NDWI", "MNDWI"))
print(stack)
names(stack)


Get Example Multispectral SpatRaster

Description

Returns a ready-to-use synthetic 6-band terra::SpatRaster for fast, reproducible examples and unit testing without downloading satellite scenes.

Usage

get_example_data()

Details

The raster is generated programmatically (10 x 10 pixels, 100 m x 100 m extent, EPSG:32631). It contains three simulated land-cover types: healthy vegetation (pixels 2-40), water (pixels 41-70), and built-up / bare soil (pixels 71-100). Pixel 1 is NA in all bands for boundary / NA-handling verification.

Spectral bands (reflectance 0-1):

Value

A terra::SpatRaster with 6 layers named "blue", "green", "red", "nir", "swir1", "swir2".

Examples

img <- get_example_data()
print(img)
terra::nlyr(img)


Retrieve Metadata for a Single Spectral Index

Description

Retrieve Metadata for a Single Spectral Index

Usage

get_index_meta(index)

Arguments

index

Character string specifying index name (e.g., "NDVI").

Value

A list containing detailed index metadata, parameter defaults, and formulas.


Central Registry of Spectral and Geospatial Indices

Description

Retrieves metadata for all built-in spectral indices or a specific index by name or category. Metadata includes mathematical formulas, required spectral bands, parameter defaults, purpose, interpretation guidelines, limitations, scale sensitivity, and scientific literature references.

Usage

index_registry(category = NULL)

Arguments

category

Optional character string to filter indices by category (e.g., "vegetation", "water", "urban", "soil", "moisture", "snow").

Value

A data.frame containing the registry of supported indices and their metadata.

Examples

# View all indices
reg <- index_registry()
reg[, c("index", "name", "category")]

# View vegetation indices only
veg_reg <- index_registry(category = "vegetation")
veg_reg$index


Summary Statistics for Spectral Indices

Description

Computes descriptive statistics for one or multiple spectral index layers in a terra::SpatRaster object, including min, max, mean, median, standard deviation, percentiles (5th, 25th, 75th, 95th), and NA percentage.

Usage

index_summary(x, digits = 4)

Arguments

x

A terra::SpatRaster object containing one or more index layers.

digits

Integer indicating the number of decimal places to round results. Defaults to 4.

Value

A data.frame of class "geo_index_summary" with one row per layer:

index

Layer/index name.

min

Minimum index value.

max

Maximum index value.

mean

Mean index value.

median

Median index value.

sd

Standard deviation.

q05

5th percentile.

q25

25th percentile (1st quartile).

q75

75th percentile (3rd quartile).

q95

95th percentile.

na_pct

Percentage of NA values (0 to 100).

total_cells

Total number of raster cells.

Examples

img <- get_example_data()
ndvi <- geo_index(img, "NDVI")
index_summary(ndvi)

# Multi-layer summary
stack <- geo_indices(img, c("NDVI", "NDWI", "NDBI"))
index_summary(stack)


List Supported Spectral Index Codes

Description

List Supported Spectral Index Codes

Usage

list_indices(category = NULL)

Arguments

category

Optional character string to filter by category.

Value

A character vector of index codes.

Examples

list_indices()
list_indices("vegetation")


Extract Symbols and Validate Formula AST

Description

Recursively traverses the parsed formula AST to verify that only permitted mathematical operators, whitelisted mathematical functions, known spectral bands, and user-supplied parameters are present.

Usage

parse_and_validate_formula(
  formula_str,
  available_bands = character(0),
  param_names = character(0)
)

Arguments

formula_str

Character string containing the mathematical formula.

available_bands

Character vector of valid spectral band identifiers.

param_names

Character vector of valid parameter names.

Value

A list containing:

parsed_expr

The parsed R expression object.

used_bands

Character vector of band names referenced in the formula.

used_params

Character vector of parameter names referenced in the formula.


Visualize a Spectral Index with Thematic Color Palettes

Description

Plots a single-layer or selected layer from a terra::SpatRaster index object using tailored color palettes designed for vegetation, water, soil, urban, and custom analysis.

Usage

plot_index(x, index = NULL, main = NULL, col = NULL, ...)

Arguments

x

A terra::SpatRaster object containing index values.

index

Optional character string specifying which layer to plot if x contains multiple layers.

main

Optional plot title. Defaults to the layer name.

col

Optional color palette. If NULL (default), an appropriate palette is automatically chosen based on the index category or a perceptual palette for custom indices.

...

Additional graphical arguments passed to terra::plot.

Value

Invisible terra::SpatRaster object that was plotted.

Examples

img <- get_example_data()
ndvi <- geo_index(img, "NDVI")
plot_index(ndvi)


Resolve Bands in a SpatRaster Object

Description

Matches required band roles (e.g., "nir", "red") against the layers of a terra::SpatRaster using custom user mapping, sensor presets, or heuristic name aliases. Optionally applies a scale factor (e.g. 10000) to convert raw integer Digital Numbers into physical reflectance [0, 1].

Usage

resolve_bands(
  image,
  required_bands,
  custom_mapping = NULL,
  sensor = NULL,
  index_name = "Index",
  scale_factor = NULL
)

Arguments

image

A terra::SpatRaster object or file path.

required_bands

Character vector of required standardized band names.

custom_mapping

Optional named vector or list mapping required names to layer names or layer indices in image.

sensor

Optional character string for sensor presets.

index_name

Optional character string of the index being calculated (for error reporting).

scale_factor

Optional numeric scaling divisor (e.g. 10000 for Sentinel-2 / Landsat L2A products).

Value

A named list of single-layer terra::SpatRaster objects.


Safe Division Function Handling Zeros, Singularity, and Non-Finite Values

Description

Performs division with protection against division by zero, near-zero denominator singularities ($|den| < tol$), and non-finite values (Inf, -Inf, NaN), replacing invalid results with NA.

Usage

safe_divide(num, den, tol = 1e-06)

Arguments

num

Numerator (SpatRaster or numeric).

den

Denominator (SpatRaster or numeric).

tol

Singularity tolerance threshold. Values with $|den| < tol$ are safely converted to NA. Defaults to 1e-6.

Value

An object of the same class as inputs with values safely bounded and non-finite values replaced by NA.


Validate Raster Input or Filepath

Description

Verifies that the provided input is either a valid terra::SpatRaster object or a valid file path pointing to an existing raster file on disk. If a file path is provided, it is automatically loaded as a SpatRaster.

Usage

validate_raster_input(x, arg_name = "image")

Arguments

x

An object or file path to check.

arg_name

Character string specifying the argument name for error messages.

Value

A terra::SpatRaster object.