DEM#
DEM processing — sink filling, D8 flow direction, flow accumulation, slope, and basin filtering. Subclasses pyramids.dataset.Dataset, so all pyramids methods are inherited.
digitalrivers.dem.DEM
#
Bases: ConditioningMixin, MorphometryMixin, RoutingMixin, HydrologyMixin, Dataset
Digital Elevation Model processor.
Wraps a GDAL raster dataset and adds hydrological analysis methods: sink filling, D8 flow direction, flow accumulation, and slope computation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
Dataset
|
GDAL dataset containing a single-band elevation raster. To open a
DEM from a file path, use the inherited |
required |
access
|
str
|
|
'read_only'
|
gdal_env
|
dict[str, str] | None
|
GDAL config (cloud credentials, HTTP knobs) captured on
the dataset and re-installed around its reads, so the paths that
reopen the file authenticate the same way. Default |
None
|
open_options
|
tuple[str, ...] | list[str] | None
|
GDAL open options captured on the dataset and reapplied
when it is reopened. Default |
None
|
Source code in src/digitalrivers/dem/dem.py
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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |
values
property
#
Elevation array with no-data cells replaced by np.nan.
Reads band 0 as float32 and masks every cell whose value is
close to the raster's no-data value (relative tolerance 1e-5).
Returns:
| Type | Description |
|---|---|
|
np.ndarray: 2-D |
hand(streams, flow_direction=None, *, method='d8')
#
Compute Height Above Nearest Drainage (Rennó 2008 / Nobre 2011).
Two methods are supported:
"d8"(default) — follows the D8 / Rho8 flow-direction raster downstream from every cell until it reaches a stream cell, and assignselev[cell] - elev[stream_cell]. Orphans / sinks / no-data cells whose flow path never reaches a stream are NaN."euclidean"— for every cell, the nearest stream cell in 2-D space (Euclidean distance) is used as the reference. Cheaper than D8-HAND because there is no path tracing, but it does the wrong thing across ridges (a cell can be 2-D-closer to a stream in a different basin). Requiresscipy.ndimage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
streams
|
|
required | |
flow_direction
|
Single-direction |
None
|
|
method
|
str
|
|
'd8'
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
Dataset
|
this DEM's no-data sentinel. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/digitalrivers/dem/hydrology.py
full_hydro_pipeline(*, fill_method='priority_flood', flow_method='d8', stream_threshold_cells=None)
#
Composite: fill → flow_direction → accumulate (→ optional streams).
Convenience entry point that chains the four most common steps of a DEM-hydrology pre-processing pipeline. Equivalent to:
filled = dem.fill_depressions(method=fill_method)
fdir = filled.flow_direction(method=flow_method)
acc = fdir.accumulate()
streams = acc.streams(threshold=stream_threshold_cells) # if provided
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fill_method
|
str
|
Argument forwarded to |
'priority_flood'
|
flow_method
|
str
|
Argument forwarded to |
'd8'
|
stream_threshold_cells
|
int | None
|
Optional accumulation threshold (in
cells). When supplied, a |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
|
dict
|
(FlowDirection), and |
dict
|
optional |
dict
|
|
Source code in src/digitalrivers/dem/hydrology.py
set_outflow(outflow, direction, inplace=False)
#
Assign a fixed flow direction at the basin outfall cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outflow
|
GeoDataFrame
|
GeoDataFrame with point geometry marking the outfall location. |
required |
direction
|
int
|
D8 direction code (0–7) to force at the outfall. |
required |
inplace
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
Dataset
|
Dataset with the outfall direction applied, or |
Dataset
|
inplace is |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
This method is not yet implemented. |
Source code in src/digitalrivers/dem/routing.py
flow_direction(method='d8', exponent=1.0, forced=None, seed=None, forced_direction=None)
#
Derive a flow-direction raster from the DEM under one of five routing schemes.
Schemes:
"d8"(default) — O'Callaghan & Mark (1984). Single-direction steepest descent. Output: 1-bandint32raster of direction codes 0–7 followingDIR_OFFSETS."dinf"— Tarboton (1997). Output: 2-bandfloat32raster. Band 0 is the aspect angle in radians CCW from east in[0, 2π); band 1 is the slope magnitude along the chosen facet.-1.0in band 0 marks sinks / no-data."mfd_quinn"— Quinn et al. (1991). Multi-direction with contour-length weighting. Output: 8-bandfloat32raster of partition fractions, ordered byDIR_OFFSETS. Per-cell fractions sum to 1.0 (or all zero for sinks)."mfd_holmgren"— Holmgren (1994). Same family as Quinn but tunableexponent(default 1.0 mimics Quinn; 4–6 mimics D8). 8-band output."rho8"— Fairfield & Leymarie (1991). Stochastic single-direction; cardinal slopes are perturbed before the steepest-neighbour pick. Passseedfor reproducibility. 1-bandint32output like D8.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Routing scheme — one of |
'd8'
|
exponent
|
float
|
|
1.0
|
forced
|
GeoDataFrame | None
|
Optional GeoDataFrame with columns |
None
|
seed
|
int | None
|
Random seed for |
None
|
forced_direction
|
GeoDataFrame | None
|
Deprecated alias for |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
FlowDirection |
FlowDirection
|
typed wrapper carrying the routing scheme and encoding. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/digitalrivers/dem/routing.py
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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |
accumulate_flow(r, c, flow_dir, acc, dir_offsets)
#
Count upstream cells that drain into (r, c) (iterative).
Uses an explicit stack to perform a depth-first traversal of the flow-direction grid backwards. For every neighbour whose flow direction points toward the current cell, the neighbour is pushed onto the stack. Results are cached in acc so each cell is computed at most once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r
|
Row index of the target cell. |
required | |
c
|
Column index of the target cell. |
required | |
flow_dir
|
2-D |
required | |
acc
|
2-D |
required | |
dir_offsets
|
Direction-offset mapping (see |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of upstream cells that drain into |
int
|
(excluding the cell itself). |
Source code in src/digitalrivers/dem/routing.py
opposite_direction(dr, dc, dir_offsets)
staticmethod
#
Return the D8 direction code opposite to the given offset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dr
|
Row offset component. |
required | |
dc
|
Column offset component. |
required | |
dir_offsets
|
Direction-offset mapping (see |
required |
Returns:
| Type | Description |
|---|---|
|
int or None: Direction code whose offset is |
|
|
or |
Source code in src/digitalrivers/dem/routing.py
flow_accumulation(flow_direction, weights=None, dir_offsets=None, *, engine='auto', out_path=None, tile_size=2048, cache='evict', workers=1, scheduler='threads', client=None)
#
Compute flow accumulation under the given routing scheme.
Generalised dispatcher that delegates to FlowDirection.accumulate(...)
and returns an int32 cast for backwards compatibility with the
previous D8-only output. For weighted or fractional accumulation, call
flow_direction.accumulate(weights) directly to get the underlying
Accumulation (float32) instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flow_direction
|
A |
required | |
weights
|
Dataset | None
|
Optional per-cell weight raster aligned to the DEM. |
None
|
dir_offsets
|
dict
|
Deprecated/ignored. Kept for signature compatibility. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Dataset |
Dataset
|
|
Dataset
|
|
|
Dataset
|
(or weighted sum over) strictly-upstream cells — the cell's own |
|
Dataset
|
weight does not contribute to its own value. |
Warns:
| Type | Description |
|---|---|
UserWarning
|
When |
Examples:
-
Compute D8 cell-count accumulation on a small east-flowing DEM and inspect the outlet value:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.array( ... [[9, 9, 9, 9], [9, 5, 4, 1], [9, 9, 9, 9]], ... dtype=np.float32, ... ) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) dem = DEM(ds.raster) fd = dem.flow_direction(method="d8") acc = dem.flow_accumulation(fd) int(acc.read_array().max()) > 0 True
-
A D∞
FlowDirectiontriggers the truncation warning:import warnings import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.array( ... [[9, 9, 9, 9], [9, 5, 4, 1], [9, 9, 9, 9]], ... dtype=np.float32, ... ) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) dem = DEM(ds.raster) fd = dem.flow_direction(method="dinf") with warnings.catch_warnings(record=True) as caught: ... warnings.simplefilter("always") ... _ = dem.flow_accumulation(fd) any("int32" in str(w.message) for w in caught) True
Source code in src/digitalrivers/dem/routing.py
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | |
convert_flow_direction_to_cell_indices()
#
Convert D8 direction codes to downstream cell row/column indices.
Computes the flow direction from the DEM and translates each direction code into the absolute row and column index of the downstream neighbour.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: 3-D |
Source code in src/digitalrivers/dem/routing.py
delete_basins(basins, path)
staticmethod
#
Keep only the basin with the lowest ID and discard the rest.
Reads a basin-ID raster produced during catchment delineation, replaces every cell that does not belong to the lowest basin ID with the no-data value, and writes the result to path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
basins
|
Dataset
|
Dataset whose cell values are basin IDs (integers). The lowest unique basin ID (excluding no-data) is retained. |
required |
path
|
str
|
Output GeoTIFF file path (must end with |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If path is not a string. |
Source code in src/digitalrivers/dem/routing.py
twi(accumulation, slope_deg=None)
#
Topographic Wetness Index (Beven & Kirkby 1979).
TWI = ln(SCA / tan(slope)) where SCA = specific catchment area =
accumulation_cells * cell_size. High TWI values mark cells likely
to be wet (low slope and / or large upstream area). Slope is treated
in radians internally; values below a small floor (≈ 0.06°) are
clamped to avoid log-singularity at flat cells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accumulation
|
|
required | |
slope_deg
|
Dataset | None
|
Optional pre-computed slope raster in degrees. If
None, |
None
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
References
Beven, K. J. & Kirkby, M. J. (1979). "A physically based, variable contributing area model of basin hydrology." Hydrological Sciences Bulletin 24(1): 43-69.
Source code in src/digitalrivers/dem/morphometry.py
spi(accumulation, slope_deg=None)
#
Stream Power Index (Moore et al. 1991).
SPI = SCA * tan(slope). Proportional to the rate at which overland flow does work at a cell; useful as a proxy for erosion risk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accumulation
|
|
required | |
slope_deg
|
Dataset | None
|
Optional pre-computed slope raster in degrees. If None, computed on the fly. |
None
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
Source code in src/digitalrivers/dem/morphometry.py
sti(accumulation, slope_deg=None)
#
Sediment Transport Index (Moore & Burch 1986).
STI = (SCA / 22.13)^0.6 * (sin(slope) / 0.0896)^1.3. The 22.13 m and 0.0896 m/m constants come from the original USLE plot length and slope; STI predicts where overland flow will transport sediment rather than deposit it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accumulation
|
|
required | |
slope_deg
|
Dataset | None
|
Optional pre-computed slope raster in degrees. |
None
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
Source code in src/digitalrivers/dem/morphometry.py
tpi(window=3)
#
Topographic Position Index (Guisan 1999).
TPI = z - focal_mean(z, window). Positive values mark ridges and
upland positions; negative values mark valleys and depressions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
int
|
Side length of the focal window in cells (must be ≥ 1). Defaults to 3 (a 3×3 neighbourhood). Larger windows pick up regional / catchment-scale topography; smaller windows pick up local relief. |
3
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
Dataset
|
no-data sentinel. |
References
Guisan, A., Weiss, S. B., & Weiss, A. D. (1999). "GLM versus CCA spatial modeling of plant species distribution." Plant Ecology 143(1): 107-122.
Examples:
-
A flat surface has every cell at its focal mean → TPI = 0:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.full((5, 5), 10.0, dtype=np.float32) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) tpi = DEM(ds.raster).tpi(window=3).read_array() bool(np.allclose(tpi, 0.0)) True
-
A single ridge cell on flat terrain reports positive TPI; a pit reports negative:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.zeros((5, 5), dtype=np.float32) z[2, 2] = 9.0 ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) bool(DEM(ds.raster).tpi(window=3).read_array()[2, 2] > 0) True
Source code in src/digitalrivers/dem/morphometry.py
deviation_from_mean(window=3)
#
Deviation from mean elevation — standardised TPI.
(z - focal_mean) / focal_sd. Dimensionless ridge / valley index;
because it normalises by local roughness it allows comparing
positions across regimes with very different relief.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
int
|
Side length of the focal window in cells (≥ 1). |
3
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
Dataset
|
yield 0.0 by definition. No-data cells use this DEM's no-data |
Dataset
|
sentinel. |
Examples:
-
Flat terrain yields zero deviation everywhere:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.full((4, 4), 5.0, dtype=np.float32) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) bool(np.allclose( ... DEM(ds.raster).deviation_from_mean(window=3).read_array(), 0.0 ... )) True
-
A peak reports positive standardised deviation:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.zeros((5, 5), dtype=np.float32) z[2, 2] = 10.0 ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) out = DEM(ds.raster).deviation_from_mean(window=3).read_array() bool(out[2, 2] > 0) True
Source code in src/digitalrivers/dem/morphometry.py
elev_std(window=3)
#
Standard deviation of elevation in a focal window.
Pure focal-window SD on the elevation raster. A roughness proxy: high values mark varied terrain, low values mark smooth terrain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
int
|
Side length of the focal window in cells (≥ 1). |
3
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
Dataset
|
no-data sentinel. |
Examples:
-
Flat terrain reports zero SD everywhere:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.full((4, 4), 5.0, dtype=np.float32) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) bool(np.allclose( ... DEM(ds.raster).elev_std(window=3).read_array(), 0.0 ... )) True
-
A step in elevation produces non-zero SD along the boundary:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.zeros((5, 5), dtype=np.float32) z[:, 3:] = 10.0 ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) sd = DEM(ds.raster).elev_std(window=3).read_array() bool((sd[:, 2] > 0).all()) True
Source code in src/digitalrivers/dem/morphometry.py
curvature(kind='profile')
#
Surface curvature (Zevenbergen & Thorne 1987).
Fits a partial quartic polynomial z = Ax²y² + Bx²y + Cxy² + Dx² +
Ey² + Fxy + Gx + Hy + I to the 3×3 neighbourhood of each cell and
evaluates one of the five canonical curvature variants from the
coefficient grid:
"plan"— curvature perpendicular to the slope direction; positive on diverging slopes, negative on converging ones."profile"— curvature parallel to the slope direction; positive on convex (decelerating) slopes, negative on concave (accelerating) ones."total"—2 * (D + E); sign-independent total relief."mean"— average of the two principal curvatures."gaussian"— product of the two principal curvatures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str
|
One of |
'profile'
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
Dataset
|
DEM's no-data sentinel. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
References
Zevenbergen, L. W. & Thorne, C. R. (1987). "Quantitative analysis of land surface topography." Earth Surface Processes and Landforms 12(1): 47-56.
Examples:
-
Every curvature variant is zero on a flat DEM:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.full((5, 5), 10.0, dtype=np.float32) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) bool(np.allclose( ... DEM(ds.raster).curvature(kind="total").read_array(), 0.0 ... )) True
-
Mean curvature equals total / 2 on a paraboloid (interior):
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM x, y = np.meshgrid(np.arange(-3, 4), np.arange(-3, 4)) z = (-(x * x + y * y)).astype(np.float32) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) dem = DEM(ds.raster) total = dem.curvature(kind="total").read_array()[2:-2, 2:-2] mean = dem.curvature(kind="mean").read_array()[2:-2, 2:-2] bool(np.allclose(mean, total / 2.0, atol=1e-5)) True
Source code in src/digitalrivers/dem/morphometry.py
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 | |
normal_vector_deviation(window=3)
#
Per-cell angular deviation of the surface normal from its focal mean.
Computes each cell's outward-pointing surface normal from finite
differences of the elevation grid, then takes the focal-mean of the
unit-normal components in a window×window neighbourhood. The
result at each cell is the angle (in radians) between the local
normal and the focal-mean normal — a roughness metric that grows
with how strongly the surface bends within the window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
int
|
Side length of the focal window in cells (≥ 1). |
3
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
Dataset
|
|
Examples:
-
Flat terrain yields zero angular deviation:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.full((5, 5), 10.0, dtype=np.float32) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) bool(np.allclose( ... DEM(ds.raster).normal_vector_deviation(window=3).read_array(), ... 0.0, atol=1e-5, ... )) True
-
A constant-slope plane has identical normals in its deep interior, so deviation there is ~0:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM x, y = np.meshgrid(np.arange(7), np.arange(7)) z = (2.0 * x + y).astype(np.float32) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) arr = DEM(ds.raster).normal_vector_deviation(window=3).read_array() bool(np.allclose(arr[2:-2, 2:-2], 0.0, atol=1e-4)) True
Source code in src/digitalrivers/dem/morphometry.py
openness(*, search_radius=10, kind='positive')
#
Topographic openness (Yokoyama 2002).
For each cell, walks outward along 8 azimuths up to search_radius
cells and records the maximum elevation angle (positive openness)
or the minimum (negative openness) along each walk. The per-cell
output is the mean of (π/2 - horizon_angle) across the 8
directions, in radians.
High positive openness marks exposed / high-relief locations; high negative openness marks deep depressions / valley floors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
search_radius
|
int
|
Maximum walk distance in cells. Must be ≥ 1. Defaults to 10. |
10
|
kind
|
str
|
|
'positive'
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
Dataset
|
use this DEM's no-data sentinel. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
References
Yokoyama, R., Shirasawa, M., & Pike, R. J. (2002). "Visualizing topography by openness: A new application of image processing to digital elevation models." Photogrammetric Engineering and Remote Sensing 68(3): 257-265.
Examples:
-
Flat terrain: every horizon angle is 0, so positive openness is
π/2at every cell:import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.full((5, 5), 10.0, dtype=np.float32) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) arr = DEM(ds.raster).openness(search_radius=2).read_array() bool(np.allclose(arr, np.pi / 2.0, atol=1e-5)) True
-
A peak on flat terrain has strictly larger positive openness than its neighbours (which look up at it):
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.zeros((5, 5), dtype=np.float32) z[2, 2] = 10.0 ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) arr = DEM(ds.raster).openness(search_radius=3).read_array() bool(arr[2, 2] > arr[1, 2]) True
Source code in src/digitalrivers/dem/morphometry.py
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 | |
sky_view_factor(*, search_radius=10)
#
Sky-view factor (Zakšek et al. 2011).
For each cell, the fraction of the upper hemisphere that is visible
from that cell. Walks along 8 azimuths up to search_radius,
records the maximum elevation angle along each walk, and returns
the mean of (1 - sin(horizon_angle)) across the 8 directions —
equivalent to the fraction of an isotropic sky dome not occluded
by surrounding terrain.
Shares the horizon-walk kernel with openness (W-27); the two
differ only in the per-direction aggregation function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
search_radius
|
int
|
Maximum walk distance in cells. Must be ≥ 1. Defaults to 10. |
10
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
Dataset
|
this DEM's no-data sentinel. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
References
Zakšek, K., Oštir, K., & Kokalj, Ž. (2011). "Sky-view factor as a relief visualization technique." Remote Sensing 3(2): 398-415.
Examples:
-
Flat terrain: nothing occludes the sky, SVF = 1 everywhere:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.full((5, 5), 10.0, dtype=np.float32) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) arr = DEM(ds.raster).sky_view_factor(search_radius=2).read_array() bool(np.allclose(arr, 1.0, atol=1e-5)) True
-
A pit surrounded by higher cells reports SVF strictly less than 1 (the walls occlude part of the sky):
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.full((5, 5), 10.0, dtype=np.float32) z[2, 2] = 0.0 ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) arr = DEM(ds.raster).sky_view_factor(search_radius=2).read_array() bool(arr[2, 2] < 1.0) True
Source code in src/digitalrivers/dem/morphometry.py
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 | |
ruggedness(window=3)
#
Terrain Ruggedness Index — Wilson (2007) mean-absolute-difference form.
Per-cell mean of absolute elevation differences to every other cell
in a window×window neighbourhood. Output unit is the DEM elevation
unit (metres). Higher values mark rougher terrain; flat terrain is
zero.
Note
This implements the Wilson et al. (2007) mean-absolute-
difference variant, not Riley's original root-sum-square TRI.
For the Riley form use Terrain.tri(algorithm="Riley") (the
GDAL default), which equals sqrt(Σ(z_c − z_i)²) over the 3x3
neighbourhood; Terrain.tri(algorithm="Wilson") reproduces
this method's formula on a fixed 3x3 window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
int
|
Side length of the focal window in cells (≥ 1). Defaults to 3 (the original 3×3 neighbourhood). |
3
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
Dataset
|
DEM's no-data sentinel. |
References
Wilson, M. F. J., O'Connell, B., Brown, C., Guinan, J. C., & Grehan, A. J. (2007). "Multiscale terrain analysis of multibeam bathymetry data for habitat mapping on the continental slope." Marine Geodesy 30(1-2): 3-35.
Riley, S. J., DeGloria, S. D., & Elliot, R. (1999). "A terrain ruggedness index that quantifies topographic heterogeneity." Intermountain Journal of Sciences 5(1-4): 23-27.
Examples:
-
Flat terrain has zero ruggedness everywhere:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.full((4, 4), 5.0, dtype=np.float32) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) bool(np.allclose( ... DEM(ds.raster).ruggedness(window=3).read_array(), 0.0 ... )) True
-
A peak surrounded by flat terrain contributes positive ruggedness at the peak and its 8-neighbours:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.zeros((5, 5), dtype=np.float32) z[2, 2] = 9.0 ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) tri = DEM(ds.raster).ruggedness(window=3).read_array() bool(tri[2, 2] > 0 and tri[1, 2] > 0 and tri[3, 2] > 0) True
Source code in src/digitalrivers/dem/morphometry.py
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 | |
slope(*, engine='auto', out_path=None, tile_size=2048)
#
Compute the maximum downhill slope at every cell.
Calculates slopes in all eight D8 directions via
_get_8_direction_slopes and returns a raster whose cell
values are the maximum slope across the eight neighbours.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
engine
|
str
|
|
'auto'
|
out_path
|
str | None
|
Destination for the tiled path, which writes as it streams rather than materialising the result. Required when the tiled engine runs, ignored otherwise. |
None
|
tile_size
|
int | tuple[int, int]
|
Tile shape for the tiled path, as an edge length or an
explicit |
2048
|
Returns:
| Name | Type | Description |
|---|---|---|
Dataset |
Dataset
|
Single-band raster with the same geometry as the DEM, containing the maximum slope value per cell. |
Out-of-core
Slope is a local 3×3 stencil, so engine="tiled" streams it tile-by-tile to out_path with
constant memory (bit-for-bit identical to the whole-array result). engine="auto" (default) only
switches to it for rasters large enough to risk exhausting RAM; engine="tiled" requires out_path.
See Also
Terrain.slope: GDAL-based slope using Horn or Zevenbergen-Thorne algorithms.
Source code in src/digitalrivers/dem/morphometry.py
fill_depressions(method='priority_flood', epsilon=0.0, inplace=False, *, engine='auto', out_path=None, tile_size=2048, cache='evict', workers=1, scratch_dir=None, eps_fill='exact')
#
Fill closed depressions in the DEM.
Three algorithms are available via the method argument:
"priority_flood"(default) — Barnes, Lehman & Mulla (2014) Priority-Flood with the two-queue plateau optimisation. Withepsilon == 0it produces flat fills; withepsilon > 0it produces a monotonic surface (every cell has at least one lower neighbour along the drainage path) at the cost of a small elevation inflation proportional to plateau width. Theepsilon > 0gradient is selected byeps_fill(see below)."wang_liu"— Wang & Liu (2006). Flat fill, no epsilon. Equivalent in output topriority_floodwithepsilon == 0; kept as a named alternative for callers who plan to resolve flats explicitly afterwards (P4)."planchon_darboux"— Planchon & Darboux (2002). Iterative directional-sweep algorithm. Slower than Priority-Flood on large DEMs; kept as a low-relief reference. Requiresepsilon > 0.
No-data handling is uniform across methods: cells flagged no-data act as outlets (they cannot be filled, and data cells adjacent to them are seeded as drainage sources alongside the true raster boundary).
Precision note. Priority-flood / planchon-darboux compute the cumulative lift
in float64 but the output is cast back to the input dtype. For float32 DEMs
with epsilon in the 0.1-class on wide plateaus, the accumulated lift can
approach float32's relative precision near the spill elevation and very long
plateaus may underflow to identical filled values. Prefer float64 inputs
when running with epsilon > 0 and large depressions; wang_liu /
epsilon=0 are immune.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
One of |
'priority_flood'
|
epsilon
|
float
|
Per-step elevation lift inside depressions. |
0.0
|
inplace
|
bool
|
If |
False
|
engine
|
str
|
|
'auto'
|
out_path
|
str | None
|
Destination GeoTIFF the tiled path streams its result into. Required whenever the tiled engine runs, ignored otherwise. |
None
|
tile_size
|
int | tuple[int, int]
|
Core tile shape for the tiled path, as an edge length or an
explicit |
2048
|
cache
|
str
|
Tile-store mode for the tiled path. |
'evict'
|
workers
|
int
|
Tiled path only. |
1
|
scratch_dir
|
str | None
|
Directory the tiled path spills |
None
|
eps_fill
|
str
|
Gradient for |
'exact'
|
Returns:
| Type | Description |
|---|---|
DEM | None
|
DEM | None: A new |
DEM | None
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
NotImplementedError
|
If the tiled engine is asked for |
Out-of-core
engine="auto" (default) runs the in-memory algorithm unless the DEM is large enough to risk
exhausting RAM, in which case it streams a tiled Barnes-2016 fill to out_path. Force the path with
engine="in_memory" / engine="tiled". engine="tiled" requires out_path and does not support
inplace. For epsilon>0, eps_fill="exact" (default, alias "monotone") produces a tiled fill
byte-for-byte identical to the in-memory result; eps_fill="barnes" (the classic step-count) is
in-memory only and is rejected by engine="tiled".
Examples:
-
The default priority-flood fill raises a one-cell pit to its rim, so the filled depression is flat:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.full((3, 3), 5.0, dtype=np.float64) z[1, 1] = 1.0 ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) filled = DEM(ds.raster).fill_depressions() float(filled.values[1, 1]) 5.0
-
A positive
epsilonlifts the pit above its rim instead, leaving D8 routing a downhill path out of the fill:import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.full((3, 3), 5.0, dtype=np.float64) z[1, 1] = 1.0 ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) filled = DEM(ds.raster).fill_depressions(epsilon=0.5) float(filled.values[1, 1]) 5.5
-
inplace=Truerewrites the instance and returns nothing:import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.full((3, 3), 5.0, dtype=np.float64) z[1, 1] = 1.0 ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) dem = DEM(ds.raster) dem.fill_depressions(epsilon=0.5, inplace=True) is None True float(dem.values[1, 1]) 5.5
See Also
DEM.breach_depressions: Cuts a channel through the barrier instead of raising
the pit floor.
DEM.fill_sinks: Deprecated alias that routes here with
method="priority_flood", epsilon=0.1.
Source code in src/digitalrivers/dem/conditioning.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 | |
breach_depressions(method='least_cost', max_depth=None, max_length=None, fill_remaining=True, inplace=False)
#
Breach depressions in the DEM (Lindsay 2016 family).
Breaching is the structural alternative to filling: instead of raising the pit floor, it cuts a channel through the lowest barrier between the pit and an outlet. On LiDAR DEMs this is usually more realistic — most internal pits are data artefacts and the natural drainage path is preserved by cutting the artefact away rather than inflating the surrounding terrain.
Three methods are available via the method argument:
"single_cell"— cheap O(n) preprocessing pass that resolves isolated 1-cell pits by lowering an intermediate first-order neighbour to the midpoint of the pit and a lower second-order cell. Does nothing if no such configuration exists."least_cost"(default) — Lindsay 2016 Dijkstra-from-each-pit. Carves a strictly monotonic channel from the pit to the nearest outlet. Optionalmax_depthandmax_lengthconstraints abort the breach for any pit whose channel would exceed them; aborted pits are left unresolved."hybrid"— tryleast_costfirst; pits that fail their constraint fall back to the Priority-Flood depression fill (P2). The breach phase has already lowered parts of the DEM where partial breaching occurred, so the fill operates on a modified surface and produces less overall lift than fill-only.
No-data cells act as free outlets — any Dijkstra path that reaches a no-data cell terminates the search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
One of |
'least_cost'
|
max_depth
|
float | None
|
Maximum cumulative |
None
|
max_length
|
int | None
|
Maximum path length in cells. |
None
|
fill_remaining
|
bool
|
Only meaningful when |
True
|
inplace
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
DEM | None
|
DEM | None: A new |
DEM | None
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/digitalrivers/dem/conditioning.py
resolve_flats(max_iter=1000, epsilon=1e-05, connectivity=8, inplace=False)
#
Impose a deterministic gradient on every flat plateau in the DEM.
After fill_depressions(method="wang_liu") (or "priority_flood" with
epsilon=0), every closed depression is filled to its spill elevation — but the
interior of each filled depression is a flat plateau with no defined steepest
descent, so D8 flow direction over the result has NO_FLOW cells across every
plateau. resolve_flats nudges those cells so each has a unique downhill
neighbour: combined Garbrecht & Martz (1997) gradient — drain towards the
nearest outlet (LEC) with a tiebreak that drains away from the nearest rim
(HEC). The towards-lower gradient is weighted 2x so it dominates and the
away-from-higher gradient acts as a deterministic tiebreaker.
Plateaus without a low-edge cell (closed depressions that survived the fill — they
should not exist if you ran fill_depressions first) are left untouched.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_iter
|
int
|
Safety cap on BFS levels per plateau. Real plateaus rarely exceed
|
1000
|
epsilon
|
float
|
Per-BFS-step elevation lift. Total lift over a plateau is at most
|
1e-05
|
connectivity
|
int
|
4 or 8. Controls plateau-labelling and BFS step direction; LEC/HEC classification always uses 8-connectivity (Garbrecht-Martz convention). Default is 8. |
8
|
inplace
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
DEM | None
|
DEM | None: A new |
DEM | None
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/digitalrivers/dem/conditioning.py
stochastic_depressions(sigma, n_runs=100, *, seed=None, method='priority_flood')
#
Per-cell depression-occurrence probability via Monte-Carlo.
Adds Gaussian noise (zero-mean, supplied sigma) to the DEM, runs
depression detection on each noisy realisation, and aggregates the
per-cell probability across n_runs realisations. Cells with high
probability are robust depressions; low probability cells are likely
noise artefacts of a noisy DEM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sigma
|
float
|
Standard deviation of the Gaussian noise in DEM elevation units. Must be non-negative. A reasonable choice is the DEM's stated vertical error. |
required |
n_runs
|
int
|
Number of Monte-Carlo realisations. Must be positive. Defaults to 100. |
100
|
seed
|
int | None
|
Optional seed for the random number generator. Pass an integer for reproducible results. |
None
|
method
|
str
|
Fill-depressions algorithm passed through to
|
'priority_flood'
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
Dataset
|
aligned to this DEM. No-data sentinel |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/digitalrivers/dem/conditioning.py
burn_streams(streams, method='fill_burn', *, sharp=10.0, smooth=2.0, buffer_cells=5, constant_drop=1.0, max_breach_depth=None, max_breach_length=None, inplace=False)
#
Condition the DEM by burning a vector stream network into it.
Implements all three P20 methods. "fill_burn" (Lindsay 2018 —
used by WhiteboxTools' FillBurn) is the default; "agree"
(Hellweger 1997) and "topological_breach" (Lindsay 2016) are
also available.
Fill-burn algorithm:
- Rasterise every LineString in
streamsonto a stream mask. - Lower every stream cell's elevation by
constant_drop. - Run
fill_depressions(method="priority_flood")so the surrounding cells drain naturally into the channel.
AGREE algorithm: lower stream cells by sharp, then ramp the drop
linearly from sharp at the channel to 0 at a buffer_cells-wide
perimeter (offset by smooth), producing a smooth trench.
Topological-breach algorithm: rasterise and lower the stream cells,
then run the Phase 1 least-cost breach so every interior pit carves
outward to a stream cell, honouring max_breach_depth /
max_breach_length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
streams
|
|
required | |
method
|
str
|
|
'fill_burn'
|
sharp / smooth / buffer_cells
|
AGREE parameters (unused for fill_burn and topological_breach). |
required | |
constant_drop
|
float
|
Elevation drop applied to every stream cell in fill_burn and topological_breach (default 1.0 map unit; unused for agree). |
1.0
|
max_breach_depth / max_breach_length
|
topological_breach parameters (unused for fill_burn and agree). |
required | |
inplace
|
bool
|
If True, update the instance; else return a new DEM. |
False
|
Returns:
| Type | Description |
|---|---|
DEM | None
|
DEM | None: New DEM with the conditioned surface, or None when |
DEM | None
|
|
Examples:
-
Fill-burn lowers the stream-row of a flat DEM:
import numpy as np import geopandas as gpd from shapely.geometry import LineString from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.full((5, 5), 10.0, dtype=np.float32) ds = Dataset.from_array( ... z, ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) dem = DEM(ds.raster)
Horizontal stream down row 2 (y = -2.5).#
line = LineString([(0.5, -2.5), (4.5, -2.5)]) layer = gpd.GeoDataFrame(geometry=[line], crs=4326) burnt = dem.burn_streams(layer, constant_drop=2.0) bool(float(burnt.values[2, 2]) < float(burnt.values[0, 0])) True
Source code in src/digitalrivers/dem/conditioning.py
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 | |
enforce_culverts(roads, streams, culvert_drop=0.5, inplace=False)
#
Lower DEM cells at every stream-road intersection by
culvert_drop so subsequent flow routing crosses roads instead of
dead-ending against them. Simplified version of WhiteboxTools'
BurnStreamsAtRoads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
roads
|
|
required | |
streams
|
|
required | |
culvert_drop
|
float
|
Elevation drop applied to each intersection cell. |
0.5
|
inplace
|
bool
|
If True, update the instance; else return a new DEM. |
False
|
Returns:
| Type | Description |
|---|---|
DEM | None
|
DEM | None: New DEM with culverts enforced, or None when |
DEM | None
|
|
Source code in src/digitalrivers/dem/conditioning.py
hydroflatten(water_polygons, method='min', inplace=False)
#
Flatten lake / pond surfaces to a single elevation per polygon.
For each input polygon, sample the DEM cells the polygon covers
and assign every cell in the polygon the per-polygon statistic
("min" by default — the most defensive choice for hydrology;
"mean" and "median" are also supported).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
water_polygons
|
|
required | |
method
|
str
|
|
'min'
|
inplace
|
bool
|
If True, update the instance; else return a new DEM. |
False
|
Returns:
| Type | Description |
|---|---|
DEM | None
|
DEM | None: Hydroflattened DEM. |
Source code in src/digitalrivers/dem/conditioning.py
burn_buildings(building_polygons, lift=50.0, inplace=False)
#
Lift building footprints above the DEM by lift map units so
2D flood routing flows around them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
building_polygons
|
|
required | |
lift
|
float
|
Elevation added to every cell whose centre falls inside a polygon. |
50.0
|
inplace
|
bool
|
If True, update the instance; else return a new DEM. |
False
|
Returns:
| Type | Description |
|---|---|
DEM | None
|
DEM | None: DEM with buildings raised. |
Source code in src/digitalrivers/dem/conditioning.py
enforce_breaklines(breaklines, lift=5.0, inplace=False)
#
Raise linear barriers (levees, walls, kerbs) above the surrounding DEM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
breaklines
|
|
required | |
lift
|
float
|
Elevation added at each rasterised cell along the lines. |
5.0
|
inplace
|
bool
|
If True, update the instance; else return a new DEM. |
False
|
Returns:
| Type | Description |
|---|---|
DEM | None
|
DEM | None: DEM with breaklines enforced. |
Source code in src/digitalrivers/dem/conditioning.py
fill_sinks(inplace=False)
#
Deprecated alias for fill_depressions(method="priority_flood", epsilon=0.1).
The original implementation was a single-pass, single-cell sink fill that did not cascade through nested pits. Calls now route through the Priority-Flood + epsilon algorithm, which is correct on cascading depressions. The output differs from the historical algorithm in two ways:
- Cascading pits are fully resolved (each pit fills to the rim of its enclosing pit, not just to its immediate-neighbour minimum).
- Drainage paths within filled depressions inherit a 0.1-unit gradient — so
D8 routing on the result avoids
NO_FLOWcells inside the fill.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
DEM | None
|
DEM | None: New |
DEM | None
|
|
Source code in src/digitalrivers/dem/conditioning.py
__init__(src, access='read_only', *, gdal_env=None, open_options=None)
#
Wrap a GDAL dataset as a digital elevation model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
Dataset
|
Open GDAL dataset to wrap. The handle is adopted, not copied.
To open a DEM from a file path use the inherited
|
required |
access
|
str
|
|
'read_only'
|
gdal_env
|
dict[str, str] | None
|
GDAL config (cloud credentials, HTTP knobs) captured on the
dataset and re-installed around its reads. Default |
None
|
open_options
|
tuple[str, ...] | list[str] | None
|
GDAL open options captured on the dataset and reapplied
when it is reopened. Default |
None
|
Source code in src/digitalrivers/dem/dem.py
subgrid_bathymetry(scale_factor, n_bins=10)
#
Build per-coarse-cell bathymetry tables (SFINCS-style).
For each coarse cell (scale_factor × scale_factor block of fine
cells), compute a histogram-like table mapping a coarsened water-
depth level to the wetted area within the block. This is the
sub-grid representation SFINCS and similar reduced-order 2D models
use to recover small-scale topography without resolving it on the
coarse grid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale_factor
|
int
|
Integer aggregation factor (>= 2). |
required |
n_bins
|
int
|
Number of depth bins per coarse cell. |
10
|
Returns:
| Type | Description |
|---|---|
'pd.DataFrame'
|
|
'pd.DataFrame'
|
|
'pd.DataFrame'
|
|
'pd.DataFrame'
|
fraction of fine cells at or below the |
'pd.DataFrame'
|
For flat blocks ( |
'pd.DataFrame'
|
is |
Raises:
| Type | Description |
|---|---|
ValueError
|
For |
Examples:
-
A flat block produces
frac_below_<k> == 1.0for every bin (B1 regression — the columns are always present):import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM ds = Dataset.from_array( ... np.full((4, 4), 5.0, dtype=np.float32), ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) df = DEM(ds.raster).subgrid_bathymetry(scale_factor=2, n_bins=3) sorted(df.columns.tolist()) ['frac_below_1', 'frac_below_2', 'frac_below_3', 'z_max', 'z_min'] float(df["frac_below_1"].iloc[0]) 1.0
Source code in src/digitalrivers/dem/dem.py
export(path, target, *, breaklines=None, walls=None, buildings=None, manning_n=None, boundary_conditions=None, validate=True, **kwargs)
#
Export the DEM to a hydrodynamic-model format.
Every target listed below ships with a working writer. Most were
backfilled after the initial Phase-3 cut; lisflood_fp is the
canonical Arc-ASCII writer and remains the only target that
actually requires a sinks-free input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Output file path. |
required |
target
|
str
|
One of |
required |
breaklines / walls / buildings / manning_n / boundary_conditions
|
Reserved for target-specific bundles. Currently ignored by the LISFLOOD-FP writer. |
required | |
validate
|
bool
|
When |
True
|
**kwargs
|
Target-specific options. |
{}
|
Returns:
| Type | Description |
|---|---|
dict
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
For unknown |
RuntimeError
|
When |
Source code in src/digitalrivers/dem/dem.py
anudem_interpolate(mask=None, max_iter=200, tol=0.001, method='laplacian', inplace=False)
#
ANUDEM-lite: Laplacian-relaxation gap fill (P25).
A pragmatic subset of Hutchinson 1989 ANUDEM that handles the
common gap-filling case: a DEM with NaN holes (cloud shadows,
survey gaps, vegetation occlusion) is filled by Gauss-Seidel
Laplacian relaxation, holding the known cells fixed. Each
iteration replaces every unknown cell with the mean of its four
4-connected neighbours; iteration stops when the maximum change
in a sweep drops below tol or after max_iter sweeps.
Two solver methods are available:
"laplacian"(default): solves Δz = 0 via the 4-neighbour mean iteration. Fast, smooth interior, but only C⁰ continuity at the anchor cells — the surface has visible "kinks" at known points."biharmonic": solves Δ²z = 0 by alternating two Laplacian sweeps (relaxu = Δz, then relaxzsoΔz = u). C¹ continuity at anchors; closer to Hutchinson 1989 ANUDEM's tension-spline objective but still without multigrid acceleration or drainage enforcement.
Limitations vs full ANUDEM:
- No multigrid acceleration; iteration cost is O(N · max_iter).
- No drainage enforcement. For stream-conditioned DEMs, combine
with :meth:
burn_streamsbefore or after. - No tension parameter (Hutchinson's λ); the biharmonic mode is a fixed-λ approximation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
Optional bool array same shape as the DEM. |
None
|
|
max_iter
|
int
|
Maximum relaxation sweeps. |
200
|
tol
|
float
|
Convergence tolerance — stop when |
0.001
|
method
|
str
|
|
'laplacian'
|
inplace
|
bool
|
If True, update the instance; else return a new DEM. |
False
|
Returns:
| Type | Description |
|---|---|
DEM | None
|
DEM | None: Filled DEM, or None when |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input DEM has no finite cells or |
Examples:
-
Fill a single-cell NaN hole with the default Laplacian solver; the filled value sits inside the bracketing range:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.array( ... [[1.0, 2.0, 3.0], [4.0, np.nan, 6.0], [7.0, 8.0, 9.0]], ... dtype=np.float32, ... ) ds = Dataset.from_array( ... np.where(np.isnan(z), -9999.0, z), ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) filled = DEM(ds.raster).anudem_interpolate( ... method="laplacian", max_iter=200, tol=1e-6, ... ) out = filled.values bool(1.0 <= out[1, 1] <= 9.0) True
-
The biharmonic mode (P32 backfill) approximates Hutchinson 1989's Delta^2 z = 0 by alternating Laplacian sweeps:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM z = np.array( ... [[1.0, 2.0, 3.0], [4.0, np.nan, 6.0], [7.0, 8.0, 9.0]], ... dtype=np.float32, ... ) ds = Dataset.from_array( ... np.where(np.isnan(z), -9999.0, z), ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) filled = DEM(ds.raster).anudem_interpolate( ... method="biharmonic", max_iter=200, tol=1e-5, ... ) bool(np.isfinite(filled.values).all()) True
-
Unknown method raises ValueError:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM ds = Dataset.from_array( ... np.ones((2, 2), dtype=np.float32), ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) DEM(ds.raster).anudem_interpolate(method="bogus") Traceback (most recent call last): ... ValueError: method must be 'laplacian' or 'biharmonic'; got 'bogus'
-
The 5-point stencil uses edge-replication (Neumann) boundary padding, so a NaN cell adjacent to the raster boundary is filled from its in-bounds neighbours only — no periodic-wrap contamination from the opposite edge:
import numpy as np from pyramids.dataset import Dataset, GeoReference from digitalrivers import DEM
Top-left NaN with very different anchor at bottom-right.#
z = np.full((5, 5), 10.0, dtype=np.float32) z[-1, -1] = -100.0 z[0, 0] = np.nan ds = Dataset.from_array( ... np.where(np.isnan(z), -9999.0, z), ... geo_ref=GeoReference( ... top_left_corner=(0.0, 0.0), ... cell_size=1.0, ... epsg=4326, ... ), ... no_data_value=-9999.0, ... ) filled = DEM(ds.raster).anudem_interpolate( ... method="laplacian", max_iter=300, tol=1e-6, ... ) bool(abs(float(filled.values[0, 0]) - 10.0) < 5.0) True
See Also
DEM.fill_depressions: hydrologic conditioning that removes sinks. DEM.burn_streams: stream-network drainage enforcement.
Source code in src/digitalrivers/dem/dem.py
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |