Flow Pipeline Module

High-level flow computation pipeline with basin preservation.

This module provides a validated flow computation pattern that properly handles ocean detection, endorheic basin detection, water body integration, and DEM conditioning. It orchestrates the lower-level functions from Flow Accumulation Module and Water Bodies Module.

Pipeline Steps

  1. Ocean Detection - Identify ocean/sea-level cells

  2. Endorheic Basin Detection - Find and preserve internally-draining basins

  3. Water Body Integration - Lake routing with spillway identification

  4. DEM Conditioning - Breach sinks and fill residual depressions

  5. Flow Direction - D8 flow directions with combined masks

  6. Drainage Area - Upstream contributing area computation

  7. Discharge Potential - Optional rainfall-weighted flow accumulation

API Reference

Flow computation pipeline with basin preservation.

This module provides a validated flow computation pattern that properly handles: 1. Ocean detection 2. Endorheic basin detection and preservation 3. Water body (lake) integration with basin awareness 4. DEM conditioning with combined masks 5. Flow direction and drainage area computation

The pattern is extracted from validate_flow_with_water_bodies.py and provides a reusable orchestrator for flow analysis.

src.terrain.flow_pipeline.compute_flow_with_basins(dem, dem_transform, precipitation=None, precip_transform=None, lake_mask=None, lake_outlets=None, detect_basins=True, min_basin_size=5000, min_basin_depth=1.0, backend='spec', coastal_elev_threshold=0.0, edge_mode='all', max_breach_depth=25.0, max_breach_length=150, epsilon=0.0001, ocean_threshold=0.0, ocean_border_only=True, upscale_precip=False, upscale_factor=4, upscale_method='auto', verbose=True)[source]

Compute flow using validated basin preservation pattern.

This function implements the approach validated in validate_flow_with_water_bodies.py: 1. Detect ocean mask 2. Detect endorheic basins (optional) 3. Create conditioning mask (ocean + basins + selective lakes) 4. Condition DEM with combined mask 5. Compute flow direction with lake routing (if lakes provided) 6. Compute drainage area 7. Compute upstream rainfall (if precipitation provided)

Basin-aware lake handling: - Lakes INSIDE preserved basins → pre-masked (act as drainage sinks) - Lakes OUTSIDE basins → NOT masked (act as river connectors)

Parameters:
  • dem (np.ndarray) – Digital elevation model (2D array)

  • dem_transform (Affine) – Geographic transform for DEM

  • precipitation (np.ndarray, optional) – Precipitation data (same shape as DEM). If None, upstream rainfall not computed.

  • precip_transform (Affine, optional) – Geographic transform for precipitation (currently unused, assumed same as DEM)

  • lake_mask (np.ndarray, optional) – Labeled mask of water bodies (0 = no lake, >0 = lake ID)

  • lake_outlets (np.ndarray, optional) – Boolean mask of lake outlet cells

  • detect_basins (bool, default=True) – Whether to detect and preserve endorheic basins

  • min_basin_size (int, default=5000) – Minimum basin size in cells to preserve. When set to the default (5000), uses adaptive scaling (4e-5 × total_cells) to handle different DEM sizes. Set to a specific value to override adaptive scaling.

  • min_basin_depth (float, default=1.0) – Minimum basin depth in meters to be considered endorheic

  • backend (str, default="spec") – Flow algorithm backend (‘spec’ or ‘legacy’)

  • coastal_elev_threshold (float, default=0.0) – Max elevation for coastal outlets in meters (spec backend only)

  • edge_mode (str, default="all") – Boundary outlet strategy: ‘all’, ‘local_minima’, ‘outward_slope’, ‘none’

  • max_breach_depth (float, default=25.0) – Max vertical breach per cell in meters (spec backend only)

  • max_breach_length (int, default=150) – Max breach path length in cells (spec backend only)

  • epsilon (float, default=1e-4) – Min gradient in filled areas (spec backend only)

  • ocean_threshold (float, default=0.0) – Elevation threshold for ocean detection

  • ocean_border_only (bool, default=True) – Only detect ocean from border pixels

  • upscale_precip (bool, default=False) – Whether to upscale precipitation data using ESRGAN before accumulation

  • upscale_factor (int, default=4) – Upscaling factor for precipitation (2, 4, or 8)

  • upscale_method (str, default="auto") – Upscaling method: “auto” (try ESRGAN, fall back to bilateral), “esrgan”, “bilateral”, or “bicubic”

  • verbose (bool, default=True) – Print progress messages

Returns:

Dictionary with keys: - ‘flow_direction’: np.ndarray, D8 flow direction codes - ‘drainage_area’: np.ndarray, drainage area in cells - ‘dem_conditioned’: np.ndarray, depression-filled DEM - ‘ocean_mask’: np.ndarray, boolean ocean mask - ‘basin_mask’: np.ndarray or None, boolean endorheic basin mask - ‘lake_inlets’: np.ndarray or None, boolean mask of lake inlet cells - ‘upstream_rainfall’: np.ndarray or None, upstream rainfall (if precip provided) - ‘conditioning_mask’: np.ndarray, combined mask used for DEM conditioning

Return type:

dict

Examples

Basic usage without lakes:

>>> results = compute_flow_with_basins(dem, dem_transform)
>>> flow_dir = results['flow_direction']
>>> drainage = results['drainage_area']

With lakes and precipitation:

>>> results = compute_flow_with_basins(
...     dem, dem_transform,
...     precipitation=precip,
...     lake_mask=lakes,
...     lake_outlets=outlets,
...     detect_basins=True
... )
>>> upstream_rain = results['upstream_rainfall']

Notes

This function uses the ‘spec’ backend by default, which provides: - Breaching-based depression handling - Configurable coastal outlet detection - Endorheic basin preservation

See Also