DSAIL Hydrology Team

Felix Muruti

Research Intern

Table of Contents

    Table of Contents

      Hydrology Catchment Delineation PySheds Digital Elevation Models GIS & Python

      Watershed Delineation with PySheds: Demystifying Drainage Basins & River Networks

      By Felix Muruti · DSAIL Hydrology Team · ~16 min read

      Watershed Delineation Overview showing Extent, Flow Direction, Flow Accumulation, and Elevation

      Introduction to Hydrology & Catchment Science

      Hydrology is the science that examines the occurrence, circulation, storage, and distribution of water across the Earth system. It encompasses the underlying physical, chemical, and biological mechanisms governing moisture exchange between the atmosphere, the continental surface, and subsurface aquifers. In environmental engineering and computational earth observation, understanding the spatial boundaries of water movement is foundational to predicting river discharge, managing water resource allocations, and mitigating severe flood hazards.

      The continuous motion of water is formalized through the hydrologic cycle: water evaporates from oceans, lakes, and vegetative surfaces, condenses into clouds, precipitates over landmasses, navigates complex mountain topography as surface runoff and shallow subsurface flow, and ultimately reconverges into river networks that return to the sea.

      The Global Hydrological Cycle illustrating precipitation, runoff, infiltration, and evaporation

      Figure 1: The terrestrial hydrologic cycle, depicting continuous moisture exchange between atmospheric, surface water, and subsurface groundwater compartments.

      From a systems engineering perspective, Ven Te Chow et al. (1988) conceptualized the hydrologic cycle as a continuous sequence of three interconnected, open physical subsystems: the atmospheric system, the surface water system, and the subsurface water system.

      Flowchart representation of the hydrologic system as proposed by Chow et al. (1988)

      Figure 2: Flowchart representation of the hydrologic system (Chow et al., 1988) showing fluxes and control volumes across atmospheric, surface, and groundwater domains.

      Defining the Fundamental Unit: Watersheds & Catchments

      In hydrology, the terms watershed, catchment, and river basin are used synonymously to describe a topographically defined land area from which all surface water runoff drains through a common, discrete outlet point known as the pour point. The geographical boundary separating two adjacent catchments is known as the drainage divide or ridgeline.

      Schematic diagram defining drainage basin boundary, tributary stream networks, and pour point outlet

      Figure 3: Conceptual schematic of a drainage basin, showing the perimeter drainage divide, converging tributary flow paths, and the downstream pour point.

      Historically, delineating drainage basins required manual tracing of topographic contours from paper topographic maps. In this tutorial, we implement a modern, automated Python workflow using PySheds—a high-performance, open-source library specifically optimized for rapid digital elevation model (DEM) conditioning, flow routing, and catchment delineation.

      Our region of interest is the critical Upper Ewaso Nyiro River Basin (UENRB) in Kenya, draining from the slopes of Mount Kenya and the Aberdare Range down to the arid lowlands of Archer's Post. In the next tutorial, this delineated catchment forms the topological skeleton for streamflow imputation using Graph Neural Networks (GNNs).

      Interactive Jupyter Notebook Available

      Get the complete Watershed_Delineation.ipynb notebook and reproduce all hydrologic workflows interactively.

      Download (.ipynb)

      Step 1: Data Acquisition & Geospatial Exploration

      To perform watershed delineation, our first requirement is a high-resolution, georeferenced Digital Elevation Model (DEM). We utilize the NASA Shuttle Radar Topography Mission (SRTM) 30m Global DEM accessed programmatically via the OpenTopography REST API.

      We define an approximate geographic bounding box enclosing the entire Upper Ewaso Nyiro River Basin in central Kenya:

      • Western Longitude: $36.2^\circ\,\text{E}$ (Great Rift Valley escarpment)
      • Eastern Longitude: $37.9^\circ\,\text{E}$ (downstream plains past Archer's Post)
      • Southern Latitude: $-0.4^\circ\,\text{S}$ (Aberdare Range & Mount Kenya southern flanks)
      • Northern Latitude: $1.1^\circ\,\text{N}$ (semi-arid Samburu savannah)
      Python
      import os
      import requests
      import rioxarray as rxr
      from pysheds.grid import Grid
      
      # Set bounding box for the Upper Ewaso Nyiro River Basin (UENRB)
      bounds = {
          "west": 36.2,
          "east": 37.9,
          "south": -0.4,
          "north": 1.1,
      }
      
      output_path = "uenrb_dem.tif"
      
      # API Endpoint for global SRTM GL1 30m DEM
      url = "https://portal.opentopography.org/API/globaldem"
      params = {
          "demtype": "SRTMGL1",
          "south": bounds["south"],
          "north": bounds["north"],
          "west": bounds["west"],
          "east": bounds["east"],
          "outputFormat": "GTiff",
          "API_Key": os.getenv("OPENTOPO_API", "YOUR_API_KEY_HERE")
      }
      
      # Download raster directly if not already present
      if not os.path.exists(output_path):
          print("Downloading SRTM 30m DEM from OpenTopography...")
          response = requests.get(url, params=params, stream=True)
          if response.status_code == 200:
              with open(output_path, "wb") as f:
                  for chunk in response.iter_content(chunk_size=1024 * 1024):
                      f.write(chunk)
              print("Download complete.")
          else:
              raise RuntimeError(f"API request failed with status: {response.status_code}")
      
      # Read downloaded GeoTIFF using rioxarray
      uenrb_dem = rxr.open_rasterio(output_path).drop_vars("band")[0]
      print(f"DEM Dimensions: {uenrb_dem.shape} (rows, cols)")
      print(f"Spatial Resolution: {abs(uenrb_dem.rio.resolution()[0]):.6f} degrees (~30m)")
      print(f"Coordinate Reference System: {uenrb_dem.rio.crs}")
      Terminal Output — Raster Properties
      [INFO] Raster loaded successfully into memory Dimensions: (5400, 6120) [Height x Width = 33,048,000 pixels] Spatial Resolution: 0.000278 degrees (~30.87 meters at Equator) CRS: EPSG:4326 (WGS 84 geographic latitude/longitude) Elevation Range: 523.0 meters (plains) to 5,199.0 meters (Batian Peak, Mt. Kenya) NoData Value: -32768

      Next, we extract the underlying NumPy array, affine spatial transformation matrix, and coordinate reference system metadata, then pass them into PySheds:

      Python
      from pysheds.view import Raster, ViewFinder
      
      data = uenrb_dem.data
      affine = uenrb_dem.rio.transform()
      crs = uenrb_dem.rio.crs
      nodata = data.dtype.type(-9999)
      
      # Construct PySheds ViewFinder and initialize high-performance Grid
      viewfinder = ViewFinder(affine=affine, shape=data.shape, crs=crs, nodata=nodata)
      dem = Raster(data, viewfinder=viewfinder)
      grid = Grid.from_raster(dem)
      
      print(f"Grid Extent: {grid.extent}")
      print(f"Total Grid Cells: {grid.size:,}")

      Step 2: DEM Conditioning — Resolving Pits, Depressions, and Flats

      A fundamental requirement for surface water routing is that water falling anywhere on the terrain must be capable of moving progressively downhill until it exits the grid boundary. Raw digital elevation models—regardless of whether they originate from radar interferometry (SRTM), LiDAR, or photogrammetry—invariably suffer from measurement noise, vegetation canopy scattering, and interpolation errors. These artifacts manifest as artificial sinks that break drainage connectivity.

      The Three Classes of DEM Sinks
      • Pits: Single isolated grid cells whose elevation is strictly lower than all 8 surrounding neighbors ($z_i < \min_{k \in N(i)} z_k$). Water entering a pit has no outlet and becomes indefinitely trapped.
      • Depressions: Contiguous multi-cell basins enclosed by a perimeter of higher elevation pixels. A depression cannot drain until water ponds to the elevation of the lowest spillover pour point on its rim.
      • Flats: Planar areas where adjacent cells have identical elevation values ($\nabla z = 0$). In perfectly flat areas, the local hydraulic gradient is zero, leaving standard single-flow direction algorithms unable to determine a deterministic routing path.

      1. Detecting and Filling Pits

      We identify isolated pits using grid.detect_pits() and apply grid.fill_pits() to raise pit cell elevations until they equal the lowest adjacent neighbor:

      Python
      import matplotlib.pyplot as plt
      
      # Detect pits in the raw DEM
      pits = grid.detect_pits(dem)
      npits = np.count_nonzero(pits)
      print(f"Detected Pits in Raw DEM: {npits:,}")
      
      if npits > 0:
          fig, ax = plt.subplots(figsize=(10, 8))
          im = ax.imshow(dem, cmap="terrain", extent=grid.extent)
          plt.colorbar(im, ax=ax, label="Elevation (m)")
      
          # Overlay pit coordinates
          y_pits, x_pits = np.where(pits)
          ax.scatter(grid.coords[1][x_pits], grid.coords[0][y_pits], 
                     s=15, facecolors='none', edgecolors='blue', alpha=0.7, label='Pits')
          ax.set_title("Raw DEM with Detected Pits")
          ax.set_xlabel("Longitude (°E)")
          ax.set_ylabel("Latitude (°N)")
          ax.legend(loc="upper right")
          plt.show()
      
      # Fill pits and assert complete elimination
      pit_filled_dem = grid.fill_pits(dem)
      pits_remaining = grid.detect_pits(pit_filled_dem)
      assert not pits_remaining.any(), "Error: Pits still remain after pit filling!"
      print("All individual pits successfully eliminated.")
      Raw SRTM 30m Digital Elevation Model showing detected pits highlighted across the basin

      Figure 4: Raw SRTM 30m Digital Elevation Model of central Kenya. Blue markers indicate detected elevation pits that would otherwise interrupt hydrological routing.

      2. Detecting and Filling Depressions

      Beyond single-pixel pits, broader multi-cell topographic depressions must be resolved. PySheds implements the efficient priority-queue flooding algorithm:

      Python
      # Detect multi-cell depressions
      depressions = grid.detect_depressions(pit_filled_dem)
      ndepressions = np.count_nonzero(depressions)
      print(f"Detected Depressions: {ndepressions:,} cells")
      
      # Fill depressions by simulating hydraulic ponding up to the spillover elevation
      flooded_dem = grid.fill_depressions(pit_filled_dem, depressions=depressions)
      
      # Verify no remaining depressions exist
      depressions_check = grid.detect_depressions(flooded_dem)
      assert not depressions_check.any(), "Error: Depressions remain after flooding!"
      print("All depressions filled to spillover rim elevation.")

      3. Detecting and Resolving Flats

      Once depressions are flooded to their rims, the resulting water surfaces form zero-slope plains. To route flow across these flat surfaces toward the true outlet, we invoke grid.resolve_flats(), which imposes an infinitesimal gradient directed toward lower downstream spillover cells:

      Python
      # Detect flat areas
      flats = grid.detect_flats(flooded_dem)
      nflats = np.count_nonzero(flats)
      print(f"Detected Flat Cells: {nflats:,}")
      
      # Visualize flat areas requiring artificial slope inflation
      fig, ax = plt.subplots(figsize=(10, 8))
      masked_flats = np.ma.masked_where(~flats, flats)
      ax.set_facecolor("#e6e6e6")
      ax.imshow(dem, cmap="terrain", extent=grid.extent, alpha=0.6)
      ax.imshow(masked_flats, cmap="autumn", extent=grid.extent, zorder=2)
      ax.set_title("Flat Areas Identified in Flooded DEM (Zero Slope)")
      ax.set_xlabel("Longitude (°E)")
      ax.set_ylabel("Latitude (°N)")
      plt.show()
      
      # Resolve flats by applying a slight gradient inflation
      inflated_dem = grid.resolve_flats(flooded_dem)
      print("Conditioning complete: DEM is now fully hydrologically sound and drainable.")
      Flat regions identified across the flooded DEM requiring slope inflation

      Figure 5: Flat regions identified across the flooded DEM. Slope inflation resolves directional ambiguity across lakes, floodplains, and ponded basins.

      Step 3: Flow Routing & Flow Accumulation

      With a hydrologically conditioned terrain surface ($z_{\text{inflated}}$), we now model surface drainage patterns. This step consists of two sequential operations: determining flow direction for every cell, and computing flow accumulation across the entire river network.

      The D8 Single-Flow Direction Algorithm

      The D8 (Deterministic 8-direction) model (O'Callaghan & Mark, 1984; Jenson & Domingue, 1988) assumes that all water entering a given cell exits entirely into exactly one of its eight orthogonal or diagonal nearest neighbors along the steepest downward slope gradient:

      $$S_{ik} = \frac{z_i - z_k}{d_{ik}}$$

      where $z_i$ and $z_k$ are the elevations of the focal cell $i$ and neighbor cell $k$, and $d_{ik}$ is the planimetric distance between their cell centers ($d_{ik} = \Delta x$ for cardinal neighbors, $d_{ik} = \sqrt{2}\Delta x$ for diagonal neighbors). The chosen flow direction is:

      $$k^* = \arg\max_{k \in N(i)} S_{ik}$$

      PySheds encodes these directions using standard powers-of-two bitmasks: East ($1$), Northeast ($2$), North ($4$), Northwest ($8$), West ($16$), Southwest ($32$), South ($64$), and Southeast ($128$).

      Flow Accumulation

      Once the flow direction matrix $\mathbf{F}$ is established, each pixel's flow accumulation $A_i$ represents the total number of upstream cells whose drainage path traverses cell $i$:

      $$A_i = 1 + \sum_{j \in U(i)} A_j$$

      where $U(i)$ denotes the set of immediate upstream cells whose D8 routing points directly into cell $i$. High accumulation values delineate the primary river channels and tributaries, while values near $1$ represent headwater ridges and drainage divides.

      Python
      import matplotlib.colors as colors
      
      # 1. Compute D8 flow direction based on fully conditioned DEM
      fdir = grid.flowdir(inflated_dem)
      
      # 2. Compute flow accumulation based on flow direction matrix
      acc = grid.accumulation(fdir)
      
      # 3. Visualize flow accumulation using a logarithmic color scale
      fig, ax = plt.subplots(figsize=(10, 8))
      fig.patch.set_alpha(0)
      plt.grid(True, zorder=0, alpha=0.2)
      
      im = ax.imshow(
          acc,
          extent=grid.extent,
          zorder=2,
          cmap="cubehelix",
          norm=colors.LogNorm(vmin=1, vmax=acc.max())
      )
      cbar = plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
      cbar.set_label("Upstream Accumulated Cells (log scale)")
      ax.set_title("Flow Accumulation Map for Upper Ewaso Nyiro Basin")
      ax.set_xlabel("Longitude (°E)")
      ax.set_ylabel("Latitude (°N)")
      plt.show()
      
      print(f"Maximum Accumulated Drainage Area: {acc.max():,} cells (~{acc.max() * 30.87**2 / 1e6:.1f} km²)")
      Logarithmic flow accumulation grid clearly delineating the braided Upper Ewaso Nyiro channel system

      Figure 6: Flow accumulation matrix plotted on a logarithmic scale. White and pale filaments represent high-accumulation stream corridors converging toward the main river stem.

      Step 4: Pour Point Snapping & Delineating the UENRB Catchment

      Now that the entire regional flow routing topology has been mapped, we can extract the precise catchment draining to any specific point along the river. In catchment hydrology, this outlet location is called the pour point.

      Why Pour Point Snapping is Essential

      Field GPS readings for hydrometric stream gauges are recorded with standard consumer measurement uncertainty ($\pm 5$ to $15\,\text{m}$). On a $30\,\text{m}$ grid, an outlet point that lies even a single cell away from the true river thalweg will fall onto a dry valley bank where accumulation is small ($A_i \approx 5$). Delineating directly from unsnapped coordinates would extract a trivial micro-catchment of a few hillside hectares instead of the entire multi-thousand square-kilometer river basin!

      We specify the geographic coordinates of the historical Archer's Post Hydrometric Gauging Station: $$\text{Outlet} = (37.68^\circ\,\text{E},\, 0.64^\circ\,\text{N})$$ Using grid.snap_to_mask(), PySheds automatically searches the local neighborhood and snaps the outlet point to the nearest cell with high flow accumulation ($A_i > 1{,}000$ cells):

      Python
      # Define target hydrometric gauging station coordinates (Archer's Post)
      outlet = (37.68, 0.64)
      
      # Snap outlet point to the nearest pixel possessing substantial flow accumulation (> 1000 cells)
      x_snap, y_snap = grid.snap_to_mask(acc > 1000, outlet)
      print(f"Raw Target Outlet:   Lon = {outlet[0]:.4f}, Lat = {outlet[1]:.4f}")
      print(f"Snapped Stream Thalweg: Lon = {x_snap:.4f}, Lat = {y_snap:.4f}")
      
      # Delineate the upstream contributing watershed boundary
      catch = grid.catchment(x=x_snap, y=y_snap, fdir=fdir, xytype="coordinate")
      
      # Clip the grid coordinate view to the delineated catchment bounding box
      grid.clip_to(catch)
      catch_view = grid.view(catch, nodata=grid.nodata)
      fdir_view = grid.view(fdir, nodata=grid.nodata)
      acc_view = grid.view(acc, nodata=grid.nodata)
      dem_view = grid.view(dem, nodata=grid.nodata)
      
      # Plot comprehensive 4-panel multi-layer visualization
      fig, axes = plt.subplots(2, 2, figsize=(11, 9))
      fig.patch.set_alpha(0)
      
      # 1. Catchment Boundary Extent
      axes[0, 0].imshow(catch_view, extent=grid.extent, zorder=1, cmap="Greys_r")
      axes[0, 0].set_title("1. Delineated Catchment Extent")
      axes[0, 0].set_ylabel("Latitude (°N)")
      
      # 2. D8 Flow Directions
      axes[0, 1].imshow(fdir_view, extent=grid.extent, zorder=1, cmap="viridis")
      axes[0, 1].set_title("2. Flow Direction (D8 Code)")
      
      # 3. Flow Accumulation
      im_acc = axes[1, 0].imshow(acc_view, extent=grid.extent, zorder=1, cmap="cubehelix",
                                 norm=colors.LogNorm(1, 1e5))
      axes[1, 0].set_title("3. Flow Accumulation")
      axes[1, 0].set_xlabel("Longitude (°E)")
      axes[1, 0].set_ylabel("Latitude (°N)")
      
      # 4. Conditioned Topography DEM
      im_dem = axes[1, 1].imshow(dem_view, extent=grid.extent, zorder=1, cmap="terrain")
      axes[1, 1].set_title("4. Elevation DEM (m)")
      axes[1, 1].set_xlabel("Longitude (°E)")
      
      # Overlay snapped outlet point on all panels
      for ax in axes.flat:
          ax.scatter([x_snap], [y_snap], c="red", s=40, zorder=5, edgecolors="white", label="Outlet")
      
      plt.tight_layout()
      plt.show()
      
      catchment_area_km2 = np.count_nonzero(catch_view) * (30.87 * 30.87) / 1e6
      print(f"Total Delineated Catchment Area: {catchment_area_km2:,.1f} km²")
      Four-panel visualization showing delineated catchment extent, D8 flow directions, flow accumulation, and elevation

      Figure 7: Four-panel visualization of the delineated Upper Ewaso Nyiro River Basin: (1) Binary catchment footprint; (2) D8 direction codes; (3) Flow accumulation river channels; (4) Topographic elevation raster. Red star marks the Archer's Post pour point.

      Step 5: Catchment Morphometry — Distance to Outlet

      A critical diagnostic metric in rainfall-runoff modeling and catchment morphometry is the hydraulic distance to the outlet. Rather than measuring straight-line Euclidean distance, we trace the actual downhill stream path that a parcel of rainwater must travel from any cell through the drainage network until it reaches the gauging station.

      This distance grid directly dictates the basin's Time of Concentration ($T_c$)—the time required for runoff from the most hydrologically remote headwater in the basin to reach the pour point:

      $$T_c = \sum_{k \in \mathcal{P}_i} \frac{\Delta L_k}{v_k}$$

      where $\mathcal{P}_i$ is the ordered downstream flow path from cell $i$ to the outlet, $\Delta L_k$ is the incremental cell distance, and $v_k$ is the local flow velocity governed by Manning's equation.

      Python
      # Compute distance from each cell to the pour point along the D8 drainage path
      dist = grid.distance_to_outlet(
          x=x_snap,
          y=y_snap,
          fdir=fdir,
          xytype="coordinate"
      )
      
      # Convert cell-count distance to approximate planimetric kilometers (1 cell ~ 0.03087 km)
      dist_km = dist * 0.03087
      
      # Visualize the travel distance across the delineated catchment
      fig, ax = plt.subplots(figsize=(9, 7))
      fig.patch.set_alpha(0)
      
      im = ax.imshow(dist_km, extent=grid.extent, zorder=2, cmap="cividis_r")
      cbar = plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
      cbar.set_label("Hydraulic Distance to Outlet (km)")
      
      ax.scatter([x_snap], [y_snap], c="red", s=60, marker="o", edgecolors="white", zorder=5, label="Archer's Post")
      ax.set_title("Hydraulic Distance to Basin Outlet (Flow Path Length)")
      ax.set_xlabel("Longitude (°E)")
      ax.set_ylabel("Latitude (°N)")
      ax.legend(loc="lower left")
      plt.show()
      
      print(f"Maximum Flow Path Length in UENRB: {np.nanmax(dist_km):.1f} km")
      Hydraulic distance from every point in the Upper Ewaso Nyiro catchment to Archer's Post outlet

      Figure 8: Flow path travel distance across the Upper Ewaso Nyiro basin. Yellow zones indicate immediate proximity to the Archer's Post outlet; dark blue zones represent headwater reaches over $200\,\text{km}$ upstream on the slopes of the Aberdares.

      Step 6: Stream Network Extraction

      To extract vector stream channels from the continuous flow accumulation grid, we specify a channel initiation threshold $\tau_{\text{threshold}}$. Any pixel whose upstream contributing area exceeds $\tau_{\text{threshold}}$ is classified as a permanent or ephemeral river reach.

      Setting $\tau = 5{,}000$ cells corresponds to an upstream contributing area of: $$A_{\text{thresh}} = 5{,}000 \times (30.87\,\text{m})^2 \approx 4.76\,\text{km}^2$$ Using grid.extract_river_network(), PySheds automatically parses the flow direction tree into connected polyline geometries in GeoJSON format:

      Python
      # Extract vector stream network with drainage area threshold > 5000 cells (~4.76 km²)
      branches = grid.extract_river_network(fdir, acc > 5000)
      
      fig, ax = plt.subplots(figsize=(9, 8))
      fig.patch.set_alpha(0)
      
      # Plot catchment elevation as a muted topographic backdrop
      ax.imshow(dem_view, extent=grid.extent, cmap="Greys", alpha=0.3, zorder=1)
      
      # Plot each vector stream branch
      for branch in branches["features"]:
          coords = np.asarray(branch["geometry"]["coordinates"])
          ax.plot(coords[:, 0], coords[:, 1], color="#0284c7", linewidth=1.2, zorder=3)
      
      # Highlight outlet point
      ax.scatter([x_snap], [y_snap], c="red", s=70, marker="o", edgecolors="black", zorder=5, label="Archer's Post Pour Point")
      
      ax.set_title("Extracted Stream Network for Upper Ewaso Nyiro River Basin")
      ax.set_xlabel("Longitude (°E)")
      ax.set_ylabel("Latitude (°N)")
      ax.legend(loc="upper right")
      plt.show()
      
      print(f"Total Stream Segments Extracted: {len(branches['features']):,}")
      Vector channel network extracted from flow accumulation overlaid across the catchment topography

      Figure 9: Vector stream network extracted using an accumulation threshold of $5{,}000$ cells ($4.76\,\text{km}^2$), illustrating the convergence of tributaries from Mount Kenya and the Aberdares into the main Ewaso Nyiro stem.

      Step 7: Interfacing with Xarray & Hypsometric Analysis

      Modern spatiotemporal and environmental data science heavily relies on Xarray for multidimensional array manipulation, NetCDF serialization, and spatial aggregation. We convert our clipped PySheds catchment elevation raster into an xarray.DataArray with explicit geographical coordinates (latitude and longitude arrays):

      Python
      import xarray as xr
      
      # Extract clipped catchment array and coordinates
      catchment = dem_view
      data = catchment.data
      
      # Retrieve sorted latitude and longitude axes
      lat = np.unique(catchment.coords[:, 0])
      lat = np.flip(lat)  # Reverse latitude order for top-to-bottom spatial indexing
      lon = np.unique(catchment.coords[:, 1])
      
      # Construct georeferenced xarray DataArray
      catch_xr = xr.DataArray(
          catchment.base,
          coords={"y": lat, "x": lon},
          dims=["y", "x"],
          attrs={
              "description": "Upper Ewaso Nyiro River Basin Elevation",
              "units": "meters above sea level",
              "crs": "EPSG:4326"
          }
      )
      
      # Plot using xarray's native visualization engine
      fig, ax = plt.subplots(1, 1, figsize=(9, 7))
      catch_xr.plot(ax=ax, cmap="plasma", cbar_kwargs={"label": "Elevation (m a.s.l.)"})
      ax.set_title("UENRB Watershed Elevation Array in Xarray")
      ax.set_xlabel("Longitude (°E)")
      ax.set_ylabel("Latitude (°N)")
      plt.show()
      Clipped Upper Ewaso Nyiro River Basin elevation raster visualized in xarray using plasma colormap

      Figure 10: Georeferenced Xarray DataArray displaying elevation gradients across the Upper Ewaso Nyiro River Basin, ranging from $800\,\text{m}$ in the Samburu lowlands to over $5{,}100\,\text{m}$ at the crest of Mount Kenya.

      Hypsometric Integral & Landscape Maturity

      With the elevation values organized in Xarray, we can calculate the Hypsometric Integral ($HI$)—a dimensionless morphological index that characterizes the vertical distribution of landmass within a drainage basin (Strahler, 1952):

      $$HI = \frac{\bar{z} - z_{\min}}{z_{\max} - z_{\min}}$$

      where $\bar{z}$ is the mean basin elevation, and $z_{\min}$ and $z_{\max}$ represent minimum and maximum altitudes. High values ($HI > 0.6$) indicate young, un-eroded, tectonically active plateaus; intermediate values ($0.35 \le HI \le 0.6$) characterize mature fluvial equilibrium; and low values ($HI < 0.35$) designate heavily eroded old-age terrain.

      Python
      # Extract valid catchment elevation pixels (excluding nodata)
      valid_elevs = catch_xr.values[~np.isnan(catch_xr.values) & (catch_xr.values > 0)]
      
      z_min = float(np.min(valid_elevs))
      z_max = float(np.max(valid_elevs))
      z_mean = float(np.mean(valid_elevs))
      z_median = float(np.median(valid_elevs))
      
      # Calculate Hypsometric Integral
      HI = (z_mean - z_min) / (z_max - z_min)
      
      print(f"Minimum Elevation:  {z_min:.1f} m")
      print(f"Maximum Elevation:  {z_max:.1f} m")
      print(f"Mean Elevation:     {z_mean:.1f} m")
      print(f"Median Elevation:   {z_median:.1f} m")
      print(f"Hypsometric Integral (HI): {HI:.3f} (Mature Fluvial Landscape)")

      Watershed Delineation Summary & Key Takeaways

      The table below synthesizes the complete sequence of computational transformations required to translate raw topographic data into an analytical river basin model:

      Workflow Stage Underlying Algorithm PySheds Operation Primary Output Asset
      1. Ingestion OpenTopography REST API / GeoTIFF rxr.open_rasterio(), Grid.from_raster() Raw Elevation Array & ViewFinder
      2. Pit Conditioning Jenson & Domingue (1988) Neighbor Match grid.detect_pits(), grid.fill_pits() Pit-Free Elevation Surface
      3. Depression Filling Planchon & Darboux Priority-Queue Flood grid.detect_depressions(), grid.fill_depressions() Flooded Depression-Free DEM
      4. Flat Resolution Infinitesimal Gradient Inflation grid.detect_flats(), grid.resolve_flats() Fully Drainable Conditioned DEM
      5. Direction Routing Deterministic 8-Direction (D8) grid.flowdir(inflated_dem) D8 Flow Direction Matrix (1..128)
      6. Accumulation Recursive Graph Traversal grid.accumulation(fdir) Contributing Area Grid (cells)
      7. Pour Snapping Nearest High-Accumulation Search grid.snap_to_mask(acc > 1000, outlet) Snapped Channel Thalweg Point
      8. Catchment Delineation Upstream Tree Pruning grid.catchment(x_snap, y_snap, fdir) Binary Catchment Footprint Mask
      9. Channel Extraction Drainage Threshold Contouring grid.extract_river_network(fdir, acc > tau) GeoJSON Topological Polylines
      10. Morphometry Dijkstra Downhill Path Accumulation grid.distance_to_outlet() Hydraulic Distance Grid (km)
      Watershed Delineation Summary illustrating the entire algorithmic pipeline

      Figure 11: End-to-end procedural architecture for automated catchment delineation, stream extraction, and hydrologic modeling from raw satellite elevation rasters.

      Frequently Asked Questions

      Why must we snap the pour point using an accumulation threshold?

      Standard GPS readings reflect gauge station offices, bridge abutments, or riverbank positions, which do not coincide with the lowest pixel in a 30-meter DEM. If an outlet point is even one pixel away from the river thalweg, PySheds would trace only that dry hillside cell, resulting in an erroneous micro-catchment rather than the full upstream basin. Snapping dynamically migrates the point to the highest adjacent accumulation path.

      When should I use D8 versus D-Infinity or Multiple Flow Direction (MFD)?

      The D8 algorithm routes all flow from a pixel to a single neighbor. It is the gold standard for defining discrete river channel networks and catchment boundaries because it prevents artificial stream splitting. In contrast, D-Infinity (Tarboton, 1997) or MFD distribute flow proportionally across multiple downslope neighbors, making them superior for modeling diffuse overland flow, soil moisture distribution, and hillslope sheetwash erosion.

      How does this tutorial connect to the GNN Hydrology tutorial?

      In the GNN for Hydrological Spatial Imputation tutorial, river sub-basins are structured into directed acyclic graph (DAG) adjacency matrices. The catchment boundary, stream network, and flow directions extracted here using PySheds provide the exact topological wiring and hydraulic distances required by Graph Convolutional Networks (GCNs) to route streamflow between gauging stations.

      What resolution DEM is ideal for catchment delineation?

      For regional river basins ($> 1{,}000\,\text{km}^2$), 30-meter SRTM or Copernicus DEMs provide the optimal balance between spatial accuracy and computational speed. For small urban watersheds or hillside culverts ($< 10\,\text{km}^2$), high-resolution LiDAR or 12.5-meter ALOS PALSAR elevation data is recommended to resolve artificial embankments, road ditches, and micro-topography.

      References & Further Reading

      • Chow, V. T., Maidment, D. R., & Mays, L. W. (1988). Applied Hydrology. McGraw-Hill Book Company, New York.
      • Bartos, M. (2020). PySheds: Simple, fast, pythonic digital elevation model processing. GitHub repository: https://github.com/mdbartos/pysheds.
      • Jenson, S. K., & Domingue, J. O. (1988). Extracting Topographic Features from Digital Elevation Data for Geographic Information System Analysis. Photogrammetric Engineering and Remote Sensing, 54(11), 1593–1600.
      • O'Callaghan, J. F., & Mark, D. M. (1984). The extraction of drainage networks from digital elevation data. Computer Vision, Graphics, and Image Processing, 28(3), 323–344.
      • Tarboton, D. G. (1997). A new method for the determination of flow directions and upslope areas in grid digital elevation models. Water Resources Research, 33(2), 309–319.
      • Strahler, A. N. (1952). Hypsometric (area-altitude) analysis of erosional topography. Geological Society of America Bulletin, 63(11), 1117–1142.