WflowBaseModel#

The WflowBaseModel class provides core methods and components shared by all Wflow models.

WflowBaseModel([root, config_filename, ...])

Base Class for all Wflow Model implementations.

High level and I/O methods#

WflowBaseModel.build(*[, write])

Single method to build a model from scratch based on settings in steps.

WflowBaseModel.update(*[, model_out, write, ...])

Single method to update a model based the settings in steps.

WflowBaseModel.read([config_filename, ...])

Read components from disk.

WflowBaseModel.write([config_filename, ...])

Write the complete model schematization and configuration to file.

Attributes#

WflowBaseModel.crs

Returns coordinate reference system embedded in region.

WflowBaseModel.root

Model root

WflowBaseModel.flwdir

Return the pyflwdir.FlwdirRaster object parsed from wflow ldd.

WflowBaseModel.basins

Returns a basin(s) geometry as a geopandas.GeoDataFrame.

WflowBaseModel.rivers

Return a river geometry as a geopandas.GeoDataFrame.

Setup methods#

WflowBaseModel.setup_config(data)

Set the config dictionary at key(s) with values.

WflowBaseModel.setup_config_output_timeseries(mapname)

Set the default gauge map based on basin outlets.

WflowBaseModel.setup_basemaps(region, ...[, ...])

Build the DEM and flow direction for a Wflow model.

WflowBaseModel.setup_rivers(hydrography_fn)

Set all river parameter maps.

WflowBaseModel.setup_riverwidth([predictor, ...])

Set the river width parameter based on power-law relationship with a predictor.

WflowBaseModel.setup_lulcmaps(lulc_fn, *[, ...])

Derive several wflow maps based on landuse-landcover (LULC) data.

WflowBaseModel.setup_lulcmaps_from_vector(...)

Derive several wflow maps based on vector landuse-landcover (LULC) data.

WflowBaseModel.setup_outlets([river_only, ...])

Set the default gauge map based on basin outlets.

WflowBaseModel.setup_gauges(gauges_fn[, ...])

Set a gauge map based on gauges_fn data.

WflowBaseModel.setup_constant_pars(**kwargs)

Generate constant parameter maps for all active model cells.

WflowBaseModel.setup_grid_from_raster(...[, ...])

Add data variable(s) from raster_fn to grid object.

WflowBaseModel.setup_areamap(area_fn, col2raster)

Set area map from vector data to save wflow outputs for specific area.

class WflowBaseModel(root: str | None = None, config_filename: str | None = None, mode: str = 'w', data_libs: list[str] | str | None = None, **catalog_keys)[source]

Bases: Model

Base Class for all Wflow Model implementations.

DO NOT USE THIS CLASS DIRECTLY. ONLY USE SUBCLASSES OF THIS CLASS.

It provides common functionality (IO, components and workflows). Any specific implementation details for either sediment of sbm should be handled in the derived classes.

Parameters:
  • root (str, optional) – Model root, by default None (current working directory)

  • config_filename (str, optional) – A path relative to the root where the configuration file will be read and written if user does not provide a path themselves. By default “wflow.toml”

  • mode ({'r','r+','w'}, optional) – read/append/write mode, by default “w”

  • data_libs (list[str] | str, optional) – List of data catalog configuration files, by default None

  • **catalog_keys – Additional keyword arguments to be passed down to the DataCatalog.

name: str = 'wflow'
property config: WflowConfigComponent

Return the config component.

property forcing: WflowForcingComponent

Return the forcing component.

property geoms: WflowGeomsComponent

Return the geoms component.

property states: WflowStatesComponent

Return the states component.

property staticmaps: WflowStaticmapsComponent

Return the staticmaps component.

property tables: WflowTablesComponent

Return the WflowTablesComponent instance.

property output_grid: WflowOutputGridComponent

Return the WflowOutputGridComponent instance.

property output_scalar: WflowOutputScalarComponent

Return the WflowOutputScalarComponent instance.

property output_csv: WflowOutputCsvComponent

Return the WflowOutputCsvComponent instance.

setup_config(data: dict[str, Any])[source]

Set the config dictionary at key(s) with values.

Parameters:

data (dict[str, Any]) – A dictionary with the values to be set. keys can be dotted like in set()

Examples

Setting data as a nested dictionary:

>> self.setup_config({'a': 1, 'b': {'c': {'d': 2}}})
>> self.config.data
{'a': 1, 'b': {'c': {'d': 2}}}

Setting data using dotted notation:

