hydrological_modules package¶
Initialize¶
miscInitial module¶
Initializing some variables
- class cwatm.hydrological_modules.miscInitial.miscInitial(model)[source]¶
Bases:
objectMiscellaneous initialization module for basic model parameters and conversions.
Establishes fundamental model parameters including grid cell characteristics, temporal parameters, unit conversion factors, and commonly used mathematical expressions that are repeatedly accessed throughout model execution.
Global variables
Variable [self.var]
Type
Description
Unit
M3toM
Array
Coefficient to change units
–
DtSec
Array
number of seconds per timestep (default = 86400)
s
twothird
Number
2025-03-02 00:00:00
–
MtoM3
Array
Coefficient to change units
–
InvDtSec
Array
inversere of seconds per timestep (default 1/86400)
1/s
InvCellArea
Array
Inverse of cell area of each simulated mesh
1/m2
DtDay
Array
seconds in a timestep (default=86400)
s
InvDtDay
Array
inverse seconds in a timestep (default=86400)
1/s
MMtoM
Number
Coefficient to change units
–
MtoMM
Number
Coefficient to change units
–
con_precipitation
Array
conversion factor for precipitation
–
con_e
Array
conversion factor for evaporation
–
cellArea
Array
Area of cell
m2
- Variables
var (object) – Reference to model variables object containing state variables
model (object) – Reference to the main CWatM model instance
Notes
This module handles essential initialization tasks: - Grid cell area determination (user-defined or derived from projection) - Time step definitions and conversion factors - Unit conversion factors (mm to m, m³ to m, etc.) - Precipitation and evaporation conversion parameters - Mathematical constants and frequently used expressions
Only used during model initialization phase.
- initial()[source]¶
Initialize basic model parameters and conversion factors.
Sets up fundamental model parameters including grid cell characteristics, temporal parameters, unit conversions, and mathematical constants required throughout model execution.
Notes
Initialization includes: - Grid cell area calculation (user-defined maps or equal-area projection) - Time step parameters (daily time step in seconds and fractions) - Unit conversion factors (mm/m, m/m³, inverse relationships) - Precipitation and evaporation conversion coefficients - Mathematical constants (e.g., 2/3 power for interception calculations)
Grid size handling: - User-defined: Reads cell area from external map files - Default: Derives from equal-area projection assuming square cells
All conversion factors are established to maintain unit consistency throughout hydrological calculations.
initcondition module¶
Load initial storage parameter maps
- class cwatm.hydrological_modules.initcondition.initcondition(model)[source]¶
Bases:
objectInitial conditions management module for model state persistence.
Handles reading and writing of initial conditions for warm start capabilities, crop parameterization from Excel files, reservoir configuration, and other initialization data required for model setup and restart functionality.
Global variables
Variable [self.var]
Type
Description
Unit
modflow
Flag
True if modflow_coupling = True in settings file
bool
Crops_names
Array
Internal: List of specific crops
–
includeCrops
Flag
1 when includeCrops=True in Settings, 0 otherwise
bool
Crops
Array
Internal: List of specific crops and Kc/Ky parameters
–
daily_crop_KC
Array
–
loadInit
Flag
If true initial conditions are loaded
bool
includeDesal
Flag
–
unlimitedDesal
Flag
–
desalAnnualCap
Number
–
wwt_def
Flag
–
wastewater_to_reservoirs
Array
–
initLoadFile
Number
load file name of the initial condition data
Strin
saveInit
Flag
If true initial conditions are saved
bool
saveInitFile
Flag
save file name of the initial condition data
bool
reservoir_info
List
Number of lakes and reservoirs in Excel
–
reservoir_transfers
Array
[[‘Giving reservoir’][i], [‘Receiving reservoir’][i], [‘Fraction of li
array
coverTypes
Array
land cover types - forest - grassland - irrPaddy - irrNonPaddy - water
–
- Variables
var (object) – Reference to model variables object containing state variables
model (object) – Reference to the main CWatM model instance
Notes
The module provides functionality for: - Saving and loading model state variables for warm starts - Crop parameter initialization from Excel configurations - Reservoir operational parameter setup - Water transfer and wastewater configuration - Desalination capacity initialization
All initial conditions can be stored at the end of a model run to be used as a warm start for subsequent model executions.
- crops_initialise(xl_settings_file_path)[source]¶
Initialize crop parameters from Excel configuration file.
Reads crop-specific parameters including planting dates, growth stages, crop coefficients (KC), and yield response factors (KY) from Excel spreadsheet for crop-specific water use modeling.
- Parameters
xl_settings_file_path (str) – Path to Excel file containing crop parameter configurations
Notes
Processes crop data including: - Planting month/date for each crop - Four growth stage lengths (GS1-GS4) - Crop coefficients for each stage (KC1-KC4) - Yield response factors for each stage (KY1-KY4)
Supports both monthly and daily time step configurations with automatic detection based on growth stage lengths.
- desalinationCapacity(xl_settings_file_path)[source]¶
Initialize desalination plant capacity and operational parameters.
Configures desalination facility characteristics including production capacities, energy requirements, and operational constraints from Excel configuration data.
- Parameters
xl_settings_file_path (str) – Path to Excel file containing desalination capacity configurations
- dynamic()[source]¶
Dynamic part of the initcondition module write initital conditions into a single netcdf file
Note
Several dates can be stored in different netcdf files
- initial()[source]¶
- initial part of the initcondition module
Puts all the variables which has to be stored in 2 lists:
initCondVar: the name of the variable in the init netcdf file
initCondVarValue: the variable as it can be read with the ‘eval’ command
Reads the parameter save_initial and save_initial to know if to save or load initial values
- reservoir_addinfo(xl_settings_file_path)[source]¶
Load additional reservoir information from Excel configuration.
Reads supplementary reservoir parameters including new reservoir locations, operational characteristics, and configuration flags from Excel spreadsheet for enhanced reservoir modeling.
- Parameters
xl_settings_file_path (str) – Path to Excel file containing reservoir configuration data
- reservoir_transfers(xl_settings_file_path)[source]¶
Configure inter-reservoir water transfer parameters.
Sets up water transfer relationships between reservoirs including transfer rates, operational rules, and connectivity information from Excel configuration files.
- Parameters
xl_settings_file_path (str) – Path to Excel file containing reservoir transfer configurations
- wasterwater_def(xl_settings_file_path)[source]¶
Define wastewater treatment parameters and characteristics.
Configures wastewater treatment system parameters including treatment capacities, removal efficiencies, and operational parameters from Excel configuration files.
- Parameters
xl_settings_file_path (str) – Path to Excel file containing wastewater treatment definitions
- wastewater_to_reservoirs(xl_settings_file_path)[source]¶
Configure wastewater discharge to reservoirs.
Sets up wastewater treatment and discharge parameters including treatment efficiencies, discharge locations, and operational characteristics from Excel configuration data.
- Parameters
xl_settings_file_path (str) – Path to Excel file containing wastewater discharge configurations
landcoverType module¶
Generate landcover types
- cwatm.hydrological_modules.landcoverType.decompress(map, nanvalue=None)[source]¶
Decompress CWatM maps from 1D compressed to 2D spatial arrays.
Converts compressed 1D arrays back to full 2D spatial maps using the model mask, handling missing values appropriately.
- Parameters
map (numpy.ndarray) – Compressed 1D array to be expanded to 2D
nanvalue (float, optional) – Value to assign to NaN locations in the decompressed map
- Returns
Decompressed 2D spatial array with mask-based reconstruction
- Return type
numpy.ndarray
- class cwatm.hydrological_modules.landcoverType.landcoverType(model)[source]¶
Bases:
objectLand cover type management module for multi-class hydrological modeling.
Orchestrates hydrological processes across different land cover types by managing land cover fractions, calling appropriate soil routines for each type, and integrating results for comprehensive water balance calculations.
Global variables
Variable [self.var]
Type
Description
Unit
modflow
Flag
True if modflow_coupling = True in settings file
bool
snowEvap
Array
total evaporation from snow for a snow layers
m
iceEvap
Array
Evaporation from ice (sublimation)
m
load_initial
Flag
Settings initLoad holds initial conditions for variables
bool
compress_LR
Array
boolean map as mask map for compressing lake/reservoir
–
decompress_LR
Array
boolean map as mask map for decompressing lake/reservoir
–
MtoM3C
Array
conversion factor from m to m3 (compressed map)
–
waterBodyTypTemp
Array
waterbody temp e.g. lake, reservoir, wetlands
–
maxGWCapRise
Array
influence of capillary rise above groundwater level
m
minCropKC
Array
minimum crop factor (default 0.2)
–
minInterceptCap
Array
Maximum interception read from file for forest and grassland land cove
m
irrigatedArea_original
Array
–
frac_totalnonIrr
Array
Fraction sown with specific non-irrigated crops
%
frac_totalIrr_max
Array
Fraction sown with specific irrigated crops, maximum throughout simula
%
frac_totalnonIrr_max
Array
Fraction sown with specific non-irrigated crops, maximum throughout si
%
GeneralCrop_Irr
Array
Fraction of irrigated land class sown with generally representative cr
%
fallowIrr
Array
Fraction of fallowed irrigated land
%
fallowIrr_max
Array
Fraction of fallowed irrigated land, maximum throughout simulation
%
GeneralCrop_nonIrr
Array
Fraction of grasslands sown with generally representative crop
%
fallownonIrr
Array
Fraction of fallowed non-irrigated land
%
fallownonIrr_max
Array
Fraction of fallowed non-irrigated land, maximum throughout simulation
%
availableArableLand
Array
Fraction of land not currently planted with specific crops
%
sum_gwRecharge
Array
groundwater recharge
m
interceptStor
Array
simulated vegetation interception storage
m
lakeStorage
Array
Storage volume of lakes
m3
resStorage
Array
Storage volume of reservoirs
m3
riverbedExchangeM
Array
Flow from channel into groundwater
m
leakageIntoGw
Array
Canal leakage leading to groundwater recharge
m
leakageIntoRunoff
Array
Canal leakage leading to runoff
m
dynamicLandcover
Flag
If landcover changes per year or is constant
bool
staticLandCoverMaps
Flag
1=staticLandCoverMaps in settings file is True, 0=otherwise
bool
landcoverSum
Array
Sum of all landcover, should be 1.0
%
totalET
Array
Total evapotranspiration for each cell including all landcover types
m
sum_interceptStor
Array
Total of simulated vegetation interception storage including all landc
m
minTopWaterLayer
Array
minimum water level above the top soil zone (for paddy rice)
m
maxRootDepth
Array
maximum root depth
m
rootDepth
Array
rootdepth of different layers
m
KSat1
Array
Saturated conductivity layer 1
cm/da
KSat2
Array
Saturated conductivity layer 2
cm/da
KSat3
Array
Saturated conductivity layer 3
cm/da
alpha1
Array
Van Genuchten parameter alpha layer1
–
alpha2
Array
Van Genuchten parameter alpha layer2
–
alpha3
Array
Van Genuchten parameter alpha layer3
–
lambda1
Array
Pore size index (lambda) layer 1
–
lambda2
Array
Pore size index (lambda) layer 2
–
lambda3
Array
Pore size index (lambda) layer 3
–
thetas1
Array
Saturated volumetric soil moisture content layer 1
–
thetas2
Array
Saturated volumetric soil moisture content layer 2
–
thetas3
Array
Saturated volumetric soil moisture content layer 3
–
thetar1
Array
Residual volumetric soil moisture content layer 1
–
thetar2
Array
Residual volumetric soil moisture content layer 2
–
thetar3
Array
Residual volumetric soil moisture content layer 3
–
genuM1
Array
soil: lambda / (1+ lambda) layer1
–
genuM2
Array
soil: lambda / (1+ lambda) layer2
–
genuM3
Array
soil: lambda / (1+ lambda) layer3
–
genuInvM1
Array
soil:1 / genuM1
–
genuInvM2
Array
soil:1 / genuM2
–
genuInvM3
Array
soil:1 / genuM3
–
ws1
Array
Maximum storage capacity in layer 1
m
ws2
Array
Maximum storage capacity in layer 2
m
ws3
Array
Maximum storage capacity in layer 3
m
wres1
Array
Residual storage capacity in layer 1
m
wres2
Array
Residual storage capacity in layer 2
m
wres3
Array
Residual storage capacity in layer 3
m
wrange1
Array
maximum soil moisture (ws) - residual soil mositure (wres) layer 1
m
wrange2
Array
maximum soil moisture (ws) - residual soil mositure (wres) layer 2
m
wrange3
Array
maximum soil moisture (ws) - residual soil mositure (wres) layer 3
m
wwp1
Array
Soil moisture at wilting point in layer 1
m
wwp2
Array
Soil moisture at wilting point in layer 2
m
wwp3
Array
Soil moisture at wilting point in layer 3
m
kUnSat3FC
Array
calculation from van Genuchten, Mualem equation
m/day
kunSatFC12
Array
calculation from van Genuchten, Mualem equation
m/day
kunSatFC23
Array
calculation from van Genuchten, Mualem equation
m/day
rootFraction1
Array
–
cropCoefficientNC_filename
List
–
interceptCapNC_filename
List
–
coverFractionNC_filename
Array
landcover type + coverFractionNC
–
ElevationStD
Array
Standard elevation from DEM
m
arnoBetaOro
Array
chosen ModFlow model timestep (1day, 7days, 30days, etc.)
m
arnoBeta
Array
arnoBeta defines the shape of soil water capacity distribution curve a
–
adjRoot
Array
–
sum_topwater
Array
quantity of water on the soil (flooding) (weighted sum for all landcov
m
sum_soil
Array
sum of all soilmpositure in all 3 layers + topwater
m
sum_w1
Array
sum of actual soil mositure, weighted by the fraction of landcover
m
sum_w2
Array
sum of actual soil mositure, weighted by the fraction of landcover
m
sum_w3
Array
sum of actual soil mositure, weighted by the fraction of landcover
m
totalSto
Array
Total soil,snow and vegetation storage for each cell including all lan
m
maxtopwater
Array
maximum heigth of topwater
m
totAvlWater
Array
Field capacity minus wilting point in soil layers 1 and 2
m
Rain_times_fracPaddy
Array
–
Rain_times_fracNonPaddy
Array
–
fracGlacierCover
Array
Fraction of glacier cover in a grid cell
%
pretotalSto
Array
Previous totalSto
m
prefFlow_GW
Array
Preferential flow to groundwater. sum_prefFlow goes either to groundwa
m
sum_prefFlow
Array
Preferential flow from soil to groundwater (summed up for all land cov
m
sum_perc3toGW
Array
Percolation from 3rd soil layer to groundwater (summed up for all land
m
perc3toGW_GW
Array
Percolation from 3rd soil layer to groundwater. sum_perc3toGW goes eit
m
riverbedExchangeM3
Array
–
lakebedExchangeM
Array
Flow of water from lakes and reservoirs into groundwater
m
sum_actTransTotal
Array
actual total transpiration (sum over all land cover types)
m
sum_actBareSoilEvap
Array
actual bare soil evaporation (sum over all land cover types)
m
sum_interceptEvap
Array
–
sum_runoff
Array
Runoff above the soil, more interflow, including all landcover types
m
sum_directRunoff
Array
direct runoff from surface (sum over all land cover types)
m
GWVolumeVariation
Number
–
MtoM3
Array
Coefficient to change units
–
InvCellArea
Array
Inverse of cell area of each simulated mesh
1/m2
Precipitation
Array
Precipitation (input for the model)
m
includeGlaciers
Flag
Include glaciers
bool
waterBodyID
Array
lakes/reservoirs map with a single ID for each lake/reservoir
–
sum_openWaterEvap
Array
sum of open water evaporation from all different land cover types
m
coverTypes
Array
land cover types - forest - grassland - irrPaddy - irrNonPaddy - water
–
sum_interflow
Array
sum of iterflow from all land cover types
m
availWaterInfiltration
Array
quantity of water reaching the soil after interception, more snowmelt
m
Rain
Array
Precipitation less snow
m
SnowCover
Array
snow cover (sum over all layers)
m
frac_totalIrr
Array
Fraction sown with specific irrigated crops
%
soilLayers
Array
Number of soil layers
–
soildepth
Array
Thickness of the first soil layer
m
wfc1
Array
Soil moisture at field capacity in layer 1
m
wfc2
Array
Soil moisture at field capacity in layer 2
m
wfc3
Array
Soil moisture at field capacity in layer 3
m
w1
Array
Simulated water storage in the layer 1
m
w2
Array
Simulated water storage in the layer 2
m
w3
Array
Simulated water storage in the layer 3
m
topwater
Array
quantity of water above the soil (flooding)
m
baseflow
Array
simulated baseflow (= groundwater discharge to river)
m
capriseindex
Array
–
soildepth12
Array
Total thickness of layer 2 and 3
m
leakageriver_factor
Array
–
leakagelake_factor
Array
–
modflow_timestep
Array
Chosen ModFlow model timestep (1day, 7days, 30days, etc.)
day
wwtUrbanLeakage
Array
–
wwtColArea
Array
–
urbanleak
Array
–
fracVegCover
Array
Fraction of specific land covers (0=forest, 1=grasslands, etc.)
%
cellArea
Array
Area of cell
m2
includeWastewater
Flag
–
lakeVolumeM3C
Array
compressed map of lake volume
m3
lakeStorageC
Array
–
reservoirStorageM3C
Array
–
lakeResStorageC
Array
–
lakeResStorage
Array
–
act_SurfaceWaterAbstract
Array
Surface water abstractions
m
readAvlChannelStorageM
Array
–
leakageCanals_M
Array
–
includeWastewaterPits
Flag
–
pitLatrinToGW
Array
–
addtoevapotrans
Array
Irrigation application loss to evaporation
m
- Variables
var (object) – Reference to model variables object containing state variables
model (object) – Reference to the main CWatM model instance
Notes
Manages six primary land cover types: 0. Forest 1. Grassland 2. Irrigated paddy 3. Irrigated non-paddy 4. Sealed surfaces 5. Water bodies
The module handles land cover fraction dynamics, calls soil processes for each type, and aggregates results weighted by land cover fractions for pixel-scale water balance calculations.
- dynamic()[source]¶
Execute land cover type processes for current time step.
Orchestrates hydrological calculations across all land cover types, calling appropriate modules for each type and integrating results weighted by land cover fractions.
Notes
Processing sequence: 1. Update dynamic land cover fractions if applicable 2. Call interception module for relevant land cover types 3. Execute snow/frost processes for each type 4. Run soil water dynamics for each land cover type 5. Process sealed water and open water dynamics 6. Aggregate results weighted by land cover fractions 7. Calculate total pixel-scale water balance components
Each land cover type maintains separate state variables that are integrated based on their spatial fractions within each pixel.
- dynamic_fracIrrigation(init=False, dynamic=True)[source]¶
Update irrigation fractions dynamically or during initialization.
Manages temporal changes in irrigation area fractions for paddy and non-paddy irrigation, handling both initialization and dynamic updates throughout model execution.
- Parameters
init (bool, optional) – Flag for initialization mode (default: False)
dynamic (bool, optional) – Flag for dynamic update mode (default: True)
Notes
Updates irrigation fractions based on: - Temporal irrigation datasets - Seasonal irrigation patterns - Long-term irrigation changes - Crop calendar considerations
- initial()[source]¶
Initialize land cover type fractions and parameters.
Sets up spatial distributions of land cover types, irrigation fractions, crop parameters, and other land cover-specific characteristics required for hydrological process differentiation.
Notes
Initialization includes: - Land cover fraction maps for all types - Irrigation area fractions and dynamics - Crop coefficient parameters - Land cover-specific hydrological parameters - Temporal dynamics of land cover changes
Land cover types: 0 Forest - Natural forest areas 1 Grasland/non irrigated land No.1 2 Paddy irrigation No.2 3 non-Paddy irrigation No.3 4 Sealed area No.4 5 Water covered area No.5
And initialize the soil variables
Hydrology I - from rain to soil¶
readmeteo module¶
Read meteorological input data
- class cwatm.hydrological_modules.readmeteo.readmeteo(model)[source]¶
Bases:
objectMeteorological data reader and processor for CWatM.
Handles reading meteorological forcing data from NetCDF files, performs spatial downscaling using WorldClim data, manages temporal interpolation, and provides data preprocessing for hydrological calculations.
Global variables
Variable [self.var]
Type
Description
Unit
DtDay
Array
seconds in a timestep (default=86400)
s
con_precipitation
Array
conversion factor for precipitation
–
con_e
Array
conversion factor for evaporation
–
meteo
Array
store all meteo data in memeory for warm start (eg calibration)
compl
ETRef
Array
potential evapotranspiration rate from reference crop
m
Precipitation
Array
Precipitation (input for the model)
m
pet_modus
Number
Index which ETP approach is used e.g. 1 for Penman-Monteith
bool
only_radiation
Flag
Boolean if only radiation is use for calculation e.g JRC EMO dataset
bool
TMin
Array
minimum air temperature
K
TMax
Array
maximum air temperature
K
Tavg
Array
Input, average air Temperature
K
Rsds
Array
short wave downward surface radiation fluxes
W/m2
EAct
Array
Daily vapor pressure
hPa
Psurf
Array
Instantaneous surface pressure
Pa
Qair
Array
specific humidity
kg/kg
Rsdl
Array
long wave downward surface radiation fluxes
W/m2
Wind
Array
wind speed
m/s
EWRef
Array
potential evaporation rate from water surface
m
includeGlaciers
Flag
Include glaciers
bool
meteomapsscale
Array
if meteo maps have the same extend as the other spatial static maps ->
–
meteodown
Array
if meteo maps should be downscaled
–
InterpolationMethod
Number
can be spline or kron
Strin
buffer
List
–
includeOnlyGlaciersMelt
Flag
Include only glacier melt but not rain on glacier
bool
preMaps
Array
choose between steady state precipitation maps for steady state modflo
–
tempMaps
Array
choose between steady state temperature maps for steady state modflow
–
evaTMaps
Array
choose between steady state ETP water maps for steady state modflow or
–
eva0Maps
Array
choose between steady state ETP reference maps for steady state modflo
–
RSDSMaps
Array
Surface Downwelling Shortwave Radiation
w/m2
RSDLMaps
Array
Surface Downwelling Longwave Radiation
W/m2
glaciermeltMaps
Array
Melt from glacier
m
glacierrainMaps
Array
Rain on glacier
m
snowmelt_radiation
Array
–
wc2_tavg
Array
High resolution WorldClim map for average temperature
K
wc4_tavg
Array
upscaled to low resolution WorldClim map for average temperature
K
wc2_tmin
Array
High resolution WorldClim map for min temperature
K
wc4_tmin
Array
upscaled to low resolution WorldClim map for min temperature
K
wc2_tmax
Array
High resolution WorldClim map for max temperature
K
wc4_tmax
Array
upscaled to low resolution WorldClim map for max temperature
K
wc2_prec
Array
High resolution WorldClim map for precipitation
m
wc4_prec
Array
upscaled to low resolution WorldClim map for precipitation
m
xcoarse_prec
List
–
ycoarse_prec
List
–
xfine_prec
List
–
yfine_prec
List
–
meshlist_prec
List
–
xcoarse_tavg
List
–
ycoarse_tavg
List
–
xfine_tavg
List
–
yfine_tavg
List
–
meshlist_tavg
List
–
prec
Array
precipitation in kg m-2s-1 = mm/s (output variable)
kg m-
temp
Array
average temperature in Celsius deg
°C
WtoMJ
Array
Conversion factor from [W] to [MJ] for radiation: 86400 * 1E-6
–
GlacierMelt
Array
melt from glacier
m
GlacierRain
Array
rain on glacier
m
SnowFactor
Array
Multiplier applied to precipitation that falls as snow
–
- Variables
model (object) – Reference to the main CWatM model instance
var (object) – Reference to model variables object containing state variables
- downscaling2(input, downscaleName='', wc2=0, wc4=0, x=None, y=None, xfine=None, yfine=None, meshlist=None, MaskMapBoundaries=None, downscale=0)[source]¶
Spatially downscale meteorological data using delta method with WorldClim.
Performs statistical downscaling of coarse-resolution meteorological data to higher spatial resolution using high-resolution climatological data from WorldClim. Supports multiple interpolation methods including spline, bilinear, and Kronecker product approaches.
- Parameters
input (numpy.ndarray) – Coarse-resolution input meteorological data
downscaleName (str, optional) – Name of high-resolution WorldClim dataset for downscaling
wc2 (numpy.ndarray, optional) – High-resolution WorldClim climatological data
wc4 (numpy.ndarray, optional) – WorldClim data upscaled to input resolution
x (numpy.ndarray, optional) – Coarse grid x-coordinates for bilinear interpolation
y (numpy.ndarray, optional) – Coarse grid y-coordinates for bilinear interpolation
xfine (numpy.ndarray, optional) – Fine grid x-coordinates for bilinear interpolation
yfine (numpy.ndarray, optional) – Fine grid y-coordinates for bilinear interpolation
meshlist (list, optional) – Mesh coordinates for bilinear interpolation
MaskMapBoundaries (tuple, optional) – Boundary flags indicating if mask touches input data boundaries
downscale (int, optional) – Downscaling mode: 0=no scaling, 1=temperature, 2=precipitation
- Returns
Downscaled meteorological data and auxiliary arrays
- Return type
numpy.ndarray or tuple
Notes
Implements delta method downscaling based on: - Temperature: additive corrections using climatological differences - Precipitation: multiplicative corrections using climatological ratios
References
Moreno and Hasenauer (2015): Spatial downscaling of European climate data. International Journal of Climatology.
Mosier et al. (2018): 30-arcsecond monthly climate surfaces with global land coverage. International Journal of Climatology.
- dynamic()[source]¶
Read and process meteorological data for current time step.
Loads meteorological forcing data from NetCDF files for the current time step, applies spatial downscaling when configured, performs unit conversions, and validates data ranges. Handles different variable sets depending on evapotranspiration calculation method.
Notes
Processing workflow: - Load precipitation data and convert units - Read temperature data with Kelvin/Celsius handling - Apply spatial downscaling when configured - Load additional variables based on PET method - Perform data validation and range checks - Store data for calibration mode if enabled
Variable loading depends on configuration: - Basic mode: precipitation, temperature, reference ET - Full PET mode: additional temperature extremes, humidity, wind, pressure - Radiation mode: solar and longwave radiation data - Glacier mode: glacier-specific precipitation and melt data
- initial()[source]¶
Initialize meteorological data processing configuration.
Sets up spatial resolution relationships between meteorological forcing data and model domain, configures downscaling parameters, determines required meteorological variables based on evapotranspiration method, and prepares data structures for efficient data access.
Notes
Key initialization tasks: - Resolution matching between meteo data and model grid - WorldClim downscaling configuration setup - Variable selection based on PET calculation method - Coordinate system and spatial extent validation - Multi-file NetCDF data preparation
inflow module¶
Read river discharge time series as inflow data
- class cwatm.hydrological_modules.inflow.inflow(model)[source]¶
Bases:
objectInflow hydrographs module for adding external water inputs.
Processes inflow hydrograph time series data from external files and applies them at specified spatial locations within the model domain. This module is optional and only activates when the ‘inflow’ option is enabled.
Global variables
Variable [self.var]
Type
Description
Unit
sampleInflow
Number
location of inflow point
lat/l
noinflowpoints
Array
number of inflow points
–
inflowTs
Array
inflow time series data
m3/s
totalQInM3
Array
total inflow over time (for mass balance calculation)
m3
inflowM3
Array
inflow to basin
m3
DtSec
Array
number of seconds per timestep (default = 86400)
s
QInM3Old
Array
Inflow from previous day
m3
- Variables
var (object) – Reference to model variables object containing state variables
model (object) – Reference to the main CWatM model instance
- dynamic()[source]¶
Apply inflow hydrographs at specified locations for current time step.
Retrieves inflow values from time series data for the current time step, applies them at the corresponding spatial locations, and updates cumulative inflow tracking variables.
Notes
Inflow values are: - Read from pre-loaded time series data - Converted from m³/s to m³ per time step - Applied at specified inflow point locations - Accumulated for mass balance tracking
- initial()[source]¶
Initialize inflow points and load time series data.
Reads inflow point locations from configuration files or coordinates, loads time series data from multiple files, and prepares data structures for dynamic inflow application during model execution.
Notes
This method performs several key operations: - Identifies spatial locations for inflow application - Reads and validates time series data from multiple files - Merges time series data from different sources - Initializes cumulative inflow tracking variables
snow_frost module¶
Calculate snow and frost
- class cwatm.hydrological_modules.snow_frost.snow_frost(model)[source]¶
Bases:
objectSnow and frost processes module for precipitation partitioning and snow dynamics.
Handles the partitioning of precipitation into rain and snow, calculates snowmelt and ice melt using temperature-based and radiation-based approaches, manages snow redistribution across elevation zones, and computes frost index for soil freezing. Supports multi-layer snow zones for topographic variability representation.
Global variables
Variable [self.var]
Type
Description
Unit
load_initial
Flag
Settings initLoad holds initial conditions for variables
bool
fracGlacierCover
Array
Fraction of glacier cover in a grid cell
%
DtDay
Array
seconds in a timestep (default=86400)
s
Precipitation
Array
Precipitation (input for the model)
m
only_radiation
Flag
Boolean if only radiation is use for calculation e.g JRC EMO dataset
bool
Tavg
Array
Input, average air Temperature
K
Rsds
Array
short wave downward surface radiation fluxes
W/m2
EAct
Array
Daily vapor pressure
hPa
Rsdl
Array
long wave downward surface radiation fluxes
W/m2
includeGlaciers
Flag
Include glaciers
bool
snowmelt_radiation
Array
–
dzRel
Array
relative elevation in a gridcell by fraction of area
m
SnowMelt
Array
total snow melt from all layers
m
IceMelt
Array
Ice melt (not really ice but an additional snow melt in summer)
m
dem
Array
Digital elevation model
m
lat
Array
Latitude
deg
Rain
Array
Precipitation less snow
m
SnowCover
Array
snow cover (sum over all layers)
m
SnowFactor
Array
Multiplier applied to precipitation that falls as snow
–
numberSnowLayersFloat
Array
Number of snow layers (up to 10)
–
numberSnowLayers
Array
Number of snow layers (up to 10)
–
glaciertransportZone
Number
Number of layers which can be mimiced as glacier transport zone
–
dzSnow
Array
which dzRel is taken for snow calculation
–
lapseratevar
Flag
True or False if a variable lapse rate is used
–
lapseR
Array
Lapserate per month
deg C
lapseRate
Array
Lapserate per month
deg C
frac_snow_redistribution
Array
Maximum fraction of snow that can be redistributed in elevation zones
–
SnowDayDegrees
Array
day of the year to degrees: 360/365.25 = 0.9856
–
SeasonalSnowMeltSin
Array
–
excludeGlacierArea
Flag
True or False to exclude glacier areas from calculation because they a
–
summerSeasonStart
Array
day when summer season starts = 165
–
IceDayDegrees
Array
days of summer (15th June-15th Sept.) to degree: 180/(259-165)
–
SnowSeason
Array
seasonal melt factor
m (Ce
TempSnowLow
Array
Temperature below which all precipitation is snow
°C
TempSnowHigh
Array
Temperature above which all precipitation is rain
°C
TempSnow
Array
Average temperature at which snow melts
°C
SnowMeltCoef
Array
Snow melt coefficient - default: 0.004
–
IceMeltCoef
Array
Ice melt coefficnet - default 0.007
–
TempMelt
Array
Average temperature at which snow melts
°C
SnowMeltRad
Array
calibration value a factor to radiation coefficient
–
SnowCoverS
Array
snow cover for each layer
m
adv_frost
–
maxFrostIndex
–
Kfrost
Array
Snow depth reduction coefficient, (HH, p. 7.28)
m-1
Afrost
Array
Daily decay coefficient, (Handbook of Hydrology, p. 7.28)
–
FrostIndexThreshold
Array
Degree Days Frost Threshold (stops infiltration, percolation and capil
–
SnowWaterEquivalent
Array
Snow water equivalent, (based on snow density of 450 kg/m3) (e.g. Tarb
–
FrostIndex
Array
FrostIndex - Molnau and Bissel (1983), A Continuous Frozen Ground Inde
–
Snow
Array
Snow (equal to a part of Precipitation)
m
Snow1
Array
–
Rain1
Array
–
snow_redistributed_previous
Array
–
SnowFraction
Array
Fraction of snow in a gridcell
–
precipitation_sn
Array
–
fracVegCover
Array
Fraction of specific land covers (0=forest, 1=grasslands, etc.)
%
- Variables
var (object) – Reference to model variables object containing state variables
model (object) – Reference to the main CWatM model instance
- dynamic()[source]¶
Calculate snow and frost processes for current time step.
Performs precipitation partitioning into rain and snow based on temperature thresholds, computes snowmelt and ice melt using temperature-index and radiation-based approaches, handles snow redistribution between elevation zones, and updates frost index for soil freezing conditions.
Notes
The method processes each elevation zone sequentially and handles: - Temperature correction based on elevation and lapse rate - Precipitation partitioning using temperature thresholds - Snow and ice melt calculation with seasonal variations - Snow redistribution based on holding capacity and slope - Snow fraction calculation for each elevation zone - Frost index update based on air temperature and snow cover
References
Snow melt equations modified from: Speers, D.D., Versteeg, J.D. (1979) Runoff forecasting for reservoir operations - the past and the future. In: Proceedings 52nd Western Snow Conference, 149-156
Frost index calculations based on: Molnau and Bissel (1983) A Continuous Frozen Ground Index for Flood Forecasting. In: Maidment, Handbook of Hydrology, p. 7.28, 7.55
Snow redistribution inspired by: Frey and Holzmann (2015) doi:10.5194/hess-19-4517-2015
- initial()[source]¶
Initialize snow and frost module parameters and elevation zones.
Loads parameters for the day-degree approach for precipitation partitioning, snowmelt, and ice melt calculations. Sets up multiple elevation zones for representing topographic variability, initializes snow cover distributions, and configures frost index parameters.
Notes
Key initialization components: - Elevation zone configuration (1-10 zones) based on relative elevation data - Temperature lapse rate setup (constant or variable) - Snow redistribution parameters based on slope and land cover - Seasonal snow melt coefficient parameters - Initial snow cover distribution across elevation zones - Frost index parameters for soil freezing calculations
evaporationPot module¶
Calculate potential Evaporation
- class cwatm.hydrological_modules.evaporationPot.evaporationPot(model)[source]¶
Bases:
objectCalculate potential reference evapotranspiration.
This class computes potential evapotranspiration from climate data using methods primarily based on FAO 56 guidelines and LISVAP. The calculations are based on the Penman-Monteith equation for reference evapotranspiration.
Global variables
Variable [self.var]
Type
Description
Unit
cropCorrect
Array
calibration factor of crop KC factor
–
crop_correct_landCover
Array
–
AlbedoCanopy
Array
Albedo of vegetation canopy (FAO,1998) default =0.23
–
AlbedoSoil
Array
Albedo of bare soil surface (Supit et. al. 1994) default = 0.15
–
AlbedoWater
Array
Albedo of water surface (Supit et. al. 1994) default = 0.05
–
co2
Array
Co2 leads to an increased transpiration. CO2 concentration for Yang et
ppm
albedoLand
Array
albedo from land surface (from GlobAlbedo database)
–
albedoOpenWater
Array
albedo from open water surface (from GlobAlbedo database)
–
thermalI
Array
ThermalIndex. Use to calculate pot. Evaporation with Thornthwaite
deg C
ETRef
Array
potential evapotranspiration rate from reference crop
m
pet_modus
Number
Index which ETP approach is used e.g. 1 for Penman-Monteith
bool
only_radiation
Flag
Boolean if only radiation is use for calculation e.g JRC EMO dataset
bool
TMin
Array
minimum air temperature
K
TMax
Array
maximum air temperature
K
Tavg
Array
Input, average air Temperature
K
Rsds
Array
short wave downward surface radiation fluxes
W/m2
EAct
Array
Daily vapor pressure
hPa
Psurf
Array
Instantaneous surface pressure
Pa
Qair
Array
specific humidity
kg/kg
Rsdl
Array
long wave downward surface radiation fluxes
W/m2
Wind
Array
wind speed
m/s
EWRef
Array
potential evaporation rate from water surface
m
dem
Array
Digital elevation model
m
lat
Array
Latitude
deg
- Variables
var (object) – Model variables container
model (object) – CWatM model instance
References
FAO 56 Guidelines: http://www.fao.org/docrep/X0490E/x0490e08.htm#penman%20monteith%20equation LISVAP Documentation: https://ec.europa.eu/jrc/en/publication/eur-scientific-and-technical-research-reports/lisvap-evaporation-pre-processor-lisflood-water-balance-and-flood-simulation-model
- dynamic()[source]¶
Calculate potential evapotranspiration dynamically.
Main routine that determines which ET calculation method to use based on configuration settings and calls appropriate calculation methods.
- dynamic_1()[source]¶
Calculate ET using modified Penman approach.
Computes potential evapotranspiration using a modified Penman equation that includes temperature, humidity, wind speed, and radiation components.
- dynamic_2()[source]¶
Calculate ET using Penman-Monteith approach.
Computes potential evapotranspiration using the full Penman-Monteith equation as recommended by FAO 56, incorporating aerodynamic and surface resistances.
- dynamic_4()[source]¶
Calculate ET using Hargreaves-Samani method.
Computes potential evapotranspiration using the Hargreaves-Samani equation which requires only temperature data and extraterrestrial radiation.
- dynamic_5()[source]¶
Read potential evapotranspiration from input data.
Loads pre-calculated potential evapotranspiration values from input files instead of calculating them within the model.
- initial()[source]¶
Initialize potential evapotranspiration calculations.
Sets up parameters for ET calculation methods, reads configuration settings for different ET calculation approaches, and initializes required variables.
evaporation module¶
Calculate actual evapotranspiration
- class cwatm.hydrological_modules.evaporation.evaporation(model)[source]¶
Bases:
objectEvaporation module for hydrological modeling.
This class handles the calculation of potential evaporation and potential transpiration for different land cover types. It processes crop coefficients, calculates bare soil evaporation, and manages crop-specific evapotranspiration calculations.
Global variables
Variable [self.var]
Type
Description
Unit
cropKCmonth
Array
Crop KC factor for different crops and different seasons
–
snowEvap
Array
total evaporation from snow for a snow layers
m
iceEvap
Array
Evaporation from ice (sublimation)
m
Crops_names
Array
Internal: List of specific crops
–
activatedCrops
Array
Fraction of area a specific crop is planted
–
load_initial
Flag
Settings initLoad holds initial conditions for variables
bool
monthCounter
Array
Month counter for each crop after crop has planted
–
fracCrops_IrrLandDemand
Array
Month counter for each crop after crop has planted
–
fracCrops_nonIrrLandDemand
–
ratio_a_p_nonIrr
Array
Ratio actual to potential evapotranspiration, monthly, non-irrigated [
%
totalPotET_month
Array
Total potential evapotranspiration in a month
m
ratio_a_p_Irr
Array
Ratio actual to potential evapotranspiration, monthly [crop specific]
%
Yield_nonIrr
Array
Relative monthly non-irrigated yield [crop specific]
%
currentKY
Array
Yield sensitivity coefficient [crop specific]
–
Yield_Irr
Array
Relative monthly irrigated yield [crop specific]
%
currentKC
Array
Current crop coefficient for specific crops
–
generalIrrCrop_max
Array
–
generalnonIrrCrop_max
Array
–
weighted_KC_nonIrr
Array
–
weighted_KC_nonIrr_woFallow
Array
–
weighted_KC_Irr
Array
–
_weighted_KC_Irr
Array
–
weighted_KC_Irr_woFallow
Array
–
totalPotET_month_segment
Array
–
PotETaverage_crop_segments
Array
–
areaCrops_Irr_segment
Array
–
areaCrops_nonIrr_segment
Array
–
areaPaddy_Irr_segment
Array
–
Precipitation_segment
Array
–
availableArableLand_segment
Array
–
cropCorrect
Array
calibration factor of crop KC factor
–
crop_correct_landCover
Array
–
includeCrops
Flag
1 when includeCrops=True in Settings, 0 otherwise
bool
Crops
Array
Internal: List of specific crops and Kc/Ky parameters
–
daily_crop_KC
Array
–
interceptCap
Array
interception capacity of vegetation
m
potTranspiration
Array
Potential transpiration (after removing of evaporation)
m
cropKC
Array
crop coefficient for each of the 4 different land cover types (forest,
–
minCropKC
Array
minimum crop factor (default 0.2)
–
minInterceptCap
Array
Maximum interception read from file for forest and grassland land cove
m
irrigatedArea_original
Array
–
frac_totalnonIrr
Array
Fraction sown with specific non-irrigated crops
%
frac_totalIrr_max
Array
Fraction sown with specific irrigated crops, maximum throughout simula
%
frac_totalnonIrr_max
Array
Fraction sown with specific non-irrigated crops, maximum throughout si
%
GeneralCrop_Irr
Array
Fraction of irrigated land class sown with generally representative cr
%
fallowIrr
Array
Fraction of fallowed irrigated land
%
fallowIrr_max
Array
Fraction of fallowed irrigated land, maximum throughout simulation
%
GeneralCrop_nonIrr
Array
Fraction of grasslands sown with generally representative crop
%
fallownonIrr
Array
Fraction of fallowed non-irrigated land
%
fallownonIrr_max
Array
Fraction of fallowed non-irrigated land, maximum throughout simulation
%
availableArableLand
Array
Fraction of land not currently planted with specific crops
%
ETRef
Array
potential evapotranspiration rate from reference crop
m
Precipitation
Array
Precipitation (input for the model)
m
coverTypes
Array
land cover types - forest - grassland - irrPaddy - irrNonPaddy - water
–
SnowMelt
Array
total snow melt from all layers
m
IceMelt
Array
Ice melt (not really ice but an additional snow melt in summer)
m
potBareSoilEvap
Array
potential bare soil evaporation (calculated with minus snow evaporatio
m
irr_Paddy_month
Array
–
ET_crop_Irr_paddy
Array
–
ET_crop_Irr_paddy_fraccrop
Array
–
fracCrops_Irr
Array
Fraction of cell currently planted with specific irrigated crops
%
fracCrops_nonIrr
Array
Fraction of cell currently planted with specific non-irr crops
%
actTransTotal_month_nonIrr
Array
Internal variable: Running total of transpiration for specific non-ir
m
actTransTotal_month_Irr
Array
Internal variable: Running total of transpiration for specific irriga
m
irr_crop_month
Number
–
frac_totalIrr
Array
Fraction sown with specific irrigated crops
%
weighted_KC_Irr_woFallow_fullKc
Array
–
totalPotET
Array
Potential evaporation per land use class
m
PotET_crop
Array
–
fracVegCover
Array
Fraction of specific land covers (0=forest, 1=grasslands, etc.)
%
adminSegments
Array
Domestic agents
Int
cellArea
Array
Area of cell
m2
- Variables
var (object) – Model variables container
model (object) – CWatM model instance
- dynamic(coverType, No)[source]¶
Calculate potential evapotranspiration for a specific land cover type.
This method computes potential evaporation and transpiration using crop coefficients, handles crop dynamics when crops are enabled, and calculates bare soil evaporation. It processes monthly crop coefficient data with daily interpolation.
- Parameters
coverType (str) – Land cover type identifier (e.g., ‘forest’, ‘grassland’, ‘irrPaddy’)
No (int) – Numerical identifier for land cover type (forest=0, grassland=1, etc.)
- Returns
Potential evaporation from bare soil and potential transpiration values
- Return type
tuple
interception module¶
Calculate interception
- class cwatm.hydrological_modules.interception.interception(model)[source]¶
Bases:
objectInterception module for calculating canopy interception processes.
Handles the interception of precipitation by vegetation canopies and subsequent evaporation of intercepted water for different land cover types. Calculates throughfall, interception storage, and evaporation from intercepted water.
Global variables
Variable [self.var]
Type
Description
Unit
snowEvap
Array
total evaporation from snow for a snow layers
m
iceEvap
Array
Evaporation from ice (sublimation)
m
interceptCap
Array
interception capacity of vegetation
m
potTranspiration
Array
Potential transpiration (after removing of evaporation)
m
interceptEvap
Array
simulated evaporation from water intercepted by vegetation
m
minInterceptCap
Array
Maximum interception read from file for forest and grassland land cove
m
interceptStor
Array
simulated vegetation interception storage
m
twothird
Number
2/3 –
EWRef
Array
potential evaporation rate from water surface
m
availWaterInfiltration
Array
quantity of water reaching the soil after interception, more snowmelt
m
SnowMelt
Array
total snow melt from all layers
m
IceMelt
Array
Ice melt (not really ice but an additional snow melt in summer)
m
Rain
Array
Precipitation less snow
m
actualET
Array
simulated evapotranspiration from soil, flooded area and vegetation
m
- Variables
var (object) – Reference to model variables object containing state variables
model (object) – Reference to the main CWatM model instance
- dynamic(coverType, No)[source]¶
Calculate interception processes for a specific land cover type.
Computes throughfall, interception storage, and evaporation from intercepted water based on precipitation, interception capacity, and potential transpiration. Updates state variables for water available for infiltration and actual evapotranspiration.
- Parameters
coverType (str) – Land cover type identifier (e.g., ‘forest’, ‘grassland’, ‘irrPaddy’, ‘irrNonPaddy’, ‘sealed’)
No (int) – Index number of the land cover type in model arrays
Notes
The method handles different interception processes based on land cover type: - Forest/grassland: Uses seasonal interception capacity with 2/3 power law - Irrigated areas: Uses minimum interception capacity with 2/3 power law - Sealed surfaces: Uses reference evapotranspiration for interception evaporation
sealed_water module¶
Calculate water runoff from impermeable surface
- class cwatm.hydrological_modules.sealed_water.sealed_water(model)[source]¶
Bases:
objectSealed surface and open water runoff and evaporation module.
Handles runoff generation and evaporation processes for impermeable surfaces (sealed/urban areas) and open water land cover types. Accounts for water bodies not explicitly represented in the lakes/reservoirs/channels framework.
Global variables
Variable [self.var]
Type
Description
Unit
modflow
Flag
True if modflow_coupling = True in settings file
bool
EWRef
Array
potential evaporation rate from water surface
m
availWaterInfiltration
Array
quantity of water reaching the soil after interception, more snowmelt
m
actualET
Array
simulated evapotranspiration from soil, flooded area and vegetation
m
directRunoff
Array
Simulated surface runoff
m
openWaterEvap
Array
Simulated evaporation from open areas
m
capillar
Array
Flow from groundwater to the third CWATM soil layer. Used with MODFLOW
m
- Variables
var (object) – Reference to model variables object containing state variables
model (object) – Reference to the main CWatM model instance
Notes
The module addresses hydrological processes on: - Sealed surfaces: Impermeable urban/built-up areas with limited evaporation - Open water: Water land cover including small rivers, ponds, wetlands
Open water evaporation accounts for water bodies not captured by explicit lakes, reservoirs, and channels. For instance, if explicit water bodies cover 10% of a cell but water land class covers 20%, this module handles evaporation from the additional 10% of unrepresented water surfaces.
Evaporation rates differ by surface type: - Water surfaces: Full reference evapotranspiration rate - Sealed surfaces: Reduced rate (0.2 × reference) for ponded water
- dynamic(coverType, No)[source]¶
Calculate runoff and evaporation for sealed surfaces and open water.
Processes water balance for impermeable surfaces and open water land cover types, determining direct runoff and evaporation rates based on surface characteristics and available water.
- Parameters
coverType (str) – Land cover type identifier (‘sealed’ or ‘water’)
No (int) – Index number of the land cover type in model arrays
Notes
Processing logic: - Sealed surfaces (No=4): Limited evaporation (0.2 × EWRef), remainder to runoff - Open water (No=5): Full evaporation rate (1.0 × EWRef), remainder to runoff - ModFlow integration: Includes capillary rise contributions to runoff - Updates actual evapotranspiration and direct runoff arrays
The method only processes land cover types with No > 3 (sealed and water), as other land covers are handled by different modules.
Hydrology II - from soil to river¶
soil module¶
Calculate fluxes in 3 layer soil
- class cwatm.hydrological_modules.soil.soil(model)[source]¶
Bases:
objectSoil water dynamics module using the Arno scheme for vertical water transfer.
Simulates soil water movement, evapotranspiration, and runoff generation using a multi-layer soil model based on the Arno scheme. Handles infiltration, percolation, capillary rise, preferential flow, and transpiration processes across different land cover types.
Global variables
Variable [self.var]
Type
Description
Unit
capRiseFrac
Array
fraction of a grid cell where capillar rise may happen
m
modflow
Flag
True if modflow_coupling = True in settings file
bool
activatedCrops
Array
Fraction of area a specific crop is planted
–
currentKC
Array
Current crop coefficient for specific crops
–
weighted_KC_Irr_woFallow
Array
–
storGroundwater
Array
Groundwater storage (non-fossil). This is primarily used when not usin
m
includeCrops
Flag
1 when includeCrops=True in Settings, 0 otherwise
bool
Crops
Array
Internal: List of specific crops and Kc/Ky parameters
–
potTranspiration
Array
Potential transpiration (after removing of evaporation)
m
cropKC
Array
crop coefficient for each of the 4 different land cover types (forest,
–
minCropKC
Array
minimum crop factor (default 0.2)
–
rootDepth
Array
rootdepth of different layers
m
KSat1
Array
Saturated conductivity layer 1
cm/da
KSat2
Array
Saturated conductivity layer 2
cm/da
KSat3
Array
Saturated conductivity layer 3
cm/da
genuM1
Array
soil: lambda / (1+ lambda) layer1
–
genuM2
Array
soil: lambda / (1+ lambda) layer2
–
genuM3
Array
soil: lambda / (1+ lambda) layer3
–
genuInvM1
Array
soil:1 / genuM1
–
genuInvM2
Array
soil:1 / genuM2
–
genuInvM3
Array
soil:1 / genuM3
–
ws1
Array
Maximum storage capacity in layer 1
m
ws2
Array
Maximum storage capacity in layer 2
m
ws3
Array
Maximum storage capacity in layer 3
m
wres1
Array
Residual storage capacity in layer 1
m
wres2
Array
Residual storage capacity in layer 2
m
wres3
Array
Residual storage capacity in layer 3
m
wrange1
Array
maximum soil moisture (ws) - residual soil mositure (wres) layer 1
m
wrange2
Array
maximum soil moisture (ws) - residual soil mositure (wres) layer 2
m
wrange3
Array
maximum soil moisture (ws) - residual soil mositure (wres) layer 3
m
wwp1
Array
Soil moisture at wilting point in layer 1
m
wwp2
Array
Soil moisture at wilting point in layer 2
m
wwp3
Array
Soil moisture at wilting point in layer 3
m
kunSatFC12
Array
calculation from van Genuchten, Mualem equation
m/day
kunSatFC23
Array
calculation from van Genuchten, Mualem equation
m/day
arnoBeta
Array
arnoBeta defines the shape of soil water capacity distribution curve a
–
adjRoot
Array
–
maxtopwater
Array
maximum heigth of topwater
m
EWRef
Array
potential evaporation rate from water surface
m
availWaterInfiltration
Array
quantity of water reaching the soil after interception, more snowmelt
m
FrostIndexThreshold
Array
Degree Days Frost Threshold (stops infiltration, percolation and capil
–
FrostIndex
Array
FrostIndex - Molnau and Bissel (1983), A Continuous Frozen Ground Inde
–
potBareSoilEvap
Array
potential bare soil evaporation (calculated with minus snow evaporatio
m
irr_Paddy_month
Array
–
ET_crop_Irr_paddy
Array
–
ET_crop_Irr_paddy_fraccrop
Array
–
fracCrops_Irr
Array
Fraction of cell currently planted with specific irrigated crops
%
fracCrops_nonIrr
Array
Fraction of cell currently planted with specific non-irr crops
%
actTransTotal_month_nonIrr
Array
Internal variable: Running total of transpiration for specific non-ir
m
actTransTotal_month_Irr
Array
Internal variable: Running total of transpiration for specific irriga
m
irr_crop_month
Number
–
frac_totalIrr
Array
Fraction sown with specific irrigated crops
%
weighted_KC_Irr_woFallow_fullKc
Array
–
totalPotET
Array
Potential evaporation per land use class
m
PotET_crop
Array
–
actualET
Array
simulated evapotranspiration from soil, flooded area and vegetation
m
soilLayers
Array
Number of soil layers
–
soildepth
Array
Thickness of the first soil layer
m
wfc1
Array
Soil moisture at field capacity in layer 1
m
wfc2
Array
Soil moisture at field capacity in layer 2
m
wfc3
Array
Soil moisture at field capacity in layer 3
m
w1
Array
Simulated water storage in the layer 1
m
w2
Array
Simulated water storage in the layer 2
m
w3
Array
Simulated water storage in the layer 3
m
topwater
Array
quantity of water above the soil (flooding)
m
directRunoff
Array
Simulated surface runoff
m
interflow
Array
Simulated flow reaching runoff instead of groundwater
m
openWaterEvap
Array
Simulated evaporation from open areas
m
percolationImp
Array
Fraction of area covered by the corresponding landcover type
m
cropGroupNumber
Array
soil water depletion fraction, Van Diepen et al., 1988: WOFOST 6.0, p.
–
cPrefFlow
Array
Factor influencing preferential flow (flow from surface to GW)
–
pumping_actual
Array
–
gwdepth_observations
Array
Input, gw_depth_observations, groundwater depth observations
m
gwdepth_adjuster
Array
Groundwater depth adjuster
m
rws
Array
Transpiration reduction factor (in case of water stress)
–
actBareSoilEvap
Array
Simulated evaporation from the first soil layer
m
prefFlow
Array
Flow going directly from soil surface to groundwater [land class speci
m
infiltration
Array
Water actually infiltrating the soil
m
capRiseFromGW
Array
Simulated capillary rise from groundwater
m
NoSubSteps
Array
Number of sub steps to calculate soil percolation
–
perc1to2
Array
Simulated water flow from soil layer 1 to soil layer 2
m
perc2to3
Array
Simulated water flow from soil layer 2 to soil layer 3
m
perc3toGW
Array
Simulated water flow from soil layer 3 to groundwater
m
theta1
Array
fraction of water in soil compartment 1 for each land use class
–
theta2
Array
fraction of water in soil compartment 2 for each land use class
–
theta3
Array
fraction of water in soil compartment 3 for each land use class
–
actTransTotal
Array
Total actual transpiration from the three soil layers
m
actTransTotal_forest
Array
Transpiration from forest land cover
m
actTransTotal_grasslands
Array
Transpiration from grasslands land cover
m
actTransTotal_paddy
Array
Transpiration from paddy land cover
m
actTransTotal_nonpaddy
Array
Transpiration from non-paddy land cover
m
actTransTotal_crops_Irr
Array
Transpiration associated with specific irrigated crops
m
actTransTotal_crops_nonIrr
Array
Transpiration associated with specific non-irr crops
m
ET_crop_Irr
Array
–
ET_crop_nonIrr
Array
–
irr_crop
Array
–
ratio_a_p_nonIrr_daily
Array
–
ratio_a_p_Irr_daily
Array
–
irrM3_crop_month_segment
Array
–
irrM3_Paddy_month_segment
Array
–
gwRecharge
Array
groundwater recharge
m
baseflow
Array
simulated baseflow (= groundwater discharge to river)
m
capillar
Array
Flow from groundwater to the third CWATM soil layer. Used with MODFLOW
m
capriseindex
Array
–
soildepth12
Array
Total thickness of layer 2 and 3
m
fracVegCover
Array
Fraction of specific land covers (0=forest, 1=grasslands, etc.)
%
adminSegments
Array
Domestic agents
Int
cellArea
Array
Area of cell
m2
act_irrConsumption
Array
actual irrigation water consumption
m
act_irrNonpaddyWithdrawal
Array
non-paddy irrigation withdrawal
m
act_irrPaddyWithdrawal
Array
paddy irrigation withdrawal
m
- Variables
var (object) – Reference to model variables object containing state variables
model (object) – Reference to the main CWatM model instance
Notes
The module implements: - Multi-layer soil water balance (typically 3 layers) - Arno scheme for heterogeneous runoff generation - Root zone dynamics for transpiration - Preferential flow and interflow processes - Soil hydraulic property management - Capillary rise from groundwater
Based on concepts from PCRGLOBE, LISFLOOD, and HBV models. References the Arno scheme for spatially variable soil moisture.
- dynamic(coverType, No)[source]¶
Calculate soil water dynamics for a specific land cover type.
Simulates vertical water transport, evapotranspiration, and runoff generation for a land cover class using multi-layer soil water balance with the Arno scheme. Handles infiltration, percolation, capillary rise, transpiration, and preferential flow.
- Parameters
coverType (str) – Land cover type identifier (e.g., ‘forest’, ‘grassland’, ‘irrPaddy’, ‘irrNonPaddy’)
No (int) – Index number of the land cover type in model arrays
Notes
Processing sequence: 1. Water stress calculation and transpiration limitation 2. Bare soil evaporation from upper layer 3. Infiltration capacity using Arno scheme 4. Preferential flow calculation 5. Multi-layer percolation with Van Genuchten equations 6. Capillary rise between layers and from groundwater 7. Interflow and groundwater recharge calculation
Special handling for irrigated paddy fields: - Maintains surface water storage (topwater) - Open water evaporation from flooded fields - Modified infiltration when fields are flooded
The Arno scheme accounts for spatial variability in soil saturation within grid cells, leading to heterogeneous runoff generation.
- initial()[source]¶
Initialize soil hydraulic properties and layer configuration.
Sets up soil layer structure, hydraulic parameters, and initial conditions for soil water dynamics including percolation limitations, preferential flow, root zone characteristics, and field capacity relationships.
Notes
Initialization includes: - Soil layer configuration (typically 3 layers) - Hydraulic properties (field capacity, wilting point, saturation) - Preferential flow and interflow parameters - Root zone depth and distribution - Percolation impedance factors - Initial soil moisture conditions - Crop-specific parameters for water uptake
Soil layers represent different depths and hydraulic characteristics for realistic vertical water movement simulation.
capillarRise module¶
Calculate capillar rise from groundwater
- class cwatm.hydrological_modules.capillarRise.capillarRise(model)[source]¶
Bases:
objectCapillary rise module for groundwater-surface interaction.
This class calculates the cell fraction influenced by capillary rise based on groundwater depth and relative elevation within each grid cell. It determines areas where groundwater can reach the surface through capillary action.
Global variables
Variable [self.var]
Type
Description
Unit
capRiseFrac
Array
fraction of a grid cell where capillar rise may happen
m
modflow
Flag
True if modflow_coupling = True in settings file
bool
storGroundwater
Array
Groundwater storage (non-fossil). This is primarily used when not usin
m
specificYield
Array
groundwater reservoir parameters (if ModFlow is not used) used to comp
m
maxGWCapRise
Array
influence of capillary rise above groundwater level
m
dzRel
Array
relative elevation in a gridcell by fraction of area
m
- Variables
var (object) – Model variables container
model (object) – CWatM model instance
- dynamic()[source]¶
Calculate capillary rise dynamics for the current time step.
Computes the cell fraction influenced by capillary rise based on the approximate height of groundwater and relative elevation within each grid cell. This determines areas where groundwater contributes to surface processes through capillary action.
groundwater module¶
Calculate groundwater
- class cwatm.hydrological_modules.groundwater.groundwater(model)[source]¶
Bases:
objectGroundwater dynamics module.
This class manages groundwater processes including groundwater flow, storage changes, and interactions with surface water systems.
Global variables
Variable [self.var]
Type
Description
Unit
modflow
Flag
True if modflow_coupling = True in settings file
bool
load_initial
Flag
Settings initLoad holds initial conditions for variables
bool
storGroundwater
Array
Groundwater storage (non-fossil). This is primarily used when not usin
m
specificYield
Array
groundwater reservoir parameters (if ModFlow is not used) used to comp
m
recessionCoeff
Array
groundwater storage times this coefficient gives baseflow
frac
readAvlStorGroundwater
Array
same as storGroundwater but equal to 0 when inferior to a treshold
m
loadInit
Flag
If true initial conditions are loaded
bool
sum_gwRecharge
Array
groundwater recharge
m
baseflow
Array
simulated baseflow (= groundwater discharge to river)
m
capillar
Array
Flow from groundwater to the third CWATM soil layer. Used with MODFLOW
m
nonFossilGroundwaterAbs
Array
Non-fossil groundwater abstraction. Used primarily without MODFLOW.
m
- Variables
var (object) – Model variables container
model (object) – CWatM model instance
runoff_concentration module¶
Calculate runoff concentration - from grid cell to grid cell corner
- class cwatm.hydrological_modules.runoff_concentration.runoff_concentration(model)[source]¶
Bases:
objectRunoff concentration module for temporal flow concentration within grid cells.
Handles the intermediate process between runoff generation and channel routing, concentrating runoff from different land cover classes within each grid cell using lag-time and diffusion processes based on topographic and land cover characteristics.
Global variables
Variable [self.var]
Type
Description
Unit
load_initial
Flag
Settings initLoad holds initial conditions for variables
bool
leakageIntoRunoff
Array
Canal leakage leading to runoff
m
fracGlacierCover
Array
Fraction of glacier cover in a grid cell
%
includeGlaciers
Flag
Include glaciers
bool
includeOnlyGlaciersMelt
Flag
Include only glacier melt but not rain on glacier
bool
coverTypes
Array
land cover types - forest - grassland - irrPaddy - irrNonPaddy - water
–
runoff
Array
Total runoff from surface, interflow and groundwater
m
sum_interflow
Array
sum of iterflow from all land cover types
m
GlacierMelt
Array
melt from glacier
m
GlacierRain
Array
rain on glacier
m
runoff_peak
Array
peak time of runoff in seconds for each land use class
s
tpeak_interflow
Array
peak time of interflow
s
tpeak_baseflow
Array
peak time of baseflow
s
tpeak_glaciers
Array
peak time of glacier
s
maxtime_runoff_conc
Array
maximum time till all flow is at the outlet
s
runoff_conc
Array
runoff after concentration - triangular-weighting method
m
gridcell_storage
Array
storage of water due to runoff concentration
m
sum_landSurfaceRunoff
Array
Runoff concentration above the soil more interflow including all landc
m
landSurfaceRunoff
Array
Runoff concentration above the soil more interflow
m
directRunoffGlacier
Array
direct runoff from glacier
m
directRunoff
Array
Simulated surface runoff
m
interflow
Array
Simulated flow reaching runoff instead of groundwater
m
baseflow
Array
simulated baseflow (= groundwater discharge to river)
m
fracVegCover
Array
Fraction of specific land covers (0=forest, 1=grasslands, etc.)
%
cellArea
Array
Area of cell
m2
- Variables
var (object) – Reference to model variables object containing state variables
model (object) – Reference to the main CWatM model instance
Notes
The concentration process accounts for: - Variable lag times based on slope, length, and land cover - Temporal diffusion using triangular weighting functions - Different peak times for surface runoff, interflow, and baseflow - Land cover-specific concentration parameters
Mathematical formulation: Q(t) = sum_{i=0}^{max} c(i) * Q_source(t - i + 1)
where c(i) represents the triangular weighting coefficients: c(i) = integral from (i-1) to i of [2/max - (u - max/2) * 4/max^2] du
References
Based on triangular weighting function concepts for temporal concentration
- dynamic()[source]¶
Calculate runoff concentration for current time step.
Applies temporal concentration to runoff components from different land cover types, distributing flow over time using pre-calculated lag times and triangular weighting functions.
Notes
Processing includes: - Temporal distribution of surface runoff, interflow, and baseflow - Application of triangular weighting functions - Integration of concentrated flows from all land cover types - Update of flow concentration arrays for routing
The concentration process smooths the temporal distribution of runoff, representing the natural lag between runoff generation and arrival at grid cell outlets.
- initial()[source]¶
Initialize runoff concentration parameters and lag time calculations.
Sets up concentration time parameters for different runoff components and calculates land cover-specific lag times based on topographic characteristics and flow path properties.
Notes
Peak time settings: - Surface runoff: 3 time steps - Interflow: 4 time steps - Baseflow: 5 time steps
Concentration time calculation considers: - Grid cell slope and length - Land cover-specific Manning roughness - Flow velocity relationships - Triangular weighting function parameters
The lag times determine the temporal distribution of runoff concentration for each land cover type within grid cells.
Hydrology III - Socio-economic - Water demand¶
water_demand.water_demand¶
Calculate water demand from different sectors
- class cwatm.hydrological_modules.water_demand.water_demand.water_demand(model)[source]¶
Bases:
objectMain coordinating class for integrated water demand calculations across all sectors.
This class orchestrates water demand calculations for domestic, industrial, livestock, irrigation, environmental, and wastewater sectors. It manages complex water allocation algorithms, coordinates agent-based modeling for irrigation and domestic sectors, handles water abstraction fractions from different sources (surface water, groundwater, lakes, reservoirs), and processes command area operations for efficient water distribution.
The class implements sophisticated water demand-supply balance algorithms, manages sector-specific and source-specific abstraction strategies, and handles desalination operations when configured. It supports both traditional grid-based modeling and agent-based approaches for enhanced spatial representation of water management decisions.
Global variables
Variable [self.var]
Type
Description
Unit
channelStorage
Array
Channel water storage
m3
unmetDemand_runningSum
Array
Unmet water demand (too less water availability)
m
modflow
Flag
True if modflow_coupling = True in settings file
bool
pot_domesticConsumption
Array
–
load_initial
Flag
Settings initLoad holds initial conditions for variables
bool
readAvlStorGroundwater
Array
same as storGroundwater but equal to 0 when inferior to a treshold
m
pot_industryConsumption
Array
–
loadInit
Flag
If true initial conditions are loaded
bool
includeDesal
Flag
–
unlimitedDesal
Flag
–
desalAnnualCap
Number
–
efficiencyPaddy
Array
Input, irrPaddy_efficiency, paddy irrigation efficiency, the amount of
frac
efficiencyNonpaddy
Array
Input, irrNonPaddy_efficiency, non-paddy irrigation efficiency, the am
frac
returnfractionIrr
Array
Input, irrigation_returnfraction, the fraction of non-efficient water
frac
irrPaddyDemand
Array
Paddy irrigation demand
m
compress_LR
Array
boolean map as mask map for compressing lake/reservoir
–
decompress_LR
Array
boolean map as mask map for decompressing lake/reservoir
–
MtoM3C
Array
conversion factor from m to m3 (compressed map)
–
resId_restricted
Array
waterbody ID for waste water
–
waterBodyBuffer
Array
Create a buffer around water bodies as command areas for lakes and res
m2
waterBodyBuffer_wwt
Array
Create a buffer around water bodies as command areas for lakes and res
m2
reservoir_releases_excel_option
Flag
If Excel file is used for addition reservoirs, watertransfer, release
bool
lakeResStorage_release_ratioC
Array
daily release ration for reservoirs - compressed
–
M3toM
Array
Coefficient to change units
–
MtoM3
Array
Coefficient to change units
–
InvDtSec
Array
inversere of seconds per timestep (default 1/86400)
1/s
InvCellArea
Array
Inverse of cell area of each simulated mesh
1/m2
GW_pumping
Flag
Input, True if Groundwater_pumping=True
bool
availableGWStorageFraction
Array
–
groundwater_storage_available
Array
Groundwater storage. Used with MODFLOW.
m
gwstorage_full
Number
Groundwater storage at full capacity
m
wwtColArea
Array
–
wwtSewerCollection
Array
–
wwtOverflowOutM
Array
–
fracVegCover
Array
Fraction of specific land covers (0=forest, 1=grasslands, etc.)
%
adminSegments
Array
Domestic agents
Int
cellArea
Array
Area of cell
m2
nonFossilGroundwaterAbs
Array
Non-fossil groundwater abstraction. Used primarily without MODFLOW.
m
includeWastewater
Flag
–
waterBodyTyp_unchanged
Array
–
lakeVolumeM3C
Array
compressed map of lake volume
m3
lakeStorageC
Array
–
reservoirStorageM3C
Array
–
lakeResStorageC
Array
–
lakeResStorage
Array
–
reservoir_supply
Array
–
waterBodyTypCTemp
Array
waterbody temp e.g. lake, reservoir, wetlands -> compressed
–
smalllakeVolumeM3
Array
–
smalllakeStorage
Array
–
act_SurfaceWaterAbstract
Array
Surface water abstractions
m
readAvlChannelStorageM
Array
–
leakageCanals_M
Array
–
includeWastewaterPits
Flag
–
pitLatrinToGW
Array
–
addtoevapotrans
Array
Irrigation application loss to evaporation
m
act_irrConsumption
Array
actual irrigation water consumption
m
act_irrNonpaddyWithdrawal
Array
non-paddy irrigation withdrawal
m
act_irrPaddyWithdrawal
Array
paddy irrigation withdrawal
m
act_bigLakeResAbst
Array
Abstractions to satisfy demands from lakes and reservoirs
m
act_smallLakeResAbst
Array
Abstractions from small lakes at demand location
m
returnFlow
Array
–
act_nonIrrConsumption
Array
Non-irrigation consumption
m
act_nonIrrWithdrawal
Array
Non-irrigation withdrawals
m
act_irrWithdrawal
Array
Irrigation withdrawals
m
waterdemandFixed
Array
–
modfPumpingM
Array
–
activate_domestic_agents
Flag
Input, True if activate_domestic_agents = True
bool
domesticDemand
Array
Domestic demand
m
swAbstractionFraction_domestic
Array
With domestic agents, derived from surface water over total water requ
%
demand_unit
Flag
–
sectorSourceAbstractionFractions
Array
–
swAbstractionFraction_Channel_Domes
Array
Input, Fraction of Domestic demands to be satisfied with Channel
%
swAbstractionFraction_Lift_Domestic
Array
Input, Fraction of Domestic demands to be satisfied with Lift
%
swAbstractionFraction_Res_Domestic
Array
Input, Fraction of Domestic demands to be satisfied with Reservoirs
%
swAbstractionFraction_Lake_Domestic
Array
Input, Fraction of Domestic demands to be satisfied with Lake
%
gwAbstractionFraction_Domestic
Array
Fraction of domestic water demand to be satisfied by groundwater
%
dom_efficiency
Array
–
envFlow
Array
–
industryDemand
Array
–
ind_efficiency
Array
–
unmetDemandPaddy
Array
Unmet paddy demand
m
unmetDemandNonpaddy
Array
Unmet nonpaddy demand
m
unmetDemand
Array
Unmet groundwater demand to determine potential fossil groundwaterwate
m
irrDemand
Array
Cover-specific Irrigation demand
m
irrNonpaddyDemand
Array
–
totalIrrDemand
Array
Irrigation demand
m
livestockDemand
Array
–
pot_livestockConsumption
Array
Potential livestock consumption
m
liv_efficiency
Number
Livestock water use efficiency
–
wwtEffluentsGenerated
Array
–
wwtSewerCollection_domestic
Array
–
wwtSewerCollection_industry
Array
–
includeIndusDomesDemand
Flag
Input, True if includeIndusDomesDemand = True
bool
activate_irrigation_agents
Flag
Input, True if activate_irrigation_agents = True
bool
relaxGWagent
Flag
–
relaxSWagent
Flag
–
irrWithdrawalSW_max
Array
–
irrWithdrawalGW_max
Array
–
relax_irrigation_agents
Flag
–
relax_abstraction_fraction_initial
Array
–
waterdemandFixedYear
Array
–
swAbstractionFraction_Channel_Lives
Array
Input, Fraction of Livestock demands to be satisfied from Channels
%
swAbstractionFraction_Channel_Indus
Array
Input, Fraction of Industrial water demand to be satisfied by Channels
%
swAbstractionFraction_Channel_Irrig
Array
Input, Fraction of Irrigation demand to be satisfied from Channels
%
swAbstractionFraction_Lake_Livestoc
Array
Input, Fraction of Livestock water demands to be satisfied by Lakes
%
swAbstractionFraction_Lake_Industry
Array
Input, Fraction of Industrial water demand to be satisfied by Lakes
%
swAbstractionFraction_Lake_Irrigati
Array
Input, Fraction of Irrigation demand to be satisfied by Lakes
%
swAbstractionFraction_Res_Livestock
Array
Input, Fraction of Livestock water demands to be satisfied by Reservoi
%
swAbstractionFraction_Res_Industry
Array
Input, Fraction of Industrial water demand to be satisfied by Reservoi
%
swAbstractionFraction_Res_Irrigatio
Array
Input, Fraction of Irrigation demand to be satisfied by Reservoirs
%
othAbstractionFraction_Desal_Domest
Array
–
othAbstractionFraction_Desal_Livest
Array
–
othAbstractionFraction_Desal_Indust
Array
–
othAbstractionFraction_Desal_Irriga
Array
–
wwtAbstractionFraction_Res_Domestic
Array
–
wwtAbstractionFraction_Res_Livestoc
Array
–
wwtAbstractionFraction_Res_Industry
Array
–
wwtAbstractionFraction_Res_Irrigati
Array
–
gwAbstractionFraction_Livestock
Array
Fraction of livestock water demand to be satisfied by groundwater
%
gwAbstractionFraction_Industry
Array
Fraction of industrial water demand to be satisfied by groundwater
%
gwAbstractionFraction_Irrigation
Array
Fraction of irrigation water demand to be satisfied by groundwater
%
using_reservoir_command_areas
Flag
True if using_reservoir_command_areas = True, False otherwise
bool
load_command_areas
Flag
–
load_command_areas_wwt
Flag
–
reservoir_command_areas
Array
–
reservoir_command_areas_wwt
Array
–
Water_conveyance_efficiency
Array
–
segmentArea
Array
–
segmentArea_wwt
Array
–
canals
Array
–
canals_wwt
Array
–
canalsArea
Array
–
canalsAreaC
Array
–
canalsArea_wwt
Array
–
canalsArea_wwtC
Array
–
swAbstractionFraction_Lift_Livestoc
Array
Input, Fraction of Livestock water demands to be satisfied from Lift a
%
swAbstractionFraction_Lift_Industry
Array
Input, Fraction of Industrial water demand to be satisfied from Lift a
%
swAbstractionFraction_Lift_Irrigati
Array
Input, Fraction of Irrigation demand to be satisfied from Lift areas
%
using_lift_areas
Flag
True if using_lift_areas = True in Settings, False otherwise
bool
lift_command_areas
Array
–
allocSegments
Array
–
swAbstractionFraction
Array
Input, Fraction of demands to be satisfied with surface water
%
allocation_zone
Array
–
modflowPumping
Array
–
leakage
Array
Canal leakage leading to either groundwater recharge or runoff
m3
pumping
Array
–
Pumping_daily
Array
Groundwater abstraction asked of MODFLOW. modfPumpingM_actual is the r
m
modflowDepth2
Array
–
modflowTopography
Array
–
allowedPumping
Array
–
ratio_irrWithdrawalGW_month
Array
–
ratio_irrWithdrawalSW_month
Array
–
act_irrWithdrawalSW_month
Array
Running total agent surface water withdrawals for the month
m
act_irrWithdrawalGW_month
Array
Running total agent groundwater withdrawals for the month
m
Desal_Domestic
Array
–
Desal_Industry
Array
–
Desal_Livestock
Array
–
Desal_Irrigation
Array
–
Channel_Domestic
Array
Channel water abstracted for domestic
m
Channel_Industry
Array
Channel water abstracted for industry
m
Channel_Livestock
Array
Channel water abstracted for livestock
m
Channel_Irrigation
Array
Channel water abstracted for irrigation
m
Lift_Domestic
Array
–
Lift_Industry
Array
–
Lift_Livestock
Array
–
Lift_Irrigation
Array
–
wwt_Domestic
Array
–
wwt_Industry
Array
–
wwt_Livestock
Array
–
wwt_Irrigation
Array
–
Lake_Domestic
Array
–
Lake_Industry
Array
–
Lake_Livestock
Array
–
Lake_Irrigation
Array
–
Res_Domestic
Array
–
Res_Industry
Array
–
Res_Livestock
Array
–
Res_Irrigation
Array
–
GW_Domestic
Array
Groundwater withdrawals to satisfy domestic water requests
m
GW_Industry
Array
Groundwater withdrawals to satisfy Industrial water requests
m
GW_Livestock
Array
Groundwater withdrawals to satisfy Livestock water requests
m
GW_Irrigation
Array
Groundwater withdrawals for Irrigation
m
abstractedLakeReservoirM3
Array
Abstractions from lakes and reservoirs at the location of the waterbod
m3
leakage_wwtC_daily
Array
–
act_bigLakeResAbst_wwt
Array
–
act_DesalWaterAbstractM
Array
–
act_totalIrrConsumption
Array
Total irrigation consumption
m
act_totalWaterConsumption
Array
Total water consumption
m
act_indConsumption
Array
Industrial consumption
m
act_domConsumption
Array
Domestic consumption
m
act_livConsumption
Array
Livestock consumptions
m
returnflowIrr
Array
–
returnflowNonIrr
Array
–
nonIrrReturnFlowFraction
Array
–
nonIrruse
Array
–
act_indDemand
Array
Industrial demand
m
act_domDemand
Array
Domestic demand
m
act_livDemand
Array
Livestock demands
m
nonIrrDemand
Array
–
totalWaterDemand
Array
Irrigation and non-irrigation demand
m
act_totalWaterWithdrawal
Array
Total water withdrawals
m
act_indWithdrawal
Array
Industrial withdrawal
m
act_domWithdrawal
Array
Domestic withdrawal
m
act_livWithdrawal
Array
Livestock withdrawals
m
unmet_lost
Array
Fossil water that disappears instead of becoming return flow
m
pot_GroundwaterAbstract
Array
Potential groundwater abstraction. Primarily used without MODFLOW.
m
WB_elec
Array
Fractions of live storage to be exported from basin
366-d
act_nonpaddyConsumption
Array
Non-paddy irrigation consumption
m
act_paddyConsumption
Array
Paddy consumption
m
act_irrPaddyDemand
Array
paddy irrigation demand
m
act_irrNonpaddyDemand
Array
non-paddy irrigation demand
m
pot_nonIrrConsumption
Array
–
act_DesalWaterAbstractM3
Array
–
AvlDesalM3
Array
–
act_channelAbst
Array
Abstractions to satisfy demands from channels
m
act_channelAbstract_Lift
Array
Abstractions from the channel in lift areas at the location of the cha
m
Lift_Other
Array
–
abstractedLakeReservoirM3C
Array
Compressed abstractedLakeReservoirM3
m3
remainNeed
Array
–
act_ResAbst_wwt
Array
–
act_lakeAbst
Array
Abstractions from lakes at demand location
m
act_ResAbst
Array
Abstractions from reservoirs at demand location
m
leakageC_daily
Array
–
leakageCanalsC_M
Array
–
Channel_Domestic_fromZone
Array
–
Channel_Livestock_fromZone
Array
–
Channel_Industry_fromZone
Array
–
Channel_Irrigation_fromZone
Array
–
Channel_Other
Array
–
GW_Domestic_fromZone
Array
–
GW_Livestock_fromZone
Array
–
GW_Industry_fromZone
Array
–
GW_Irrigation_fromZone
Array
–
GW_Other
Array
–
waterAbstract
Array
–
PumpingM3_daily
Array
–
unmet_lostirr
Array
Fossil water for irrigation that disappears instead of becoming return
m
unmet_lostNonirr
Array
Fossil water for non-irrigation that disappears instead of becoming re
m
wwtEffluentsGenerated_domestic
Array
–
wwtEffluentsGenerated_industry
Array
–
wwtSewerCollectedBySoruce
Array
–
waterabstraction
Array
–
- Parameters
model (object) – The main CWatM model instance containing all model variables and configuration.
- Variables
var (object) – Reference to model variables container for accessing and storing model state variables.
model (object) – Reference to the main CWatM model instance.
domestic (waterdemand_domestic) – Domestic water demand calculation module.
industry (waterdemand_industry) – Industrial water demand calculation module.
livestock (waterdemand_livestock) – Livestock water demand calculation module.
irrigation (waterdemand_irrigation) – Irrigation water demand calculation module.
environmental_need (waterdemand_environmental_need) – Environmental flow requirements calculation module.
wastewater (waterdemand_wastewater) – Wastewater treatment and reuse calculation module.
Notes
This is the main orchestrating module that coordinates all water demand sectors. Industrial, domestic, and livestock demands are based on precalculated spatial maps, while agricultural water demand is computed dynamically based on crop water requirements.
The module supports advanced features including: - Agent-based modeling for spatially explicit water management decisions - Sector-specific and source-specific water abstraction strategies - Command area operations for coordinated irrigation water allocation - Integration with MODFLOW for groundwater-surface water interactions - Desalination operations for augmenting water supply - Complex water allocation algorithms with priority-based distribution
- commandAreaOperation(remainNeed, command_areas, maxFracForIrrigation, water_conveyance_efficiency, wwt_only=False)[source]¶
Execute coordinated water allocation operations within reservoir command areas.
This method performs sophisticated water allocation calculations for command areas served by reservoirs, handling complex spatial aggregation of water demands, identification of dominant reservoirs within command areas, application of abstraction limits based on reservoir rules, and calculation of conveyance efficiency losses. It supports both regular water supply and wastewater treatment operations with differentiated reservoir access controls.
The method implements a multi-step allocation algorithm: 1. Aggregates water demands across all cells within each command area 2. Identifies the reservoir with maximum storage within each command area 3. Applies reservoir-specific abstraction limits and operational rules 4. Calculates actual water abstraction considering conveyance efficiency 5. Computes abstraction factors for proportional allocation across reservoirs
- Parameters
remainNeed (ndarray) – Remaining water demand per grid cell after other sources [m/day]. Represents unmet water demand that could be satisfied by reservoir abstraction.
command_areas (ndarray of int) – Command area identifier map where cells with same positive integer values belong to the same command area. Cells with non-positive values are not included in command area operations.
maxFracForIrrigation (ndarray) – Maximum fraction of reservoir storage available for irrigation abstraction per reservoir [dimensionless, 0-1]. Represents operational constraints and environmental flow requirements.
water_conveyance_efficiency (ndarray) – Water conveyance efficiency factor [dimensionless, 0-1]. Accounts for losses during water transport from reservoirs to demand locations through canals and distribution infrastructure.
wwt_only (bool, optional) – Flag indicating wastewater treatment only operations (default False). When True, limits operations to reservoirs designated for wastewater treatment. When False, excludes wastewater treatment reservoirs.
- Returns
- ResAbstractFactorCndarray
Compressed abstraction factors for reservoir cells [dimensionless]. Fraction of available reservoir storage to be abstracted.
- act_bigLakeResAbst_allocndarray
Actual water abstraction allocated per command area [m³]. Total volume to be abstracted considering all constraints.
- demand_Segmentndarray
Total water demand per command area [m³]. Aggregated demand across all cells within each command area.
- resStorageTotal_allocCndarray
Compressed total reservoir storage per command area [m³]. Storage of the dominant reservoir serving each command area.
- Return type
tuple of (ResAbstractFactorC, act_bigLakeResAbst_alloc, demand_Segment, resStorageTotal_allocC)
Notes
Command Area Logic: The method identifies the reservoir with maximum storage within each command area as the primary water source. This approach handles cases where multiple reservoirs exist within a single command area by selecting the most significant one based on current storage levels.
Wastewater Operations: When wwt_only=True, the method restricts operations to reservoirs specifically designated for wastewater treatment (resId_restricted > 0). This enables separate management of treated wastewater supplies versus conventional water sources.
Conveyance Efficiency: Water demands are adjusted by conveyance efficiency to account for distribution losses. The method ensures that reservoir abstractions account for these losses to meet actual demand requirements at delivery points.
Abstraction Limits: Reservoir abstraction is limited by both storage availability and operational rules (maxFracForIrrigation). The method ensures sustainable reservoir operations while meeting water demands within physical and regulatory constraints.
- dynamic()[source]¶
Execute the complete dynamic water demand-supply allocation cycle for the current time step.
This is the main orchestrating method that coordinates all aspects of water demand calculation, water source allocation, abstraction operations, and consumption tracking across all sectors. It implements sophisticated water allocation algorithms that balance demands against available supplies from multiple sources (surface water, groundwater, reservoirs, lakes, desalination, wastewater treatment) while respecting physical constraints, environmental requirements, and operational rules.
The method executes a comprehensive water management cycle including:
Sectoral Demand Calculation: Computes water demands for all active sectors (domestic, industrial, livestock, irrigation, environmental) using current meteorological conditions and socio-economic factors.
Water Source Assessment: Evaluates available water supplies from all sources including channel storage, groundwater availability, reservoir storage, lake storage, desalination capacity, and treated wastewater supplies.
Demand-Supply Balancing: Implements complex allocation algorithms to match demands with available supplies, considering spatial distribution, infrastructure constraints, and operational priorities.
Agent-Based Allocation: When activated, processes agent-based water management decisions for irrigation and domestic sectors, handling spatial administrative units and their specific allocation rules and constraints.
Multi-Source Abstraction: Orchestrates water abstraction from multiple sources using sector-specific and source-specific abstraction fractions, managing complex allocation hierarchies and constraint satisfaction.
Command Area Operations: Executes coordinated water allocation within reservoir and canal command areas, handling conveyance losses and operational efficiency considerations.
Consumption and Return Flow: Calculates actual water consumption by sector, computes return flows to water bodies, and tracks water use efficiency across all sectors.
Groundwater-Surface Water Integration: When MODFLOW coupling is active, coordinates groundwater pumping with surface water abstractions, managing aquifer-river interactions and sustainable yield constraints.
Notes
This method implements the core water allocation logic of CWatM and handles numerous complex scenarios and configurations:
Temporal Dynamics: Handles both daily time step calculations and monthly/annual demand updates, managing temporal variability in water demands and supply availability. Supports fixed-year demand scenarios for scenario analysis and historical reconstructions.
Spatial Complexity: Manages spatial heterogeneity in water demands, supply sources, infrastructure capacity, and allocation rules. Handles multi-scale allocation from individual grid cells to large administrative regions and command areas.
Sectoral Integration: Coordinates water allocation across competing sectors with different priorities, use efficiencies, return flow characteristics, and operational constraints. Manages inter-sectoral water transfers and reuse opportunities.
Source Portfolio Management: Optimizes water allocation across diverse supply portfolios including conventional sources (rivers, lakes, groundwater) and alternative sources (desalination, wastewater reuse), considering economic and environmental constraints.
Infrastructure Constraints: Accounts for physical infrastructure limitations including canal capacity, pumping capacity, conveyance losses, treatment plant capacity, and distribution system constraints that affect water delivery efficiency.
Environmental Protection: Enforces environmental flow requirements, groundwater sustainability constraints, and ecosystem water needs while optimizing human water use efficiency and reliability.
Unmet Demand Management: Tracks and manages unmet water demands through demand management strategies, alternative source development, and adaptive allocation algorithms that respond to water scarcity conditions.
The method supports both simple water allocation scenarios for basic hydrological modeling and highly sophisticated water management configurations for detailed water resources planning and management applications.
- initial()[source]¶
Initialize the comprehensive water demand system configuration and all model variables.
This method performs extensive initialization of the integrated water demand system, setting up configuration flags, loading spatial data layers, configuring agent-based modeling components, establishing water abstraction fractions for different sectors and sources, and initializing command area operations. It handles both simple and advanced water demand configurations including sector-specific abstraction strategies, desalination operations, wastewater treatment, and complex spatial allocation systems.
The initialization process includes: - Configuration of water demand activation flags and sectoral inclusion options - Setup of agent-based modeling for irrigation and domestic sectors with spatial allocation - Loading and processing of abstraction fraction maps for different water sources and sectors - Configuration of command area operations for coordinated water distribution - Initialization of desalination and wastewater treatment components - Setup of lift irrigation systems and canal conveyance efficiency parameters - Configuration of groundwater-surface water partitioning algorithms - Initialization of all tracking variables for water demand, withdrawal, and consumption
Notes
This method handles complex conditional initialization based on configuration options:
Water Demand Activation: - Configures whether water demand calculations are enabled - Sets flags for including industrial, domestic, and livestock demands vs irrigation-only - Activates wastewater treatment and reuse components when configured
Agent-Based Modeling: - Sets up administrative segments for spatially explicit water management decisions - Configures irrigation and domestic agent systems with withdrawal limits and relaxation factors - Handles agent-based allocation of water resources across spatial administrative units
Abstraction Fractions: - Configures sector-specific and source-specific abstraction strategies when enabled - Sets up abstraction fractions for channels, lakes, reservoirs, and groundwater by sector - Handles desalination and wastewater reuse abstraction fractions - Configures groundwater abstraction limitations and surface water partitioning
Command Area Operations: - Sets up reservoir command areas for coordinated irrigation water distribution - Configures canal systems and conveyance efficiency for water transport - Handles both regular and wastewater treatment reservoir command areas - Sets up lift irrigation areas for pumping operations
Spatial Allocation: - Configures allocation zones for water demand-supply balancing - Sets up spatial aggregation systems for efficient water resource management - Handles coordinate system transformations and spatial indexing
Variable Initialization: - Initializes extensive arrays for tracking water demands, withdrawals, and consumption - Sets up sectoral water use efficiency parameters - Configures unmet demand tracking and fossil groundwater abstraction variables - Initializes MODFLOW coupling variables for groundwater-surface water interactions
water_demand.domestic¶
Read water demand for domestic
- class cwatm.hydrological_modules.water_demand.domestic.waterdemand_domestic(model)[source]¶
Bases:
objectDomestic water demand module for household and municipal water requirements.
This class calculates residential water consumption based on population and per-capita use rates. It supports urban water demand modeling with temporal and spatial variations. The module handles both agent-based and traditional demand calculations, supporting surface water and groundwater abstraction fractions.
Global variables
Variable [self.var]
Type
Description
Unit
domWithdrawalVar
List
Input, domesticWithdrawalvarname, variable name for netCDF
str
domConsumptionVar
List
Input, domesticConsuptionvarname, variable name for netCDF
str
domestic_agent_SW_request_month_m3
Array
map of domestic agent surface water request, in million m3 per month
Mm3
domestic_agent_GW_request_month_m3
Array
map of domestic agent groundwater request, in million m3 per month
Mm3
pot_domesticConsumption
Array
–
M3toM
Array
Coefficient to change units
–
domesticTime
List
Monthly’ when domesticTimeMonthly = True, and ‘Yearly’ otherwise.
str
InvCellArea
Array
Inverse of cell area of each simulated mesh
1/m2
activate_domestic_agents
Flag
Input, True if activate_domestic_agents = True
bool
domesticDemand
Array
Domestic demand
m
swAbstractionFraction_domestic
Array
With domestic agents, derived from surface water over total water requ
%
demand_unit
Flag
–
sectorSourceAbstractionFractions
Array
–
swAbstractionFraction_Channel_Domes
Array
Input, Fraction of Domestic demands to be satisfied with Channel
%
swAbstractionFraction_Lift_Domestic
Array
Input, Fraction of Domestic demands to be satisfied with Lift
%
swAbstractionFraction_Res_Domestic
Array
Input, Fraction of Domestic demands to be satisfied with Reservoirs
%
swAbstractionFraction_Lake_Domestic
Array
Input, Fraction of Domestic demands to be satisfied with Lake
%
gwAbstractionFraction_Domestic
Array
Fraction of domestic water demand to be satisfied by groundwater
%
dom_efficiency
Array
–
- Variables
var (object) – Model variables container from parent model
model (object) – Parent CWatM model instance
- dynamic(wd_date)[source]¶
Calculate dynamic domestic water demand for the current time step.
Reads monthly or yearly water demand from NetCDF files and transforms units to m/day if necessary. Handles both agent-based domestic demand (with predefined monthly requests) and traditional demand calculation from input files. Applies scaling factors and calculates abstraction fractions for different water sources.
- Parameters
wd_date (datetime) – Current simulation date for reading time-dependent data
- initial()[source]¶
Initialize domestic water demand parameters and variables.
Sets up time resolution (monthly/yearly), variable names for withdrawal and consumption, agent-based domestic demand parameters, and abstraction fractions for different water sources (surface water, groundwater, channels, reservoirs, lakes).
water_demand.industry¶
Read water demand for industry
- class cwatm.hydrological_modules.water_demand.industry.waterdemand_industry(model)[source]¶
Bases:
objectIndustrial water demand module for manufacturing and commercial water requirements.
This class computes water consumption for industrial activities based on economic indicators and sectoral water use patterns. It handles industrial water efficiency trends and supports both monthly and yearly demand calculations with scaling factors. The module processes withdrawal and consumption data separately.
Global variables
Variable [self.var]
Type
Description
Unit
industryTime
List
Monthly’ when industryTimeMonthly = True, and ‘Yearly’ otherwise.
–
indWithdrawalVar
List
Settings industryWithdrawalvarname, variable name in industryWaterDema
–
indConsumptionVar
List
Settings industryConsuptionvarname, variable name in domesticWaterDema
–
pot_industryConsumption
Array
–
M3toM
Array
Coefficient to change units
–
InvCellArea
Array
Inverse of cell area of each simulated mesh
1/m2
demand_unit
Flag
–
industryDemand
Array
–
ind_efficiency
Array
–
- Variables
var (object) – Model variables container from parent model
model (object) – Parent CWatM model instance
- dynamic(wd_date)[source]¶
Calculate dynamic industrial water demand for the current time step.
Reads monthly or yearly industrial water demand from NetCDF files and transforms units to m/day if necessary. Processes both withdrawal and consumption data, applies scaling factors if configured, and calculates industrial water efficiency. Filters out small demands below the minimum cell area threshold.
- Parameters
wd_date (datetime) – Current simulation date for reading time-dependent data
water_demand.livestock¶
Read water demand for livestock
- class cwatm.hydrological_modules.water_demand.livestock.waterdemand_livestock(model)[source]¶
Bases:
objectLivestock water demand module for animal husbandry water requirements.
This class computes water consumption for different livestock categories and densities. It handles seasonal variations and regional differences in livestock water needs based on precalculated maps. The module supports both monthly and yearly demand calculations and can be enabled or disabled through configuration settings.
Global variables
Variable [self.var]
Type
Description
Unit
M3toM
Array
Coefficient to change units
–
domesticTime
List
Monthly’ when domesticTimeMonthly = True, and ‘Yearly’ otherwise.
str
livestockTime
List
–
livVar
List
–
uselivestock
Flag
True if uselivestock=True in Settings, False otherwise
bool
InvCellArea
Array
Inverse of cell area of each simulated mesh
1/m2
demand_unit
Flag
–
livestockDemand
Array
–
pot_livestockConsumption
Array
Potential livestock consumption
m
liv_efficiency
Number
Livestock water use efficiency
–
- Variables
var (object) – Model variables container from parent model
model (object) – Parent CWatM model instance
- dynamic(wd_date)[source]¶
Calculate dynamic livestock water demand for the current time step.
Reads monthly or yearly livestock water demand from NetCDF files when enabled, transforms units to m/day if necessary, and processes livestock water consumption. Sets livestock demand to zero when livestock calculations are disabled. Assumes 100% efficiency for livestock water use (consumption equals demand).
- Parameters
wd_date (datetime) – Current simulation date for reading time-dependent data
- initial()[source]¶
Initialize livestock water demand parameters and settings.
Sets up time resolution (monthly/yearly), variable names for livestock demand data, and configures whether livestock water demand calculations are enabled. Initializes livestock demand processing parameters for animal water requirements.
water_demand.irrigation¶
Calculate water demand for irrigation
- class cwatm.hydrological_modules.water_demand.irrigation.waterdemand_irrigation(model)[source]¶
Bases:
objectAgricultural irrigation water demand module for crop water requirements.
This class calculates irrigation needs based on crop water stress and soil moisture deficits. It supports multiple irrigation systems (paddy and non-paddy) and crop-specific water application methods. The module computes potential irrigation consumption based on soil water availability, crop coefficients, and infiltration capacity, considering irrigation efficiency and return flow fractions.
Global variables
Variable [self.var]
Type
Description
Unit
unmetDemand_runningSum
Array
Unmet water demand (too less water availability)
m
load_initial
Flag
Settings initLoad holds initial conditions for variables
bool
cropKC
Array
crop coefficient for each of the 4 different land cover types (forest,
–
efficiencyPaddy
Array
Input, irrPaddy_efficiency, paddy irrigation efficiency, the amount of
frac
efficiencyNonpaddy
Array
Input, irrNonPaddy_efficiency, non-paddy irrigation efficiency, the am
frac
returnfractionIrr
Array
Input, irrigation_returnfraction, the fraction of non-efficient water
frac
alphaDepletion
Array
Input, alphaDepletion, irrigation aims to alphaDepletion of field capa
frac
minimum_irrigation
Array
Cover-specific irrigation in metres is 0 if less than this, currently
1/m2
pot_irrConsumption
Array
Cover-specific potential irrigation consumption
m/m
fraction_IncreaseIrrigation_Nonpadd
Array
Input, fraction_IncreaseIrrigation_Nonpaddy, scales pot_irrConsumption
frac
irrPaddyDemand
Array
Paddy irrigation demand
m
ws1
Array
Maximum storage capacity in layer 1
m
ws2
Array
Maximum storage capacity in layer 2
m
wwp1
Array
Soil moisture at wilting point in layer 1
m
wwp2
Array
Soil moisture at wilting point in layer 2
m
arnoBeta
Array
arnoBeta defines the shape of soil water capacity distribution curve a
–
maxtopwater
Array
maximum heigth of topwater
m
totAvlWater
Array
Field capacity minus wilting point in soil layers 1 and 2
m
InvCellArea
Array
Inverse of cell area of each simulated mesh
1/m2
availWaterInfiltration
Array
quantity of water reaching the soil after interception, more snowmelt
m
totalPotET
Array
Potential evaporation per land use class
m
wfc1
Array
Soil moisture at field capacity in layer 1
m
wfc2
Array
Soil moisture at field capacity in layer 2
m
w1
Array
Simulated water storage in the layer 1
m
w2
Array
Simulated water storage in the layer 2
m
topwater
Array
quantity of water above the soil (flooding)
m
fracVegCover
Array
Fraction of specific land covers (0=forest, 1=grasslands, etc.)
%
unmetDemandPaddy
Array
Unmet paddy demand
m
unmetDemandNonpaddy
Array
Unmet nonpaddy demand
m
unmetDemand
Array
Unmet groundwater demand to determine potential fossil groundwaterwate
m
irrDemand
Array
Cover-specific Irrigation demand
m
irrNonpaddyDemand
Array
–
totalIrrDemand
Array
Irrigation demand
m
- Variables
var (object) – Model variables container from parent model
model (object) – Parent CWatM model instance
- dynamic()[source]¶
Calculate dynamic irrigation water demand for current time step.
Computes irrigation water requirements for paddy (No=2) and non-paddy (No=3) systems based on crop coefficients, soil moisture conditions, and available water. Considers soil water stress, infiltration capacity, and crop-specific water depletion factors. Calculates potential consumption and total demand considering irrigation efficiency.
- initial()[source]¶
Initialize irrigation water demand parameters and efficiency maps.
Sets up unmet water demand tracking for paddy and non-paddy irrigation, loads irrigation efficiency maps, return flow fractions, and depletion coefficients. Initializes minimum irrigation thresholds and prepares variables for irrigation demand calculations.
water_demand.environmental_need¶
Read water for environmental need
- class cwatm.hydrological_modules.water_demand.environmental_need.waterdemand_environmental_need(model)[source]¶
Bases:
objectEnvironmental water requirements module for ecosystem water allocation.
This class calculates minimum flow requirements for maintaining aquatic ecosystem health. It supports environmental flow standards and habitat preservation water needs based on precalculated maps. The module handles monthly environmental flow data and converts flow rates to water depths for hydrological calculations.
Global variables
Variable [self.var]
Type
Description
Unit
cut_ef_map
Flag
if TRUE calculated maps of environmental flow are clipped to the area
bool
use_environflow
Flag
Use calculation of environmental flow
bool
envFlowm3s
Array
Amount of environmental flow
m3
M3toM
Array
Coefficient to change units
–
chanLength
Array
Input, Channel length
m
channelAlpha
Array
–
envFlow
Array
–
- Variables
var (object) – Model variables container from parent model
model (object) – Parent CWatM model instance
- dynamic()[source]¶
Calculate dynamic environmental flow requirements for the current time step.
Reads monthly environmental flow data from NetCDF files and transforms flow rates from m³/s to water depths in meters. Uses channel geometry parameters to convert volumetric flow to equivalent water depth for hydrological calculations. Sets minimum environmental flow when environmental flows are disabled.
water_demand.wastewater¶
Calculate waste water
- class cwatm.hydrological_modules.water_demand.wastewater.waterdemand_wastewater(model)[source]¶
Bases:
objectWastewater treatment and return flow module for water recycling processes.
This class simulates wastewater generation, treatment efficiency, and return flow dynamics. It handles treated wastewater discharge, water quality improvement processes, and supports many-to-many relations between wastewater treatment plants (WWTP) and reservoirs. The module includes urban leakage, evaporation from treatment facilities, and two types of wastewater export (untreated and treated).
The module processes domestic and industrial wastewater through collection areas, applies treatment with configurable parameters (volume, treatment time, efficiency), and manages discharge to overflow points or reuse via distribution reservoirs.
Global variables
Variable [self.var]
Type
Description
Unit
wwt_def
Flag
–
wastewater_to_reservoirs
Array
–
compress_LR
Array
boolean map as mask map for compressing lake/reservoir
–
waterBodyOut
Array
biggest outlet (biggest accumulation of ldd network) of a waterbody
–
decompress_LR
Array
boolean map as mask map for decompressing lake/reservoir
–
waterBodyOutC
Array
compressed map biggest outlet of each lake/reservoir
–
resYear
Array
Settings waterBodyYear, with first operating year of reservoirs
map
resVolume
Array
Reservoir volume
m3
EWRef
Array
potential evaporation rate from water surface
m
wwtUrbanLeakage
Array
–
wwtColArea
Array
–
urbanleak
Array
–
wwtID
Array
–
compress_WWT
Array
–
decompress_WWT
Array
–
wwtC
Array
–
act_bigLakeResAbst_UNRestricted
Array
–
act_bigLakeResAbst_Restricted
Array
–
wwtOverflow
Array
–
wwtStorage
Array
–
wwtColShare
Array
–
wwtSewerCollectedC
Array
–
wwtSewerTreatedC
Array
–
wwtExportedTreatedC
Array
–
wwtSewerToTreatmentC
Array
–
wwtSewerOverflowC
Array
–
wwtSewerResOverflowC
Array
–
wwtTreatedOverflowC
Array
–
wwtSentToResC
Array
–
wwtSewerCollection
Array
–
wwtOverflowOut
Array
–
wwtEvapC
Array
–
wwtSewerCollected
Array
–
wwtExportedCollected
Array
–
wwtSewerTreated
Array
–
wwtExportedTreated
Array
–
wwtSewerToTreatment
Array
–
wwtSewerExported
Array
–
wwtSewerOverflow
Array
–
wwtSentToRes
Array
–
wwtSewerResOverflow
Array
–
wwtTreatedOverflow
Array
–
wwtEvap
Array
–
wwtInTreatment
Array
–
wwtIdsOrdered
List
–
wwtVolC
Array
–
wwtTimeC
Array
–
toResManageC
Array
–
minHRTC
Array
–
maskDomesticCollection
Array
–
maskIndustryCollection
Array
–
extensive
Flag
–
noPools_extensive
Array
–
poolVolume_extensive
Array
–
wwtSurfaceAreaC
Array
–
extensive_counter
Array
–
wwtResIDTemp_compress
Array
–
wwtResIDC
Array
–
wwtResTypC
Array
–
wwtResYearC
Array
–
wwtSentToResC_LR
Array
–
wwtOverflowOutM
Array
–
cellArea
Array
Area of cell
m2
includeWastewater
Flag
–
waterBodyTyp_unchanged
Array
–
lakeVolumeM3C
Array
compressed map of lake volume
m3
lakeStorageC
Array
–
reservoirStorageM3C
Array
–
lakeResStorageC
Array
–
lakeResStorage
Array
–
wwtEffluentsGenerated
Array
–
wwtSewerCollection_domestic
Array
–
wwtSewerCollection_industry
Array
–
- Parameters
inputs (Optional) –
wwtID : Wastewater treatment plant identifiers
wwtVol : Daily treatment volume capacity
wwtYear : Year of establishment
wwtTime : Treatment duration in days (default: 2 days, range: 1-3 days)
wwtOverflow : Overflow/discharge point locations
wwt_ColArea : Effluent collection area definitions
inputs –
wwtColShare : Collection efficiency ratio (0-1)
wwtToResManagement : Reservoir management strategy (-1, 0-1)
urbanleak : Urban leakage coefficient
- Variables
var (object) – Model variables container from parent model
model (object) – Parent CWatM model instance
Notes
Treatment levels: 1=primary, 2=secondary, 3=tertiary Management options: -1=discharge only, 0=send to reservoir, 0-1=export fraction
- dynamic()[source]¶
Execute daily wastewater treatment operations for all active facilities.
Performs the main processing cycle for each time step, handling sewer collection, treatment processes, storage dynamics, evaporation losses, and discharge operations. Processes wastewater through collection areas, applies treatment with facility-specific parameters, and manages discharge to overflow points or distribution reservoirs.
Notes
Daily processing sequence: 1. Initialize annual configurations if new year/start 2. Calculate total sewer collection from domestic and industrial sources 3. Handle export of untreated wastewater from areas without facilities 4. Process each treatment facility in ordered sequence:
Check daily capacity limits and calculate overflow
Apply hydraulic retention time constraints
Calculate evaporation losses from treatment pools
Update storage arrays (extensive vs standard systems)
Release treated water based on management strategy
Allocate water to reservoirs or overflow discharge points
Storage management: - Standard systems: Simple queue with daily advancement - Extensive systems: Multiple pools with residence time tracking - Evaporation calculated from surface area and reference ET
Discharge management strategies (toResManageC): - -1: Discharge all treated water to overflow points - 0: Send all treated water to reservoirs (if available) - 0-1: Export fraction, send remainder to reservoirs - 1: Export all treated wastewater
Water allocation to reservoirs uses iterative proportional allocation based on available capacity, with overflow handling for excess volumes.
Updates all output variables including collected volumes, treated volumes, overflow discharges, reservoir transfers, and evaporation losses.
- dynamic_init()[source]¶
Initialize annual wastewater treatment plant configurations and storage systems.
Updates wastewater treatment plant definitions from Excel settings for the current simulation year. Filters facilities by operational years, creates ordered processing lists, and sets up annual treatment parameters including volumes, treatment times, and export shares. Configures extensive treatment systems with multiple pools and calculates surface areas for evaporation processes.
Notes
Treatment plant definitions loaded from Excel include: - Daily treatment capacity (Volume in m³/day) - Treatment duration (Days, typically 1-3) - Treatment level (1=primary, 2=secondary, 3=tertiary) - Export share (fraction of outflows exported from basin) - Wastewater sources (Domestic and/or Industrial boolean flags) - Minimum hydraulic retention time (min_HRT in days)
The method handles technology changes by preserving existing storage when treatment parameters change (e.g., from 30 to 20 days treatment time). All stored water is allocated to the final treatment pool for release.
Extensive systems (treatment time >= 2 days) use multiple treatment pools (default: 3 pools) to simulate realistic treatment processes and timing.
Sets up the following annual arrays: - wwtVolC : Daily treatment volumes [m³/day] - wwtTimeC : Treatment duration [days] - toResManageC : Reservoir management strategy [-1 to 1] - minHRTC : Minimum hydraulic retention times [days] - wwtSurfaceAreaC : Treatment facility surface areas [m²]
Collection masks are updated for domestic and industrial wastewater sources based on facility-specific configuration flags.
- initial()[source]¶
Initialize wastewater treatment facilities and variables.
Sets up wastewater treatment plant locations, collection areas, storage systems, and output variables. Configures treatment facility parameters including daily volumes, collection shares, and urban leakage coefficients. Initializes big maps for tracking wastewater flows, treatment processes, and discharge outputs.
Hydrology IV - Lakes, reservoirs and river¶
lakes_reservoirs module¶
Calculate water retention in lakes
- class cwatm.hydrological_modules.lakes_reservoirs.lakes_reservoirs(model)[source]¶
Bases:
objectLakes and reservoirs module for water retention and release calculations.
Simulates water storage and outflow dynamics in natural lakes and artificial reservoirs using modified Puls method for lakes and rule-based operations for reservoirs. Handles different water body types including wetlands with variable area characteristics.
The module implements: - Modified Puls approach for natural lake water balance - Rule-based reservoir operations with multiple storage zones - Wetland dynamics with seasonal area variations - Water body initialization from spatial datasets and Excel configurations - Reservoir transfers and water supply/demand management
Global variables
Variable [self.var]
Type
Description
Unit
modflow
Flag
True if modflow_coupling = True in settings file
bool
load_initial
Flag
Settings initLoad holds initial conditions for variables
bool
wastewater_to_reservoirs
Array
–
saveInit
Flag
If true initial conditions are saved
bool
reservoir_info
List
Number of lakes and reservoirs in Excel
–
reservoir_transfers
Array
[[‘Giving reservoir’][i], [‘Receiving reservoir’][i], [‘Fraction of li
array
waterBodyID_C
Array
ID of the waterbody - compressed
–
compress_LR
Array
boolean map as mask map for compressing lake/reservoir
–
waterBodyOut
Array
biggest outlet (biggest accumulation of ldd network) of a waterbody
–
dirUp
Array
river network in upstream direction
–
ldd_LR
Array
change river network (put pits in where lakes are)
–
lddCompress
Array
compressed river network (without missing values)
–
lddCompress_LR
Array
compressed river network lakes/reservoirs (without missing values)
–
dirUp_LR
Array
river network direction upstream lake/reservoirs
–
dirupLen_LR
Array
number of bifurcation upstream lake/reservoir
–
downstruct_LR
Array
river network downstream lake/reservoir
–
catchment_LR
Array
catchments lake/reservoir
–
dirDown_LR
Array
river network direktion downstream lake/reservoir
–
lendirDown_LR
Array
number of river network connections lake/reservoir
–
decompress_LR
Array
boolean map as mask map for decompressing lake/reservoir
–
waterBodyOutC
Array
compressed map biggest outlet of each lake/reservoir
–
resYear
Array
Settings waterBodyYear, with first operating year of reservoirs
map
resYearC
Array
Compressed map of resYear
–
resVolumeC
Array
compressed map of reservoir volume
Milli
waterBodyTyp
Array
Settings, waterBodyTyp, with waterbody type 1-4
map
waterBodyTypC
Array
water body types 3 reservoirs and lakes (used as reservoirs but before
–
lakeArea
Array
area of each lake/reservoir
m2
lakeAreaC
Array
compressed map of the area of each lake/reservoir
m2
lakeDis0
Array
compressed map average discharge at the outlet of a lake/reservoir
m3/s
lakeDis0C
Array
average discharge at the outlet of a lake/reservoir
m3/s
lakeAC
Array
compressed map of parameter of channel width, gravity and weir coeffic
–
reservoir_transfers_net_M3C
Array
Net transfer from one point to the other
m3
reservoir_transfers_net_M3
Array
net reservoir transfers, after exports, transfers, and imports
m3
reservoir_transfers_in_M3C
Array
Transfer - what goes into the receiving reservoir
m3
reservoir_transfers_in_M3
Array
water received into reservoirs
m3
reservoir_transfers_out_M3C
Array
Transfer - what goes out from the giving reservoir
m3
reservoir_transfers_out_M3
Array
water given from reservoirs
m3
lakeEvaFactorC
Array
compressed map of a factor which increases evaporation from lake becau
–
reslakeoutflow
Array
outflow of lakes and reservoirs
m3
lakeVolume
Array
volume of lakes
m3
lakeLevel
Array
Waterlevel of lakes
m
outLake
Array
outflow from lakes
m
lakeInflow
Array
Inflow into lakes
m3
lakeOutflow
Array
lake outflow - uncompressed for all basin cells
m3
reservoirStorage
Array
Storage of reservoirs
m3
MtoM3C
Array
conversion factor from m to m3 (compressed map)
–
EvapWaterBodyMOutlet
Array
Evaporation from waterbodies - sum at the outlet
m
lakeResInflowM
Array
lake reservoir inflow in [m]
m
lakeResOutflowM
Array
lake reservoiroutflow in [m]
m
wetlands_variable_area
Array
variable area of wetlands per day
m2
wetland_area
Array
variable area of wetlands per day
m2
wetland_maxlevel
Array
maximum waterlevel of wetlands
m
resVolume
Array
Reservoir volume
m3
includeType4
Flag
True if there is a reservoir of waterbody type 4 in waterBodyTyp map
bool
resId_restricted
Array
waterbody ID for waste water
–
waterBodyBuffer
Array
Create a buffer around water bodies as command areas for lakes and res
m2
waterBodyBuffer_wwt
Array
Create a buffer around water bodies as command areas for lakes and res
m2
lakeFactor
Array
factor for the Modified Puls approach to calculate retention of the la
–
lakeFactorSqr
Array
square root factor for the Modified Puls approach to calculate retenti
–
lakeInflowOldC
Array
inflow to the lake from previous days
m/3
lakeLevelC
Array
compressed map of lake level
m
lakeOutflowC
Array
compressed map of lake outflow
m3/s
conLimitC
Array
Reservoir calculation: conservativeStorageLimit
–
normLimitC
Array
Reservoir calculation: normalStorageLimit
–
floodLimitC
Array
Reservoir calculation:
–
minQC
Array
Reservoir calculation:
m3/s
normQC
Array
Reservoir calculation:
m3/s
nondmgQC
Array
Reservoir calculation:
m3/s
adjust_Normal_FloodC
Array
Reservoir calculation:
–
norm_floodLimitC
Array
Reservoir calculation:
–
deltaO
Array
Reservoir calculation:
m3/s
deltaLN
Array
Reservoir calculation:
–
deltaLF
Array
Reservoir calculation:
–
deltaNFL
Array
Reservoir calculation:
–
reservoirFillC
Array
actual filling fraction of a reservoir
–
reservoir_releases_excel_option
Flag
If Excel file is used for addition reservoirs, watertransfer, release
bool
reservoir_releases
Array
Release of reservoirs
–
waterBodyTypTemp
Array
waterbody temp e.g. lake, reservoir, wetlands
–
sumEvapWaterBodyC
Array
evaporation from waterbodies - compressed
m
sumlakeResInflow
Array
infow into waterbodies
m3
sumlakeResOutflow
Array
outflow of waterbodies
m3
lakeResStorage_release_ratio
Array
daily release ration for reservoirs
–
lakeResStorage_release_ratioC
Array
daily release ration for reservoirs - compressed
–
lakeIn
Array
Inflow into lakes
m3
lakeEvapWaterBodyC
Array
Evaporation from lakes and reservoirs
m3
resEvapWaterBodyC
Array
evaporation from reservoirs
m
EvapWaterBodyM
Array
Evaporation from lakes and reservoirs
m
lakeResStorage_filled
Array
Puts the value of lakeResStorage into all cells covered by the waterb
m3
lakeResStorage_buffer
Array
–
lakeStorage
Array
Storage volume of lakes
m3
resStorage
Array
Storage volume of reservoirs
m3
DtSec
Array
number of seconds per timestep (default = 86400)
s
MtoM3
Array
Coefficient to change units
–
InvDtSec
Array
inversere of seconds per timestep (default 1/86400)
1/s
waterBodyID
Array
lakes/reservoirs map with a single ID for each lake/reservoir
–
UpArea1
Array
upstream area of a grid cell
m2
dirupID_LR
Array
index river upstream lake/reservoir
–
lakeEvaFactor
Array
a factor which increases evaporation from lake because of wind
–
dtRouting
Array
number of seconds per routing timestep
s
evapWaterBodyC
Array
Compressed version of EvapWaterBodyM
m
sumLakeEvapWaterBodyC
Array
–
noRoutingSteps
Number
Number of routing step - how often the subroutine is run during a day
–
sumResEvapWaterBodyC
Array
–
discharge
Array
Channel discharge
m3/s
inflowDt
Number
–
downstruct
Array
structure of the river network in downstream direction
–
runoff
Array
Total runoff from surface, interflow and groundwater
m
fracVegCover
Array
Fraction of specific land covers (0=forest, 1=grasslands, etc.)
%
cellArea
Array
Area of cell
m2
includeWastewater
Flag
–
waterBodyTyp_unchanged
Array
–
lakeVolumeM3C
Array
compressed map of lake volume
m3
lakeStorageC
Array
–
reservoirStorageM3C
Array
–
lakeResStorageC
Array
–
lakeResStorage
Array
–
reservoir_supply
Array
–
waterBodyTypCTemp
Array
waterbody temp e.g. lake, reservoir, wetlands -> compressed
–
- Variables
var (object) – Reference to model variables object containing state variables
model (object) – Reference to the main CWatM model instance
Notes
Lake calculations use the Modified Puls Method with assumptions: 1. Storage volume increases proportionally to elevation: S = A * H 2. Outflow follows parabolic weir relationship: Q = a * H^2
Mathematical formulation: (Qin1 + Qin2)/2 - (Qout1 + Qout2)/2 = (S2 - S1)/dt
Solved as quadratic equation: Q = (-LakeFactor + sqrt(LakeFactor^2 + 2*SI))^2
References
LISFLOOD manual Annex 3 (Burek et al. 2013) Maniak hydraulics textbook, p.331ff Aigner (2008) for parabolic cross-section relationships
- dynamic_inloop(NoRoutingExecuted)[source]¶
Dynamic part to calculate outflow from lakes and reservoirs
lakes with modified Puls approach
reservoirs with special filling levels
- Parameters
NoRoutingExecuted – actual number of routing substep
- Returns
outLdd: outflow in m3 to the network
Note
outflow to adjected lakes and reservoirs is calculated separately
- initWaterbodies()[source]¶
Initialize water bodies Read parameters from maps e.g area, location, initial average discharge, type 9reservoir or lake) etc.
Compress numpy array from mask map to the size of lakes+reservoirs (marked as capital C at the end of the variable name)
- initial_lakes()[source]¶
Initial part of the lakes module Using the Modified Puls approach to calculate retention of a lake
lakes_res_small module¶
Calculate water retention in small lakes
- class cwatm.hydrological_modules.lakes_res_small.lakes_res_small(model)[source]¶
Bases:
objectSmall lakes and reservoirs module for water bodies with limited catchment area.
Handles water retention and outflow calculations for small water bodies (catchment area < 5000 km² or lake area < 100 km²) using the modified Puls approach. Processes distributed small water bodies within grid cells rather than individual large water bodies.
Global variables
Variable [self.var]
Type
Description
Unit
load_initial
Flag
Settings initLoad holds initial conditions for variables
bool
smallpart
Array
fraction of the cellarea which is a small lake
–
smalllakeArea
Array
Lake area of small lakes (not part of the main river network)
m2
smalllakeDis0
Array
Starting discharge of small lakes
m3/s
smalllakeA
Array
Lake A facor of small lakes
–
smalllakeFactor
Array
Internal calculation value for modified Puls approach for small lakes
–
smalllakeFactorSqr
Array
Internal calculation value for modified Puls approach for small lakes
–
smalllakeInflowOld
Array
Inflow of the previous day
m3/s
smalllakeOutflow
Array
Outflow from small alkes
m3/s
smalllakeLevel
Array
Lake level for small lakes
m
minsmalllakeVolumeM3
Array
Storage volume of small lakes
m3
smallLakedaycorrect
Array
a water balance correction term for a day because Modified Puld approa
m
smallLakeIn
Array
Inflow into small lakes = lakeIn * time / area
m
smallevapWaterBody
Array
Evaporation from small lakes
m
smallLakeout
Array
small lake outflow but in [m]
m
smallrunoffDiff
Number
Not used
–
DtSec
Array
number of seconds per timestep (default = 86400)
s
InvDtSec
Array
inversere of seconds per timestep (default 1/86400)
1/s
EWRef
Array
potential evaporation rate from water surface
m
lakeEvaFactor
Array
a factor which increases evaporation from lake because of wind
–
runoff
Array
Total runoff from surface, interflow and groundwater
m
cellArea
Array
Area of cell
m2
smalllakeVolumeM3
Array
–
smalllakeStorage
Array
–
- Variables
var (object) – Reference to model variables object containing state variables
model (object) – Reference to the main CWatM model instance
Notes
Small water bodies are treated as distributed features within grid cells, with each cell containing a fraction of water body coverage. The module uses the same modified Puls method as large water bodies but applies it to aggregated small water body characteristics.
- dynamic()[source]¶
Calculate outflow from small water bodies for current time step.
Processes water balance for distributed small lakes and reservoirs within each grid cell, applying the modified Puls method to determine outflow based on inflow from cell runoff and current storage conditions.
Notes
Processing steps: - Update water body areas and catchment fractions if dynamic - Calculate inflow from cell runoff based on catchment fraction - Apply modified Puls method for outflow calculation - Account for evaporation losses from water surfaces - Update storage and water levels - Modify cell runoff to account for water body effects
The method partitions cell runoff between: - Flow to small water bodies (smallpart fraction) - Direct runoff to channel network (1-smallpart fraction)
- initial()[source]¶
Initialize small water body parameters and initial conditions.
Loads spatial data for small water bodies including catchment fractions, water body areas, discharge characteristics, and initial storage conditions. Calculates hydraulic parameters for modified Puls method application.
Notes
Initialization includes: - Reading catchment area fractions for each grid cell - Loading small water body surface areas - Calculating discharge coefficients and lake factors - Setting initial storage, inflow, and outflow conditions - Configuring minimum storage constraints if specified
Small water bodies are characterized by: - Distributed coverage within grid cells (smallpart fraction) - Aggregated hydraulic characteristics per cell - Modified Puls parameters adapted for small-scale features
routing_reservoirs.routing_kinematic module¶
River routing - kinematic wave
- class cwatm.hydrological_modules.routing_reservoirs.routing_kinematic.routing_kinematic(model)[source]¶
Bases:
objectKinematic wave routing module for river flow simulation.
This class implements kinematic wave routing to simulate river flow using the kinematic wave approximation of the Saint-Venant equations. It handles channel flow routing, evaporation from channels, and water body interactions.
Global variables
Variable [self.var]
Type
Description
Unit
channelStorage
Array
Channel water storage
m3
modflow
Flag
True if modflow_coupling = True in settings file
bool
load_initial
Flag
Settings initLoad holds initial conditions for variables
bool
inflowM3
Array
inflow to basin
m3
Crops
Array
Internal: List of specific crops and Kc/Ky parameters
–
compress_LR
Array
boolean map as mask map for compressing lake/reservoir
–
dirUp
Array
river network in upstream direction
–
lddCompress
Array
compressed river network (without missing values)
–
dirupLen_LR
Array
number of bifurcation upstream lake/reservoir
–
dirDown_LR
Array
river network direktion downstream lake/reservoir
–
lendirDown_LR
Array
number of river network connections lake/reservoir
–
lakeArea
Array
area of each lake/reservoir
m2
lakeEvaFactorC
Array
compressed map of a factor which increases evaporation from lake becau
–
riverbedExchangeM3
Array
–
DtSec
Array
number of seconds per timestep (default = 86400)
s
ETRef
Array
potential evapotranspiration rate from reference crop
m
EWRef
Array
potential evaporation rate from water surface
m
QInM3Old
Array
Inflow from previous day
m3
waterBodyID
Array
lakes/reservoirs map with a single ID for each lake/reservoir
–
UpArea1
Array
upstream area of a grid cell
m2
dirupID_LR
Array
index river upstream lake/reservoir
–
lakeEvaFactor
Array
a factor which increases evaporation from lake because of wind
–
dtRouting
Array
number of seconds per routing timestep
s
evapWaterBodyC
Array
Compressed version of EvapWaterBodyM
m
sumLakeEvapWaterBodyC
Array
–
noRoutingSteps
Number
Number of routing step - how often the subroutine is run during a day
–
sumResEvapWaterBodyC
Array
–
discharge
Array
Channel discharge
m3/s
inflowDt
Number
–
downstruct
Array
structure of the river network in downstream direction
–
sum_openWaterEvap
Array
sum of open water evaporation from all different land cover types
m
chanLength
Array
Input, Channel length
m
totalCrossSectionArea
Array
–
dirupLen
Array
–
dirupID
Array
–
catchment
Array
–
dirDown
Array
–
lendirDown
Number
–
UpArea
Array
upstream area of a grid cell
m2
beta
Array
–
chanMan
Array
Input, Channel Manning’s roughness coefficient
s/m^(
chanGrad
Array
–
chanWidth
Array
Input, Channel width
m
chanDepth
Array
Input, Channel depth
m
invbeta
Array
–
invchanLength
Array
–
invdtRouting
Array
–
totalCrossSectionAreaBankFull
Array
–
chanWettedPerimeterAlpha
Array
–
alpPower
Array
–
channelAlpha
Array
–
invchannelAlpha
Array
–
riverbedExchange
Array
–
Xcel
List
–
EvapoChannel
Array
Channel evaporation
m3
QDelta
Array
–
sumsideflow
Number
–
prechannelStorage
Array
–
dis_outlet
Array
–
humanConsumption
Array
–
humanUse
Array
–
natureUse
Array
–
ETRefAverage_segments
Array
–
precipEffectiveAverage_segments
Array
–
head_segments
Array
Simulated water level, averaged over adminSegments [masl]
m
gwdepth_adjusted_segments
Array
Adjusted depth to groundwater table, averaged over adminSegments
m
gwdepth_segments
Array
Groundwater depth, averaged over adminSegments
m
adminSegments_area
Array
Spatial area of domestic agents
m2
runoff
Array
Total runoff from surface, interflow and groundwater
m
openWaterEvap
Array
Simulated evaporation from open areas
m
infiltration
Array
Water actually infiltrating the soil
m
actTransTotal_paddy
Array
Transpiration from paddy land cover
m
actTransTotal_nonpaddy
Array
Transpiration from non-paddy land cover
m
actTransTotal_crops_nonIrr
Array
Transpiration associated with specific non-irr crops
m
head
Array
Simulated ModFlow water level [masl]
m
gwdepth_adjusted
Array
Adjusted depth to groundwater table
m
gwdepth
Array
Depth to groundwater table
m
fracVegCover
Array
Fraction of specific land covers (0=forest, 1=grasslands, etc.)
%
adminSegments
Array
Domestic agents
Int
cellArea
Array
Area of cell
m2
act_SurfaceWaterAbstract
Array
Surface water abstractions
m
addtoevapotrans
Array
Irrigation application loss to evaporation
m
act_bigLakeResAbst
Array
Abstractions to satisfy demands from lakes and reservoirs
m
act_smallLakeResAbst
Array
Abstractions from small lakes at demand location
m
returnFlow
Array
–
act_nonIrrConsumption
Array
Non-irrigation consumption
m
act_nonIrrWithdrawal
Array
Non-irrigation withdrawals
m
act_irrWithdrawal
Array
Irrigation withdrawals
m
- Variables
var (object) – Model variables container
model (object) – CWatM model instance
lakes_reservoirs_module (object) – Lakes and reservoirs module instance
- catchment(point, ldd)[source]¶
Extract catchment boundaries upstream of a specified point.
Creates a river network from the local drainage direction (LDD) map and calculates the catchment area upstream of a given point.
- Parameters
point (array_like) – Point location for catchment delineation
ldd (array_like) – Local drainage direction map
- Returns
Catchment map, x-coordinate offset, y-coordinate offset
- Return type
tuple
- dynamic()[source]¶
Execute dynamic routing calculations for the current time step.
Performs the main routing calculations including channel evaporation, riverbed-groundwater exchange, water body retention (if enabled), lateral inflow calculations, and kinematic wave routing using optimized C++ libraries for computational efficiency.
- initial()[source]¶
Initialize routing parameters and river network properties.
Sets up the river network by loading and processing drainage direction data, calculates river network parameters including channel geometry (length, width, depth, gradient), initializes channel storage and discharge, and configures Manning’s roughness coefficients for kinematic wave calculations.
routing_reservoirs.routing_sub module¶
Sub routines for river routing
- cwatm.hydrological_modules.routing_reservoirs.routing_sub.Compress(map, mask)[source]¶
Compress 2D map to 1D array removing masked values.
Converts a 2D spatial map to a 1D compressed array by removing cells that are masked (missing values or outside model domain).
- Parameters
map (array_like) – Input 2D spatial map to be compressed
mask (array_like) – Boolean mask array indicating valid cells
- Returns
1D compressed array without missing values
- Return type
numpy.ndarray
- cwatm.hydrological_modules.routing_reservoirs.routing_sub.catchment1(dirUp, points)[source]¶
calculates all cells which belongs to a catchment from point onward
- Parameters
dirUp –
points –
- Returns
subcatchment
- cwatm.hydrological_modules.routing_reservoirs.routing_sub.decompress1(map)[source]¶
Decompress 1D array back to 2D spatial map.
Converts a compressed 1D array back to its original 2D spatial representation using stored mask information.
- Parameters
map (array_like) – 1D compressed array to be decompressed
- Returns
2D spatial map with missing values restored
- Return type
numpy.ndarray
- cwatm.hydrological_modules.routing_reservoirs.routing_sub.defLdd2(ldd)[source]¶
defines river network
- Parameters
ldd – river network
- Returns
ldd variables
- cwatm.hydrological_modules.routing_reservoirs.routing_sub.dirDownstream(dirUp, lddcomp, dirDown)[source]¶
runs the river network tree downstream - from source to outlet
- Parameters
dirUp –
lddcomp –
dirDown –
- Returns
direction downstream
- cwatm.hydrological_modules.routing_reservoirs.routing_sub.dirUpstream(dirshort)[source]¶
Build upstream direction network from drainage direction map.
Creates upstream direction lookup tables from the compressed drainage direction array, enabling traversal from outlets to sources.
- Parameters
dirshort (array_like) – Compressed drainage direction array
- Returns
Upstream direction arrays (dirUp, dirupLen, dirupID)
- Return type
tuple
- cwatm.hydrological_modules.routing_reservoirs.routing_sub.downstream1(dirUp, weight)[source]¶
calculated 1 cell downstream
- Parameters
dirUp –
weight –
- Returns
dowmnstream 1 cell
- cwatm.hydrological_modules.routing_reservoirs.routing_sub.lddrepair(lddnp, lddOrder)[source]¶
repairs a river network
eliminate unsound parts
add pits at points with no connections
- Parameters
lddnp – rivernetwork as 1D array
lddOrder –
- Returns
repaired ldd
- cwatm.hydrological_modules.routing_reservoirs.routing_sub.postorder(dirUp, catchment, node, catch, dirDown)[source]¶
Perform postorder tree traversal of drainage network.
Traverses the drainage network tree structure in postorder to assign catchment identifiers and establish downstream flow directions.
- Parameters
dirUp (list) – Upstream direction lookup table
catchment (array_like) – Catchment identifier array
node (int) – Current node being processed
catch (int) – Catchment identifier to assign
dirDown (list) – Downstream direction list being built
- Returns
Updated dirDown and catchment arrays
- Return type
tuple
- cwatm.hydrological_modules.routing_reservoirs.routing_sub.subcatchment1(dirUp, points, ups)[source]¶
calculates subcatchments of points
- Parameters
dirUp –
points –
ups –
- Returns
subcatchment
- cwatm.hydrological_modules.routing_reservoirs.routing_sub.upstream1(downstruct, weight)[source]¶
Calculates 1 cell upstream
- Parameters
downstruct –
weight –
- Returns
upstream 1cell
- cwatm.hydrological_modules.routing_reservoirs.routing_sub.upstreamArea(dirDown, dirshort, area)[source]¶
Calculate cumulative upstream area for each cell.
Computes the total upstream contributing area for each grid cell by accumulating cell areas along flow paths.
- Parameters
dirDown (array_like) – Downstream direction array pointing to next downstream cell
dirshort (array_like) – Short drainage direction array
area (array_like) – Cell area in square meters for each grid cell
- Returns
Cumulative upstream area for each cell
- Return type
numpy.ndarray