0
# Spectral Index Computation
1
2
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.
3
4
## Capabilities
5
6
### Main Index Computation
7
8
Computes one or more spectral indices from the standardized catalogue. Automatically handles parameter validation, expression evaluation, and result formatting based on input data types.
9
10
```python { .api }
11
def computeIndex(
12
index: Union[str, List[str]],
13
params: Optional[dict] = None,
14
online: bool = False,
15
returnOrigin: bool = True,
16
coordinate: str = "index",
17
**kwargs
18
) -> Any:
19
"""
20
Computes one or more Spectral Indices from the Awesome Spectral Indices list.
21
22
Parameters:
23
- index: Index name or list of index names to compute
24
- params: Dictionary of parameters/bands for computation (compatible with overloaded operators)
25
- online: Whether to retrieve most recent index list from GitHub (default: False)
26
- returnOrigin: Whether to return results in original data type format (default: True)
27
- coordinate: Name of coordinate for xarray concatenation (default: "index")
28
- **kwargs: Alternative parameter specification (ignored if params provided)
29
30
Returns:
31
Computed spectral indices with type depending on inputs:
32
- Single index with numeric inputs: float
33
- Multiple indices with numeric inputs: list[float]
34
- NumPy arrays: numpy.ndarray
35
- Pandas Series: pandas.DataFrame
36
- Xarray DataArray: xarray.DataArray
37
- Earth Engine Image: ee.Image
38
- Earth Engine Number: ee.List
39
- Dask Array: dask.Array
40
- Dask DataFrame: dask.DataFrame
41
"""
42
```
43
44
**Usage Examples:**
45
46
```python
47
import spyndex
48
import numpy as np
49
import pandas as pd
50
import xarray as xr
51
52
# Single index with numeric values
53
ndvi = spyndex.computeIndex("NDVI", params={"N": 0.643, "R": 0.175})
54
# Returns: 0.5721271393643031
55
56
# Multiple indices with keyword arguments
57
indices = spyndex.computeIndex(
58
["NDVI", "SAVI"],
59
N=0.643,
60
R=0.175,
61
L=0.5
62
)
63
# Returns: [0.5721271393643031, 0.5326251896813354]
64
65
# NumPy arrays
66
nir = np.random.normal(0.67, 0.12, 10000)
67
red = np.random.normal(0.12, 0.05, 10000)
68
result = spyndex.computeIndex(
69
["NDVI", "GNDVI"],
70
params={
71
"N": nir,
72
"R": red,
73
"G": np.random.normal(0.34, 0.07, 10000)
74
}
75
)
76
# Returns: numpy.ndarray with shape (2, 10000)
77
78
# Pandas DataFrame
79
df = pd.DataFrame({
80
"Red": np.random.normal(0.12, 0.05, 1000),
81
"NIR": np.random.normal(0.67, 0.12, 1000)
82
})
83
result = spyndex.computeIndex(
84
"NDVI",
85
params={
86
"N": df["NIR"],
87
"R": df["Red"]
88
}
89
)
90
# Returns: pandas.Series
91
92
# Xarray DataArray
93
data = xr.DataArray(
94
np.array([
95
np.random.normal(0.1, 0.1, (100, 100)), # Blue
96
np.random.normal(0.3, 0.1, (100, 100)), # Green
97
np.random.normal(0.1, 0.1, (100, 100)), # Red
98
np.random.normal(0.6, 0.1, (100, 100)) # NIR
99
]),
100
dims=("band", "x", "y"),
101
coords={"band": ["B", "G", "R", "N"]}
102
)
103
result = spyndex.computeIndex(
104
["NDVI", "SAVI"],
105
params={
106
"N": data.sel(band="N"),
107
"R": data.sel(band="R"),
108
"L": 0.5
109
}
110
)
111
# Returns: xarray.DataArray with index dimension
112
```
113
114
### Kernel Computation
115
116
Computes kernel functions used in kernel-based spectral indices. Supports linear, polynomial, and RBF (Radial Basis Function) kernels with configurable parameters.
117
118
```python { .api }
119
def computeKernel(
120
kernel: str,
121
params: Optional[dict] = None,
122
**kwargs
123
) -> Any:
124
"""
125
Computes a kernel k(a,b) for kernel-based spectral indices.
126
127
Parameters:
128
- kernel: Kernel type ("linear", "poly", "RBF")
129
- params: Kernel parameters dictionary
130
- For "linear": requires 'a' and 'b' (band values)
131
- For "poly": requires 'a', 'b', 'p' (degree), 'c' (trade-off)
132
- For "RBF": requires 'a', 'b', 'sigma' (length-scale)
133
- **kwargs: Alternative parameter specification
134
135
Returns:
136
Computed kernel value (type matches input data)
137
"""
138
```
139
140
**Kernel Formulas:**
141
- **Linear**: `a * b`
142
- **Polynomial**: `((a * b) + c) ** p`
143
- **RBF**: `exp((-1.0 * (a - b) ** 2.0) / (2.0 * sigma ** 2.0))`
144
145
**Usage Examples:**
146
147
```python
148
import spyndex
149
import numpy as np
150
151
# Linear kernel for kNDVI computation
152
knr_linear = spyndex.computeKernel(
153
"linear",
154
params={"a": 0.68, "b": 0.13}
155
)
156
157
# RBF kernel computation
158
knr_rbf = spyndex.computeKernel(
159
"RBF",
160
params={
161
"a": 0.68,
162
"b": 0.13,
163
"sigma": (0.68 + 0.13) / 2
164
}
165
)
166
167
# Use kernel in kNDVI index computation
168
kndvi = spyndex.computeIndex(
169
"kNDVI",
170
params={
171
"kNN": 1.0,
172
"kNR": knr_rbf
173
}
174
)
175
176
# Polynomial kernel with arrays
177
nir = np.random.normal(0.67, 0.12, 1000)
178
red = np.random.normal(0.12, 0.05, 1000)
179
180
knr_poly = spyndex.computeKernel(
181
"poly",
182
params={
183
"a": nir,
184
"b": red,
185
"p": 2.0,
186
"c": spyndex.constants.c.default
187
}
188
)
189
# Returns: numpy.ndarray with computed polynomial kernel values
190
```
191
192
## Parameter Validation
193
194
All computation functions automatically validate required parameters:
195
196
- **Index validation**: Checks if requested index exists in catalogue
197
- **Parameter completeness**: Ensures all required bands/parameters are provided
198
- **Earth Engine compatibility**: Automatically detects and handles Earth Engine objects
199
200
## Data Type Handling
201
202
### Return Type Logic
203
204
The `returnOrigin` parameter controls output formatting:
205
206
- **`returnOrigin=True`** (default): Returns results in format matching input data type
207
- Multiple indices are concatenated/stacked appropriately
208
- Single index returns the computed value directly
209
210
- **`returnOrigin=False`**: Always returns a list of computed values
211
- Useful when you need consistent list output regardless of input type
212
213
### Multi-Index Results
214
215
When computing multiple indices:
216
217
- **NumPy arrays**: Stacked as `numpy.ndarray` with first dimension as index count
218
- **Pandas Series**: Combined into `pandas.DataFrame` with index names as columns
219
- **Xarray DataArray**: Concatenated along specified coordinate dimension
220
- **Earth Engine Image**: Combined into multi-band `ee.Image` with index names as band names
221
- **Earth Engine Number**: Returned as `ee.List`
222
- **Dask arrays**: Stacked as `dask.Array`
223
- **Dask DataFrames**: Concatenated with index names as columns
224
225
## Online Index Retrieval
226
227
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.