### Install spyndex, xcube, and xcube-sh Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/xcube.ipynb Install the necessary libraries using conda. Note that xcube-sh may require installation from source. ```bash $ conda install -c conda-forge spyndex $ conda install -c conda-forge xcube $ conda install -c conda-forge xcube-sh ``` -------------------------------- ### Install Libraries Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/pc.ipynb Install the necessary libraries: spyndex, planetary-computer, and stackstac. This is a prerequisite for using the Planetary Computer API and spyndex. ```python !pip install -U spyndex planetary-computer stackstac ``` -------------------------------- ### Install Spyndex using pip Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/started.md Install the latest version of spyndex from PyPI. This is the most common installation method. ```bash pip install spyndex ``` -------------------------------- ### Install necessary packages Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/geopandas.ipynb Installs the eemont and geemap libraries required for Earth Engine integration and geospatial data handling. ```python !pip install eemont geemap ``` -------------------------------- ### Install spyndex Source: https://context7.com/awesome-spectral-indices/spyndex/llms.txt Install the spyndex library using pip or conda. For Google Earth Engine support, install with the 'ee' extra. ```bash pip install spyndex ``` ```bash conda install -c conda-forge spyndex ``` ```bash pip install "spyndex[ee]" ``` ```bash pip install git+https://github.com/davemlz/spyndex ``` -------------------------------- ### Install Spyndex Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/ee.ipynb Install the spyndex library using pip. Ensure you have the latest version. ```python !pip install -U spyndex ``` -------------------------------- ### Install Spyndex development version from GitHub Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/started.md Install the latest development version of spyndex directly from its GitHub repository. Use this if you need the newest features or bug fixes before they are released on PyPI. ```bash pip install git+https://github.com/davemlz/spyndex ``` -------------------------------- ### spyndex.datasets Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/reference.md Provides example datasets for use with spyndex. This module is automatically loaded with `import spyndex`. Functions from this module can be accessed directly (e.g., `spyndex.datasets.open()`). ```APIDOC ## spyndex.datasets Example datasets. Automatically loaded with `import spyndex`. Functions from this module can be loaded from the module (e.g., `spyndex.datasets.open()`): ``` -------------------------------- ### Accessing Constants Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.axioms.Constants.md This example demonstrates how to access the list of spectral index constants using the `spyndex.constants` attribute. ```APIDOC ## Accessing Constants ### Description This example demonstrates how to access the list of spectral index constants using the `spyndex.constants` attribute. ### Method Attribute Access ### Endpoint N/A ### Parameters N/A ### Request Example ```pycon >>> import spyndex >>> spyndex.constants Constants(['L', 'g', 'C1', ..., 'sigma', 'p', 'c']) ``` ### Response #### Success Response (200) - **Constants** (list) - A list of available spectral index constants. ``` -------------------------------- ### Install Spyndex using conda Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/started.md Install the latest version of spyndex from the conda-forge channel. This is an alternative installation method for users who prefer conda. ```bash conda install -c conda-forge spyndex ``` -------------------------------- ### Prepare Parameters for SAVI and NDVI Calculation with Floats Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/python_builtin.ipynb Prepare parameters for SAVI and NDVI calculations, scaling reflectance values to a range suitable for SAVI (e.g., 0 to 1) and including the 'L' parameter. Note the different scaling for NIR and RED compared to the integer example. ```python parameters = {"N": NIR / 10000, "R": RED / 10000, "L": 0.5} ``` -------------------------------- ### Define a New Python Method Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/contributing.md Example of defining a new method with NumPy-style docstrings. Ensure your docstrings clearly explain parameters, return values, and include usage examples. ```python def my_new_method(x,other): '''Returns the addition of and image and a float. Parameters ---------- x : float Float to add. other : float Float to add. Returns ------- float Addition of two floats. Examples -------- >>> import spyndex >>> spyndex.my_new_method(0.5,0.5) 1.0 ''' return x + other ``` -------------------------------- ### Accessing Band Information Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.axioms.Band.md Demonstrates how to import spyndex and access band information using the Band object. Shows how to get the Band object itself and its long name attribute. ```pycon >>> import spyndex >>> spyndex.bands.B Band(B: Blue) >>> spyndex.bands.B.long_name 'Blue' ``` -------------------------------- ### Upgrade Spyndex using pip Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/started.md Upgrade an existing installation of spyndex to the latest version from PyPI. ```bash pip install -U spyndex ``` -------------------------------- ### Get kNDVI Reference Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/xarray.ipynb Retrieve the citation or reference for the kNDVI index. ```python spyndex.indices.kNDVI.reference ``` -------------------------------- ### Get kNDVI Bands Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/xarray.ipynb List the required bands for computing the kNDVI. These are kernel-based bands. ```python spyndex.indices.kNDVI.bands ``` -------------------------------- ### GPU Acceleration with CuPy Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/README.md Utilize GPU acceleration for spectral index computation with CuPy. This example demonstrates direct CuPy array usage and integration with xarray via cupy-xarray. ```python import spyndex import cupy as cp # cupy.ndarray objects N = cp.random.normal(0.6,0.10,10000) R = cp.random.normal(0.1,0.05,10000) # Returns a cupy.ndarray object idx = spyndex.computeIndex( index = "NDVI", N = N, R = R ) ``` ```python import spyndex import xarray as xr import cupy_xarray # Open a dataset (in this case a xarray.DataArray) snt = spyndex.datasets.open("sentinel") # Convert it to a dataset of cupy.ndarray objects snt_cupy = snt.cupy.as_cupy() # Scale the data (remember that the valid domain for reflectance is [0,1]) snt_cupy = snt_cupy / 10000 # Compute the desired spectral indices idx_cupy = spyndex.computeIndex( index = ["NDVI","GNDVI","SAVI"], params = { "N": snt_cupy.sel(band = "B08"), "R": snt_cupy.sel(band = "B04"), "G": snt_cupy.sel(band = "B03"), "L": 0.5 } ) # Convert back to numpy! idx = idx_cupy.as_numpy() ``` -------------------------------- ### Open Satellite Data with xcube Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/xcube.ipynb Opens a satellite data cube with specified parameters like data ID, variable names, bounding box, spatial resolution, time range, and tile size. Requires prior setup of `translate_bands` and `store`. ```python variable_names = list(translate_bands().values()) variable_names.append("SCL") ds = store.open_data( data_id, variable_names=variable_names, bbox=bbox, spatial_res=spatial_res, time_range=time_range, tile_size=tile_size, ) ds ``` -------------------------------- ### Get the reference for a spectral index (NDVI) Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/started.md Retrieve the reference (e.g., citation or source) for a specific spectral index like NDVI. This helps in citing the index correctly. ```python import spyndex # Reference of the NDVI spyndex.indices["NDVI"]["reference"] # Or with dot notation spyndex.indices.NDVI.reference ``` -------------------------------- ### Get required bands for NDVI Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/geopandas.ipynb Lists the specific bands required for calculating the NDVI spectral index. ```python spyndex.indices.NDVI.bands ``` -------------------------------- ### Compute Kernel Indices with xarray Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/started.md Use `computeKernel` to calculate kernels for indices like kNDVI. This example computes both kNDVI and NDVI, demonstrating how to pass kernel computations as parameters for other indices. ```python import spyndex import xarray as xr import matplotlib.pyplot as plt from rasterio import plot # Open a dataset (in this case a xarray.DataArray) snt = spyndex.datasets.open("sentinel") # Scale the data (remember that the valid domain for reflectance is [0,1]) snt = snt / 10000 # Compute the kNDVI and the NDVI for comparison idx = spyndex.computeIndex( index = ["NDVI","kNDVI"], params = { # Parameters required for NDVI "N": snt.sel(band = "B08"), "R": snt.sel(band = "B04"), # Parameters required for kNDVI "kNN" : 1.0, "kNR" : spyndex.computeKernel( kernel = "RBF", params = { "a": snt.sel(band = "B08"), "b": snt.sel(band = "B04"), "sigma": snt.sel(band = ["B08","B04"]).mean("band") }), } ) # Plot the indices (and the RGB image for comparison) fig, ax = plt.subplots(1,3,figsize = (15,15)) plot.show(snt.sel(band = ["B04","B03","B02"]).data / 0.3,ax = ax[0],title = "RGB") plot.show(idx.sel(index = "NDVI"),ax = ax[1],title = "NDVI") plot.show(idx.sel(index = "kNDVI"),ax = ax[2],title = "kNDVI") ``` -------------------------------- ### Prepare Parameters with Lists Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/python_builtin.ipynb Create a dictionary of parameters using Python lists for spectral bands. ```python parameters = {"N": NIR, "R": RED, "L": 0.5} ``` -------------------------------- ### Import Libraries and Initialize Earth Engine Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/ee.ipynb Import necessary libraries including spyndex, Earth Engine, eemont, and geemap. Initialize a geemap Map object. ```python import spyndex import ee, eemont, geemap Map = geemap.Map() ``` -------------------------------- ### Import Libraries Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/pandas.ipynb Import the necessary libraries, spyndex and pandas, to begin spectral index calculations. ```python import spyndex import pandas as pd ``` -------------------------------- ### Import spyndex Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/python_builtin.ipynb Import the spyndex library to access its functionalities for computing spectral indices. ```python import spyndex ``` -------------------------------- ### Create Sentinel Hub data store Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/xcube.ipynb Initialize a Sentinel Hub data store using xcube, providing authentication credentials and endpoint URLs. ```python store = new_data_store( "sentinelhub", client_id=credentials["client_id"], client_secret=credentials["client_secret"], instance_url="https://sh.dataspace.copernicus.eu", oauth2_url=( "https://identity.dataspace.copernicus.eu/auth/" "realms/CDSE/protocol/openid-connect" ) ) ``` -------------------------------- ### Get required bands for IRECI Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/geopandas.ipynb Lists the specific bands required for calculating the IRECI spectral index. ```python spyndex.indices.IRECI.bands ``` -------------------------------- ### Import necessary libraries Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/xcube.ipynb Import spyndex and required components from xcube for data handling and processing. ```python import spyndex from xcube.core.store import new_data_store from xcube.core.maskset import MaskSet ``` -------------------------------- ### Import Libraries Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/numpy.ipynb Import the necessary libraries, spyndex and numpy, for spectral index calculations. ```python import spyndex import numpy as np ``` -------------------------------- ### Get the formula for a spectral index (NDVI) Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/started.md Retrieve the computation formula for a specific spectral index like NDVI. This is useful for understanding how the index is calculated. ```python import spyndex # Formula of the NDVI spyndex.indices["NDVI"]["formula"] # Or with dot notation spyndex.indices.NDVI.formula ``` -------------------------------- ### Get Spectral Index Band Information Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/numpy.ipynb Retrieves the required spectral bands for the GLI and VARI indices. This helps in understanding which bands are needed for computation. ```python spyndex.indices.GLI.bands ``` ```python spyndex.indices.VARI.bands ``` -------------------------------- ### Import Libraries Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/xarray.ipynb Import the necessary libraries, spyndex for spectral index computation and xarray for data handling. ```python import spyndex import xarray as xr ``` -------------------------------- ### Initialize Earth Engine and geemap Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/geopandas.ipynb Imports the Earth Engine, eemont, and geemap libraries and initializes a geemap Map object for visualization. ```python import ee, eemont, geemap Map = geemap.Map() ``` -------------------------------- ### Get SAVI 'L' Parameter Information Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/python_builtin.ipynb Check the definition and default value of the 'L' parameter (canopy background adjustment) for SAVI using spyndex.constants. ```python spyndex.constants.L ``` -------------------------------- ### Import Libraries Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/pc.ipynb Import all necessary libraries for data handling, STAC searching, and visualization. ```python import spyndex import stackstac import planetary_computer as pc import numpy as np import xarray as xr import matplotlib.pyplot as plt from pystac_client import Client ``` -------------------------------- ### Get Unique Class Values Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/pandas.ipynb Extracts and displays the unique values from the 'class' column in the DataFrame, showing the different land cover types available. ```python df["class"].unique() ``` -------------------------------- ### Constant Class Initialization and Usage Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.axioms.Constant.md Demonstrates how to initialize and use the Constant object to access spectral index constants and their default values. ```APIDOC ## Class: Constant ### Description Represents a specific constant within the Spectral Indices list. Allows access to its attributes and default values. ### Parameters * **constant** (dict) - A dictionary containing the constant's data. ### Attributes * **default**: The default value of the constant. ### Examples ```pycon >>> import spyndex >>> spyndex.constants.L Constant(L: Canopy background adjustment) * Default value: 1.0 >>> spyndex.constants.L.default 1.0 ``` ``` -------------------------------- ### Prepare Parameters for NDVI Calculation Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/python_builtin.ipynb Create a dictionary to hold the parameters required for the NDVI calculation, mapping band names to their corresponding reflectance values. ```python parameters = {"N": NIR, "R": RED} ``` -------------------------------- ### Import Libraries Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/dask.ipynb Import the necessary libraries, spyndex and dask, to begin working with parallel satellite data processing. ```python import spyndex import dask ``` -------------------------------- ### Accessing and Using a Constant Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.axioms.Constant.md Demonstrates how to import spyndex, access a specific constant (L), and retrieve its default value. Use this to interact with predefined spectral index constants. ```python import spyndex spyndex.constants.L Constant(L: Canopy background adjustment) * Default value: 1.0 ``` ```python spyndex.constants.L.default 1.0 ``` -------------------------------- ### Compute Spectral Indices from Dask DataFrame Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.spyndex.computeIndex.md Apply Spyndex to Dask DataFrames for efficient computation on distributed or large tabular data. Use `.compute()` to get the final results. ```python >>> import dask.dataframe as dd >>> df = pd.DataFrame({ ... "NIR": np.random.normal(0.6,0.10,1000), ... "RED": np.random.normal(0.1,0.05,1000), ... "GREEN": np.random.normal(0.3,0.02,1000), ... }) >>> df = dd.from_pandas(df,npartitions = 10) >>> spyndex.computeIndex( ... index = ["NDVI","SAVI","GNDVI"], ... params = { ... "N": df["NIR"], ... "R": df["RED"], ... "G": df["GREEN"], ... "L": 0.5 ... } ... ).compute() ``` -------------------------------- ### Configure Planetary Computer Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/pc.ipynb Configure the Planetary Computer environment. This step is optional if you do not have an API key. ```python !planetarycomputer configure ``` -------------------------------- ### Compute Spectral Indices with Spyndex Source: https://context7.com/awesome-spectral-indices/spyndex/llms.txt Use `computeIndex` to calculate spectral indices. Set `returnOrigin=False` to always get a plain list, or `online=True` to fetch the latest index list from GitHub. ```python result_list = spyndex.computeIndex( index=["NDVI", "SAVI"], params={"N": N, "R": R, "L": 0.5}, returnOrigin=False ) print(type(result_list)) # print(len(result_list)) # 2 ``` ```python result = spyndex.computeIndex("NDVI", params={"N": 0.6, "R": 0.1}, online=True) ``` -------------------------------- ### Load and Prepare NAIP Image Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/ee.ipynb Load a NAIP image from Earth Engine and scale its band values from 0-255 to 0-1. This prepares the image for spectral index computation. ```python img = ee.Image("USDA/NAIP/DOQQ/m_3009057_ne_15_1_20170910") img = img / 255.0 ``` ```python img.getInfo() ``` -------------------------------- ### Parallel Processing with Dask Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/README.md Compute spectral indices in parallel using dask.array. Ensure dask is installed and arrays are chunked for efficient computation. The computation is lazy and requires an explicit .compute() call. ```python import spyndex import numpy as np import dask.array as da # Define the array shape array_shape = (10000,10000) # Define the chunk size chunk_size = (1000,1000) # Create a dask.array object dask_array = da.array([ da.random.normal(0.6,0.10,array_shape,chunks = chunk_size), da.random.normal(0.1,0.05,array_shape,chunks = chunk_size) ]) # "Compute" the desired spectral indices idx = spyndex.computeIndex( index = ["NDVI","SAVI"], params = { "N": dask_array[0], "R": dask_array[1], "L": 0.5 } ) # Since dask works in lazy mode, # you have to tell it that you want to compute the indices! idx.compute() ``` -------------------------------- ### Compute Spectral Indices with Dask Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/started.md Use Spyndex to compute spectral indices like NDVI and SAVI from Dask arrays. Ensure Dask is configured for lazy computation and call `.compute()` to get the results. ```python import dask.array as da import spyndex # Define the array shape array_shape = (10000,10000) # Define the chunk size chunk_size = (1000,1000) # Create a dask.array object dask_array = da.array([ da.random.normal(0.6,0.10,array_shape,chunks = chunk_size), da.random.normal(0.1,0.05,array_shape,chunks = chunk_size) ]) # "Compute" the desired spectral indices idx = spyndex.computeIndex( index = ["NDVI","SAVI"], params = { "N": dask_array[0], "R": dask_array[1], "L": 0.5 } ) # Since dask works in lazy mode, # you have to tell it that you want to compute the indices! idx.compute() ``` -------------------------------- ### Accessing Available Bands Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.axioms.Bands.md Import the spyndex library and access the `bands` attribute to see a list of available spectral bands. This is useful for understanding which bands are supported for spectral index calculations. ```python import spyndex spyndex.bands ``` -------------------------------- ### Compute Spectral Indices with pandas DataFrame Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/started.md Spyndex supports pandas DataFrames as long as they support overloaded mathematical operators. This example computes NDVI, NDWI, and NDBI using a pandas DataFrame and visualizes the results with a pairplot. ```python import spyndex import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Open a dataset (in this case a pandas.DataFrame) df = spyndex.datasets.open("spectral") # Compute the desired spectral indices idx = spyndex.computeIndex( index = ["NDVI","NDWI","NDBI"], params = { "N": df["SR_B5"], "R": df["SR_B4"], "G": df["SR_B3"], "S1": df["SR_B6"] } ) # Add the land cover column to the result idx["Land Cover"] = df["class"] # Create a color palette for plotting colors = ["#E33F62","#3FDDE3","#4CBA4B"] # Plot a pairplot to check the indices behaviour plt.figure(figsize = (15,15)) g = sns.PairGrid(idx,hue = "Land Cover",palette = sns.color_palette(colors)) g.map_lower(sns.scatterplot) g.map_upper(sns.kdeplot,fill = True,alpha = .5) g.map_diag(sns.kdeplot,fill = True) g.add_legend() plt.show() ``` -------------------------------- ### Simulate Mixed Array Types for Parameters Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/numpy.ipynb Prepares input parameters for spectral index calculation where some bands are represented by NumPy arrays and others by scalar constants. This demonstrates handling mixed data types. ```python BLUE = np.random.normal(0.13,0.05,(100,100,100)) GREEN = 0.23 RED = np.random.normal(0.14,0.07,(100,100,100)) ``` -------------------------------- ### Access Band Parameters in Spyndex Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/README.md Demonstrates how to access all available band parameters or specific bands using dictionary or dot notation. ```python import spyndex # All bands spyndex.bands # Blue band spyndex.bands["B"] # Or with dot notation spyndex.bands.B ``` -------------------------------- ### Compute Multiple Spectral Indices with xarray Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/started.md Use `computeIndex` to calculate multiple spectral indices simultaneously. Ensure data is scaled to the valid domain [0,1] before computation. This example demonstrates computing NDVI, GNDVI, and SAVI from Sentinel data. ```python import spyndex import xarray as xr import matplotlib.pyplot as plt from rasterio import plot # Open a dataset (in this case a xarray.DataArray) snt = spyndex.datasets.open("sentinel") # Scale the data (remember that the valid domain for reflectance is [0,1]) snt = snt / 10000 # Compute the desired spectral indices idx = spyndex.computeIndex( index = ["NDVI","GNDVI","SAVI"], params = { "N": snt.sel(band = "B08"), "R": snt.sel(band = "B04"), "G": snt.sel(band = "B03"), "L": 0.5 } ) # Plot the indices (and the RGB image for comparison) fig, ax = plt.subplots(2,2,figsize = (10,10)) plot.show(snt.sel(band = ["B04","B03","B02"]).data / 0.3,ax = ax[0,0],title = "RGB") plot.show(idx.sel(index = "NDVI"),ax = ax[0,1],title = "NDVI") plot.show(idx.sel(index = "GNDVI"),ax = ax[1,0],title = "GNDVI") plot.show(idx.sel(index = "SAVI"),ax = ax[1,1],title = "SAVI") ``` -------------------------------- ### Compute kNDVI with polynomial kernel using params Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.spyndex.computeKernel.md Illustrates computing kNDVI using a polynomial kernel for both kNN and kNR parameters. Parameters for the polynomial kernel, including degree 'p' and trade-off 'c', are provided. ```python import spyndex spyndex.computeIndex( index = "kNDVI", params = { "kNN": spyndex.computeKernel( kernel = "poly", params = { "a" : 0.68, "b": 0.68, "p": 2.0, "c": spyndex.constants.c.default } ), "kNR": spyndex.computeKernel( kernel = "poly", params = { "a" : 0.68, "b": 0.13, "p": 2.0, "c": spyndex.constants.c.default } ) } ) ``` -------------------------------- ### Define Reflectance Lists Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/python_builtin.ipynb Initialize lists to store reflectance values for different spectral bands. ```python NIR = [0.634, 0.654, 0.567] RED = [0.123, 0.156, 0.198] ``` -------------------------------- ### Accessing Spectral Index Information Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.axioms.SpectralIndex.md Demonstrates how to access a specific spectral index (NIRv) and retrieve its details like contributor and compute its value. ```python >>> import spyndex >>> spyndex.indices.NIRv SpectralIndex(NIRv: Near-Infrared Reflectance of Vegetation) * Application Domain: vegetation * Bands/Parameters: ('N', 'R') * Formula: ((N-R)/(N+R))*N * Reference: https://doi.org/10.1126/sciadv.1602244 >>> spyndex.indices.NIRv.contributor 'https://github.com/davemlz' >>> spyndex.indices.NIRv.compute(N = 0.67,R = 0.12) 0.4664556962025317 ``` -------------------------------- ### Compute Indices on Google Earth Engine Images Source: https://context7.com/awesome-spectral-indices/spyndex/llms.txt When spyndex[ee] is installed, spyndex automatically delegates computation to the Earth Engine API via eemont if an ee.Image or ee.Number is detected in the params. Multiple indices over an ee.Image return a multi-band ee.Image; scalar ee.Number inputs return an ee.List. ```python import ee import eemont import spyndex # Authenticate and initialize Earth Engine ee.Authenticate() ee.Initialize() # --- Compute indices on an ee.Image --- image = ( ee.ImageCollection("COPERNICUS/S2_SR") .filterDate("2023-06-01", "2023-09-01") .filterBounds(ee.Geometry.Point([-74.0, 4.6])) .sort("CLOUDY_PIXEL_PERCENTAGE") .first() .divide(10000) # Scale to [0, 1] ) idx = spyndex.computeIndex( index=["NDVI", "GNDVI", "SAVI"], params={ "N": image.select("B8"), "R": image.select("B4"), "G": image.select("B3"), "L": spyndex.constants.L.default, } ) # idx is an ee.Image with bands named ['NDVI', 'GNDVI', 'SAVI'] print(type(idx)) # print(idx.bandNames().getInfo()) # ['NDVI', 'GNDVI', 'SAVI'] ``` ```python # --- kNDVI with RBF kernel on Earth Engine --- kNR = spyndex.computeKernel( kernel="RBF", params={ "a": image.select("B8"), "b": image.select("B4"), "sigma": image.select(["B8", "B4"]).reduce(ee.Reducer.mean()), } ) kndvi = spyndex.computeIndex( index="kNDVI", params={"kNN": ee.Image(1.0), "kNR": kNR} ) ``` ```python # --- Scalar ee.Number inputs return ee.List --- result = spyndex.computeIndex( index=["NDVI", "SAVI"], params={ "N": ee.Number(0.63), "R": ee.Number(0.13), "L": spyndex.constants.L.default, } ) print(type(result)) # print(result.getInfo()) ``` -------------------------------- ### Load Sample Datasets with spyndex Source: https://context7.com/awesome-spectral-indices/spyndex/llms.txt Load built-in sample datasets for testing and demonstration purposes. The 'sentinel' dataset is an xarray.DataArray, and the 'spectral' dataset is a pandas.DataFrame. ```python import spyndex import matplotlib.pyplot as plt from rasterio import plot as rplot # --- Sentinel-2 scene (xarray.DataArray) --- snt = spyndex.datasets.open("sentinel") print(snt) # # Coordinates: # * band (band) >> import spyndex >>> spyndex.bands Constants(['L', 'g', 'C1', ..., 'sigma', 'p', 'c']) ``` ### Response #### Success Response (200) - **spyndex.bands** (Constants) - A list of available spectral band constants. ``` -------------------------------- ### Accessing Spectral Constants Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.axioms.Constants.md Import the spyndex library and access the predefined constants object to view available spectral indices. ```python import spyndex spyndex.constants ``` -------------------------------- ### Compute kNDVI with RBF kernel using kwargs Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.spyndex.computeKernel.md Shows how to compute the kNDVI index where kernel parameters for kNR are passed directly as keyword arguments to `computeKernel`. ```python import spyndex spyndex.computeIndex( index = "kNDVI", kNN = 1.0, kNR = spyndex.computeKernel("RBF",a = 0.68,b = 0.13,sigma = (0.68 + 0.13) / 2) ) ``` -------------------------------- ### Print Float Data Types and Values for SAVI Parameters Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/python_builtin.ipynb Verify the data types and values of the parameters used for SAVI calculation, ensuring they are floats and correctly scaled. ```python print(f"NIR type: {type(parameters['N'])}, value: {parameters['N']}") print(f"RED type: {type(parameters['R'])}, value: {parameters['R']}") print(f"L type: {type(parameters['L'])}, value: {parameters['L']}") ``` -------------------------------- ### Accessing Spectral Indices in Spyndex Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/README.md Demonstrates how to access all available spectral indices, a specific index (NDVI), and its attributes like formula and reference using the spyndex.indices object. Supports both dictionary-style and dot notation access. ```python import spyndex # All indices spyndex.indices # NDVI index spyndex.indices["NDVI"] # Or with dot notation spyndex.indices.NDVI # Formula of the NDVI spyndex.indices["NDVI"]["formula"] # Or with dot notation spyndex.indices.NDVI.formula # Reference of the NDVI spyndex.indices["NDVI"]["reference"] # Or with dot notation spyndex.indices.NDVI.reference ``` -------------------------------- ### Create Development Branch Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/contributing.md Use this command to create a new branch for your development work. ```bash git checkout -b name-of-dev-branch ``` -------------------------------- ### Print Integer Data Types and Values Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/python_builtin.ipynb Verify the data types and values of the defined integer reflectance variables. ```python print(f"NIR type: {type(NIR)}, value: {NIR}") print(f"RED type: {type(RED)}, value: {RED}") ``` -------------------------------- ### Compute kNDVI with RBF kernel using params Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.spyndex.computeKernel.md Demonstrates computing the kNDVI index where the kNR parameter is derived from an RBF kernel computation. Kernel parameters are passed within a dictionary. ```python import spyndex spyndex.computeIndex( index = "kNDVI", params = { "kNN": 1.0, "kNR": spyndex.computeKernel( kernel = "RBF", params = { "a" : 0.68, "b": 0.13, "sigma": (0.68 + 0.13) / 2 } ) } ) ``` -------------------------------- ### Compute Spectral Index Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.axioms.SpectralIndex.md Demonstrates how to compute a spectral index using the compute method, either with a params dictionary or keyword arguments. ```APIDOC ## Compute Spectral Index Compute a Spectral Index by passing the required `params` dictionary: ```pycon >>> import spyndex >>> spyndex.indices.NDVI.compute( ... params = { ... "N": 0.643, ... "R": 0.175 ... } ... ) 0.5721271393643031 ``` Compute a Spectral Index by passing the required `params` as keyword pairs: ```pycon >>> spyndex.indices.NDVI.compute(N = 0.643, R = 0.175, L = 0.5) 0.5721271393643031 ``` ``` -------------------------------- ### Browse Band Parameters with spyndex Source: https://context7.com/awesome-spectral-indices/spyndex/llms.txt Access and inspect spectral band information, including wavelength ranges and per-platform details. Ensure spyndex is imported to use this functionality. ```python import spyndex # List all band symbols print(spyndex.bands) # Bands(['B', 'G', 'R', 'RE1', 'RE2', 'RE3', 'N', 'N2', 'S1', 'S2', ...]) # Inspect a band b = spyndex.bands.B # Blue band print(repr(b)) # Band(B: Blue) print(b.short_name) # 'B' print(b.long_name) # 'Blue' print(b.common_name) # 'blue' (STAC EO Extension name) print(b.min_wavelength) # 450.0 (nm) print(b.max_wavelength) # 495.0 (nm) # Per-platform details s2a = spyndex.bands.B.sentinel2a print(repr(s2a)) # PlatformBand(Platform: Sentinel-2A, Band: Blue) # * Band: B2 # * Center Wavelength (nm): 492.4 # * Bandwidth (nm): 66.0 print(s2a.platform) # 'Sentinel-2A' print(s2a.band) # 'B2' print(s2a.name) # 'Blue' print(s2a.wavelength) # 492.4 print(s2a.bandwidth) # 66.0 # NIR band on Landsat 8 l8_nir = spyndex.bands.N.landsat8 print(l8_nir.band) # 'B5' print(l8_nir.wavelength) # 864.7 ``` -------------------------------- ### Prepare Parameters for Spectral Index Calculation Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/numpy.ipynb Creates a dictionary mapping band names ('B', 'G', 'R') to their corresponding NumPy arrays. This dictionary is used as input for the `spyndex.computeIndex` function. ```python parameters = {"B": BLUE, "G": GREEN, "R": RED} ``` -------------------------------- ### Band Object Initialization and Attribute Access Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.axioms.Band.md Demonstrates how to initialize a Band object and access its attributes like 'long_name'. ```APIDOC ## Class: spyndex.axioms.Band ### Description Represents a specific spectral band, allowing interaction with its properties. ### Parameters * **band** (dict) - A dictionary containing band information. ### Attributes * **long_name** (str) - The full name of the band. ### Examples ```pycon >>> import spyndex >>> spyndex.bands.B Band(B: Blue) >>> spyndex.bands.B.long_name 'Blue' ``` ### SEE ALSO * [`Bands`](spyndex.axioms.Bands.md#spyndex.axioms.Bands) * [`PlatformBand`](spyndex.axioms.PlatformBand.md#spyndex.axioms.PlatformBand) ``` -------------------------------- ### Accessing Spectral Index Constants in Spyndex Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/README.md Shows how to access all available constants and specific constants (like 'L' for Canopy Background Adjustment) using the spyndex.constants object. Demonstrates accessing the default value for a constant using both dictionary-style and dot notation. ```python import spyndex # All constants spyndex.constants # Canopy Background Adjustment spyndex.constants["L"] # Or with dot notation spyndex.constants.L # Default value spyndex.constants["L"]["default"] # Or with dot notation spyndex.constants.L.default ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/contributing.md Stage all changes, commit them with a descriptive message, and push your development branch to the remote repository. ```bash git add . git commit -m "Description of your work" git push origin name-of-dev-branch ``` -------------------------------- ### Import Visualization Libraries Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/pandas.ipynb Imports the seaborn and matplotlib.pyplot libraries for data visualization. ```python import seaborn as sns import matplotlib.pyplot as plt ``` -------------------------------- ### Compute a Single Spectral Index with Keyword Arguments Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.spyndex.computeIndex.md This approach computes a single spectral index by passing parameters directly as keyword arguments. It offers a more concise syntax for simple cases. ```python >>> spyndex.computeIndex("NDVI",N = 0.643,R = 0.175) 0.5721271393643031 ``` -------------------------------- ### Access Spectral Indices List Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.axioms.SpectralIndices.md Import the spyndex library and access the `indices` attribute to view the available spectral indices. This provides a list of all supported indices. ```python import spyndex spyndex.indices ``` -------------------------------- ### Load Spectral Dataset with Pandas Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/pandas.ipynb Opens the 'spectral' dataset from spyndex into a pandas DataFrame. This dataset contains Landsat 8 surface reflectance data. ```python df = spyndex.datasets.open("spectral") ``` -------------------------------- ### Visualize Image with Indices using Geemap Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/tutorials/ee.ipynb Visualize the original RGB bands and the computed spectral indices (VARI, ExG, NDVI) on a geemap interactive map. Center the map on the image. ```python import geemap.colormaps as cm Map = geemap.Map() Map.addLayer(img[["R","G","B"]],{"min":0,"max":0.3},"RGB") Map.addLayer(img["VARI"],{"palette":cm.palettes.ndvi},"VARI") Map.addLayer(img["ExG"],{"palette":cm.palettes.ndvi},"ExG") Map.addLayer(img["NDVI"],{"palette":cm.palettes.ndvi},"NDVI") Map.centerObject(img,13) Map ``` -------------------------------- ### Compute Multiple Spectral Indices with Keyword Arguments Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/started.md Alternatively, pass band data and parameters as keyword arguments directly to `spyndex.computeIndex` for computing multiple spectral indices. This method is suitable when the number of parameters is manageable. ```python idx = spyndex.computeIndex( index = ["NDVI","SAVI"], N = da.sel(band = "NIR"), R = da.sel(band = "Red"), L = 0.5 ) ``` -------------------------------- ### spyndex.datasets.open(dataset: str) Source: https://github.com/awesome-spectral-indices/spyndex/blob/main/docs/stubs/spyndex.datasets.open.md Opens a specified dataset. Accepts 'sentinel' for Sentinel-2 satellite imagery (xarray.DataArray) or 'spectral' for Landsat 8 reflectance samples (pandas.DataFrame). ```APIDOC ## spyndex.datasets.open(dataset: str) ### Description Opens a specified dataset. Accepts 'sentinel' for Sentinel-2 satellite imagery (xarray.DataArray) or 'spectral' for Landsat 8 reflectance samples (pandas.DataFrame). ### Parameters #### Path Parameters - **dataset** (str) - Required - One of “sentinel” or “spectral”. The sentinel dataset is loaded as a `xarray.DataArray` with a sample image of the Sentinel-2 satellite (10 m bands). The spectral dataset is loaded as a `pandas.DataFrame` with Landsat 8 reflectance samples of three different land covers. ### Returns Loaded dataset. ### Return type Any ### Examples Open the `sentinel` dataset: ```pycon >>> import spyndex >>> spyndex.datasets.open("sentinel") Coordinates: * band (band) >> spt = spyndex.datasets.open("spectral") >>> spt.dtypes SR_B1 float64 SR_B2 float64 SR_B3 float64 SR_B4 float64 SR_B5 float64 SR_B6 float64 SR_B7 float64 ST_B10 float64 class object dtype: object >>> spt.shape (120, 9) ``` ``` -------------------------------- ### Access Index Constants with spyndex Source: https://context7.com/awesome-spectral-indices/spyndex/llms.txt Retrieve and use default constants required for spectral index calculations. Import spyndex and access constants via `spyndex.constants`. ```python import spyndex # List all constant symbols print(spyndex.constants) # Constants(['L', 'g', 'C1', 'C2', 'cexp', 'nexp', 'alpha', 'beta', # 'gamma', 'omega', 'k', 'PAR', 'lambdaG', 'lambdaR', # 'lambdaN', 'sigma', 'p', 'c']) # Canopy background adjustment (used in SAVI, EVI, etc.) L = spyndex.constants.L print(repr(L)) # Constant(L: Canopy background adjustment) # * Default value: 1.0 print(L.short_name) # 'L' print(L.long_name) # 'Canopy background adjustment' print(L.default) # 1.0 print(L.value) # 1.0 (alias for default) # Other commonly used constants print(spyndex.constants.g.default) # 2.5 (EVI gain factor) print(spyndex.constants.C1.default) # 6.0 (EVI aerosol resistance coefficient) print(spyndex.constants.C2.default) # 7.5 (EVI aerosol resistance coefficient) print(spyndex.constants.sigma.default) # 0.5 (RBF kernel length-scale) # Use default constants directly in computeIndex result = spyndex.computeIndex( index=["SAVI", "EVI"], params={ "N": 0.6, "R": 0.1, "B": 0.05, "L": spyndex.constants.L.default, "g": spyndex.constants.g.default, "C1": spyndex.constants.C1.default, "C2": spyndex.constants.C2.default, } ) print(result) # [, ] ```