>> self.setup_config({'a.d.f.g': 1, 'b': {'c': {'d': 2}}})
>> self.config.data
{'a': {'d':{'f':{'g': 1}}}, 'b': {'c': {'d': 2}}}
setup_config_output_timeseries(mapname: str, toml_output: str | None = 'csv', header: list[str] | None = ['river_q'], param: list[str] | None = ['river_water__volume_flow_rate'], reducer: list[str] | None = None)[source]

Set the default gauge map based on basin outlets.

Adds model layers:

  • csv.column config: csv timeseries to save based on mapname locations

  • netcdf.variable config: netcdf timeseries to save based on mapname locations

Required setup methods:

Parameters:
  • mapname (str) – Name of the gauge map (in staticmaps.nc) to use for scalar output.

  • toml_output (str, optional) – One of [‘csv’, ‘netcdf_scalar’, None] to update [output.csv] or [output.netcdf_scalar] section of wflow toml file or do nothing. By default, ‘csv’.

  • header (list, optional) – Save specific model parameters in csv section. This option defines the header of the csv file. By default saves river_q (for river_water__volume_flow_rate).

  • param (list, optional) – Save specific model parameters in csv section. This option defines the wflow variable corresponding to the names in gauge_toml_header. By default saves river_water__volume_flow_rate (for river_q).

  • reducer (list, optional) – If map is an area rather than a point location, provides the reducer for the parameters to save. By default None.

setup_basemaps(region: dict, hydrography_fn: str | Dataset, basin_index_fn: str | Dataset | None = None, res: float | int = 0.008333333333333333, upscale_method: str = 'ihu', output_names: dict = {'basin__local_drain_direction': 'local_drain_direction', 'land_surface__slope': 'land_slope', 'subbasin_location__count': 'subcatchment'})[source]

Build the DEM and flow direction for a Wflow model.

Setup basemaps sets the region of interest and res (resolution in degrees) of the model. All DEM and flow direction related maps are then build.

We strongly recommend using the region types basin or subbasin to build a wflow model. If you know what you are doing, you can also use the bbox region type (e.g for an island) with the bbox coordinates in EPSG 4326 or the geom region type (e.g. basin polygons have been pre-processed and match EXACTLY with hydrography_fn).

E.g. of region argument for a subbasin based on a point and snapped using upstream area threshold in hydrography_fn, where the maximum boundary box of the output subbasin is known: region = {‘subbasin’: [x,y], ‘uparea’: 10, ‘bounds’: [xmin, ymin, xmax, ymax]}

(Sub)Basin delineation is done using hydromt.workflows.get_basin_geometry method. Because the delineation is computed from the flow direction data in memory, to avoid memory error when using large datasets in hydrography_fn, the user can either supply ‘bounds’ in region or a basin index dataset in basin_index_fn to limit the flow direction data to the region of interest. The basin index dataset is a GeoDataframe containing either basins polygons or bounding boxes of basin boundaries. To select the correct basins, basin ID ‘basins’ in hydrography_fn and basin_index_fn should match.

If the model resolution is larger than the source data resolution, the flow direction is upscaled using the upscale_method, by default the Iterative Hydrography Upscaling (IHU).

