Repository navigation
Expand file tree
/
Copy pathtwi_d8.py
More file actions
114 lines (89 loc) · 3.68 KB
/
Copy pathtwi_d8.py
File metadata and controls
114 lines (89 loc) · 3.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
"""Topographic Wetness Index (TWI).
Computes ``ln(a / tan(β))`` where *a* is the specific catchment area
(flow accumulation × cell size) and *β* is slope in radians.
Flat areas (slope ≈ 0) are clamped to ``tan(0.001°)`` to avoid
division by zero and infinite TWI values.
"""
from __future__ import annotations
import numpy as np
import xarray as xr
try:
import dask.array as da
except ImportError:
da = None
from xrspatial.utils import (_validate_raster, get_dataarray_resolution, has_cuda_and_cupy,
is_cupy_array)
# Minimum tan(slope) clamp: tan(0.001°)
_TAN_MIN = np.tan(np.radians(0.001))
def twi_d8(flow_accum: xr.DataArray,
slope_agg: xr.DataArray,
name: str = 'twi') -> xr.DataArray:
"""Compute the Topographic Wetness Index.
TWI = ln(a / tan(β)), where a = flow_accum × cellsize (specific
catchment area) and β = slope in radians. Slope input is expected
in degrees (matching the output of ``slope()``).
Parameters
----------
flow_accum : xarray.DataArray
2D flow accumulation grid (cell counts).
slope_agg : xarray.DataArray
2D slope grid in degrees.
name : str, default 'twi'
Name of output DataArray.
Returns
-------
xarray.DataArray
2D float64 TWI grid. NaN where either input is NaN.
"""
_validate_raster(flow_accum, func_name='twi', name='flow_accum')
_validate_raster(slope_agg, func_name='twi', name='slope_agg')
cellsize_x, cellsize_y = get_dataarray_resolution(flow_accum)
if not (np.isfinite(cellsize_x) and cellsize_x != 0
and np.isfinite(cellsize_y) and cellsize_y != 0):
raise ValueError(
f"twi(): cellsize must be finite and non-zero "
f"(got cellsize_x={cellsize_x}, cellsize_y={cellsize_y}). "
f"Ensure flow_accum has at least 2 cells per spatial dimension "
f"with finite coords."
)
cellsize = np.sqrt(abs(cellsize_x * cellsize_y))
fa_data = flow_accum.data
sl_data = slope_agg.data
if has_cuda_and_cupy() and is_cupy_array(fa_data):
out = _twi_cupy(fa_data, sl_data, cellsize)
elif da is not None and isinstance(fa_data, da.Array):
# Covers numpy- and cupy-backed dask arrays alike: TWI is purely
# elementwise, so cupy chunks run the same expression natively
# with no host round-trip.
out = _twi_dask(fa_data, sl_data, cellsize)
elif isinstance(fa_data, np.ndarray):
out = _twi_numpy(fa_data, sl_data, cellsize)
else:
raise TypeError(f"Unsupported array type: {type(fa_data)}")
return xr.DataArray(out,
name=name,
coords=flow_accum.coords,
dims=flow_accum.dims,
attrs=flow_accum.attrs)
def _twi_numpy(fa, sl, cellsize):
fa = np.asarray(fa, dtype=np.float64)
sl = np.asarray(sl, dtype=np.float64)
sca = fa * cellsize
tan_slope = np.tan(np.radians(sl))
tan_slope = np.where(tan_slope < _TAN_MIN, _TAN_MIN, tan_slope)
return np.log(sca / tan_slope)
def _twi_cupy(fa, sl, cellsize):
import cupy as cp
fa = cp.asarray(fa, dtype=cp.float64)
sl = cp.asarray(sl, dtype=cp.float64)
sca = fa * cellsize
tan_slope = cp.tan(cp.radians(sl))
tan_slope = cp.where(tan_slope < _TAN_MIN, _TAN_MIN, tan_slope)
return cp.log(sca / tan_slope)
def _twi_dask(fa, sl, cellsize):
"""Elementwise TWI on dask arrays (numpy- or cupy-backed chunks)."""
import dask.array as _da
sca = fa * cellsize
tan_slope = _da.tan(_da.radians(sl))
tan_slope = _da.where(tan_slope < _TAN_MIN, _TAN_MIN, tan_slope)
return _da.log(sca / tan_slope)