Preprocessing workflow
The preprocessing module provides a high-level function that runs the complete MOBIDIC preprocessing, from raw GIS data to inputs that can be directly used in the simulation.
Overview
The preprocessing workflow handles:
- Loading and validating configuration
- Reading all raster data (DTM, flow direction, soil parameters, etc.)
- Processing the river network (topology, ordering, routing parameters)
- Computing hillslope-reach mapping
- Processing reservoirs (optional: polygons, stage-storage curves, regulation curves/schedules)
- Organizing all data into a consolidated
GISDataobject
This is the recommended entry point for most users, as it handles all preprocessing steps automatically based on the configuration file.
Functions
Main preprocessing function
mobidic.preprocessing.preprocessor.run_preprocessing(config)
Run complete preprocessing workflow.
This function orchestrates the entire preprocessing pipeline: 1. Load raster grids (DTM, flow direction, soil parameters, etc.) 2. Apply grid decimation if needed (decimation factor > 1) 3. Convert flow direction to MOBIDIC notation 4. Process river network (topology, Strahler ordering, routing parameters) 5. Compute hillslope cells for each reach 6. Map hillslope cells to reaches
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
MOBIDICConfig
|
MOBIDIC configuration with preprocessing settings |
required |
Returns:
| Type | Description |
|---|---|
GISData
|
GISData object containing all preprocessed spatial data |
Examples:
>>> from mobidic import load_config, run_preprocessing
>>> config = load_config("Arno.yaml")
>>> gisdata = run_preprocessing(config)
>>> gisdata.save("Arno_gisdata.nc", "Arno_network.parquet")
Source code in mobidic/preprocessing/preprocessor.py
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 | |
Reservoir preprocessing function
mobidic.preprocessing.reservoirs.process_reservoirs(shapefile_path, stage_storage_path, regulation_curves_path, regulation_schedule_path, initial_volumes_path, network, grid_shape, xllcorner, yllcorner, cellsize, reference_crs=None)
Process reservoir data from input files.
This function orchestrates the complete reservoir preprocessing: 1. Read reservoir polygons from shapefile 2. Load stage-storage curves 3. Load regulation curves 4. Load regulation schedules 5. Load initial volumes 6. Map reservoirs to grid and network
Translated from MATLAB: buildgis_mysql_include.m (lines 594-740)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shapefile_path
|
str | Path
|
Path to reservoir polygon shapefile |
required |
stage_storage_path
|
str | Path
|
Path to stage-storage CSV |
required |
regulation_curves_path
|
str | Path
|
Path to regulation curves CSV |
required |
regulation_schedule_path
|
str | Path
|
Path to regulation schedule CSV |
required |
initial_volumes_path
|
Optional[str | Path]
|
Path to CSV with initial volumes (columns: ‘reservoir_id’, ‘volume_m3’). If None, initial volumes are auto-calculated as 100% capacity (volume at z_max) |
required |
network
|
GeoDataFrame
|
Processed river network GeoDataFrame |
required |
grid_shape
|
tuple[int, int]
|
Shape of computational grid (nrows, ncols) |
required |
xllcorner
|
float
|
X coordinate of lower-left corner [m] |
required |
yllcorner
|
float
|
Y coordinate of lower-left corner [m] |
required |
cellsize
|
float
|
Grid cell size [m] |
required |
reference_crs
|
Any
|
CRS of the DTM. If given, the shapefile must have the same CRS (no reprojection is performed). A geographic CRS is always rejected. |
None
|
Returns:
| Type | Description |
|---|---|
Reservoirs
|
Reservoirs object with processed data |
Source code in mobidic/preprocessing/reservoirs.py
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 | |
Workflow stages
The preprocessing pipeline consists of up to seven stages (stages 6-7 are optional if reservoirs are configured):
Stage 1: configuration loading
Loads and validates the YAML configuration file:
All subsequent steps are driven by paths and parameters in this configuration.
Stage 2: raster data loading
Reads all raster files specified in the configuration:
- Required rasters: DTM, flow direction, flow accumulation
- Soil parameters: Wc0, Wg0, ks, and optional kf
- Energy parameters: CH, Alb (if energy balance enabled)
- Flow coefficients: gamma, kappa, beta, alpha (if provided as rasters)
All rasters are:
- Checked against the DTM, which defines the model grid and CRS: same shape, cell size,
origin and CRS, otherwise preprocessing stops with a GridAlignmentError naming the file.
Nothing is resampled or reprojected automatically.
- Converted to numpy arrays with NaN for nodata (see Nodata handling)
- Stored in the GISData.grids dictionary
Stage 3: river network processing
Processes the river network shapefile:
network = process_river_network(
shapefile_path=config.vector_files.river_network.shp,
join_single_tributaries=True,
routing_params={
"wcel": config.parameters.routing.wcel,
"Br0": config.parameters.routing.Br0,
"NBr": config.parameters.routing.NBr,
"n_Man": config.parameters.routing.n_Man,
}
)
This step: - Builds network topology - Enforces binary tree structure - Computes Strahler ordering - Calculates routing parameters - Determines calculation order
Stage 4: hillslope-reach mapping
Maps hillslope grid cells to river reaches:
network = compute_hillslope_cells(network, grid_path)
reach_map = map_hillslope_to_reach(network, flowdir_path, flow_dir_type)
This establishes the connection between the distributed grid and the river network for lateral inflow routing.
Stage 5: data consolidation
Packages everything into a GISData object:
gisdata = GISData()
gisdata.grids = all_grid_data
gisdata.network = processed_network
gisdata.metadata = spatial_reference_info
The GISData object can then be saved for reuse or passed directly to the simulation.
Stage 6: reservoir preprocessing (optional)
If reservoirs are configured (config.parameters.reservoirs.res_shape is set), process reservoir data:
reservoirs = process_reservoirs(
shapefile_path=config.parameters.reservoirs.res_shape,
stage_storage_path=config.parameters.reservoirs.stage_storage,
regulation_curves_path=config.parameters.reservoirs.regulation_curves,
regulation_schedule_path=config.parameters.reservoirs.regulation_schedule,
initial_volumes_path=config.initial_conditions.reservoir_volumes,
network=gisdata.network,
grid_shape=gisdata.metadata['shape'],
xllcorner=gisdata.metadata['xllcorner'],
yllcorner=gisdata.metadata['yllcorner'],
cellsize=gisdata.metadata['resolution'][0],
)
gisdata.reservoirs = reservoirs
This step: - Reads reservoir polygon shapefile - Rasterizes polygons to identify basin pixels - Loads stage-storage curves from CSV - Loads regulation curves and schedules from CSV - Identifies inlet/outlet reaches by network topology - Auto-calculates initial volumes from z_max if not provided - Consolidates all reservoir data into Reservoirs container
Stage 7: reservoir I/O (optional)
Save/load processed reservoir data:
# Save reservoirs to GeoParquet
gisdata.save(
gisdata_path=config.paths.gisdata,
network_path=config.paths.network,
reservoirs_path=config.paths.reservoirs,
)
# Load reservoirs from GeoParquet
gisdata = GISData.load(
gisdata_path=config.paths.gisdata,
network_path=config.paths.network,
reservoirs_path=config.paths.reservoirs,
)
Complete example
from mobidic import load_config, run_preprocessing
# Load configuration
config = load_config("config.yaml")
# Run complete preprocessing
gisdata = run_preprocessing(config)
# Inspect results
print(f"Basin: {config.basin.id}")
print(f"Grid shape: {gisdata.metadata['shape']}")
print(f"Resolution: {gisdata.metadata['resolution']} m")
print(f"CRS: {gisdata.metadata['crs']}")
print(f"Grid variables: {list(gisdata.grids.keys())}")
print(f"Network reaches: {len(gisdata.network)}")
print(f"Strahler orders: {sorted(gisdata.network['strahler_order'].unique())}")
# Save for later use
gisdata.save(
gisdata_path=config.paths.gisdata,
network_path=config.paths.network
)
Note: To configure logging behavior (level, output file, etc.), see the Logging section in the Configuration reference.
Configuration requirements
The preprocessing workflow requires the following configuration sections:
Required paths
paths:
meteodata: path/to/meteo.nc
gisdata: path/to/gisdata.nc # Output path
network: path/to/network.parquet # Output path
states: path/to/states/ # For simulation states
output: path/to/output/ # For simulation outputs
Required vector files
vector_files:
river_network:
shp: path/to/river_network.shp
id_field: REACH_ID # Optional, for tracking original IDs
Required raster files
raster_files:
dtm: path/to/dtm.tif
flow_dir: path/to/flowdir.tif
flow_acc: path/to/flowacc.tif
Wc0: path/to/wc0.tif # Capillary capacity
Wg0: path/to/wg0.tif # Gravitational capacity
ks: path/to/ks.tif # Hydraulic conductivity
Required raster settings
Required routing parameters
parameters:
routing:
method: Linear
wcel: 5.0 # Wave celerity (m/s)
Br0: 1.0 # Base channel width (m)
NBr: 1.5 # Channel width exponent
n_Man: 0.03 # Manning's n (s/m^(1/3))
Optional reservoir parameters
parameters:
reservoirs:
res_shape: path/to/reservoirs.shp # Reservoir polygon shapefile
stage_storage: path/to/stage_storage.csv # Stage-storage curves
regulation_curves: path/to/regulation_curves.csv # Stage-discharge curves
regulation_schedule: path/to/regulation_schedule.csv # Regulation period schedule
initial_conditions:
reservoir_volumes: path/to/initial_volumes.csv # Optional (auto-calculated if omitted)
paths:
reservoirs: path/to/reservoirs.parquet # Output path for consolidated reservoir data
output_states:
reservoir_states: true # Enable reservoir state output
CSV file formats:
- stage_storage.csv: Columns:
reservoir_id,stage_m,volume_m3 - regulation_curves.csv: Columns:
reservoir_id,regulation_name,stage_m,discharge_m3s - regulation_schedule.csv: Columns:
reservoir_id,start_date,end_date,regulation_name - initial_volumes.csv: Columns:
reservoir_id,volume_m3(optional, defaults to auto-calculation from z_max)
See the sample configuration for a complete example.
Error handling
The preprocessing workflow performs comprehensive validation:
Configuration validation
- All required paths and parameters are present
- Numeric parameters are within valid ranges
- File paths exist (if validation enabled)
Spatial consistency
The DTM defines the model grid and CRS. Inputs are never resampled or reprojected
automatically: a mismatch raises GridAlignmentError (a ValueError) mentioning the file to fix.
- All rasters must have the same shape, cell size, origin and CRS as the DTM
- River network and reservoir shapefiles must have the same CRS as the DTM
- Geographic CRSs (e.g. EPSG:4326) are rejected: MOBIDIC requires a projected CRS in metres
- A raster or shapefile with no CRS only triggers a warning and is assumed to be in the DTM CRS
- A warning is logged when reaches fall outside the grid and get no hillslope cells
- At simulation start, the bounding box of the meteorological stations must overlap the grid (station coordinates carry no CRS and are assumed to be in the DTM CRS)
Nodata handling
The model domain is the set of cells where the DTM, the flow direction and the flow accumulation are all valid. Every NaN that affects the domain is reported with a warning:
| Where | What happens |
|---|---|
flow_dir or flow_acc NaN inside the DTM |
The cells are excluded from the model domain |
Parameter raster (Wc0, Wg0, ks, kf, gamma, kappa, beta, alpha, CH, Alb, Ma, Mf) NaN inside the domain |
Replaced with the default from the configuration (e.g. parameters.soil.ks for ks), in the raster’s units |
CLC NaN inside the domain |
The cells use the default parameters.soil.Kc |
Raster with no declared nodata value containing -9999, -99999, -32768 or -32767 |
Warning only: the values are read as valid data. Declare the nodata value of the file if they are nodata |
| Precipitation or PET forcing NaN inside the domain (raster forcing, or all stations NaN) | Replaced with 0 |
| Other forcing variables NaN inside the domain | Reported, not replaced (no default value) |
| NaN flux in a cell draining to a reach during the simulation | Reported: the cell’s water cannot reach the river network |
During a simulation each NaN problem is reported the first time it occurs, and the number of affected time steps is summarised at the end of the run.
Data quality
These checks ensure the quality and consistency of the input data before running the simulation:
- Rasters have valid nodata handling (see above)
- Network has no topological errors
- Flow direction is valid (no invalid direction codes)
- Flow accumulation is consistent with flow direction
Advanced usage
Skipping preprocessing stages
If you already have some preprocessed data, you can skip certain stages and load existing files:
from mobidic import load_network, load_gisdata, GISData
# Option 1: Load complete preprocessed data
gisdata = load_gisdata("existing_gisdata.nc", "existing_network.parquet")
# Option 2: Load network separately
gisdata = GISData()
# ... load grids manually
gisdata.network = load_network("existing_network.parquet")
Integration with simulation
After preprocessing, the GISData object is ready for simulation:
from mobidic import run_preprocessing, run_simulation
# Preprocessing
gisdata = run_preprocessing(config)
# Simulation (future implementation)
results = run_simulation(config, gisdata)
The simulation will access:
- gisdata.grids: Spatially-distributed parameters
- gisdata.network: River network topology and parameters
- gisdata.metadata: Spatial reference information