API Reference
This section provides complete API documentation for all public classes, functions, and modules in MESHflow.
Core API
Main Workflow Class
|
Automates the setup of MESH models through a flexible workflow. |
Utility Functions
The utility modules provide specialized functions for various tasks.
Geometry Processing
Functions for handling geometric operations and spatial data processing.
|
Extract centroid latitude and longitude for each polygon in a GeoDataFrame. |
|
Convert a DataFrame of mesh coordinates to an xarray.Dataset with specified dimension names. |
Containing common modules to manipulate and interpret geometrical objects such as Polygons, LineStrings, MultiPolygons, etc.
- meshflow.utility.geom.extract_centroid(gdf, obj_id, epsg=4326)[source]
Extract centroid latitude and longitude for each polygon in a GeoDataFrame.
- Parameters:
gdf (geopandas.GeoDataFrame) – GeoDataFrame containing polygon geometries in the ‘geometry’ column.
obj_id (str) – Name of the column containing unique IDs for each polygon element.
epsg (int, optional) – EPSG code for the output coordinate reference system (default: 4326).
- Returns:
- DataFrame with columns:
obj_id: IDs for each polygon (copied from input)
lat: Centroid latitude in the specified CRS
lon: Centroid longitude in the specified CRS
- Return type:
Notes
If the input GeoDataFrame has no CRS, EPSG:4326 is assumed.
Only polygon geometries are supported; other types may yield errors.
Centroids are calculated in an equal-area projection and reprojected to the requested CRS for accurate coordinates.
Examples
>>> import geopandas as gpd >>> from shapely.geometry import Polygon >>> gdf = gpd.GeoDataFrame({ ... 'id': [1], ... 'geometry': [Polygon([(0,0), (1,0), (1,1), (0,1)])] ... }, crs='EPSG:4326') >>> extract_centroid(gdf, obj_id='id')
- meshflow.utility.geom.prepare_mesh_coords(coords, cat_dim, hru_dim)[source]
Convert a DataFrame of mesh coordinates to an xarray.Dataset with specified dimension names.
- Parameters:
coords (pandas.DataFrame) – DataFrame containing mesh coordinates. Must include a column for catchment element IDs.
cat_dim (str) – Name of the column representing catchment element IDs (e.g., ‘COMID’).
hru_dim (str) – Desired name for the output dimension (e.g., ‘hru’).
- Returns:
Dataset with coordinates indexed by hru_dim.
- Return type:
xr.Dataset
Examples
>>> import pandas as pd >>> import xarray as xr >>> df = pd.DataFrame({ ... 'COMID': [1, 2], ... 'lat': [45.0, 46.0], ... 'lon': [-75.0, -76.0] ... }) >>> ds = prepare_mesh_coords(df, cat_dim='COMID', hru_dim='hru') >>> print(ds)
Network Analysis
Functions for river network processing and topology analysis.
|
Generate MESH-compatible rank and next variables for river segments. |
|
Prepares the drainage database (ddb) for the MESH model. |
containing modules to set up MESH models
- meshflow.utility.network.extract_rank_next(seg, ds_seg, outlet_value=-9999)[source]
Generate MESH-compatible rank and next variables for river segments.
- Parameters:
seg (array-like or list-like) – Ordered segment IDs for river reaches in the area of interest.
ds_seg (array-like or list-like) – Ordered downstream segment IDs corresponding to seg elements.
outlet_value (int, optional) – Value assigned to to_segment indicating outlet/sink from the system. Default is -9999.
- Returns:
rank_var (numpy.ndarray) – Rank of each segment ID, following MESH modelling standards.
next_var (numpy.ndarray) – Downstream segment index for each river reach, matching rank_var.
seg_id (numpy.ndarray) – Segment IDs reordered to match rank_var and next_var.
to_segment (numpy.ndarray) – Downstream segment IDs reordered to match rank_var and next_var.
- Return type:
Notes
Developed by Dr. Ala Bahrami and Cooper Albano for North American MESH model workflows. Minor changes by Kasra Keshavarz.
- Original workflow:
- meshflow.utility.network.prepare_mesh_ddb(riv, cat, landcover, cat_dim, gru_dim, hru_dim, gru_names, include_vars, attr_local, attr_global, min_values=None, fill_na=None, ordered_dims=None, ddb_units=None, ddb_to_units=None)[source]
Prepares the drainage database (ddb) for the MESH model.
This function applies a set of manipulations to river network and catchment geospatial data to construct the drainage database required by MESH.
- Parameters:
riv (str, list of str, or geopandas.GeoDataFrame) – Path(s) to ESRI Shapefile(s) or a GeoDataFrame containing river LineString(s).
cat (str, list of str, or geopandas.GeoDataFrame) – Path(s) to ESRI Shapefile(s) or a GeoDataFrame containing catchment Polygon(s) or MultiPolygon(s).
landcover (pandas.DataFrame) – DataFrame of land use class fractions (values between 0 and 1) for each catchment. Columns are land cover classes; rows are catchment elements.
cat_dim (str) – Name of the catchment dimension present in cat, riv, and landcover.
gru_dim (str) – Name of the landcover class dimension after processing landcover.
hru_dim (str) – Name of the hydrological response unit (HRU) dimension for output.
gru_names (Sequence of str) – List of landcover class names, ordered to match processed landcover.
include_vars (dict) – Dictionary mapping variable names in input data to output names in ddb.
attr_local (dict) – Dictionary mapping output variable names to their attribute dictionaries.
attr_global (dict) – Dictionary mapping global attribute names to their descriptions.
min_values (dict, optional) – Minimum values for variables in ddb. Keys must match output variable names.
fill_na (dict, optional) – Values to fill for NaNs in each variable of ddb. Keys are variable names.
ordered_dims (dict, optional) – Dictionary mapping dimension names to ordered values for sorting ddb.
ddb_units (dict, optional) – Dictionary mapping variable names to their units for quantification.
ddb_to_units (dict, optional) – Dictionary mapping variable names to target units for conversion.
- Returns:
ddb – Drainage database as an xarray.Dataset containing all required variables and attributes for MESH model setup.
- Return type:
Forcing Data Preparation
Functions for preparing meteorological forcing data for MESH models.
|
Prepare a MESH forcing file by merging, converting, and annotating data. |
|
Return the full name of a time offset alias based on pandas conventions. |
|
Calculate the time difference in hours between two IANA time zones. |
Containing important functions for preparing “forcing” database for MESH models
- meshflow.utility.forcing_prep.prepare_mesh_forcing(path, variables, units, hru_dim=None, unit_registry=None, to_units=None, aggregate=False, local_attrs=None, global_attrs=None)[source]
Prepare a MESH forcing file by merging, converting, and annotating data.
- Parameters:
path (str) – Path to input forcing files.
variables (Sequence[str]) – Sequence of variable names to include in the output file.
units (dict of str) – Dictionary mapping variable names to their units.
hru_dim (str, optional) – Name of the HRU dimension to use in the output dataset.
unit_registry (pint.UnitRegistry, optional) – Pint unit registry for unit conversion. Default is None.
to_units (dict of str, optional) – Dictionary mapping variable names to target units for conversion.
aggregate (bool, default False) – If True, merge multiple input files into one using CDO. If False, assumes input files are already in the correct format and reads them directly. This is useful for MESH, which only reads one file. If aggregate is False, the input files are assumed to be already in the correct chunk format and are read directly. If aggregate is True, CDO is used to merge the files. Note that CDO is a binary dependency and must be installed separately.
local_attrs (dict of dict, optional) –
Dictionary of local attributes for each forcing variable. The keys are variable names and the values are dictionaries of attributes to assign to each variable.
- Example:
- {‘air_temperature’: {‘long_name’: ‘Air Temperature’,
’units’: ‘K’}}
global_attrs (dict of str, optional) – Dictionary of global attributes for the output dataset. The keys are attribute names and the values are their descriptions.
- Returns:
Merged and converted dataset containing forcing variables.
- Return type:
- Raises:
TypeError – If variables is not a sequence of string values.
ValueError – If units for variables are not provided, or if any variable in units cannot be found in the dataset.
Notes
Merges all input forcing files into a single NetCDF file, as MESH only reads one file. CDO is used for merging, but the function returns an xarray.Dataset.
The variables sequence should include: ‘air_pressure’, ‘specific_humidity’, ‘air_temperature’, ‘wind_speed’, ‘precipitation’, ‘shortwave_radiation’, ‘longwave_radiation’.
The units and to_units dictionaries must contain the same keys as variables.
The merge functionality may be expanded in future versions.
- meshflow.utility.forcing_prep.freq_long_name(freq_alias)[source]
Return the full name of a time offset alias based on pandas conventions.
- Parameters:
freq_alias (str) – Time offset alias representing time interval frequency, such as ‘H’ for ‘hours’, ‘T’ for ‘minutes’, etc.
- Returns:
Full name of the time offset (e.g., ‘hours’, ‘minutes’).
- Return type:
- Raises:
TypeError – If freq_alias is not a string.
ValueError – If freq_alias is not a recognized offset alias.
Examples
>>> freq_long_name('H') 'hours' >>> freq_long_name('T') 'minutes'
- meshflow.utility.forcing_prep.calculate_time_difference(initial_time_zone, target_time_zone)[source]
Calculate the time difference in hours between two IANA time zones.
- Parameters:
- Returns:
Time difference in hours between the two time zones. If the time zones are the same, returns 0.
- Return type:
- Raises:
AssertionError – If either time zone argument is not a string.
ValueError – If the time zone format is incorrect or not valid.
Notes
Time zone naming follows IANA conventions: https://data.iana.org/time-zones/releases/tzdb-2025b.tar.lz
Examples
>>> calculate_time_difference('UTC', 'America/Toronto') -4.0 >>> calculate_time_difference('America/Edmonton', 'America/Toronto') 2.0
Configuration Templating
Functions for generating MESH configuration files from templates.
|
Render a CLASS configuration file using Jinja2 templates. |
|
Render a hydrology parameters INI template using Jinja2. |
|
Render a run options configuration file using Jinja2 templates. |
|
Recursively merge d2 dictionary into d1. |
Utility functions for generating MESH model configuration files using the Jinja2 templating engine.
This module provides helpers to render CLASS, hydrology, and run options configuration files from Python dictionaries, leveraging default templates and parameters for consistent file generation.
- meshflow.utility.templating.deep_merge(d1, d2)
Recursively merge d2 dictionary into d1.
- meshflow.utility.templating.raise_helper(msg)
Jinja2 helper function to raise exceptions.
- meshflow.utility.templating.render_class_template(class_info, class_case, class_grus, default_header_path=PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/mesh-workflow/checkouts/latest/src/meshflow/templates/default_CLASS_header.json'), default_params_path=PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/mesh-workflow/checkouts/latest/src/meshflow/templates/default_CLASS_parameters.json'), default_case_path=PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/mesh-workflow/checkouts/latest/src/meshflow/templates/default_CLASS_case.json'), default_lines_path=PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/mesh-workflow/checkouts/latest/src/meshflow/templates/default_CLASS_lines.json'), default_types_path=PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/mesh-workflow/checkouts/latest/src/meshflow/templates/default_CLASS_types.json'), template_class_jinja_path='MESH_parameters_CLASS.ini.jinja')
Render a CLASS configuration file using Jinja2 templates.
- Parameters:
class_info (dict) – Dictionary containing metadata and info for the CLASS file header.
class_case (dict) – Dictionary containing case-specific settings for the CLASS file.
class_grus (Sequence[dict]) – Sequence of dictionaries, each representing GRU parameters.
default_header_path (PathLike, optional) – Path to the default CLASS header JSON file.
default_params_path (PathLike, optional) – Path to the default CLASS parameters JSON file.
default_case_path (PathLike, optional) – Path to the default CLASS case JSON file.
default_lines_path (PathLike, optional) – Path to the default CLASS lines JSON file.
default_types_path (PathLike, optional) – Path to the default CLASS types JSON file.
template_class_jinja_path (PathLike, optional) – Path to the Jinja2 template for the CLASS file.
- Returns:
Rendered CLASS configuration file as a string.
- Return type:
- Raises:
FileNotFoundError – If any of the template or default files do not exist.
Exception – If a Jinja2 template error occurs.
- meshflow.utility.templating.render_hydrology_template(routing_params={}, hydrology_params={}, default_params_path=PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/mesh-workflow/checkouts/latest/src/meshflow/templates/default_hydrology_parameters.json'), template_hydrology_path='MESH_parameters_hydrology.ini.jinja', parameters_ds=None, hru_dim='subbasin', gru_dim='NGRU', return_ds=False, *args, **kwargs)
Render a hydrology parameters INI template using Jinja2.
- Parameters:
routing_params (dict, optional) – Dictionary containing routing parameters for the template.
hydrology_params (dict, optional) – Dictionary containing hydrology parameters for the template.
default_params_path (PathLike, optional) – Path to the default hydrology parameters JSON file.
template_hydrology_path (PathLike, optional) – Path to the Jinja2 template for hydrology parameters.
parameters_ds (xarray.Dataset, optional) – An optional xarray.Dataset containing hydrology-specific parameters that may be needed for rendering the template. If not provided, it will be generated based on the routing parameters if necessary.
hru_dim (str, optional) – Name of the dimension representing HRUs (or subbasins) in the parameters dataset.
gru_dim (str, optional) – Name of the dimension representing GRUs in the parameters dataset.
return_ds (bool, optional) – Whether to return the xarray.Dataset containing hydrology-specific parameters along with the rendered template. If True, the function will return a tuple of (rendered_template, parameters_ds). If False, it will return only the rendered template.
- Returns:
str – Rendered hydrology template as a string.
xr.Dataset, optional – If return_ds is True, also return the xarray.Dataset containing hydrology-specific parameters.
- Raises:
FileNotFoundError – If any of the template or default files do not exist.
Exception – If a Jinja2 template error occurs.
- Return type:
- meshflow.utility.templating.render_run_options_template(run_options_dict, template_run_options_path='MESH_input_run_options.ini.jinja')
Render a run options configuration file using Jinja2 templates.
- Parameters:
run_options_dict (dict) – Dictionary containing run options to be used in the template.
template_run_options_path (PathLike, optional) – Path to the Jinja2 template for run options.
- Returns:
Rendered run options configuration file as a string.
- Return type:
- Raises:
FileNotFoundError – If any of the template or default files do not exist.
Exception – If a Jinja2 template error occurs.