The default hydrography_fn is “merit_hydro” (MERIT hydro at 3 arcsec resolution). Alternative sources include “merit_hydro_1k” at 30 arcsec resolution. Users can also supply their own elevation and flow direction data in any CRS and not only EPSG:4326. The ArcGIS D8 convention is supported (see also PyFlwDir documentation <https://deltares.github.io/pyflwdir/latest/_examples/flwdir.html>).

Note that in order to define the region, using points or bounding box, the coordinates of the points / bounding box should be in the same CRS than the hydrography data. The wflow model will then also be in the same CRS than the hydrography data in order to avoid assumptions and reprojection errors. If the user wishes to use a different CRS, we recommend first to reproject the hydrography data separately, before calling hydromt build. You can find examples on how to reproject or prepare hydrography data in the prepare flow directions example notebook.

Adds model layers:

  • local_drain_direction map: flow direction in LDD format [-]

  • subcatchment map: basin ID map [-]

  • meta_upstream_area map: upstream area [km2]

  • meta_streamorder map: Strahler stream order [-]

  • land_elevation map: average elevation [m+REF]

  • meta_subgrid_elevation map: subgrid outlet elevation [m+REF]

  • land_slope map: average land surface slope [m/m]

  • basins geom: basins boundary vector

  • region geom: region boundary vector

Parameters:
  • region (dict) – Dictionary describing region of interest. See hydromt.workflows.basin_mask.parse_region() for all options

  • hydrography_fn (str, xarray.Dataset) –

    Name of RasterDataset source for basemap parameters.

    • Required variables: ‘flwdir’ [LLD or D8 or NEXTXY], ‘elevtn’ [m+REF]

    • Required variables if used with basin_index_fn: ‘basins’ [-]

    • Required variables if used for snapping in region: ‘uparea’ [km2],

      ’strord’ [-]

    • Optional variables: ‘lndslp’ [m/m], ‘mask’ [bool]

  • basin_index_fn (str, geopandas.GeoDataFrame, optional) –

    Name of GeoDataFrame source for basin_index data linked to hydrography_fn.

    • Required variables: ‘basid’ [-]

  • res (float, optional) – Output model resolution

  • upscale_method ({'ihu', 'eam', 'dmm'}, optional) – Upscaling method for flow direction data, by default ‘ihu’.

  • output_names (dict, optional) – Dictionary with output names that will be used in the model netcdf input files. Users should provide the Wflow.jl variable name followed by the name in the netcdf file.

See also

hydromt.workflows.parse_region, hydromt.workflows.get_basin_geometry, workflows.hydrography, workflows.topography

setup_rivers(hydrography_fn: str | Dataset, river_geom_fn: str | GeoDataFrame | None = None, river_upa: float = 30, slope_len: float = 2000.0, min_rivlen_ratio: float = 0.0, smooth_len: float = 5000.0, min_rivwth: float = 30, rivdph_method: str | None = 'powlaw', min_rivdph: float = 1, output_names: dict = {'river__depth': 'river_depth', 'river__length': 'river_length', 'river__slope': 'river_slope', 'river__width': 'river_width', 'river_location__mask': 'river_mask'})[source]

Set all river parameter maps.

The river mask is defined by all cells with a minimum upstream area threshold river_upa [km2].

The river length is defined as the distance from the subgrid outlet pixel to the next upstream subgrid outlet pixel. The min_rivlen_ratio is the minimum global river length to avg. cell resolution ratio and is used as a threshold in window-based smoothing of river length.

The river slope is derived from the subgrid elevation difference between pixels at a half distance slope_len [m] up- and downstream from the subgrid outlet pixel.

The river width is derived from the nearest river segment in river_geom_fn. Data gaps are filled by the nearest valid upstream value and averaged along the flow directions over a length smooth_len [m].

Optionally, river depth is derived using rivdph_method if provided (default is “powlaw”). Data gaps are filled similarly to river width.

Adds model layers:

  • wflow_river map: river mask [-]

  • river_length map: river length [m]

  • river_width map: river width [m]

  • river_slope map: river slope [m/m]

  • river_depth map: river depth [m] (if rivdph_method is not None)

  • rivers geom: river vector based on wflow_river mask

Required setup methods:

Parameters:
  • hydrography_fn (str, Path, xarray.Dataset) –

    Name of RasterDataset source for hydrography data. Must be same as setup_basemaps for consistent results.

    • Required variables: ‘flwdir’ [LLD or D8 or NEXTXY], ‘uparea’ [km2], ‘elevtn’ [m+REF]

    • Optional variables: ‘rivwth’ [m]

  • river_geom_fn (str, Path, geopandas.GeoDataFrame, optional) –

    Name of GeoDataFrame source for river data.

    • Required variables: ‘rivwth’ [m]

  • river_upa (float, optional) – Minimum upstream area threshold for the river map [km2]. By default 30.0

  • slope_len (float, optional) – Length [km] over which the river slope is calculated. By default 2.0

  • min_rivlen_ratio (float, optional) – Ratio of cell resolution used as a minimum length threshold in a moving window-based smoothing of river length, by default 0.0. The river length smoothing is skipped if min_rivlen_ratio = 0. For details about the river length smoothing, see pyflwdir.FlwdirRaster.smooth_rivlen()

  • smooth_len (float, optional) – Length [m] over which to smooth the output river width and depth, by default 5000.0

  • min_rivwth (float, optional) – Minimum river width [m], by default 30.0

  • rivdph_method (str, optional) – Method for estimating river depth. Default is “powlaw”. Set to None to skip river depth estimation.

  • min_rivdph (float, optional) – Minimum river depth [m], by default 1.0

  • output_names (dict, optional) – Dictionary with output names that will be used in the model netcdf input files. Users should provide the Wflow.jl variable name followed by the name in the netcdf file. By default, includes river mask, length, width, slope, and depth.

setup_riverwidth(predictor: str = 'discharge', fill: bool = False, fit: bool = False, min_wth: float = 1.0, precip_fn: str | DataArray = 'chelsa', climate_fn: str | DataArray = 'koppen_geiger', output_name: str = 'river_width', **kwargs)[source]

Set the river width parameter based on power-law relationship with a predictor.

By default the riverwidth is estimated based on discharge as predictor and used to set the riverwidth globally based on pre-defined power-law parameters per climate class. With fit set to True, the power-law relationships parameters are set on-the-fly. With fill set to True, the estimated river widths are only used to fill gaps in the observed data. Alternative predictor values are precip (accumulated precipitation) and uparea (upstream area). For these predictors values fit default to True. By default the predictor is based on discharge which is estimated through multiple linear regression with precipitation and upstream area per climate zone.

  • river_width map: river width [m]

Parameters:
  • predictor ({"discharge", "precip", "uparea"}) – Predictor used in the power-law equation: width = a * predictor ^ b. Discharge is based on multiple linear regression per climate zone. Precip is based on the 10x the daily average accumulated precipitation [m3/s]. Uparea is based on the upstream area grid [km2]. Other variables, e.g. bankfull discharge, can also be provided if present in the grid

  • fill (bool, optional) – If True (default), use estimate to fill gaps, outliers and lake/res areas in observed width data (if present); if False, set all riverwidths based on predictor (automatic choice if no observations found)

  • fit (bool, optional) – If True, the power-law parameters are fitted on the fly By default True for all but “discharge” predictor. A-priori derived parameters will be overwritten if True.

  • a (float, optional kwarg) – Manual power-law parameters

  • b (float, optional kwarg) – Manual power-law parameters

  • min_wth (float, optional) – Minimum river width, by default 1.0

  • precip_fn (str, xarray.DataArray) – Source of long term precipitation grid if the predictor is set to ‘discharge’ or ‘precip’. By default “chelsa”.

  • climate_fn (str, xarray.DataArray) – Source of long-term climate grid if the predictor is set to ‘discharge’. By default “koppen_geiger”.

  • output_name (str) – The name of the output river__width map.

setup_lulcmaps(lulc_fn: str | DataArray, *, lulc_mapping_fn: str | Path | DataFrame | None = None, lulc_vars: list[str] = ['landuse', 'vegetation_kext', 'land_manning_n', 'soil_compacted_fraction', 'vegetation_root_depth', 'vegetation_leaf_storage', 'vegetation_wood_storage', 'land_water_fraction', 'vegetation_crop_factor', 'vegetation_feddes_alpha_h1', 'vegetation_feddes_h1', 'vegetation_feddes_h2', 'vegetation_feddes_h3_high', 'vegetation_feddes_h3_low', 'vegetation_feddes_h4'], output_names_suffix: str | None = None)[source]

Derive several wflow maps based on landuse-landcover (LULC) data.

Lookup table lulc_mapping_fn columns are converted to lulc classes model parameters based on literature. The data is remapped at its original resolution and then resampled to the model resolution using the average value, unless noted differently.

Currently, if lulc_fn is set to the “vito”, “globcover”, “esa_worldcover” “corine” or “glmnco”, default lookup tables are available and will be used if lulc_mapping_fn is not provided.

Adds model layers:

  • landuse map:

    Landuse class [-]

  • vegetation_kext map:

    Extinction coefficient in the canopy gap fraction equation [-]

  • vegetation_leaf_storage map:

    Specific leaf storage [mm]

  • vegetation_wood_storage map:

    Fraction of wood in the vegetation/plant [-]

  • vegetation_root_depth map:

    Length of vegetation roots [mm]

  • soil_compacted_fraction map:

    The fraction of compacted or urban area per grid cell [-]

  • land_water_fraction map:

    The fraction of open water per grid cell [-]

  • land_manning_n map:

    Manning Roughness [-]

  • vegetation_crop_factor map:

    Crop coefficient [-]

  • vegetation_feddes_alpha_h1 map:

    Root water uptake reduction at soil water pressure head h1 (0 or 1) [-]

  • vegetation_feddes_h1 map:

    Soil water pressure head h1 at which root water uptake is reduced (Feddes) [cm]

  • vegetation_feddes_h2 map:

    Soil water pressure head h2 at which root water uptake is reduced (Feddes) [cm]

  • vegetation_feddes_h3_high map:

    Soil water pressure head h3 (high) at which root water uptake is reduced (Feddes) [cm]

  • vegetation_feddes_h3_low map:

    Soil water pressure head h3 (low) at which root water uptake is reduced (Feddes) [cm]

  • vegetation_feddes_h4 map:

    Soil water pressure head h4 at which root water uptake is reduced (Feddes) [cm]

Required setup methods:

Parameters:
  • lulc_fn (str, xarray.DataArray) – Name of RasterDataset source in data_sources.yml file.

  • lulc_mapping_fn (str, Path, pd.DataFrame) – Path to a mapping csv file from landuse in source name to parameter values in lulc_vars. If lulc_fn is one of {“globcover”, “vito”, “corine”, “esa_worldcover”, “glmnco”}, a default mapping is used and this argument becomes optional.

  • lulc_vars (list[str]) – List of landuse parameters to prepare. The names are the columns of the mapping file. Can be a subset of: [“landuse”, “vegetation_kext”, “land_manning_n”, “soil_compacted_fraction”, “vegetation_root_depth”, “vegetation_leaf_storage”, “vegetation_wood_storage”, “land_water_fraction”, “vegetation_crop_factor”, “vegetation_feddes_alpha_h1”, “vegetation_feddes_h1”, “vegetation_feddes_h2”, “vegetation_feddes_h3_high”, “vegetation_feddes_h3_low”, “vegetation_feddes_h4”]

  • output_names_suffix (str, optional) – Suffix to be added to the output names to avoid having to rename all the columns of the mapping tables. For example if the suffix is “vito”, all variables in lulc_vars will be renamed to “landuse_vito”, “Kext_vito”, etc.

setup_lulcmaps_from_vector(lulc_fn: str | GeoDataFrame, *, lulc_mapping_fn: str | Path | DataFrame | None = None, lulc_vars: list[str] = ['landuse', 'vegetation_kext', 'land_manning_n', 'soil_compacted_fraction', 'vegetation_root_depth', 'vegetation_leaf_storage', 'vegetation_wood_storage', 'land_water_fraction', 'vegetation_crop_factor', 'vegetation_feddes_alpha_h1', 'vegetation_feddes_h1', 'vegetation_feddes_h2', 'vegetation_feddes_h3_high', 'vegetation_feddes_h3_low', 'vegetation_feddes_h4'], lulc_res: float | int | None = None, all_touched: bool = False, buffer: int = 1000, save_raster_lulc: bool = False, output_names_suffix: str | None = None)[source]

Derive several wflow maps based on vector landuse-landcover (LULC) data.

The vector lulc data is first rasterized to a raster map at the model resolution or at a higher resolution specified in lulc_res (recommended).

Lookup table lulc_mapping_fn columns are converted to lulc classes model parameters based on literature. The data is remapped at its original resolution and then resampled to the model resolution using the average value, unless noted differently.

Adds model layers:

  • landuse map:

    Landuse class [-]

  • vegetation_kext map:

    Extinction coefficient in the canopy gap fraction equation [-]

  • vegetation_leaf_storage map:

    Specific leaf storage [mm]

  • vegetation_wood_storage map:

    Fraction of wood in the vegetation/plant [-]

  • vegetation_root_depth map:

    Length of vegetation roots [mm]

  • soil_compacted_fraction map:

    The fraction of compacted or urban area per grid cell [-]

  • land_water_fraction map:

    The fraction of open water per grid cell [-]

  • land_manning_n map: Manning Roughness [-]

  • vegetation_crop_factor map:

    Crop coefficient [-]

  • vegetation_feddes_alpha_h1 map:

    Root water uptake reduction at soil water pressure head h1 (0 or 1) [-]

  • vegetation_feddes_h1 map:

    Soil water pressure head h1 at which root water uptake is reduced (Feddes) [cm]

  • vegetation_feddes_h2 map:

    Soil water pressure head h2 at which root water uptake is reduced (Feddes) [cm]

  • vegetation_feddes_h3_high map:

    Soil water pressure head h3 (high) at which root water uptake is reduced (Feddes) [cm]

  • vegetation_feddes_h3_low map:

    Soil water pressure head h3 (low) at which root water uptake is reduced (Feddes) [cm]

  • vegetation_feddes_h4 map:

    Soil water pressure head h4 at which root water uptake is reduced (Feddes) [cm]

Required setup methods:

Parameters:
  • lulc_fn (str, gpd.GeoDataFrame) –

    GeoDataFrame or name in data catalog / path to (vector) landuse map.

    • Required columns: ‘landuse’ [-]

  • lulc_mapping_fn (str, Path, pd.DataFrame, None, optional) – Path to a mapping csv file from landuse in source name to parameter values in lulc_vars. If lulc_fn is one of {“globcover”, “vito”, “corine”, “esa_worldcover”, “glmnco”}, a default mapping is used and this argument becomes optional.

  • lulc_vars (list[str], optional) – List of landuse parameters to prepare. The names are the columns of the mapping file. Can be a subset of: [“landuse”, “vegetation_kext”, “land_manning_n”, “soil_compacted_fraction”, “vegetation_root_depth”, “vegetation_leaf_storage”, “vegetation_wood_storage”, “land_water_fraction”, “vegetation_crop_factor”, “vegetation_feddes_alpha_h1”, “vegetation_feddes_h1”, “vegetation_feddes_h2”, “vegetation_feddes_h3_high”, “vegetation_feddes_h3_low”, “vegetation_feddes_h4”]

  • lulc_res (float, int, None, optional) – Resolution of the intermediate rasterized landuse map. The unit (meter or degree) depends on the CRS of lulc_fn (projected or not). By default None, which uses the model resolution.

  • all_touched (bool, optional) – If True, all pixels touched by the vector will be burned in the raster, by default False.

  • buffer (int, optional) – Buffer around the bounding box of the vector data to ensure that all landuse classes are included in the rasterized map, by default 1000.

  • save_raster_lulc (bool, optional) – If True, the (high) resolution rasterized landuse map will be saved to maps/landuse_raster.tif, by default False.

  • output_names_suffix (str, None, optional) – Suffix to be added to the output names to avoid having to rename all the columns of the mapping tables. For example if the suffix is “vito”, all variables in lulc_vars will be renamed to “landuse_vito”, “Kext_vito”, etc.

See also

workflows.landuse_from_vector

setup_outlets(river_only: bool = True, toml_output: str = 'csv', gauge_toml_header: list[str] = ['river_q'], gauge_toml_param: list[str] = ['river_water__volume_flow_rate'])[source]

Set the default gauge map based on basin outlets.

If the subcatchment map is available, the catchment outlets IDs will be matching the subcatchment IDs. If not, then IDs from 1 to number of outlets are used.

Can also add csv/netcdf_scalar output settings in the TOML.

Adds model layers:

  • outlets map: IDs map from catchment outlets [-]

  • outlets geom: polygon of catchment outlets

Required setup methods:

Parameters:
  • river_only (bool, optional) – Only derive outlet locations if they are located on a river instead of locations for all catchments, by default True.

  • toml_output (str, optional) – One of [‘csv’, ‘netcdf_scalar’, None] to update [output.csv] or [output.netcdf_scalar] section of wflow toml file or do nothing. By default, ‘csv’.

  • gauge_toml_header (list, optional) – Save specific model parameters in csv section. This option defines the header of the csv file. By default saves river_q (for river_water__volume_flow_rate).

  • gauge_toml_param (list, optional) – Save specific model parameters in csv section. This option defines the wflow variable corresponding to the names in gauge_toml_header. By default saves river_water__volume_flow_rate (for river_q).

setup_gauges(gauges_fn: str | Path | GeoDataFrame, index_col: str | None = None, snap_to_river: bool = True, mask: ndarray | None = None, snap_uparea: bool = False, max_dist: float = 10000.0, wdw: int = 3, rel_error: float = 0.05, abs_error: float = 50.0, fillna: bool = False, derive_subcatch: bool = False, basename: str | None = None, toml_output: str = 'csv', gauge_toml_header: list[str] = ['river_q', 'precip'], gauge_toml_param: list[str] = ['river_water__volume_flow_rate', 'atmosphere_water__precipitation_volume_flux'], **kwargs)[source]

Set a gauge map based on gauges_fn data.

Supported gauge datasets include data catlog entries, direct GeoDataFrame or “<path_to_source>” for user supplied csv or geometry files with gauge locations. If a csv file is provided, a “x” or “lon” and “y” or “lat” column is required and the first column will be used as IDs in the map.

There are four available methods to prepare the gauge map:

  • no snapping: mask=None, snap_to_river=False, snap_uparea=False. The gauge locations are used as is.

  • snapping to mask: the gauge locations are snapped to a boolean mask map based on the closest dowsntream cell within the mask: either provide mask or set snap_to_river=True to snap to the river cells (default). max_dist can be used to set the maximum distance to snap to the mask.

  • snapping based on upstream area matching: : snap_uparea=True. The gauge locations are snapped to the closest matching upstream area value. Requires gauges_fn to have an uparea [km2] column. The closest value will be looked for in a cell window of size wdw and the absolute and relative differences between the gauge and the closest value should be smaller than abs_error and rel_error.

  • snapping based on upstream area matching and mask: snap_uparea=True, mask or snap_to_river=True. The gauge locations are snapped to the closest matching upstream area value within the mask.

If derive_subcatch is set to True, an additional subcatch map is derived from the gauge locations.

Finally the output locations can be added to wflow TOML file sections [output.csv] or [output.netcdf_scalar] using the toml_output option. The gauge_toml_header and gauge_toml_param options can be used to define the header and corresponding wflow variable names in the TOML file.

Adds model layers:

  • gauges_source map: gauge IDs map from source [-] (if gauges_fn)

  • subcatchment_source map: subcatchment based on gauge locations [-] (if derive_subcatch)

  • gauges_source geom: polygon of gauges from source

  • subcatchment_source geom: polygon of subcatchment based on gauge locations [-] (if derive_subcatch)

Required setup methods:

Parameters:
  • gauges_fn (str, Path, geopandas.GeoDataFrame) –

    Catalog source name, path to gauges file geometry file or geopandas.GeoDataFrame.

    • Required variables if snap_uparea is True: ‘uparea’ [km2]

  • index_col (str, optional) – Column in gauges_fn to use for ID values, by default None (use the default index column)

  • mask (np.boolean, optional) – If provided snaps to the mask, else snaps to the river (default).

  • snap_to_river (bool, optional) – Snap point locations to the closest downstream river cell, by default True

  • snap_uparea (bool, optional) – Snap gauges based on upstream area. Gauges_fn should have “uparea” in its attributes.

  • max_dist (float, optional) – Maximum distance [m] between original and snapped point location. A warning is logged if exceeded. By default 10 000m.

  • wdw (int, optional) – Window size in number of cells around the gauge locations to snap uparea to, only used if snap_uparea is True. By default 3.

  • rel_error (float, optional) – Maximum relative error (default 0.05) between the gauge location upstream area and the upstream area of the best fit grid cell, only used if snap_uparea is True.

  • abs_error (float, optional) – Maximum absolute error (default 50.0) between the gauge location upstream area and the upstream area of the best fit grid cell, only used if snap_uparea is True.

  • fillna (bool, optional) – Fill missing values in the gauges uparea column with the values from wflow upstream area (ie no snapping). By default False and the gauges with NaN values are skipped.

  • derive_subcatch (bool, optional) – Derive subcatch map for gauges, by default False

  • basename (str, optional) – Map name in grid (gauges_basename) if None use the gauges_fn basename.

  • toml_output (str, optional) – One of [‘csv’, ‘netcdf_scalar’, None] to update [output.csv] or [output.netcdf_scalar] section of wflow toml file or do nothing. By default, ‘csv’.

  • gauge_toml_header (list, optional) – Save specific model parameters in csv section. This option defines the header of the csv file. By default saves river_q (for river_water__volume_flow_rate) and precip (for “atmosphere_water__precipitation_volume_flux”).

  • gauge_toml_param (list, optional) – Save specific model parameters in csv section. This option defines the wflow variable corresponding to the names in gauge_toml_header. By default saves river_water__volume_flow_rate (for river_q) and “atmosphere_water__precipitation_volume_flux” (for precip).

  • kwargs (dict, optional) – Additional keyword arguments to pass to the get_data method ie get_geodataframe or get_geodataset depending on the data_type of gauges_fn.

setup_constant_pars(**kwargs)[source]

Generate constant parameter maps for all active model cells.

Adds model layer:

  • param_name map: constant parameter map.

Parameters:
  • dtype (str) – data type

  • nodata (int or float) – nodata value

  • kwargs – “param_name: value” pairs for constant grid. Param_name should be the Wflow.jl variable name.

setup_grid_from_raster(raster_fn: str | Dataset, reproject_method: str, variables: list[str] | None = None, wflow_variables: list[str] | None = None, fill_method: str | None = None) None[source]

Add data variable(s) from raster_fn to grid object.

If raster is a dataset, all variables will be added unless variables list is specified. The config toml can also be updated to include the new maps using wflow_variables.

Adds model layers:

  • raster.name or variables grid: data from raster_fn

Parameters:
  • raster_fn (str) – Source name of RasterDataset in data_catalog.

  • reproject_method (str) – Reprojection method from rasterio.enums.Resampling. Available methods: [‘nearest’, ‘bilinear’, ‘cubic’, ‘cubic_spline’, ‘lanczos’, ‘average’, ‘mode’, ‘gauss’, ‘max’, ‘min’, ‘med’, ‘q1’, ‘q3’, ‘sum’, ‘rms’]

  • variables (list, optional) – List of variables to add to grid from raster_fn. By default all.

  • wflow_variables (list, optional) – List of corresponding wflow variables to update the config toml (e.g: [“vegetation_root__depth”]). Should match the variables list. variables list should be provided unless raster_fn contains a single variable (len 1).

  • fill_method (str, optional) – If specified, fills nodata values using fill_nodata method. Available methods are {‘linear’, ‘nearest’, ‘cubic’, ‘rio_idw’}.

setup_areamap(area_fn: str | GeoDataFrame, col2raster: str, nodata: int | float = -1, output_names: dict = {})[source]

Set area map from vector data to save wflow outputs for specific area.

Adds model layer:

  • col2raster map: output area data map

Required setup methods:

Parameters:
  • area_fn (str, geopandas.GeoDataFrame) – Name of GeoDataFrame data corresponding to wflow output area.

  • col2raster (str) – Name of the column from area_fn to rasterize.

  • nodata (int/float, optional) – Nodata value to use when rasterizing. Should match the dtype of col2raster . By default -1.

  • output_names (dict, optional) – Dictionary with output names that will be used in the model netcdf input files. Users should provide the Wflow.jl variable name followed by the name in the netcdf file. If another name is provided than col2raster, this name will be used.

clip(region: dict, inverse_clip: bool = False, clip_forcing: bool = True, clip_states: bool = True, reservoir_maps: dict[str, str | None] = {}, reservoir_states: dict[str, str | None] = {}, crs: int = 4326, **kwargs)[source]

Clip model to region.

First the staticmaps are clipped to the region. Then the staticgeoms are re-generated to match the new grid for basins and rivers and clipped for the others. Finally the forcing and states are clipped to the new grid extent.

Parameters:
  • region (dict) – See models.wflow_base.WflowBaseModel.setup_basemaps()

  • inverse_clip (bool, optional) – Flag to perform “inverse clipping”: removing an upstream part of the model instead of the subbasin itself, by default False

  • clip_forcing (bool, optional) – Flag to clip the forcing to the new grid extent, by default True

  • clip_states (bool, optional) – Flag to clip the states to the new grid extent, by default True

  • reservoir_maps (dict[str, str | None] = {},) – Dictionnary of staticmap names in the wflow model staticmaps and corresponding wflow input variables to be treated as reservoirs. These maps are removed if empty after clipping.

  • reservoir_states (dict[str, str | None] = {},) – Dictionnary of state names in the wflow model states and corresponding wflow state variables to be treated as reservoirs. These states are removed if no reservoir was found after clipping.

  • crs (int, optional) – Default crs of the model in case it cannot be read. By default 4326 (WGS84)

  • **kwargs (dict) – Additional keyword arguments passed to clip_geom()

write(config_filename: str | None = None, grid_filename: str | None = None, geoms_folder: str = 'staticgeoms', forcing_filename: str | None = None, states_filename: str | None = None)[source]

Write the complete model schematization and configuration to file.

From this function, the output filenames/folder of the different components can be set. If not set, the default filenames/folder are used.

To change more advanced settings, use the specific write methods directly.

Parameters:
  • config_filename (str, optional) – Name of the config file, relative to model root. By default None to use the default name.

  • grid_filename (str, optional) – Name of the grid file, relative to model root/dir_input. By default None to use the name as defined in the model config file.

  • geoms_folder (str, optional) – Name of the geoms folder relative to grid_filename (ie model root/dir_input). By default ‘staticgeoms’.

  • forcing_filename (str, optional) – Name of the forcing file relative to model root/dir_input. By default None to use the name as defined in the model config file.

  • states_filename (str, optional) – Name of the states file relative to model root/dir_input. By default None to use the name as defined in the model config file.

read(config_filename: str | None = None, geoms_folder: str = 'staticgeoms')[source]

Read components from disk.

From this function, the input filenames/folder of the config and geoms components can be set. For the others, the filenames/folder as defined in the config file are used.

To change more advanced settings, use the specific read methods directly.

Parameters:
  • config_filename (str | None, optional) – Name of the config file, relative to model root. By default None to use the default name.

  • geoms_folder (str | None, optional) – Name of the geoms folder relative to grid_filename (ie model root/dir_input). By default ‘staticgeoms’.

set_states(data: DataArray | Dataset, name: str | None = None)[source]

Add data to states.

All layers of states must have identical spatial coordinates. This is an inherited method from HydroMT-core’s StatesModel.set_states with some fixes. If basin data is available the states will be masked to that upon setting.

Parameters:
  • data (xarray.DataArray or xarray.Dataset) – new map layer to add to states

  • name (str, optional) – Name of new map layer, this is used to overwrite the name of a DataArray and ignored if data is a Dataset

read_outputs()[source]

Read outputs at <root/dir_output>.

Reads netcdf_grid at output.netcdf_grid.path, netcdf_scalar at output.netcdf_scalar.path and csv outputs at output.csv.path.

Checks if dir_output is present.

property basins: GeoDataFrame | None

Returns a basin(s) geometry as a geopandas.GeoDataFrame.

property basins_highres: GeoDataFrame | None

Returns a high resolution basin(s) geometry.

property rivers: GeoDataFrame | None

Return a river geometry as a geopandas.GeoDataFrame.

If available, the stream order and upstream area values are added to the geometry properties.

property flwdir: FlwdirRaster

Return the pyflwdir.FlwdirRaster object parsed from wflow ldd.

set_flwdir(ftype='infer')[source]

Parse pyflwdir.FlwdirRaster object parsed from the wflow ldd.

root: ModelRoot

Model root

components: Dict[str, ModelComponent]