Prepare flow directions and related data from a DEM#
With HydroMT-Wflow, a user can choose to build a model in a geographic or projected coordinate system from an input Digital Elevation Model (DEM) and Flow Direction (flwdir) dataset.
While DEM data are often available, this is not always the case for the flow directions (flwdir). We made the choice to build a Wflow model directly from user provided DEM and flwdir datasets, rather than reprojecting a DEM and/or deriving flwdir on the fly. This is because deriving flow directions is often an iterative process, to be sure the flow directions match the terrain and river network. Note that for the best results the flwdir data should be derived from a high-res DEM (<100 m spatial resolution). The HydroMT-Wflow model builder will automatically resample the flwdir data to the model resolution.
Because of this, we prefer to provide this notebook as a possible pre-processing step before building a Wflow model with HydroMt-Wflow. Here, we use the different flow directions methods from HydroMT and PyFlwDir
Load dependencies#
[1]:
import os
import xarray as xr
import numpy as np
import geopandas as gpd
# pyflwdir
import pyflwdir
# hydromt
import hydromt
from hydromt.gis import flw
# plot
import matplotlib.pyplot as plt
from matplotlib import cm, colors
Deriving flow directions from Elevation data#
In this example we will use the gebco data in the pre-defined artifact_data catalog of HydroMT, and use this DEM data to derive several related hydrographic and topographic variables.
[2]:
# read data
data_catalog = hydromt.DataCatalog("artifact_data")
ds_dem = data_catalog.get_rasterdataset("gebco")
[3]:
# Define a nice colourmap
c_dem = plt.cm.terrain(np.linspace(0.25, 1, 256))
cmap = colors.LinearSegmentedColormap.from_list("dem", c_dem)
fig, ax = plt.subplots(figsize=(6, 6))
ds_dem.raster.mask_nodata().plot(
ax=ax,
cmap=cmap, vmin=0, vmax=2500,
cbar_kwargs={'label': 'Elevation [m]', 'shrink': 0.8})
ax.set_aspect('equal')
ax.set_title("DEM from GEBCO")
ax.set_xlabel("Longitude [°]")
ax.set_ylabel("Latitude [°]");
Derive the flow direction#
The flow direction can be derived from the DEM. This is done using the PyFlwDir package, also developed by Deltares. For ease of use, HydroMT provides some wrappers around PyFlwDir, so we can just call HydroMT. However, pyflwdir has much more functionality.
Let’s derive the D8 flow direction based on the elevation, using the hydromt.gis.flw.d8_from_dem method of HydroMT.
This method derives D8 flow directions grid from an elevation grid and allows several options to the users:
river burning: provide a river vector layer
gdf_rivwithuparea(km2) orrivdphcolumn to guide the derivation of flow directions. This is important to get the correct flow directions, especially in flat areas.outlets: outlets can be defined at
edges of the grid (default) or force all flow to go to the minimum elevation pointmin. The latter only makes sense if your DEM only is masked to the catchment. Additionally, the user can also force specific pits locations viaidxs_pit.depression filling: local depressions are filled based on their lowest pour point level if the pour point depth is smaller than the maximum pour point depth
max_depth, otherwise the lowest elevation in the depression becomes a pit. By defaultmax_depthis set to -1 m filling all local depressions.
[4]:
# Derive flow directions with outlets at the edges -> this is the default
flow_direction = flw.d8_from_dem(
ds_dem,
max_depth=-1, # max depression pour point depth; -1 means no local pits
outlets="edge", # option: "edge" (default), "min", "idxs_pit"
idxs_pit=None,
riv_burn_method="uparea", # options: "fixed" (default), "rivdph", "uparea"
# riv_depth=5, # fixed river depth in meters, only used if riv_burn_method="fixed"
# **kwargs to be passed to pyflwdir.dem.fill_depressions)
)
We now have flow direction data. This flow direction data is derived from the DEM, but also ensures that all cells eventually flow to the edges. Let’s plot the flow direction data, although it will probably look a bit weird.
[5]:
fig, ax = plt.subplots(figsize=(6, 6))
flow_direction.plot(
ax=ax,
levels=[0, 1, 2, 4, 8, 16, 32, 64, 128, 256],
cbar_kwargs={'label': 'Flow direction', 'shrink': 0.8}
)
ax.set_aspect('equal')
ax.set_title("D8 flow direction map")
ax.set_xlabel("Longitude [°]")
ax.set_ylabel("Latitude [°]");
Based on the flow direction, we can estimate where the rivers will be. For example, let’s define rivers as any cell with a Strahler order ≥ 3
[6]:
# Convert the xr.DataArray to a flow direction raster object, which is used by the PyFlwDir package.
flwdir = flw.flwdir_from_da(flow_direction, ftype="d8")
# And convert the cells with a Strahler order ≥ 3 to a vector for plotting,
gdf_riv_Strahler_3 = gpd.GeoDataFrame.from_features(flwdir.streams(min_sto=3))
[7]:
# plot
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot()
# plot elevation
ds_dem.plot(
ax=ax,
zorder=1,
cbar_kwargs={'label': 'Elevation [m]', 'shrink': 0.8},
cmap=cmap,
vmin=0,
vmax=2500,
)
# plot river network the derived new flow directions
gdf_riv_Strahler_3.plot(ax=ax,
color="blue",
linewidth=gdf_riv_Strahler_3["strord"] / 4)
ax.set_title("Rivers, defined by Strahler order ≥ 3")
ax.set_xlabel("Longitude [°]")
ax.set_ylabel("Latitude [°]");
This looks generally good, but there are some weird features as well, especially in flatter areas. Perhaps we should try a different definition for our rivers? Instead of the Strahler order, let’s use an upstream area of at least 10 km2 as a threshold.
[8]:
gdf_riv_uparea_10km2 = gpd.GeoDataFrame.from_features(flwdir.streams(mask=flwdir.upstream_area("km2") > 10))
[9]:
# plot
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot()
# plot elevation
ds_dem.plot(
ax=ax,
zorder=1,
cbar_kwargs={'label': 'Elevation [m]', 'shrink': 0.8},
cmap=cmap,
vmin=0,
vmax=2500,
)
# plot Strahler order 3 rivers
gdf_riv_Strahler_3.plot(
ax=ax,
color="red",
linewidth=gdf_riv_Strahler_3["strord"] / 4,
label="Strahler order 3")
# plot rivers with upstream area > 10 km²
gdf_riv_uparea_10km2.plot(
ax=ax,
color="blue",
label="Upstream area > 10 km²")
ax.set_title("Rivers, defined by upstream area > 10 km² or Strahler order 3")
ax.legend(loc='lower left')
ax.set_xlabel("Longitude [°]")
ax.set_ylabel("Latitude [°]");
The resulting rivers are completely different! Many smaller streams have disappeared, and the number of rivers is smaller.
There is unfortunately no “one-size-fits-all” solution to this. A stricter definition of a river in HydroMT (e.g. a large upstream area, or a high Strahler order) will result in fewer rivers in your Wflow model, and generally also in fewer weird “artifacts”. However, it might miss important smaller streams, especially in upstream parts of your basin.
A more lenient definition of a river in HydroMT (e.g. a small upstream area or a low Strahler order) will result in many more rivers in your model, but also has a higher chance of weird artifacts in flat areas, lakes, and reservoirs, as we just saw.
Depending on the purpose and interest of your model, you can use a more lenient or a more strict definition of rivers in HydroMT.
You could solve this another way. HydroMT allows the option to define rivers based on a provided vector file (e.g. a Shapefile). If you wanted to, you could for example make such a shapefile based on satellite data, selecting the rivers yourself.
Regardless of the approach used, deriving flow direction, upstream area, etc., is an iterative, manual, and labour-intensive process. It requires careful attention, as the derived variables are also used to define the rivers in your Wflow model. It thus has a huge influence on your eventual modelling results, and there is no standard or “best” way to do this. The methods described here are intended first and foremost on how you could do it, not how you should do it.
Deriving other data related to the flow direction#
Besides the flow direction, we can derive related data such as the upstream area, the slope, and the stream order. These are handy to have!
We can also modify our original elevation data, so that every downstream cell is at least lower or at the same elevation as each cell. We call this hydrological corrected elevation, and it is based on Yamazaki et al. (2012)
Note that this elevation correction already happened when we computed the flow directions, but that didn’t modify our original elevation data.
[10]:
# Start a xr.Dataset with our flow direction data
ds_hydro = flow_direction.to_dataset(name="flwdir")
ds_hydro = ds_hydro.raster.gdal_compliant() # update spatial metadata
dims = ds_hydro.raster.dims
[11]:
# add hydrological corrected elevation based on Yamazaki et al. (2012)
elevtn = flwdir.dem_adjust(elevtn=ds_dem.values)
attrs = dict(_FillValue=-9999, long_name="corrected elevation", units="m")
ds_hydro["elevtn"] = xr.Variable(dims, elevtn, attrs=attrs)
[12]:
# uparea (Note that this requires all upstream areas to be included.)
uparea = flwdir.upstream_area(unit="km2")
attrs = dict(_FillValue=-9999, long_name="upstream area", units="km2")
ds_hydro["uparea"] = xr.Variable(dims, uparea, attrs=attrs)
[13]:
# stream order (Note that this requires all upstream areas to be included.)
strord = flwdir.stream_order()
attrs = dict(_FillValue=np.uint8(225), long_name="stream order", units="-")
ds_hydro["strord"] = xr.Variable(dims, strord, attrs=attrs)
[14]:
# slope
slope = pyflwdir.dem.slope(
elevtn=ds_hydro["elevtn"].values,
nodata=ds_hydro["elevtn"].raster.nodata,
latlon=ds_hydro.raster.crs.is_geographic, # True if geographic crs, False if projected crs
transform=ds_hydro["elevtn"].raster.transform,
)
attrs = dict(_FillValue=-9999, long_name="slope", units="m/m")
ds_hydro["slope"] = xr.Variable(dims, slope, attrs=attrs)
[15]:
# basin at the pits locations
basins = flwdir.basins(idxs=flwdir.idxs_pit).astype(np.int32)
attrs = dict(_FillValue=0, long_name="basin ids", units="-")
ds_hydro["basins"] = xr.Variable(dims, basins, attrs=attrs)
# basin index file
gdf_basins = ds_hydro["basins"].raster.vectorize()
Nice, we now have some new variables, all derived from the DEM, that we can later use to setup our Wflow model. Let’s have a look at the dataset we produced.
[16]:
display(ds_hydro)
<xarray.Dataset> Size: 3MB
Dimensions: (latitude: 384, longitude: 336)
Coordinates:
* latitude (latitude) float64 3kB 46.8 46.79 46.79 ... 45.21 45.21 45.2
* longitude (longitude) float64 3kB 11.6 11.61 11.61 ... 12.99 12.99 13.0
spatial_ref int64 8B 0
Data variables:
flwdir (latitude, longitude) uint8 129kB 0 16 8 8 8 ... 32 32 32 32 32
elevtn (latitude, longitude) int16 258kB 797 837 956 ... -32 -32 -32
uparea (latitude, longitude) float64 1MB 0.8817 0.1469 ... 0.1512
strord (latitude, longitude) uint8 129kB 2 1 1 1 1 1 1 ... 1 1 1 1 1 1
slope (latitude, longitude) float32 516kB 0.09672 0.07225 ... 0.0 0.0
basins (latitude, longitude) int32 516kB 1 1 1 18 18 ... 73 73 73 73- latitude: 384
- longitude: 336
- latitude(latitude)float6446.8 46.79 46.79 ... 45.21 45.2
- standard_name :
- latitude
- long_name :
- latitude coordinate
- units :
- degrees_north
- axis :
- Y
array([46.797917, 46.79375 , 46.789583, ..., 45.210417, 45.20625 , 45.202083], shape=(384,)) - longitude(longitude)float6411.6 11.61 11.61 ... 12.99 13.0
- standard_name :
- longitude
- long_name :
- longitude coordinate
- units :
- degrees_east
- axis :
- X
array([11.602083, 11.60625 , 11.610417, ..., 12.989583, 12.99375 , 12.997917], shape=(336,)) - spatial_ref()int640
- crs_wkt :
- GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],CS[ellipsoidal,2],AXIS["geodetic latitude (Lat)",north,ORDER[1],ANGLEUNIT["degree",0.0174532925199433]],AXIS["geodetic longitude (Lon)",east,ORDER[2],ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4326]]
- semi_major_axis :
- 6378137.0
- semi_minor_axis :
- 6356752.314245179
- inverse_flattening :
- 298.257223563
- reference_ellipsoid_name :
- WGS 84
- longitude_of_prime_meridian :
- 0.0
- prime_meridian_name :
- Greenwich
- geographic_crs_name :
- WGS 84
- horizontal_datum_name :
- World Geodetic System 1984
- grid_mapping_name :
- latitude_longitude
- spatial_ref :
- GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],CS[ellipsoidal,2],AXIS["geodetic latitude (Lat)",north,ORDER[1],ANGLEUNIT["degree",0.0174532925199433]],AXIS["geodetic longitude (Lon)",east,ORDER[2],ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4326]]
array(0)
- flwdir(latitude, longitude)uint80 16 8 8 8 8 ... 32 32 32 32 32 32
- _FillValue :
- 247
- grid_mapping :
- spatial_ref
array([[ 0, 16, 8, ..., 8, 2, 4], [ 64, 32, 4, ..., 8, 2, 4], [128, 1, 2, ..., 4, 2, 4], ..., [ 4, 8, 2, ..., 32, 32, 32], [ 0, 16, 1, ..., 32, 32, 32], [ 64, 32, 128, ..., 32, 32, 32]], shape=(384, 336), dtype=uint8) - elevtn(latitude, longitude)int16797 837 956 1094 ... -32 -32 -32
- _FillValue :
- -9999
- long_name :
- corrected elevation
- units :
- m
array([[ 797, 837, 956, ..., 2077, 2096, 1968], [ 958, 808, 821, ..., 1916, 1951, 1848], [1101, 872, 801, ..., 1667, 1722, 1652], ..., [ 8, 9, 8, ..., -32, -32, -32], [ 7, 8, 8, ..., -32, -32, -32], [ 8, 7, 7, ..., -32, -32, -32]], shape=(384, 336), dtype=int16) - uparea(latitude, longitude)float640.8817 0.1469 ... 0.1512 0.1512
- _FillValue :
- -9999
- long_name :
- upstream area
- units :
- km2
array([[0.88174151, 0.14694933, 0.14694933, ..., 0.14694933, 0.14694933, 0.14694933], [0.14696071, 0.44088213, 0.29391004, ..., 0.14696071, 0.14696071, 0.44085937], [0.14697209, 0.29395555, 1.32272604, ..., 0.14697209, 0.14697209, 0.73479217], ..., [0.30244454, 0.15122781, 0.30244454, ..., 0.45371666, 0.3024667 , 0.15122781], [1.05865006, 0.15123889, 0.15123889, ..., 0.30248885, 0.30248885, 0.15123889], [0.15124997, 0.15124997, 0.15124997, ..., 0.15124997, 0.15124997, 0.15124997]], shape=(384, 336)) - strord(latitude, longitude)uint82 1 1 1 1 1 1 1 ... 1 1 1 1 1 1 1 1
- _FillValue :
- 225
- long_name :
- stream order
- units :
- -
array([[2, 1, 1, ..., 1, 1, 1], [1, 2, 1, ..., 1, 1, 2], [1, 1, 2, ..., 1, 1, 2], ..., [1, 1, 1, ..., 1, 1, 1], [2, 1, 1, ..., 1, 1, 1], [1, 1, 1, ..., 1, 1, 1]], shape=(384, 336), dtype=uint8) - slope(latitude, longitude)float320.09672 0.07225 0.2903 ... 0.0 0.0
- _FillValue :
- -9999
- long_name :
- slope
- units :
- m/m
array([[0.09671856, 0.0722491 , 0.29032078, ..., 0.21982841, 0.22399823, 0.11675166], [0.26419395, 0.17344822, 0.26566896, ..., 0.45828286, 0.41069072, 0.3005236 ], [0.37447214, 0.39899293, 0.01635252, ..., 0.44755074, 0.47133967, 0.34827203], ..., [0.00177037, 0.00140268, 0.00187063, ..., 0. , 0. , 0. ], [0.00162003, 0.00140268, 0.00177032, ..., 0. , 0. , 0. ], [0.00093522, 0.00089532, 0.00089532, ..., 0. , 0. , 0. ]], shape=(384, 336), dtype=float32) - basins(latitude, longitude)int321 1 1 18 18 18 ... 73 73 73 73 73
- _FillValue :
- 0
- long_name :
- basin ids
- units :
- -
array([[ 1, 1, 1, ..., 16, 16, 16], [ 1, 1, 18, ..., 16, 16, 16], [ 1, 18, 18, ..., 16, 16, 16], ..., [74, 74, 76, ..., 73, 73, 73], [74, 74, 76, ..., 73, 73, 73], [74, 74, 76, ..., 73, 73, 73]], shape=(384, 336), dtype=int32)
[17]:
# NOTE that *upstream area* and *stream order* are not correct as not all upstream area is fully included in the domain, because it was clipped
# plot
fig, axes = plt.subplots(4, 1, figsize=(6, 24), sharex=True, sharey=True)
# plot uparea; use a log scale colormap
ds_hydro["uparea"].plot(ax=axes[0],
norm=colors.LogNorm(vmin=1, vmax=ds_hydro["uparea"].max()))
axes[0].set_title("Upstream area [km2]")
# plot Strahler order
ds_hydro["strord"].plot(ax=axes[1], cmap=colors.ListedColormap(cm.Blues(np.linspace(0, 1, 7))))
axes[1].set_title("Strahler Stream order")
# plot slope
ds_hydro["slope"].plot(ax=axes[2], vmax=3)
axes[2].set_title("Slope")
# plot basins
# elevation cmap
ds_hydro["elevtn"].plot(ax=axes[3], cmap=cmap, vmin=0, vmax=2500)
axes[3].set_title("Elevation");
for ax in axes:
ax.set_xlabel("Longitude [°]")
ax.set_ylabel("Latitude [°]")
Export the data#
Once we are happy with our data, we can export it.
[18]:
# export the hydrography data as tif files (one per variable)
ds_hydro.raster.to_mapstack(root="gebco_derived_hydrography",
driver="GTiff")
# export the basin index as geojson
gdf_basins.to_file(os.path.join("gebco_derived_hydrography", "basins.geojson"),
driver="GeoJSON")
We also want to add this dataset to our data catalog, so HydroMT-Wflow can find the data as well.
[19]:
data_catalog_entry = hydromt.data_catalog.sources.RasterDatasetSource(
name="gebco_derived_hydrography",
uri="gebco_derived_hydrography/{variable}.tif",
driver={'name': "rasterio"},
metadata={'description': "Hydrography data derived from GEBCO"}
)
data_catalog.add_source(name="gebco_derived_hydrography", source=data_catalog_entry)
Let’s retrieve our newly created data through the data catalog!
[20]:
data_catalog.get_rasterdataset("gebco_derived_hydrography")
[20]:
<xarray.Dataset> Size: 3MB
Dimensions: (x: 336, y: 384)
Coordinates:
* x (x) float64 3kB 11.6 11.61 11.61 11.61 ... 12.99 12.99 13.0
* y (y) float64 3kB 46.8 46.79 46.79 46.79 ... 45.21 45.21 45.2
spatial_ref int64 8B 0
Data variables:
strord (y, x) uint8 129kB ...
flwdir (y, x) uint8 129kB ...
elevtn (y, x) int16 258kB ...
uparea (y, x) float64 1MB ...
basins (y, x) int32 516kB ...
slope (y, x) float32 516kB ...
Attributes:
description: Hydrography data derived from GEBCO- x: 336
- y: 384
- x(x)float6411.6 11.61 11.61 ... 12.99 13.0
array([11.602083, 11.60625 , 11.610417, ..., 12.989583, 12.99375 , 12.997917], shape=(336,)) - y(y)float6446.8 46.79 46.79 ... 45.21 45.2
array([46.797917, 46.79375 , 46.789583, ..., 45.210417, 45.20625 , 45.202083], shape=(384,)) - spatial_ref()int640
- crs_wkt :
- GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],CS[ellipsoidal,2],AXIS["geodetic latitude (Lat)",north,ORDER[1],ANGLEUNIT["degree",0.0174532925199433]],AXIS["geodetic longitude (Lon)",east,ORDER[2],ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4326]]
- semi_major_axis :
- 6378137.0
- semi_minor_axis :
- 6356752.314245179
- inverse_flattening :
- 298.257223563
- reference_ellipsoid_name :
- WGS 84
- longitude_of_prime_meridian :
- 0.0
- prime_meridian_name :
- Greenwich
- geographic_crs_name :
- WGS 84
- horizontal_datum_name :
- World Geodetic System 1984
- grid_mapping_name :
- latitude_longitude
- spatial_ref :
- GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],CS[ellipsoidal,2],AXIS["geodetic latitude (Lat)",north,ORDER[1],ANGLEUNIT["degree",0.0174532925199433]],AXIS["geodetic longitude (Lon)",east,ORDER[2],ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4326]]
array(0)
- strord(y, x)uint8...
- AREA_OR_POINT :
- Area
- _FillValue :
- 225
- source_file :
- strord.tif
[129024 values with dtype=uint8]
- flwdir(y, x)uint8...
- AREA_OR_POINT :
- Area
- _FillValue :
- 247
- source_file :
- flwdir.tif
[129024 values with dtype=uint8]
- elevtn(y, x)int16...
- AREA_OR_POINT :
- Area
- _FillValue :
- -9999
- source_file :
- elevtn.tif
[129024 values with dtype=int16]
- uparea(y, x)float64...
- AREA_OR_POINT :
- Area
- _FillValue :
- -9999.0
- source_file :
- uparea.tif
[129024 values with dtype=float64]
- basins(y, x)int32...
- AREA_OR_POINT :
- Area
- _FillValue :
- 0
- source_file :
- basins.tif
[129024 values with dtype=int32]
- slope(y, x)float32...
- AREA_OR_POINT :
- Area
- _FillValue :
- -9999.0
- source_file :
- slope.tif
[129024 values with dtype=float32]
- description :
- Hydrography data derived from GEBCO