meshflow.MESHWorkflow

class meshflow.MESHWorkflow(riv, cat, landcover, landcover_classes, forcing_files=None, forcing_vars=None, forcing_units=None, ddb_vars=None, ddb_units=None, main_id=None, ds_main_id=None, forcing_to_units={'air_pressure': 'pascal', 'air_temperature': 'kelvin', 'longwave_radiation': 'watt / meter ** 2', 'precipitation': 'millimeter / second', 'shortwave_radiation': 'watt / meter ** 2', 'specific_humidity': 'dimensionless', 'wind_speed': 'meter / second'}, forcing_local_attrs={}, forcing_global_attrs={'Conventions': 'CF-1.6', 'author': 'University of Calgary', 'history': 'Created using MESHFlow version v0.2.0-dev', 'license': 'GNU General Public License v3 (or any later version)', 'purpose': 'Create forcing .nc file for MESH'}, ddb_local_attrs={'ChnlLength': {'_FillValue': 'NaN', 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'Segment length'}, 'ChnlSlope': {'_FillValue': 'NaN', 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'Segment slope'}, 'GRU': {'_FillValue': -1.0, 'coordinates': 'lon lat time', 'long_name': 'Group Response Unit', 'standard_name': 'GRU'}, 'GridArea': {'_FillValue': 'NaN', 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'HRU Area'}, 'IAK': {'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'River class number (IAK)', 'standard_name': 'IAK'}, 'LandUse': {'standard_name': 'Landuse classification name'}, 'Next': {'_FillValue': -1.0, 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'Receiving ID', 'standard_name': 'Next'}, 'Rank': {'_FillValue': -1.0, 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'Element ID', 'standard_name': 'Rank'}}, ddb_global_attrs={'author': 'University of Calgary', 'featureType': 'point', 'license': 'GNU General Public License v3 (or any later version)', 'purpose': 'Create a drainage database .nc file for MESH'}, ddb_min_values={'river_length': 0.001, 'river_slope': 0.001, 'subbasin_area': 0.001}, ddb_to_units={'gru': 'dimensionless', 'landclass': 'dimensionless', 'next': 'dimensionless', 'rank': 'dimensionless', 'river_length': 'meter', 'river_slope': 'dimensionless'}, settings=None, gru_dim='NGRU', hru_dim='subbasin', outlet_value=-9999)[source]

Automates the setup of MESH models through a flexible workflow.

This class provides methods to initialize, configure, and save all necessary files for running a MESH hydrological model. It supports configuration via direct Python objects, dictionaries, or JSON files, and handles geospatial, landcover, and meteorological forcing data.

Parameters:
  • riv (str or PathLike) – Path to the river network shapefile or geospatial data file containing river segments.

  • cat (str or PathLike) – Path to the catchment/subbasin shapefile or geospatial data file containing watershed boundaries.

  • landcover (str or PathLike) – Path to the landcover CSV file containing fractional coverage of land classes for each catchment.

  • landcover_classes (dict of {str: str}) – Mapping of landcover class codes/numbers to descriptive class names.

  • forcing_files (str or PathLike, optional) – Path to meteorological forcing files (NetCDF, glob pattern, or directory).

  • forcing_vars (dict of {str: str}, optional) – Mapping of input forcing variable names to MESH standard variable names.

  • forcing_units (dict of {str: str}, optional) – Units of the input forcing variables.

  • ddb_vars (dict of {str: str}, optional) – Mapping of drainage database variable names from input data to MESH standards.

  • ddb_units (dict of {str: str}, optional) – Units of drainage database variables.

  • main_id (str, optional) – Name of the primary identifier field in the catchment and river data.

  • ds_main_id (str, optional) – Name of the downstream segment identifier field in river data.

  • forcing_to_units (dict of {str: str}, optional) – Target units for forcing variables after conversion.

  • forcing_local_attrs (dict of {str: str}, optional) – Local attributes to apply to forcing variables in output files.

  • forcing_global_attrs (dict of {str: str}, optional) – Global attributes to apply to forcing NetCDF files.

  • ddb_local_attrs (dict of {str: str}, optional) – Local attributes to apply to drainage database variables.

  • ddb_global_attrs (dict of {str: str}, optional) – Global attributes to apply to drainage database NetCDF file.

  • ddb_min_values (dict of {str: float}, optional) – Minimum allowable values for drainage database variables.

  • ddb_to_units (dict of {str: str}, optional) – Target units for drainage database variables after conversion.

  • settings (dict, optional) – Comprehensive model configuration dictionary.

  • gru_dim (str, optional) – Dimension name for Group Response Units (land classes) in output files.

  • hru_dim (str, optional) – Dimension name for Hydrologic Response Units (catchments) in output files.

  • outlet_value (int, optional) – Sentinel value used to identify outlet/terminal segments in the river network.

riv

River network data.

Type:

geopandas.GeoDataFrame

cat

Catchment/subbasin data.

Type:

geopandas.GeoDataFrame

landcover

Landcover fractions for each catchment.

Type:

pandas.DataFrame

main_id

Primary identifier field name.

Type:

str

ds_main_id

Downstream segment identifier field name.

Type:

str

outlet_value

Value used to identify outlet segments.

Type:

int

forcing_vars

Mapping of input forcing variable names to MESH standard names.

Type:

dict

forcing_units

Units of input forcing variables.

Type:

dict

forcing_to_units

Target units for forcing variables.

Type:

dict

ddb_vars

Mapping of drainage database variable names.

Type:

dict

ddb_units

Units of drainage database variables.

Type:

dict

ddb_to_units

Target units for drainage database variables.

Type:

dict

ddb_min_values

Minimum allowable values for drainage database variables.

Type:

dict

landcover_classes

Mapping of landcover class codes/numbers to descriptive class names.

Type:

dict

settings

Model configuration dictionary.

Type:

dict

gru_dim

Dimension name for Group Response Units. For MESH versions beyond r1860, the recommended value is ‘NGRU’.

Type:

str

hru_dim

Dimension name for subbasins (Hydrologic Response Units). The default value is ‘subbasin’, but it can be customized.

Type:

str

class_text

Generated CLASS configuration text by the init_class method.

Type:

str

hydrology_text

Generated hydrology configuration text by the init_hydrology method.

Type:

str

run_options_text

Generated run options configuration text by the init_options method.

Type:

str

ddb

Drainage database dataset with catchment attributes and routing information. It is generated by the init_ddb method.

Type:

xarray.Dataset

forcing

Forcing dataset with meteorological variables for each catchment. It is generated by the init_forcing method.

Type:

xarray.Dataset

run(save_path=None)[source]

Run the workflow and prepare a MESH setup. In case of multiple forcing files, each file will be processed and saved during the workflow execution. Therefore, save_path cannot be None.

Parameters:

save_path (str | bytes | PathLike | None)

Return type:

None

init()[source]

Initialize the workflow by necessary variables to start the rest of the setup process.

Return type:

None

init_ddb(return_ds=False, save_path=None)[source]

Initialize the drainage database object.

Return type:

None

init_forcing(save=False, save_path=None)[source]

Initialize the forcing object. If save is True, the forcing files will be processed and saved to the specified save_path. For multiple forcing files, each file must be processed and saved individually, therefore, save_path cannot be None.

Parameters:
Return type:

Dataset | None

init_class(return_text=False)[source]

Initialize the CLASS configuration text for MESH.

Parameters:

return_dict (bool)

Return type:

dict | None

init_hydrology(return_text=False)[source]

Initialize the hydrology configuration text for MESH.

Parameters:
Return type:

dict | None

init_options(return_text=False)[source]

Initialize the run options configuration text for MESH.

Parameters:
Return type:

dict | None

save(output_dir)[source]

Save the drainage database, forcing files, and configuration files to the specified output directory.

from_dict(init_dict)[source]

Instantiate a MESHWorkflow object from a dictionary.

Parameters:

init_dict (Dict)

Return type:

MESHWorkflow

from_json(json_str)[source]

Instantiate a MESHWorkflow object from a JSON string.

Parameters:

json_str (str)

Return type:

MESHWorkflow

from_json_file(json_file)[source]

Instantiate a MESHWorkflow object from a JSON file.

Parameters:

json_file (str)

Return type:

MESHWorkflow

See also

meshflow.utility

Utility functions for geospatial and data processing.

__init__(riv, cat, landcover, landcover_classes, forcing_files=None, forcing_vars=None, forcing_units=None, ddb_vars=None, ddb_units=None, main_id=None, ds_main_id=None, forcing_to_units={'air_pressure': 'pascal', 'air_temperature': 'kelvin', 'longwave_radiation': 'watt / meter ** 2', 'precipitation': 'millimeter / second', 'shortwave_radiation': 'watt / meter ** 2', 'specific_humidity': 'dimensionless', 'wind_speed': 'meter / second'}, forcing_local_attrs={}, forcing_global_attrs={'Conventions': 'CF-1.6', 'author': 'University of Calgary', 'history': 'Created using MESHFlow version v0.2.0-dev', 'license': 'GNU General Public License v3 (or any later version)', 'purpose': 'Create forcing .nc file for MESH'}, ddb_local_attrs={'ChnlLength': {'_FillValue': 'NaN', 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'Segment length'}, 'ChnlSlope': {'_FillValue': 'NaN', 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'Segment slope'}, 'GRU': {'_FillValue': -1.0, 'coordinates': 'lon lat time', 'long_name': 'Group Response Unit', 'standard_name': 'GRU'}, 'GridArea': {'_FillValue': 'NaN', 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'HRU Area'}, 'IAK': {'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'River class number (IAK)', 'standard_name': 'IAK'}, 'LandUse': {'standard_name': 'Landuse classification name'}, 'Next': {'_FillValue': -1.0, 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'Receiving ID', 'standard_name': 'Next'}, 'Rank': {'_FillValue': -1.0, 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'Element ID', 'standard_name': 'Rank'}}, ddb_global_attrs={'author': 'University of Calgary', 'featureType': 'point', 'license': 'GNU General Public License v3 (or any later version)', 'purpose': 'Create a drainage database .nc file for MESH'}, ddb_min_values={'river_length': 0.001, 'river_slope': 0.001, 'subbasin_area': 0.001}, ddb_to_units={'gru': 'dimensionless', 'landclass': 'dimensionless', 'next': 'dimensionless', 'rank': 'dimensionless', 'river_length': 'meter', 'river_slope': 'dimensionless'}, settings=None, gru_dim='NGRU', hru_dim='subbasin', outlet_value=-9999)[source]

Initialize a MESHWorkflow instance for automating MESH model setup.

Parameters:
  • riv (PathLike) – Path to the river network shapefile or geospatial data file containing river segments.

  • cat (PathLike) – Path to the catchment/subbasin shapefile or geospatial data file containing watershed boundaries.

  • landcover (PathLike) – Path to the landcover CSV file containing fractional coverage of land classes for each catchment. Note that currently, only MAF compliant files are supported.

  • landcover_classes (Dict[str, str]) – Mapping of landcover class codes/numbers to descriptive class names.

  • forcing_files (PathLike, optional) – Path to meteorological forcing files (NetCDF, glob pattern, or directory).

  • forcing_vars (Dict[str, str], optional) – Mapping of input forcing variable names to MESH standard variable names.

  • forcing_units (Dict[str, str], optional) – Units of the input forcing variables.

  • ddb_vars (Dict[str, str], optional) – Mapping of drainage database variable names from input data to MESH standards.

  • ddb_units (Dict[str, str], optional) – Units of drainage database variables.

  • main_id (str, optional) – Name of the primary identifier field in the catchment and river data.

  • ds_main_id (str, optional) – Name of the downstream segment identifier field in river data.

  • forcing_to_units (Dict[str, str], optional) – Target units for forcing variables after conversion.

  • forcing_local_attrs (Dict[str, str], optional) – Local attributes to apply to forcing variables in output files.

  • forcing_global_attrs (Dict[str, str], optional) – Global attributes to apply to forcing NetCDF files.

  • ddb_local_attrs (Dict[str, str], optional) – Local attributes to apply to drainage database variables.

  • ddb_global_attrs (Dict[str, str], optional) – Global attributes to apply to drainage database NetCDF file.

  • ddb_min_values (Dict[str, float], optional) – Minimum allowable values for drainage database variables.

  • ddb_to_units (Dict[str, str], optional) – Target units for drainage database variables after conversion.

  • settings (Dict[str, str], optional) – Comprehensive model configuration dictionary. Refer to the documentation for more details.

  • gru_dim (str, optional) – Dimension name for Group Response Units (land classes) in output files. Default is ‘NGRU’.

  • hru_dim (str, optional) – Dimension name for Hydrologic Response Units (catchments) in output files. Default is ‘subbasin’.

  • outlet_value (int, optional) – Sentinel value used to identify outlet/terminal segments in the river network. Default is -9999.

Raises:
  • TypeError – If any of the dictionary parameters are not of type dict.

  • AssertionError – If settings is not a dictionary.

Return type:

None

Methods

__init__(riv, cat, landcover, landcover_classes)

Initialize a MESHWorkflow instance for automating MESH model setup.

check_process_parameters(options_dict[, ...])

Check and process run options parameters for consistency and correctness.

format_date(date_str[, date_format])

Convert a date string to 'yyyymmdd' format, handling various formats

from_dict([init_dict])

Instantiate a MESHWorkflow object from a dictionary.

from_json(json_str)

Instantiate a MESHWorkflow object from a JSON string.

from_json_file(json_file)

Instantiate a MESHWorkflow object from a JSON file.

init()

Initialize the MESH workflow by setting up drainage database and forcing objects

init_class([return_dict])

Generate the CLASS configuration text for the MESH model.

init_ddb([return_ds])

Initialize the drainage database object for the workflow.

init_forcing([save, save_path])

Initialize the forcing object for the MESH workflow.

init_hydrology([return_dict, return_ds, ...])

Generate the hydrology configuration text for the MESH model.

init_options([default_options, return_dict])

Generate the MESH run options configuration text.

init_parameters_ds([return_ds])

Generate the parameters dataset for the MESH model.

maybe_int(x)

render_configs(class_dicts, hydrology_dicts, ...)

Render configuration texts for CLASS, hydrology, and run options.

run([save_path])

Run the workflow and prepare a MESH model setup.

save(output_dir)

Save the drainage database, forcing files, and configuration files to the specified output directory.

Attributes

coords

Calculate and return centroid coordinates (latitude and longitude) for the main object.

forcing_files

Returns the path or glob pattern to the forcing files.

__init__(riv, cat, landcover, landcover_classes, forcing_files=None, forcing_vars=None, forcing_units=None, ddb_vars=None, ddb_units=None, main_id=None, ds_main_id=None, forcing_to_units={'air_pressure': 'pascal', 'air_temperature': 'kelvin', 'longwave_radiation': 'watt / meter ** 2', 'precipitation': 'millimeter / second', 'shortwave_radiation': 'watt / meter ** 2', 'specific_humidity': 'dimensionless', 'wind_speed': 'meter / second'}, forcing_local_attrs={}, forcing_global_attrs={'Conventions': 'CF-1.6', 'author': 'University of Calgary', 'history': 'Created using MESHFlow version v0.2.0-dev', 'license': 'GNU General Public License v3 (or any later version)', 'purpose': 'Create forcing .nc file for MESH'}, ddb_local_attrs={'ChnlLength': {'_FillValue': 'NaN', 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'Segment length'}, 'ChnlSlope': {'_FillValue': 'NaN', 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'Segment slope'}, 'GRU': {'_FillValue': -1.0, 'coordinates': 'lon lat time', 'long_name': 'Group Response Unit', 'standard_name': 'GRU'}, 'GridArea': {'_FillValue': 'NaN', 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'HRU Area'}, 'IAK': {'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'River class number (IAK)', 'standard_name': 'IAK'}, 'LandUse': {'standard_name': 'Landuse classification name'}, 'Next': {'_FillValue': -1.0, 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'Receiving ID', 'standard_name': 'Next'}, 'Rank': {'_FillValue': -1.0, 'coordinates': 'lon lat time', 'grid_mapping': 'crs', 'long_name': 'Element ID', 'standard_name': 'Rank'}}, ddb_global_attrs={'author': 'University of Calgary', 'featureType': 'point', 'license': 'GNU General Public License v3 (or any later version)', 'purpose': 'Create a drainage database .nc file for MESH'}, ddb_min_values={'river_length': 0.001, 'river_slope': 0.001, 'subbasin_area': 0.001}, ddb_to_units={'gru': 'dimensionless', 'landclass': 'dimensionless', 'next': 'dimensionless', 'rank': 'dimensionless', 'river_length': 'meter', 'river_slope': 'dimensionless'}, settings=None, gru_dim='NGRU', hru_dim='subbasin', outlet_value=-9999)[source]

Initialize a MESHWorkflow instance for automating MESH model setup.

Parameters:
  • riv (PathLike) – Path to the river network shapefile or geospatial data file containing river segments.

  • cat (PathLike) – Path to the catchment/subbasin shapefile or geospatial data file containing watershed boundaries.

  • landcover (PathLike) – Path to the landcover CSV file containing fractional coverage of land classes for each catchment. Note that currently, only MAF compliant files are supported.

  • landcover_classes (Dict[str, str]) – Mapping of landcover class codes/numbers to descriptive class names.

  • forcing_files (PathLike, optional) – Path to meteorological forcing files (NetCDF, glob pattern, or directory).

  • forcing_vars (Dict[str, str], optional) – Mapping of input forcing variable names to MESH standard variable names.

  • forcing_units (Dict[str, str], optional) – Units of the input forcing variables.

  • ddb_vars (Dict[str, str], optional) – Mapping of drainage database variable names from input data to MESH standards.

  • ddb_units (Dict[str, str], optional) – Units of drainage database variables.

  • main_id (str, optional) – Name of the primary identifier field in the catchment and river data.

  • ds_main_id (str, optional) – Name of the downstream segment identifier field in river data.

  • forcing_to_units (Dict[str, str], optional) – Target units for forcing variables after conversion.

  • forcing_local_attrs (Dict[str, str], optional) – Local attributes to apply to forcing variables in output files.

  • forcing_global_attrs (Dict[str, str], optional) – Global attributes to apply to forcing NetCDF files.

  • ddb_local_attrs (Dict[str, str], optional) – Local attributes to apply to drainage database variables.

  • ddb_global_attrs (Dict[str, str], optional) – Global attributes to apply to drainage database NetCDF file.

  • ddb_min_values (Dict[str, float], optional) – Minimum allowable values for drainage database variables.

  • ddb_to_units (Dict[str, str], optional) – Target units for drainage database variables after conversion.

  • settings (Dict[str, str], optional) – Comprehensive model configuration dictionary. Refer to the documentation for more details.

  • gru_dim (str, optional) – Dimension name for Group Response Units (land classes) in output files. Default is ‘NGRU’.

  • hru_dim (str, optional) – Dimension name for Hydrologic Response Units (catchments) in output files. Default is ‘subbasin’.

  • outlet_value (int, optional) – Sentinel value used to identify outlet/terminal segments in the river network. Default is -9999.

Raises:
  • TypeError – If any of the dictionary parameters are not of type dict.

  • AssertionError – If settings is not a dictionary.

Return type:

None

property coords

Calculate and return centroid coordinates (latitude and longitude) for the main object.

Parameters:

None

Returns:

Tuple containing centroid latitude and longitude values.

Return type:

tuple

Notes

Utilizes utility.extract_centroid to compute the centroid based on the object’s geodataframe (self.cat) and its identifier (self.main_id).

property forcing_files

Returns the path or glob pattern to the forcing files.

Determines the correct path or glob pattern for NetCDF forcing files based on the provided forcing path. If the path matches a NetCDF file pattern (‘.nc’ or ‘.nc*’) and files exist, returns the path directly. Otherwise, constructs a glob pattern for NetCDF files in the directory and returns the pattern if matching files are found.

Returns:

Path or glob pattern to the forcing files if found, otherwise None.

Return type:

str or None

classmethod from_dict(init_dict={})[source]

Instantiate a MESHWorkflow object from a dictionary.

Parameters:

init_dict (dict) – Dictionary containing initialization parameters for the MESHWorkflow class.

Returns:

An instance of the MESHWorkflow class.

Return type:

MESHWorkflow

Raises:

Notes

The keys in init_dict must match the arguments required by the MESHWorkflow constructor.

classmethod from_json(json_str)[source]

Instantiate a MESHWorkflow object from a JSON string.

Parameters:

json_str (str) – JSON string containing initialization parameters for the MESHWorkflow class.

Returns:

An instance of the MESHWorkflow class.

Return type:

MESHWorkflow

Notes

The keys in the JSON string must match the arguments required by the MESHWorkflow constructor. Decoding uses a custom object hook to handle typical JSON-to-Python conversions.

classmethod from_json_file(json_file)[source]

Instantiate a MESHWorkflow object from a JSON file.

Parameters:

json_file (str) – Path to the JSON file containing initialization parameters for the MESHWorkflow class.

Returns:

An instance of the MESHWorkflow class.

Return type:

MESHWorkflow

Notes

The keys in the JSON file must match the arguments required by the MESHWorkflow constructor. Decoding uses a custom object hook to handle typical JSON-to-Python conversions.

run(save_path=None)[source]

Run the workflow and prepare a MESH model setup.

This method initializes the drainage database and forcing objects, generates configuration files, and prepares all necessary files for running a MESH hydrological model.

Parameters:

save_path (str or PathLike, optional) – Path to the directory where output files will be saved. Required if multiple forcing files are processed.

Raises:

ValueError – If save_path is None when processing multiple forcing files.

Return type:

None

Notes

  • For multiple forcing files, each file is processed and saved during initialization.

  • For single forcing files, the forcing object is created but not saved automatically.

  • Generates CLASS, hydrology, and run options configuration files.

init()[source]

Initialize the MESH workflow by setting up drainage database and forcing objects

Return type:

None

init_ddb(return_ds=False)[source]

Initialize the drainage database object for the workflow.

Parameters:

return_ds (bool, optional) – If True, return the drainage database as an xarray.Dataset. If False (default), assign to self.ddb and return None.

Returns:

If return_ds is True, returns the drainage database as an xarray.Dataset. Otherwise, assigns to self.ddb and returns None.

Return type:

None or xarray.Dataset

Raises:

ValueError – If ddb_vars is empty.

Notes

  • Renames input variables to MESH standard names and ensures required variables are present.

  • Generates the drainage database using geospatial and landcover data.

  • Performs ad-hoc manipulations and assigns units to GridArea.

init_forcing(save=False, save_path=None)[source]

Initialize the forcing object for the MESH workflow.

Parameters:
  • save (bool, optional) – If True, save the processed forcing files to disk. Default is False.

  • save_path (str or PathLike, optional) – Directory path where forcing files will be saved if save is True. If not provided, files are not saved.

Returns:

Returns the processed forcing dataset if not saving to disk. Otherwise, returns None after saving files. In case of multiple files, each is processed and saved individually, and nothing is returned.

Return type:

xarray.Dataset or None

Raises:
  • AssertionError – If save is not a boolean or save_path is not a string or PathLike.

  • ValueError – If required inputs (forcing_files, forcing_vars, forcing_units, forcing_to_units) are missing, or if save is True and save_path is None.

Notes

  • Handles both single and multiple forcing files based on settings.

  • Performs unit conversion and applies attributes using Pint registry.

  • For multiple files, each is processed and saved individually.

  • For single file, returns the xarray.Dataset unless saving is requested.

  • Artificial outlet segments are handled for forcing variables if present.

  • Time encoding is modified for compatibility with MESH (>r1860).

init_class(return_dict=False)[source]

Generate the CLASS configuration text for the MESH model.

Parameters:

return_dict (bool, optional) – If True, returns the generated CLASS configuration dictionary. If False (default), assigns the dictionary to self.class_dict and returns None.

Returns:

The CLASS configuration dictionary if return_dict is True, otherwise None.

Return type:

dict or None

Raises:
  • KeyError – If measurement_heights is missing in class_params or required keys are missing in measurement_heights. This is an important requirement for the CLASS configuration.

  • ValueError – If specific_humidity and air_temperature measurement heights are not equal. MESH currently requires these heights to be the same.

Notes

  • Calculates centroid coordinates for the model domain.

  • Extracts subbasin and landcover class counts.

  • Builds CLASS configuration dictionaries for case, info, and GRUs.

  • Updates GRU dictionary with user-provided class assignments if present.

  • Renders the CLASS configuration text using a template utility.

init_hydrology(return_dict=False, return_ds=False, routing_process_params=None)[source]

Generate the hydrology configuration text for the MESH model.

Parameters:
  • return_dict (bool, optional) – If True, returns the generated hydrology configuration dictionary. If False (default), assigns the dictionary to self.hydrology_dict and returns None.

  • routing_process_params (dict, optional) – Dictionary containing routing process parameters.

  • return_ds (bool)

Returns:

The hydrology configuration dictionary if return_dict is True, otherwise None.

Return type:

dict or None

Raises:

ValueError – If the number of river classes exceeds 5.

Notes

  • Builds routing and GRU-dependent hydrology dictionaries.

  • Updates dictionaries with user-provided parameters if available.

  • Renders hydrology configuration text using a template utility.

init_parameters_ds(return_ds=False)[source]

Generate the parameters dataset for the MESH model.

Parameters:

return_ds (bool, optional) – If True, returns the generated parameters dataset as an xarray.Dataset. If False (default), assigns the dataset to self.parameters_ds and returns None.

Returns:

The parameters dataset if return_ds is True, otherwise None.

Return type:

xarray.Dataset or None

Notes

  • Builds a dataset containing model parameters such as latitudes, longitudes, and coordinate reference system (CRS) information.

  • The dataset is structured with dimensions corresponding to HRUs and GRUs.

  • The method can either return the dataset directly or assign it to an instance variable.

init_options(default_options=PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/mesh-workflow/checkouts/latest/src/meshflow/templates/default_input_run_options.json'), return_dict=False)[source]

Generate the MESH run options configuration text.

Parameters:
  • default_options (PathLike, optional) – Path to the default run options JSON file. If not provided, uses the built-in default.

  • return_dict (bool, optional) – If True, returns the generated run options configuration text as a dictionary. If False (default), assigns the dictionary to self.options_dict and returns None.

Returns:

The run options configuration text if return_text is True, otherwise None.

Return type:

dict or None

Notes

  • Builds the options dictionary for MESH run configuration, including flags, output settings, and simulation dates.

  • Handles both single and multiple forcing file scenarios.

  • Automatically detects and sets time zones if not provided in settings, using the centroid of the catchment area.

  • Calculates time difference between forcing and model time zones.

  • Renders the options text using a template utility.

  • The user’s custom settings in self.settings[‘run_options’] will override the automatically generated options.

check_process_parameters(options_dict, process_details={'_necessary': {'hydrology': ['ZSNL', 'ZPLS', 'ZPLG', 'IWF'], 'routing': []}, 'baseflowflag': {'wf_lzs': {'hydrology': [], 'optional': ['WrchrgIni'], 'routing': ['flz', 'pwr']}}, 'runmode': {'noroute': {'hydrology': [], 'optional': [], 'routing': []}, 'runrte': {'hydrology': [], 'optional': ['MNDR', 'WIDEP', 'AA2', 'AA3', 'AA4'], 'routing': ['r2n', 'r1n']}, 'runsvs': {'hydrology': [], 'optional': [], 'routing': []}}}, return_processes=False)[source]

Check and process run options parameters for consistency and correctness.

Parameters:
  • options_dict (dict) – Dictionary containing run options configuration parameters.

  • process_details (dict, optional) – Dictionary defining process details, including necessary hydrology and routing parameters for each process. Default is DEFAULT_PROCESS_PARAMETERS.

  • return_processes (bool, optional) – If True, returns the extracted process parameters as a dictionary. If False (default), assigns the parameters to instance attributes and returns None.

Raises:

ValueError – If any required keys are missing in the options_dict.

Return type:

Dict[str, List] | None

Notes

  • Validates the presence of essential keys in the run options dictionary.

  • Ensures that the configuration is complete before rendering.

render_configs(class_dicts, hydrology_dicts, options_dict, process_details=None, return_texts=False, return_ds=False)[source]

Render configuration texts for CLASS, hydrology, and run options.

Parameters:
  • class_dicts (dict of dict) – Dictionary containing CLASS configuration parameters that are stored in three distinct dictionaries, including class_info, class_case, and class_grus (key names).

  • hydrology_dicts (dict of dict) – Dictionary containing hydrology configuration parameters stored in two distinct dictionaries, including hydrology_info and hydrology_case (key names).

  • options_dict (dict) – Dictionary containing run options configuration parameters.

  • process_details (dict, optional) – Dictionary defining process details, including necessary hydrology and routing parameters for each process. If provided, it will be used to check and extract necessary parameters for hydrology and routing configurations.

  • return_texts (bool, optional) – If True, return the rendered configuration texts as strings instead of writing to files.

  • return_ds (bool, optional) – If True, return the parameters dataset as an xarray.Dataset object. This is useful for calibration purposes where the dataset may be needed directly.

Returns:

A tuple containing the rendered configuration texts for CLASS, hydrology, and run options.

Return type:

Tuple[str, str, str]

Notes

  • Utilizes utility functions to render configuration texts based on provided dictionaries created via init_class, init_hydrology, and init_options methods.

  • Users can directly use this function if the configuration dictionaries are created externally.

save(output_dir)[source]

Save the drainage database, forcing files, and configuration files to the specified output directory.

This method exports the model’s drainage database and forcing files in NetCDF or text format, copies default setting files, and writes configuration files required for the model setup.

Parameters:

output_dir (str or PathLike) – Path to the directory where the model setup and associated files will be saved.

Returns:

This method does not return any value. Files are written to the specified output directory.

Return type:

None

Notes

  • If a single forcing file is used, it is saved as ‘MESH_forcing.nc’ in NetCDF format.

  • If multiple forcing files are used, a list of their paths is saved as ‘forcing_files_list.txt’.

  • Default setting files from the package are copied to the output directory.

  • Additional configuration files such as CLASS, hydrology, and run options are saved as .ini files.

format_date(date_str, date_format='%Y-%m-%d')[source]

Convert a date string to ‘yyyymmdd’ format, handling various formats

Return type:

str

maybe_int(x)[source]
Parameters:

x (Any)