Tip

For an interactive online version click here: Binder badge

Build a Wflow model from scratch using Python#

This notebook demonstrates how to build a Wflow model from scratch, step by step, using Python.

Unlike the command line interface (CLI) example, where the full model is built with a single command, we run each setup step separately. This lets you inspect the result after each step, which makes it easier to understand what each step does and to find problems early.

Let’s first load the required libraries

[1]:
import numpy as np
import pandas as pd

# For plotting
from matplotlib import colors
import matplotlib.pyplot as plt

# Import HydroMT and HydroMT-Wflow
import hydromt
from hydromt.model.processes.basin_mask import get_basin_geometry
from hydromt_wflow import WflowSbmModel

The data catalog#

For this example, we will use the artifact data for our DataCatalog, which contains data for the Piave basin in northern Italy.

Let’s have a look at the data contained in the artifact data:

[2]:
data_catalog = hydromt.DataCatalog(data_libs="artifact_data")
data_catalog
[2]:
provider version uri data_type driver crs category paper_doi paper_ref url license author unit history notes nodata info processing_notes timestamp
name
chelsa None 1.2 chelsa.tif RasterDataset RasterioDriver 4326 meteo 10.1038/sdata.2017.122 Karger et al. (2017) http://chelsa-climate.org/downloads/ CC BY 4.0 NaN NaN NaN NaN NaN NaN NaN NaN
chirps_global None v2.0 chirps_global.nc RasterDataset RasterDatasetXarrayDriver 4326 meteo 10.3133/ds832 Funk et al (2014) https://www.chc.ucsb.edu/data/chirps CC NaN NaN NaN NaN NaN NaN NaN NaN
corine None v.2020_20u1 corine.tif RasterDataset RasterioDriver NaN landuse & landcover NaN NaN https://land.copernicus.eu/pan-european/corine... https://land.copernicus.eu/pan-european/corine... European Environment Agency NaN NaN NaN NaN NaN NaN NaN
dtu10mdt None 2010 dtu10mdt.tif RasterDataset RasterioDriver 4326 topography 10.1029/2008JC005179 Andersen and Knudsen (2009) https://www.space.dtu.dk/english/research/scie... NaN NaN m+EGM2008 NaN NaN NaN NaN NaN NaN
dtu10mdt_egm96 None 2010 dtu10mdt_egm96.tif RasterDataset RasterioDriver 4326 topography 10.1029/2008JC005179 Andersen and Knudsen (2009) https://www.space.dtu.dk/english/research/scie... NaN NaN m+EGM96 NaN NaN NaN NaN NaN NaN
eobs None 22.0e eobs.nc RasterDataset RasterDatasetXarrayDriver 4326 meteo 10.1029/2017JD028200 Cornes et al (2018) https://surfobs.climate.copernicus.eu/dataacce... https://surfobs.climate.copernicus.eu/dataacce... NaN NaN NaN NaN NaN NaN NaN NaN
eobs_orography None 22.0e eobs_orography.nc RasterDataset RasterDatasetXarrayDriver 4326 meteo 10.1029/2017JD028200 Cornes et al (2018) https://surfobs.climate.copernicus.eu/dataacce... https://surfobs.climate.copernicus.eu/dataacce... NaN NaN NaN NaN NaN NaN NaN NaN
era5 None ERA5 daily data on pressure levels era5.nc RasterDataset RasterDatasetXarrayDriver 4326 meteo 10.1002/qj.3803 Hersbach et al. (2019) https://doi.org/10.24381/cds.bd0915c6 https://cds.climate.copernicus.eu/cdsapp/#!/te... NaN NaN Extracted from Copernicus Climate Data Store; ... NaN NaN NaN NaN NaN
era5_hourly None None era5_hourly.nc RasterDataset RasterDatasetXarrayDriver 4326 meteo 10.1002/qj.3803 Hersbach et al. (2019) https://doi.org/10.24381/cds.bd0915c6 https://cds.climate.copernicus.eu/cdsapp/#!/te... NaN NaN Extracted from Copernicus Climate Data Store NaN NaN NaN NaN NaN
era5_daily_zarr None None era5_daily_zarr.zarr RasterDataset RasterDatasetXarrayDriver 4326 meteo 10.1002/qj.3803 Hersbach et al. (2019) https://doi.org/10.24381/cds.bd0915c6 https://cds.climate.copernicus.eu/cdsapp/#!/te... NaN NaN Extracted from Copernicus Climate Data Store; ... NaN NaN NaN NaN NaN
era5_hourly_zarr None None era5_hourly_zarr.zarr RasterDataset RasterDatasetXarrayDriver 4326 meteo 10.1002/qj.3803 Hersbach et al. (2019) https://doi.org/10.24381/cds.bd0915c6 https://cds.climate.copernicus.eu/cdsapp/#!/te... NaN NaN Extracted from Copernicus Climate Data Store NaN NaN NaN NaN NaN
era5_orography None None era5_orography.nc RasterDataset RasterDatasetXarrayDriver 4326 meteo 10.1002/qj.3803 Hersbach et al. (2019) https://doi.org/10.24381/cds.bd0915c6 https://cds.climate.copernicus.eu/cdsapp/#!/te... NaN NaN Extracted from Copernicus Climate Data Store NaN NaN NaN NaN NaN
gadm_level1 None 1.0 gadm_level1.gpkg GeoDataFrame PyogrioDriver 4326 geography NaN NaN https://gadm.org/download_world.html https://gadm.org/license.html gadm NaN NaN last downloaded 2020-10-19; license required f... NaN NaN NaN NaN
gadm_level2 None 1.0 gadm_level2.gpkg GeoDataFrame PyogrioDriver 4326 geography NaN NaN https://gadm.org/download_world.html https://gadm.org/license.html gadm NaN NaN last downloaded 2020-10-19; license required f... NaN NaN NaN NaN
gadm_level3 None 1.0 gadm_level3.gpkg GeoDataFrame PyogrioDriver 4326 geography NaN NaN https://gadm.org/download_world.html https://gadm.org/license.html gadm NaN NaN last downloaded 2020-10-19; license required f... NaN NaN NaN NaN
gcn250 None v1 gcn250/{variable}.tif RasterDataset RasterioDriver NaN soil 10.1038/s41597-019-0155-x Jaafar et al. (2019) https://doi.org/10.6084/m9.figshare.7756202.v1 CC BY 4.0 NaN NaN NaN NaN 255.0 NaN NaN NaN
gdp_world None 1.0 gdp_world.gpkg GeoDataFrame PyogrioDriver 4326 socio economic NaN NaN NaN CC BY-4.0 Wilfred Altena NaN NaN NaN NaN data combined from World Bank (https://data.wo... NaN NaN
gebco None 2020 gebco.tif RasterDataset RasterioDriver 4326 topography 10.5285/a29c5465-b138-234d-e053-6c86abc040b9 Weatherall et al (2020) https://www.bodc.ac.uk/data/open_download/gebc... https://www.gebco.net/data_and_products/gridde... NaN m+MSL NaN NaN NaN NaN NaN NaN
ghs_smod_2015 None R2016A_v1.0 ghs_smod_2015.tif RasterDataset RasterioDriver [ESRI, 54009] socio economic NaN Pesaresi and Freire (2016) https://data.jrc.ec.europa.eu/dataset/jrc-ghsl... https://data.jrc.ec.europa.eu/licence/com_reuse JRC-ISPRA EC NaN NaN NaN NaN NaN NaN NaN
ghs_smod_2015 None R2019A_v2.0 ghs-smod_2015_v2.tif RasterDataset RasterioDriver [ESRI, 54009] socio economic 10.2905/42E8BE89-54FF-464E-BE7B-BF9E64DA5218 Pesaresi et al (2019) https://data.jrc.ec.europa.eu/dataset/42e8be89... https://data.jrc.ec.europa.eu/licence/com_reuse JRC-ISPRA EC NaN NaN NaN NaN NaN NaN NaN
ghs_pop_2015 None None ghs_pop_2015.tif RasterDataset RasterioDriver 4326 socio economic 10.2905/0C6B9751-A71F-4062-830B-43C9F432370F Schiavina et al (2019) https://data.jrc.ec.europa.eu/dataset/0c6b9751... https://data.jrc.ec.europa.eu/licence/com_reuse JRC-ISPRA EC NaN NaN NaN NaN NaN NaN NaN
ghs_pop_2015_54009 None R2019A_v1.0 ghs_pop_2015_54009.tif RasterDataset RasterioDriver [ESRI, 54009] socio economic 10.2760/062975 Florczyk et al (2019) https://ghsl.jrc.ec.europa.eu/download.php?ds=pop CC BY 4.0 NaN NaN NaN NaN NaN NaN NaN NaN
globcover_2009 None None globcover.tif RasterDataset RasterioDriver 4326 landuse & landcover 10.1594/PANGAEA.787668 Arino et al (2012) http://due.esrin.esa.int/page_globcover.php CC-BY-3.0 NaN NaN NaN NaN NaN NaN NaN NaN
glw_buffaloes None 3 glw_buffaloes.tif RasterDataset RasterioDriver 4326 socio economic 10.7910/DVN/5U8MWI Gilbert at al (2018) https://dataverse.harvard.edu/dataverse/glw_3 CC 4.0 glw (Gridded Livestock of World 3 Dataverse) NaN NaN NaN NaN NaN NaN NaN
glw_cattle None 3 glw_cattle.tif RasterDataset RasterioDriver 4326 socio economic 10.7910/DVN/GIVQ75 Gilbert at al (2018) https://dataverse.harvard.edu/dataverse/glw_3 CC 4.0 glw (Gridded Livestock of World 3 Dataverse) NaN NaN NaN NaN NaN NaN NaN
glw_chicken None 3 glw_chicken.tif RasterDataset RasterioDriver 4326 socio economic 10.7910/DVN/SUFASB Gilbert at al (2018) https://dataverse.harvard.edu/dataverse/glw_3 CC 4.0 glw (Gridded Livestock of World 3 Dataverse) NaN NaN NaN NaN NaN NaN NaN
glw_ducks None 3 glw_ducks.tif RasterDataset RasterioDriver 4326 socio economic 10.7910/DVN/ICHCBH Gilbert at al (2018) https://dataverse.harvard.edu/dataverse/glw_3 CC 4.0 glw (Gridded Livestock of World 3 Dataverse) NaN NaN NaN NaN NaN NaN NaN
glw_goats None 3 glw_goats.tif RasterDataset RasterioDriver 4326 socio economic 10.7910/DVN/OCPH42 Gilbert at al (2018) https://dataverse.harvard.edu/dataverse/glw_3 CC 4.0 glw (Gridded Livestock of World 3 Dataverse) NaN NaN NaN NaN NaN NaN NaN
glw_horses None 3 glw_horses.tif RasterDataset RasterioDriver 4326 socio economic 10.7910/DVN/7Q52MV Gilbert at al (2018) https://dataverse.harvard.edu/dataverse/glw_3 CC 4.0 glw (Gridded Livestock of World 3 Dataverse) NaN NaN NaN NaN NaN NaN NaN
glw_pigs None 3 glw_pigs.tif RasterDataset RasterioDriver 4326 socio economic 10.7910/DVN/33N0JG Gilbert at al (2018) https://dataverse.harvard.edu/dataverse/glw_3 CC 4.0 glw (Gridded Livestock of World 3 Dataverse) NaN NaN NaN NaN NaN NaN NaN
glw_sheep None 3 glw_sheep.tif RasterDataset RasterioDriver 4326 socio economic 10.7910/DVN/BLWPZN Gilbert at al (2018) https://dataverse.harvard.edu/dataverse/glw_3 CC 4.0 glw (Gridded Livestock of World 3 Dataverse) NaN NaN NaN NaN NaN NaN NaN
grdc None None grdc.csv GeoDataFrame GeoDataFrameTableDriver 4326 observed data NaN NaN https://portal.grdc.bafg.de/applications/publi... https://www.bafg.de/GRDC/EN/02_srvcs/21_tmsrs/... NaN NaN NaN NaN NaN GRDC-Station Catalogue, last downloaded 2020-0... NaN NaN
grip_roads None v4 grip_roads.gpkg GeoDataFrame PyogrioDriver 4326 road 10.1088/1748-9326/aabd42 Meijer et al, 2018 https://www.globio.info/download-grip-dataset CC0-1.0 NaN NaN NaN NaN NaN NaN NaN NaN
grwl None 1.01 grwl.gpkg GeoDataFrame PyogrioDriver NaN surface water 10.1126/science.aat0636 Allen and Pavelsky (2018) https://doi.org/10.5281/zenodo.1297434 CC BY 4.0 NaN NaN NaN NaN NaN NaN NaN NaN
grwl_mask None 1.01 grwl_tindex.gpkg RasterDataset RasterioDriver NaN NaN 10.1126/science.aat0636 Allen and Pavelsky (2018) https://doi.org/10.5281/zenodo.1297434 CC BY 4.0 NaN NaN NaN NaN 0.0 NaN NaN NaN
gswo None v1_1_2019 gswo.tif RasterDataset RasterioDriver NaN surface water 10.1038/nature20584 Pekel et al. (2016) https://global-surface-water.appspot.com/download NaN NaN NaN NaN NaN 255.0 NaN NaN NaN
gtsmv3_eu_era5 None 3.0 gtsmv3_eu_era5.nc GeoDataset GeoDatasetXarrayDriver 4326 ocean 10.24381/cds.8c59054f Copernicus Climate Change Service 2019 https://cds.climate.copernicus.eu/cdsapp#!/dat... https://cds.climate.copernicus.eu/cdsapp/#!/te... NaN NaN NaN NaN NaN NaN NaN NaN
guf_bld_2012 None None guf_bld_2012.tif RasterDataset RasterioDriver 4326 socio economic 10.1016/j.isprsjprs.2017.10.012 Esch et al (2017) http://www.dlr.de/guf https://www.dlr.de/eoc/en/PortalData/60/Resour... NaN NaN NaN NaN NaN NaN NaN NaN
hydro_lakes None 1.0 hydro_lakes.gpkg GeoDataFrame PyogrioDriver 4326 surface water NaN NaN NaN NaN Arjen Haag NaN NaN NaN NaN HydroLAKES.v10_extract NaN NaN
hydro_reservoirs None 1.0 hydro_reservoirs.gpkg GeoDataFrame PyogrioDriver 4326 surface water NaN NaN NaN NaN Alessia Matano NaN NaN NaN -99.0 GRanD.v1.1_HydroLAKES.v10_JRC.2016 NaN NaN
koppen_geiger None 2017 koppen_geiger.tif RasterDataset RasterioDriver 4326 meteo 10.1127/0941-2948/2006/0130 Kottek et al. (2006) http://koeppen-geiger.vu-wien.ac.at/present.htm NaN NaN NaN NaN NaN 0.0 NaN NaN NaN
mdt_cnes_cls18 None 18 mdt_cnes_cls18.tif RasterDataset RasterioDriver 4326 topography 10.5194/os-17-789-2021 Mulet et al (2021) https://www.aviso.altimetry.fr/en/data/product... NaN NaN m+GOCO05S NaN NaN NaN NaN NaN NaN
merit_hydro None 1.0 merit_hydro/{variable}.tif RasterDataset RasterioDriver 4326 topography 10.1029/2019WR024873 Yamazaki et al. (2019) http://hydro.iis.u-tokyo.ac.jp/~yamadai/MERIT_... CC-BY-NC 4.0 or ODbL 1.0 NaN NaN NaN NaN NaN NaN NaN NaN
merit_hydro_ihu None 0.1 merit_hydro_1k/{variable}.tif RasterDataset RasterioDriver 4326 topography 10.5194/hess-2020-582 Eilander et al. (in review) https://doi.org/10.5281/zenodo.4138776 CC-BY-NC 4.0 NaN NaN NaN NaN NaN NaN NaN NaN
merit_hydro_index None None merit_hydro_index.gpkg GeoDataFrame PyogrioDriver 4326 topography 10.5194/hess-2020-582 Eilander et al. (in review) NaN CC-BY-NC 4.0 NaN NaN NaN NaN NaN NaN NaN NaN
modis_lai None 6 modis_lai.nc RasterDataset RasterDatasetXarrayDriver 4326 landuse & landcover 10.5067/MODIS/MCD15A3H.006 Myneni et al (2015) https://lpdaac.usgs.gov/products/mcd15a3hv006/ https://lpdaac.usgs.gov/data/data-citation-and... NaN NaN NaN this dataset has been extracted from GEE ('MOD... NaN NaN NaN NaN
osm_coastlines None 1.0 osm_coastlines.gpkg GeoDataFrame PyogrioDriver 4326 geography NaN NaN https://osmdata.openstreetmap.de/data/coastlin... ODbL OpenStreetMap NaN NaN NaN NaN OpenStreetMap coastlines water polygons, last ... NaN NaN
osm_landareas None 1.0 osm_landareas.gpkg GeoDataFrame PyogrioDriver 4326 geography NaN NaN https://osmdata.openstreetmap.de/data/coastlin... ODbL OpenStreetMap NaN NaN NaN NaN OpenStreetMap coastlines land polygons, last u... NaN NaN
rgi None 6.0 rgi.gpkg GeoDataFrame PyogrioDriver 4326 surface water 10.3189/2014JoG13J176 Pfeffer et al. (2014) https://cds.climate.copernicus.eu/cdsapp#!/dat... CC BY 4.0 NaN NaN NaN NaN NaN Randolph Glacier Inventory NaN NaN
hydro_rivers_lin None 1 rivers_lin2019_v1.gpkg GeoDataFrame PyogrioDriver NaN hydrography 10.5281/zenodo.3552776 Lin et al. (2019) https://zenodo.org/record/3552776#.YVbOrppByUk CC-BY-NC 4.0 NaN NaN NaN NaN NaN NaN hydrography/rivers_lin2019/README NaN
simard None None simard.tif RasterDataset RasterioDriver 4326 landuse & landcover 10.1029/2011JG001708 Simard et al (2011) https://webmap.ornl.gov/ogc/dataset.jsp?ds_id=... NaN NaN NaN NaN NaN NaN NaN NaN NaN
soilgrids None 2017 soilgrids/{variable}.tif RasterDataset RasterioDriver 4326 soil 10.1371/journal.pone.0169748 Hengl et al. (2017) https://www.isric.org/explore/soilgrids/faq-so... ODbL NaN NaN NaN soilthickness is based on 1) soilgrids (global... NaN NaN NaN NaN
vito_2015 None 2.0.2 vito.tif RasterDataset RasterioDriver 4326 landuse & landcover 10.5281/zenodo.3939038 Buchhorn et al (2020) https://land.copernicus.eu/global/products/lc NaN NaN NaN NaN NaN NaN NaN NaN NaN
wb_countries None None wb_countries.gpkg GeoDataFrame PyogrioDriver 4326 socio-economic NaN NaN https://datacatalog.worldbank.org/dataset/worl... CC-BY 4.0 World Bank NaN NaN NaN NaN NaN NaN February 2020
worldclim None 2 worldclim.nc RasterDataset RasterDatasetXarrayDriver 4326 meteo 10.1002/joc.5086 Fick and Hijmans (2017) https://www.worldclim.org/data/worldclim21.html NaN NaN NaN NaN NaN NaN NaN NaN NaN

That’s a lot of data! The DataCatalog lists for each entry what kind of data it is, how it is formatted, what the CRS is, what the source is, etc.

HydroMT-Wflow expects for each data variable a specific name and unit. For example, elevation data should always be named elevtn and have a unit of m+REF. Of course, different datasets use widely different units and naming. With the DataCatalog, we can take care of this, by specifying for each datasets how variables should be mapped, and how units should be converted.

Let’s checkout one of the data sources, for example MERIT Hydro:

[3]:
ds_merit_hydro = data_catalog.get_rasterdataset('merit_hydro')
ds_merit_hydro
[3]:
<xarray.Dataset> Size: 97MB
Dimensions:      (x: 1680, y: 1920)
Coordinates:
  * x            (x) float64 13kB 11.6 11.6 11.6 11.6 ... 13.0 13.0 13.0 13.0
  * y            (y) float64 15kB 46.8 46.8 46.8 46.8 ... 45.2 45.2 45.2 45.2
    spatial_ref  int64 8B 0
Data variables:
    elevtn       (y, x) float32 13MB ...
    lndslp       (y, x) float32 13MB ...
    strord       (y, x) uint8 3MB ...
    hnd          (y, x) float32 13MB ...
    basins       (y, x) uint32 13MB ...
    rivwth       (y, x) float32 13MB ...
    flwdir       (y, x) uint8 3MB ...
    uparea       (y, x) float32 13MB ...
    upgrid       (y, x) int32 13MB ...
Attributes:
    crs:        4326
    category:   topography
    paper_doi:  10.1029/2019WR024873
    paper_ref:  Yamazaki et al. (2019)
    url:        http://hydro.iis.u-tokyo.ac.jp/~yamadai/MERIT_Hydro
    license:    CC-BY-NC 4.0 or ODbL 1.0

MERIT Hydro is a dataset containing both topographic (elevation, slope) and hydrographic (flow direction, upstream area) data. Let’s plot the elevation:

[4]:
# 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))

# Plot the elevation data, masking nodata values
ds_merit_hydro['elevtn'].raster.mask_nodata().plot(
    ax=ax,
    cmap=cmap,
    vmax=2500,
    cbar_kwargs={'label': 'Elevation [m]'})
ax.set_xlabel('Longitude [degrees]')
ax.set_ylabel('Latitude [degrees]')
ax.set_title('MERIT Hydro Elevation')
ax.set_aspect('equal');
../_images/_examples_build_model_python_9_0.png

Defining the model region#

When building a Wflow model with HydroMT-Wflow, we need to specify for which geographic region we want to build a model. Very often, our Wflow model area is based on a (sub)basin. For example, we can specify an outlet location of our Wflow model, and HydroMT-Wflow will derive the area upstream of this outlet, which then defines the geographic region. It is also possible to define multiple outlets, or even specify an entire area. HydroMT-Wflow will derive all (sub)basins belonging to the specified outlets or area. A Wflow model can thus contain multiple basins! For more details, see the HydroMT documentation on this.

In this notebook, we will specify a single outlet, and derive the corresponding upstream area. For HydroMT-Wflow to be able to derive the upstream area, and build the Wflow model, it needs certain hydrographic data, derived from a Digital Elevation Model (DEM).

In this example, we assume this hydrographic data has already been derived. In fact, our data catalog with artifact data already contains datasets with variables such as the local drainage direction and upstream area. If you want to know how to derive this hydrographic data from a raw DEM, please see this example notebook on how to prepare flow directions and related data from a raw DEM.

[5]:
# Outlet coordinates
x = 12.2051
y = 45.8331

# Derive the basin geometry and outlet location
gdf_basin, gdf_outlet = get_basin_geometry(
    ds=data_catalog.get_rasterdataset('merit_hydro'), # hydrography dataset from the data catalog
    kind="subbasin",
    xy=[x, y],
    uparea=70) # set a minimum upstream area to force snapping to a river

Let’s explain briefly what we just did. We supply an outlet location [x, y], and tell HydroMT-Wflow to delineate the subbasin upstream of this outlet. We also tell it to use MERIT Hydro as its hydrography dataset, but we could have used another dataset as well. Lastly, we tell it that the area upstream of our outlet should be at least 70 km2. If the cell at our supplied outlet does not meet this requirement, HydroMT-Wflow will snap it to the closest cell that does. By setting kind="subbasin" it will delineate only the area upstream of our outlet. If we had used kind="basin", it would have returned the entire basin, also downstream of our [x, y].

Let’s plot the delineated subbasin!

[6]:
# Plot the elevation data and the delineated subbasin and outlet
fig, ax = plt.subplots(figsize=(8, 8))

ds_merit_hydro['elevtn'].raster.mask_nodata().plot(
    ax=ax,
    cmap=cmap,
    vmin=0,
    vmax=2500,
    cbar_kwargs={'label': 'Elevation [m]', 'shrink': 0.7})

# Plot the boundary of the delineated  subbasin
gdf_basin.boundary.plot(ax=ax, edgecolor="k", zorder=2, label="Delineated subbasin")

# Plot the outlet of the delineated subbasin
gdf_outlet.plot(ax=ax, markersize=40, c="red", zorder=2, label="Outlet")

ax.set_xlabel('Longitude [degrees]')
ax.set_ylabel('Latitude [degrees]')
ax.set_title('MERIT Hydro Elevation')
ax.set_aspect('equal')
ax.legend(loc='lower right');
../_images/_examples_build_model_python_14_0.png

Also note that the outlet has slightly shifted from our original [x, y]:

[7]:
print(f'Original x-coordinate: {x:.4f} - Outlet x-coordinate: {gdf_outlet["geometry"].x.values[0]:.4f}')
print(f'Original y-coordinate: {y:.4f} - Outlet y-coordinate: {gdf_outlet["geometry"].y.values[0]:.4f}')
Original x-coordinate: 12.2051 - Outlet x-coordinate: 12.2054
Original y-coordinate: 45.8331 - Outlet y-coordinate: 45.8337

This is because we forced snapping to a location with an upstream area of at least 70 km2.

Initializing our model#

We just used HydroMT-Wflow to delineate a subbasin based on an outlet location. However, note that we haven’t built any model whatsoever, yet. This is just a handy step to check we correctly defined the region of our interest.

Next, we can use this geographic region of interest to build our Wflow model.

We start with a completely empty Wflow model. We only specify the directory where the model should be stored, and the data catalog configuration files (for now just the artifact data).

[8]:
# This creates a completely empty Wflow model.
model = WflowSbmModel("./wflow_test_python_full",
                      data_libs="artifact_data")

As you can see, the model is still empty:

[9]:
print("Static model data:")
display(model.staticmaps.data)
print("Model forcing data:")
display(model.forcing.data)
print("Model geometry data:")
display(model.geoms.data)
Static model data:
<xarray.Dataset> Size: 0B
Dimensions:  ()
Data variables:
    *empty*
Model forcing data:
<xarray.Dataset> Size: 0B
Dimensions:  ()
Data variables:
    *empty*
Model geometry data:
{}

Let’s start by configuring some model settings, such as the start and end time, and the timestep. Many model settings have a default value, or are adjusted automatically when we run certain workflows. For example, glaciers are by default turned off, but once we add glaciers to our model, our model settings will automatically be updated to turn the glaciers on.

You can always easily adjust the settings of your Wflow model in the Wflow model settings file (.toml). You don’t have to do it through HydroMT-Wflow.

[10]:
model.setup_config({'time.starttime': '2010-02-02T00:00:00', # Start time of our model
                    'time.endtime': '2010-02-10T00:00:00', # End time of our model
                    'time.timestepsecs': 86400, # Time step of our model in seconds
                    'output.netcdf_grid.path': 'gridded_output.nc', # Name of the NetCDF output file
                    'output.netcdf_grid.compressionlevel': 1, # Compression level for NetCDF output
                    'output.netcdf_grid.variables.land_surface__evapotranspiration_volume_flux': 'actual_evap' # Write actual evapotranspiration to a netCDF
                   })

Basemaps#

Let’s begin by adding a basemap. Setting up the basemaps is always the first step, as it defines the geographic region of our model. Not only that; it also extracts some essential data from our DataCatalog and adds it to the model, such as land elevation, local drainage direction, and the slope.

Note that we use the subbasin definition we checked earlier. It comes in handy now!

[11]:
model.setup_basemaps(region={'subbasin': [x, y], 'uparea': 70},
                     hydrography_fn='merit_hydro',
                     res=0.0083333) # resolution (unit is the same as the source CRS, so degrees in this case --> ~1 km)

Our model now has a basemap; let’s have a look at the data it now contains!

[12]:
display(model.staticmaps.data)
<xarray.Dataset> Size: 573kB
Dimensions:                  (y: 107, x: 116)
Coordinates:
  * y                        (y) float64 856B 46.69 46.68 46.67 ... 45.81 45.8
  * x                        (x) float64 928B 11.78 11.79 11.8 ... 12.73 12.74
    spatial_ref              int64 8B 0
Data variables:
    meta_subgrid_outlet_x    (y, x) float64 99kB nan nan nan nan ... nan nan nan
    meta_subgrid_outlet_y    (y, x) float64 99kB nan nan nan nan ... nan nan nan
    local_drain_direction    (y, x) uint8 12kB 255 255 255 255 ... 255 255 255
    subcatchment             (y, x) int32 50kB 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0
    meta_upstream_area       (y, x) float32 50kB -9.999e+03 ... -9.999e+03
    meta_subgrid_area        (y, x) float32 50kB -9.999e+03 ... -9.999e+03
    meta_subgrid_elevation   (y, x) float32 50kB -9.999e+03 ... -9.999e+03
    meta_streamorder         (y, x) uint8 12kB 255 255 255 255 ... 255 255 255
    meta_subgrid_outlet_idx  (y, x) int32 50kB -1 -1 -1 -1 -1 ... -1 -1 -1 -1 -1
    land_elevation           (y, x) float32 50kB -9.999e+03 ... -9.999e+03
    land_slope               (y, x) float32 50kB -9.999e+03 ... -9.999e+03

Note that HydroMT-Wflow also stores the geometry of our delineated subbasin at model resolution, as well as at the original (higher) resolution. Let’s plot our model region!

[13]:
fig, ax = plt.subplots(figsize=(8, 8))

# Plot the elevation data from the model, masking out nodata values
model.staticmaps.data['land_elevation'].raster.mask_nodata().plot(
    ax=ax,
    cmap=cmap,
    vmin=0,
    vmax=2500,
    cbar_kwargs={'label': 'Elevation [m]', 'shrink': 0.7})

model.geoms.data['basins'].plot(
    ax=ax, facecolor='none', edgecolor='black', label='Subbasin at model resolution')
model.geoms.data['meta_basins_highres'].plot(
    ax=ax, facecolor='none', edgecolor='red', label='High-resolution subbasin')
ax.set_xlabel('Longitude [degrees]')
ax.set_ylabel('Latitude [degrees]')
ax.set_title('Basemap of Wflow model')
ax.legend(loc='lower right')
ax.set_aspect('equal');
../_images/_examples_build_model_python_30_0.png

Note that we also could have used region={'geom': gdf_basin} instead of region={'subbasin': [x, y], 'uparea': 70}, reusing the basin delineation from earlier. However, using kind geom for region is not recommended, as it can lead to mistakes in the basin delineation.

Rivers#

The next step for building our model is to setup the rivers! We tell HydroMT-Wflow which datasets it should use, and it will look for those datasets in our DataCatalog, extract the relevant river data, and add it to our model.

To add the river data to our model, we need to define which cells contain a river. In HydroMT-Wflow, this is based on an upstream area threshold. Any cell that meets that threshold, is defined as a river cell and will have river data added.

It is crucial that we therefore use the same hydrography dataset for setting up the river as we had used to define our basemaps. Variables like the upstream area and local drainage direction were used to delineate our basemaps, and should therefore also be used to define which cells contain a river.

We also supply an extra dataset with river width and bankfull discharge data, as our hydrography dataset does not contain this data. This second dataset only contains data on rivers that are at least 30 meters wide. Therefore, we define a minimum river width, that will be used for cells where our second dataset has no data.

We also want to add the river depth, but we have no dataset with the river depth! As a work-around, we estimate the river depth based on the bankfull discharge (which we do have data on) and the power law, by specifying rivdph_method='powlaw'. But if you have data on the river depth, you could of course also just use that instead.

Lastly, we define the method to use for river routing, river_routing='kinematic_wave' in this case.

[14]:
model.setup_rivers(
    hydrography_fn='merit_hydro', # Point to the entry in the data catalog containing the hydrography data
    river_geom_fn='hydro_rivers_lin', # river source data with river width and bankfull discharge
    river_upa=10, # The upstream area threshold in km2 to define a river
    rivdph_method='powlaw', # The method to determine the river depth. Here, the power law is used
    min_rivdph=1, # The minimum river depth in meters
    min_rivwth=10, # The minimum river width, in meters.
    river_routing='kinematic_wave') # The method to use for river routing

Let’s look at the data we added!

[15]:
display(model.staticmaps.data)
<xarray.Dataset> Size: 784kB
Dimensions:                  (y: 107, x: 116)
Coordinates:
  * y                        (y) float64 856B 46.69 46.68 46.67 ... 45.81 45.8
  * x                        (x) float64 928B 11.78 11.79 11.8 ... 12.73 12.74
    spatial_ref              int64 8B 0
Data variables: (12/16)
    meta_subgrid_outlet_x    (y, x) float64 99kB nan nan nan nan ... nan nan nan
    meta_subgrid_outlet_y    (y, x) float64 99kB nan nan nan nan ... nan nan nan
    local_drain_direction    (y, x) uint8 12kB 255 255 255 255 ... 255 255 255
    subcatchment             (y, x) int32 50kB 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0
    meta_upstream_area       (y, x) float32 50kB -9.999e+03 ... -9.999e+03
    meta_subgrid_area        (y, x) float32 50kB -9.999e+03 ... -9.999e+03
    ...                       ...
    land_slope               (y, x) float32 50kB -9.999e+03 ... -9.999e+03
    river_mask               (y, x) uint8 12kB 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0
    river_length             (y, x) float32 50kB -9.999e+03 ... -9.999e+03
    river_slope              (y, x) float32 50kB -9.999e+03 ... -9.999e+03
    river_width              (y, x) float32 50kB -9.999e+03 ... -9.999e+03
    river_depth              (y, x) float32 50kB -9.999e+03 ... -9.999e+03

Our model geometries now also contain the rivers. Let’s plot these, using the stream order to set the width of the rivers:

[16]:
fig, ax = plt.subplots(figsize=(8, 8))

# Plot the elevation data from the model, masking out nodata values
model.staticmaps.data['land_elevation'].raster.mask_nodata().plot(
    ax=ax,
    cmap=cmap,
    vmin=0,
    vmax=2500,
    cbar_kwargs={'label': 'Elevation [m]', 'shrink': 0.7})

model.geoms.data['basins'].plot(
    ax=ax, facecolor='none', edgecolor='black')
model.geoms.data['rivers'].plot(
    ax=ax, facecolor=None, edgecolor='blue', linewidth=model.geoms.data['rivers'].strord / 3)
ax.set_xlabel('Longitude [degrees]')
ax.set_ylabel('Latitude [degrees]')
ax.set_title('Basemap of Wflow model')
ax.set_aspect('equal');
../_images/_examples_build_model_python_37_0.png

Note that river data has of course only been added to cells with a river. For example, the river width:

[17]:
fig, ax = plt.subplots(figsize=(8, 8))

# Plot the elevation data from the model, masking out nodata values
model.staticmaps.data['river_width'].raster.mask_nodata().plot(
    ax=ax,
    cmap='viridis_r',
    cbar_kwargs={'label': 'River width [m]', 'shrink': 0.7})

model.geoms.data['basins'].plot(
    ax=ax, facecolor='none', edgecolor='black', label='Subbasin at model resolution')
ax.set_xlabel('Longitude [degrees]')
ax.set_ylabel('Latitude [degrees]')
ax.set_title('River width')
ax.set_aspect('equal');
../_images/_examples_build_model_python_39_0.png

Let’s also set the Manning roughness of the rivers. In HydroMT-Wflow, we use a mapping between Manning roughness and streamorder to determine the Manning roughness of rivers. HydroMT-Wflow contains a default mapping, which we will use here:

[18]:
model.setup_river_roughness()

Reservoirs, lakes, and glaciers#

Next, let’s add controlled reservoirs, uncontrolled reservoirs (lakes), and glaciers. Again, our artifact data contains datasets with the necessary data for this. You could of course also supply your own datasets with the required data.

[19]:
model.setup_reservoirs_simple_control(
      reservoirs_fn= "hydro_reservoirs", # source for reservoirs shape and attributes
      timeseries_fn= "gww", # additional source for reservoir are timeseries to compute reservoirs, Either 'gww' using gwwapi or 'jrc' using hydroengine.
      min_area= 0.1, # minimum lake area to consider [km2]
)
Global Water Watch (gww) has shut down and is no longer supported; falling back to the reservoir database attributes (timeseries_fn=None). Use 'jrc' to retrieve reservoir time series from JRC.
[20]:
model.setup_reservoirs_no_control(
      reservoirs_fn= "hydro_lakes", # source for uncontrolled reservoirs (e.g. lakes) based on hydroLAKES: {hydro_lakes}
      min_area= 1.0, # minimum lake area to consider [km2]
)
/home/runner/work/hydromt_wflow/hydromt_wflow/.pixi/envs/docs/lib/python3.13/site-packages/geopandas/geodataframe.py:2011: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  super().__setitem__(key, value)
Replacing geom: reservoirs
[21]:
model.setup_glaciers(
    glaciers_fn= "rgi", # source for glaciers shape and attributes based on Randolph Glacier Inventory: {rgi}
    min_area= 0.1 # minimum glacier area to consider [km2]
)

Let’s have a look at the data we just added to our model. You’ll see that many variables related to glaciers and reservoirs have been added!

[22]:
model.staticmaps.data[
    [var for var in model.staticmaps.data if "reservoir" in var or "glacier" in var]]
[22]:
<xarray.Dataset> Size: 945kB
Dimensions:                         (y: 107, x: 116)
Coordinates:
  * y                               (y) float64 856B 46.69 46.68 ... 45.81 45.8
  * x                               (x) float64 928B 11.78 11.79 ... 12.73 12.74
    spatial_ref                     int64 8B 0
Data variables: (12/19)
    reservoir_area_id               (y, x) float32 50kB -999.0 -999.0 ... -999.0
    reservoir_outlet_id             (y, x) int32 50kB -999 -999 ... -999 -999
    reservoir_max_volume            (y, x) float32 50kB -999.0 -999.0 ... -999.0
    reservoir_area                  (y, x) float32 50kB -999.0 -999.0 ... -999.0
    reservoir_initial_depth         (y, x) float32 50kB -999.0 -999.0 ... -999.0
    reservoir_rating_curve          (y, x) int32 50kB -999 -999 ... -999 -999
    ...                              ...
    reservoir_e                     (y, x) float32 50kB -999.0 -999.0 ... -999.0
    reservoir_outflow_threshold     (y, x) float32 50kB -999.0 -999.0 ... -999.0
    reservoir_lower_id              (y, x) int32 50kB -999 -999 ... -999 -999
    meta_glacier_area_id            (y, x) int32 50kB 0 0 0 0 0 0 ... 0 0 0 0 0
    glacier_initial_leq_depth       (y, x) float32 50kB 0.0 0.0 0.0 ... 0.0 0.0
    glacier_fraction                (y, x) float32 50kB 0.0 0.0 0.0 ... 0.0 0.0

Also note that our model has now extra geometries:

[23]:
for geom in model.geoms.data.keys():
    print(geom)
meta_basins_highres
basins
rivers
meta_reservoirs_simple_control
reservoirs
meta_reservoirs_no_control
glaciers

Note that we have stored a high resolution polygon of all reservoirs with simple control, and all reservoirs with no control. We also have a polygon containing all reservoirs (both with and without control) at model resolution. Also, a high-resolution polygon of the glaciers has been added. Let’s plot these!

[24]:
fig, ax = plt.subplots(figsize=(8, 8))

# Plot the elevation data from the model, masking out nodata values
model.staticmaps.data['land_elevation'].raster.mask_nodata().plot(
    ax=ax,
    cmap=cmap,
    vmin=0,
    vmax=2500,
    cbar_kwargs={'label': 'Elevation [m]', 'shrink': 0.7})

model.geoms.data['basins'].plot(
    ax=ax, facecolor='none', edgecolor='black')
model.geoms.data['rivers'].plot(
    ax=ax, facecolor=None, edgecolor='blue', label='Rivers', linewidth=model.geoms.data['rivers'].strord / 3)
model.geoms.data['meta_reservoirs_no_control'].plot(
    ax=ax, facecolor='lightblue', edgecolor='black', zorder=4, label='Uncontrolled reservoirs')
model.geoms.data['meta_reservoirs_simple_control'].plot(
    ax=ax, facecolor='darkblue', edgecolor='darkblue', zorder=4, label='Controlled reservoirs')
model.geoms.data['glaciers'].plot(
    ax=ax, facecolor='grey', edgecolor='grey', zorder=4, label='Glaciers')
ax.set_xlabel('Longitude [degrees]')
ax.set_ylabel('Latitude [degrees]')
ax.set_title('Basemap of Wflow model')
ax.legend(loc='lower right')
ax.set_aspect('equal');
../_images/_examples_build_model_python_51_0.png

Landuse#

Next, let’s setup the landuse-landcover (LULC) for our Wflow model. This is an important step, as many Wflow input variables are derived based on the landuse-landcover data. There are many different landuse maps available, and you can provide your own landuse map, with your own mapping between landuse classes and Wflow parameters. For several well-known landuse datasets, HydroMT-Wflow has a default mapping available.

[25]:
model.setup_lulcmaps(lulc_fn="corine")

This also adds quite a few layers to our Wflow model. Check-out how many variables our Wflow model already has:

[26]:
print(f'The Wflow model has {len(model.staticmaps.data.keys())} static layers.')
The Wflow model has 51 static layers.

Leaf area index#

Next, we will add the leaf area index (LAI). We don’t use a static LAI, but rather make use of a LAI climatology. That is to say, every month [1, 2, 3, …, 12] gets a separate LAI.

[27]:
model.setup_laimaps(lai_fn="modis_lai")

Because we have a separate value per month, the LAI that has been added to our Wflow model has 3 dimensions: x, y, and time, whereas other variables so far just had two dimensions (x and y). Nevertheless, we group the LAI under the “static” maps of our Wflow model.

[28]:
model.staticmaps.data['vegetation_leaf_area_index']
[28]:
<xarray.DataArray 'vegetation_leaf_area_index' (time: 12, y: 107, x: 116)> Size: 596kB
dask.array<where, shape=(12, 107, 116), dtype=float32, chunksize=(12, 107, 116), chunktype=numpy.ndarray>
Coordinates:
  * time         (time) int32 48B 1 2 3 4 5 6 7 8 9 10 11 12
  * y            (y) float64 856B 46.69 46.68 46.67 46.66 ... 45.82 45.81 45.8
  * x            (x) float64 928B 11.78 11.79 11.8 11.8 ... 12.72 12.73 12.74
    spatial_ref  int64 8B 0
Attributes:
    AREA_OR_POINT:   Area
    category:        landuse & landcover
    notes:           this dataset has been extracted from GEE ('MODIS/006/MCD...
    paper_doi:       10.5067/MODIS/MCD15A3H.006
    paper_ref:       Myneni et al (2015)
    source_license:  https://lpdaac.usgs.gov/data/data-citation-and-policies/
    source_url:      https://lpdaac.usgs.gov/products/mcd15a3hv006/
    source_version:  MCD15A3H V006
    _FillValue:      nan

Let’s have a quick look:

[29]:
lai = model.staticmaps.data["vegetation_leaf_area_index"]

fig, axes = plt.subplots(4, 3, figsize=(10, 10))
axes = axes.flatten()

for i in range(12):
    im = lai.isel(time=i).plot(
        ax=axes[i],
        add_colorbar=False,
        cmap="YlGn",
        vmin=0, vmax=5,
    )

    axes[i].set_title(f"Month {i+1}")
    axes[i].set_xlabel("")
    axes[i].set_ylabel("")
    axes[i].set_xticks([])
    axes[i].set_yticks([])
    axes[i].set_aspect("equal")

cbar = fig.colorbar(
    im,
    ax=axes,
    shrink=0.7,
    label="Leaf Area Index [m2/m2]",
)

plt.show()
../_images/_examples_build_model_python_61_0.png

Soil maps#

Next, let’s setup the soilmaps. For this, we often use the SoilGrids dataset. Quite a few Wflow input parameters are derived based on this step! HydroMT-Wflow will use various pedo-transfer functions (PTF) to estimate these parameters, based on the soil composition. For the hydraulic conductivity, you can even choose which PTF you want to use!

[30]:
model.setup_soilmaps(soil_fn="soilgrids",
                     ptf_ksatver='brakensiek')

Our model has now even more layers in the staticmaps! However, note how our forcings are still empty, as we still haven’t added them.

[31]:
print(f'The Wflow model has {len(model.staticmaps.data.keys())} '
      f'static layers and {len(model.forcing.data.keys())} forcing layers.')
The Wflow model has 67 static layers and 0 forcing layers.

Meteorological forcings#

Let’s add some meteorological forcings to our model. Wflow requires three meteorological forcings: precipitation, temperature, and potential evapotranspiration.

Let’s start with the precipitation. We will use a dataset from our data catalog, but you could very easily use your own dataset here.

[32]:
model.setup_precip_forcing(precip_fn="chirps_global")

Let’s take a look at the average precipitation!

[33]:
start = model.forcing.data["time"][0].dt.strftime("%Y-%m-%d").item()
end = model.forcing.data["time"][-1].dt.strftime("%Y-%m-%d").item()

model.forcing.data["precip"].mean(dim="time").plot(
    cbar_kwargs={"label": "Mean precipitation [mm/day]"}
)
plt.title(f"Mean precipitation between {start} and {end}")
[33]:
Text(0.5, 1.0, 'Mean precipitation between 2010-02-02 and 2010-02-10')
../_images/_examples_build_model_python_69_1.png
[34]:
plt.bar(model.forcing.data['precip'].time,
        model.forcing.data['precip'].mean(dim=['x', 'y']),
        color='blue')
plt.ylabel('Mean precipitation [mm/day]')
plt.xticks(rotation=45);
plt.title('Spatially mean precipitation CHIRPS')
[34]:
Text(0.5, 1.0, 'Spatially mean precipitation CHIRPS')
../_images/_examples_build_model_python_70_1.png

The spatial resolution of our precipitation dataset is coarser than our model resolution. Nevertheless, the precipitation data will be stored at model resolution.

You can try out a few different precipitation datasets available in the artifact data, and see what their resolution is, and how they compare spatially and temporally for this region and time period. Choosing the right precipitation dataset for your Wflow model is important, so take your time for this step!

When it comes to precipitation, we always have to be a bit careful about the units. Precipitation is given in mm per timestep, in our case in mm/day. When setting up a Wflow model with HydroMT-Wflow, it is important to always check things like these, and confirm that the model makes sense.

We can now add the potential evapotranspiration (PET) and the temperature. These are derived in the same workflow, as the PET depends directly on the air temperature.

For the temperature, we can correct the temperature using the elevation lapse rate. For the PET, HydroMT-Wflow assumes the PET needs to be derived from other meteorological data, as direct PET data is often not available. There are multiple methods available to compute the PET, and the meteo variables required depend on the method chosen. Note that which method you choose also has a large effect on the eventual PET, so think carefully about this step.

Here, we will use the ERA5 dataset to derive the temperature and PET. The De Bruin method will be used to estimate the PET. The De Bruin method requires pressure, short wave incoming radiation, and TOA incident solar radiation. Just like the temperature, we can use an elevation lapse rate to correct the pressure.

For the lapse rate correction, it can help to provide a separate DEM, that has the same resolution as our original meteo data. However, if this is not provided, HydroMT-Wflow will fallback on the model DEM.

[35]:
model.setup_temp_pet_forcing(
    temp_pet_fn='era5',
    pet_method='debruin',
    temp_correction=True,
    press_correction=True,
    lapse_rate=-0.0065,
    dem_forcing_fn='era5_orography'
)

Let’s take a look at the added temperature and PET!

[36]:
fig, axes = plt.subplots(2, 1, figsize=(8, 10))

# Temperature
model.forcing.data["temp"].mean(dim="time").plot(
    ax=axes[0],
    cbar_kwargs={"label": "Mean temperature [°C]"},
    vmin=-10,
    vmax=10,
    cmap="RdYlBu_r",
)
axes[0].set_title(f"Mean temperature between {start} and {end}")

# PET
model.forcing.data["pet"].mean(dim="time").plot(
    ax=axes[1],
    cbar_kwargs={"label": "Mean PET [mm/day]"},
    cmap='cividis'
)
axes[1].set_title(f"Mean PET between {start} and {end}")

axes[0].set_aspect('equal')
axes[1].set_aspect('equal')

plt.tight_layout()
plt.show()
../_images/_examples_build_model_python_76_0.png

ERA5 actually has quite a coarse resolution of 0.25 degrees. Nevertheless, due to the lapse rate correction, you can’t directly see this in the resulting temperature and PET data. However, if you look carefully you can still see the outlines of the original ERA5 grid cells!

Add model outlet and gauges#

Wflow can output many, many different variables. If we are interested in a certain variable, we could of course have Wflow write output for that variable for every single grid cell. However, that is quite data intensive, and we are often interested in specific locations or areas. For this, we can make use of gauges in Wflow.

These are not necessarily actual gauges, but just points of interest in our model. We can have Wflow write model output for a variable at these gauges. This is for example handy when we are interested in river discharge at a specific location in our basin.

We can also derive the corresponding subcatchments from our model gauges. For these subcatchments, we can subsequently have Wflow write spatially aggregated data. For example, we could have Wflow write the mean/min/max groundwater recharge for each subcatchment.

With HydroMT-Wflow, we can add these handy gauges to our Wflow model. One “gauge” that we always want to include is the outlet of our model. Let’s start with that.

[37]:
model.setup_outlets()

However, we might also be interested in some locations within our model domain. As an example, let’s say we are interested in the locations defined in test_stations.csv:

[38]:
df_gauges = pd.read_csv("test_stations.csv").drop(columns='uparea')
df_gauges
[38]:
ID Name x y
0 1001 Gauge1 11.9594 45.8925
1 1002 Gauge2 12.3395 46.1492
2 1003 Gauge3 12.0785 46.1122

Let’s add these locations to our Wflow model as well. We can enforce that every gauge should be snapped to a river cell. Let’s also derive the corresponding subcatchment for each gauge.

[39]:
model.setup_gauges(gauges_fn="test_stations.csv",
                   snap_to_river=True,
                   derive_subcatch=True)

Let’s have a look at the resulting model!

[40]:
fig, ax = plt.subplots(figsize=(8, 8))

# Plot the elevation data from the model, masking out nodata values
model.staticmaps.data['land_elevation'].raster.mask_nodata().plot(
    ax=ax,
    cmap=cmap,
    vmin=0,
    vmax=2500,
    cbar_kwargs={'label': 'Elevation [m]', 'shrink': 0.7})

model.geoms.data['basins'].plot(
    ax=ax, facecolor='none', edgecolor='black')
model.geoms.data['subcatchment_test-stations'].plot(
    ax=ax, facecolor='none', edgecolor='black')
model.geoms.data['rivers'].plot(
    ax=ax, facecolor=None, edgecolor='blue', label='Rivers', linewidth=model.geoms.data['rivers'].strord / 3)
model.geoms.data['meta_reservoirs_no_control'].plot(
    ax=ax, facecolor='lightblue', edgecolor='black', zorder=4, label='Uncontrolled reservoirs')
model.geoms.data['meta_reservoirs_simple_control'].plot(
    ax=ax, facecolor='darkblue', edgecolor='darkblue', zorder=4, label='Controlled reservoirs')
model.geoms.data['glaciers'].plot(
    ax=ax, facecolor='grey', edgecolor='grey', zorder=4, label='Glaciers')
model.geoms.data['gauges_test-stations'].plot(
    ax=ax, facecolor='orange', marker="^", zorder=4, label='Gauges')
model.geoms.data['outlets'].plot(
    ax=ax, facecolor='red', marker="o", zorder=4, label='Outlet')
ax.set_xlabel('Longitude [degrees]')
ax.set_ylabel('Latitude [degrees]')
ax.set_title('Basemap of Wflow model')
ax.legend(loc='lower right')
ax.set_aspect('equal');
../_images/_examples_build_model_python_85_0.png

Notice also the delineated subcatchments. For each gauge (including the outlet) we can have Wflow output point data, for example the river discharge at that location to a CSV or to a scalar netCDF. Furthermore, for each subcatchment (as well as the entire model domain), we can have Wflow output spatially aggregated data, for example the average actual evapotranspiration per subcatchment.

Constant parameters#

We are almost done setting up our Wflow model. There are still some Wflow input parameters we haven’t added yet. For some parameters, we might not have any available data. Or, if a parameter can be estimated based on other data, we might not have the required auxiliary data available.

For these parameters we can set a constant value for the entire model domain. Nevertheless, each constant parameter is still added as 2D layer, with a value per grid cell.

[41]:
model.setup_constant_pars(
      subsurface_water__horizontal_to_vertical_saturated_hydraulic_conductivity_ratio=100,
      snowpack__degree_day_coefficient=3.75653,
      soil_surface_water__infiltration_reduction_parameter=0.038,
      vegetation_canopy_water__mean_evaporation_to_mean_precipitation_ratio=0.11,
      compacted_soil_surface_water__infiltration_capacity=10,
      soil_water_saturated_zone_bottom__max_leakage_volume_flux=0,
      soil_wet_root__sigmoid_function_shape_parameter=-500,
      atmosphere_air__snowfall_temperature_threshold=0,
      atmosphere_air__snowfall_temperature_interval=2,
      snowpack__melting_temperature_threshold=0,
      snowpack__liquid_water_holding_capacity=0.1,
      glacier_ice__degree_day_coefficient=3,
      glacier_firn_accumulation__snowpack_dry_snow_leq_depth_fraction=0.001,
      glacier_ice__melting_temperature_threshold=0)

Writing our model to disk#

We are finished setting up our model. At the start, we had set the model root to ./wflow_test_python_full, but you might have noticed that this directory is still empty (save for perhaps some data HydroMT-Wflow downloaded for the reservoirs). That is because our entire model is still in memory. As a final step, let’s write our model to disk.

[42]:
model.write()
[########################################] | 100% Completed | 101.53 ms

For such a small model as this one, it will be pretty quick, but for larger model it might take a bit longer. Especially for models with a long temporal domain, writing the forcing data can take a while.

You should now see several files in your model root, such as the staticmaps.nc (containing the static data), the inmaps.nc (containing forcing data), wflow_sbm.toml (setting of the model), hydromt_data.yml (a data catalog containing the data we used to build the model), and a directory with the model geometries (/staticgeoms). You can now run your model!