Inputs#
Inputs#
hapi.inputs.Inputs
#
Rainfall-runoff inputs preparation for distributed hydrological models.
The Inputs class provides methods to prepare meteorological and parameter
raster data so they align with a reference DEM. It supports extracting
HBV model parameter boundaries and computing lumped inputs from distributed
rasters. Chronological ordering is handled by pyramids at read time
(read_multiple_files(with_order=True, ...)), not by renaming files on disk.
Attributes:
| Name | Type | Description |
|---|---|---|
source_dem |
Path to the reference DEM raster used for spatial alignment (coordinate system, rows, columns, resolution). |
Examples:
>>> from hapi.inputs import Inputs
>>> inp = Inputs("data/dem.tif")
Source code in src/hapi/inputs.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 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 | |
__init__(src: str)
#
Initialize the Inputs instance with a reference DEM path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
str
|
Path to the spatial information source raster used to
obtain the coordinate system, number of rows and columns,
and resolution. The path should include the file name and
extension (e.g., |
required |
Source code in src/hapi/inputs.py
67 68 69 70 71 72 73 74 75 76 | |
create_lumped_inputs(path: str, regex_string: str = '\\d{4}.\\d{2}.\\d{2}', date: bool = True, file_name_data_fmt: str | None = None, start: str | None = None, end: str | None = None, fmt: str = '%Y-%m-%d', extension: str = '.tif') -> list
staticmethod
#
Create lumped inputs by averaging distributed raster values.
Reads a time series of rasters from the given directory, computes the spatial mean of each raster, and returns the averages as a list. This is used to convert distributed meteorological or parameter data into lumped (catchment-average) values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the folder containing the raster files. |
required |
regex_string
|
str
|
A regex pattern to locate the date (or ordering
number) within each file name. Default is
|
'\\d{4}.\\d{2}.\\d{2}'
|
date
|
bool
|
If True, the number extracted from file names is interpreted as a date. Default is True. |
True
|
file_name_data_fmt
|
str | None
|
The date format string matching dates in
the file names (e.g., |
None
|
start
|
str | None
|
Start date to filter the rasters. If not provided, all rasters in the directory are read. |
None
|
end
|
str | None
|
End date to filter the rasters. If not provided, all rasters in the directory are read. |
None
|
fmt
|
str
|
Format of the |
'%Y-%m-%d'
|
extension
|
str
|
File extension to filter by. Default is |
'.tif'
|
Returns:
| Type | Description |
|---|---|
list
|
The spatial mean of each raster, in chronological order. The elements
are NumPy scalars ( |
Examples:
- Reduce two dated rasters to one catchment average each, in date order:
>>> import numpy as np, os, tempfile >>> from pyramids.dataset import Dataset >>> from hapi.inputs import Inputs >>> src_dir = tempfile.mkdtemp() >>> for stamp, value in (("2020.01.02", 4.0), ("2020.01.01", 2.0)): ... Dataset.create_from_array( ... np.full((2, 2), value, dtype="float32"), ... top_left_corner=(0.0, 2.0), cell_size=1.0, epsg=4326, ... no_data_value=-9999.0, ... path=os.path.join(src_dir, f"prec_{stamp}.tif"), ... ).close() >>> averages = Inputs.create_lumped_inputs( ... src_dir, regex_string=r"\d{4}.\d{2}.\d{2}", date=True, ... file_name_data_fmt="%Y.%m.%d", ... ) >>> [float(value) for value in averages] [2.0, 4.0] - A uniform raster averages to its own value:
>>> import numpy as np, os, tempfile >>> from pyramids.dataset import Dataset >>> from hapi.inputs import Inputs >>> src_dir = tempfile.mkdtemp() >>> Dataset.create_from_array( ... np.full((3, 3), 7.5, dtype="float32"), ... top_left_corner=(0.0, 3.0), cell_size=1.0, epsg=4326, ... no_data_value=-9999.0, ... path=os.path.join(src_dir, "prec_2021.06.01.tif"), ... ).close() >>> averages = Inputs.create_lumped_inputs( ... src_dir, regex_string=r"\d{4}.\d{2}.\d{2}", date=True, ... file_name_data_fmt="%Y.%m.%d", ... ) >>> float(averages[0]) 7.5
See Also
Inputs.prepare_inputs: Align and crop the same rasters onto the DEM grid.
Source code in src/hapi/inputs.py
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 | |
extract_parameters(gdf: FeatureCollection | None, scenario: str, as_raster: bool = False, save_to: str = '')
#
Extract HBV parameter values or rasters for a catchment.
Retrieves one of 12 global HBV parameter sets (Beck et al., 2016)
from the directory specified by the HAPI_DATA_DIR environment
variable. When as_raster is False, computes zonal statistics
(min, max, mean, std) over the catchment polygon. When
as_raster is True, aligns and crops the parameter rasters to
the source DEM and saves them to save_to.
Reference
Beck, H. E., Dijk, A. I. J. M. van, Ad de Roo, Diego G. Miralles, T. R. M. & Jaap Schellekens, and L. A. B. (2016). Global-scale regionalization of hydrologic model parameters. Water Resources Research, 3599-3622. doi:10.1002/2015WR018247.
The 18 HBV parameters are:
tt, rfcf, sfcf, cfmax, cwh, cfr, fc, beta, etf, lp, k0, k1,
k2, uzl, perc, maxbas, K_muskingum, x_muskingum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf
|
FeatureCollection | None
|
The catchment polygon, as a
:class: |
required |
scenario
|
str
|
Name of the parameter set. One of |
required |
as_raster
|
bool
|
If True, save aligned parameter rasters to
|
False
|
save_to
|
str
|
Path to the directory where aligned parameter rasters
will be saved. Only used when |
''
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
When |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the |
FileNotFoundError
|
If the parameter data directory does not exist. |
Source code in src/hapi/inputs.py
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 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 | |
extract_parameters_boundaries(basin: FeatureCollection)
staticmethod
#
Extract upper and lower parameter boundaries for a catchment.
Reads the global maximum and minimum HBV parameter rasters from
the directory specified by the HAPI_DATA_DIR environment
variable, clips them to the given basin polygon, and returns the
max/min statistics for each parameter.
The 18 HBV parameters are:
tt, rfcf, sfcf, cfmax, cwh, cfr, fc, beta, etf, lp, k0, k1,
k2, uzl, perc, maxbas, K_muskingum, x_muskingum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
basin
|
FeatureCollection
|
The catchment polygon, as a
:class: |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A DataFrame indexed by parameter name with
columns |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the |
FileNotFoundError
|
If the parameter data directory or the
|
Source code in src/hapi/inputs.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | |
prepare_inputs(inputs_dir: str | Path, outputs_dir: str | Path)
#
Align and crop input rasters to match the source DEM.
Reads all rasters from inputs_dir, aligns them to the source
DEM's spatial properties (CRS, resolution, extent, nodata value),
crops them to the DEM footprint, and writes the results to
outputs_dir.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs_dir
|
str | Path
|
Path to the folder containing the rasters to be aligned and cropped to match the source DEM. |
required |
outputs_dir
|
str | Path
|
Path to the output folder where the aligned rasters will be saved. |
required |
Each output keeps its source file name, so the ordering of the collection is
irrelevant here and the rasters are read with with_order=False.
outputs_dir is created if it does not exist; either argument may be a
str or a :class:pathlib.Path.
Returns:
| Type | Description |
|---|---|
None
|
The aligned rasters are written to |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
Examples:
- Align two rasters onto a DEM grid and read back what was written:
>>> import numpy as np, os, tempfile >>> from pyramids.dataset import Dataset >>> from hapi.inputs import Inputs >>> root = tempfile.mkdtemp() >>> dem_path = os.path.join(root, "dem.tif") >>> Dataset.create_from_array( ... np.ones((4, 4), dtype="float32"), top_left_corner=(0.0, 4.0), ... cell_size=1.0, epsg=4326, no_data_value=-9999.0, path=dem_path, ... ).close() >>> src_dir = os.path.join(root, "src") >>> os.makedirs(src_dir) >>> for stamp in ("2020.01.01", "2020.01.02"): ... Dataset.create_from_array( ... np.full((4, 4), 5.0, dtype="float32"), top_left_corner=(0.0, 4.0), ... cell_size=1.0, epsg=4326, no_data_value=-9999.0, ... path=os.path.join(src_dir, f"prec_{stamp}.tif"), ... ).close() >>> out_dir = os.path.join(root, "out") >>> Inputs(dem_path).prepare_inputs(src_dir, out_dir) >>> sorted(os.listdir(out_dir)) ['prec_2020.01.01.tif', 'prec_2020.01.02.tif'] - A missing input directory fails fast, before the DEM is opened:
>>> import os, tempfile >>> from hapi.inputs import Inputs >>> missing = os.path.join(tempfile.mkdtemp(), "absent") >>> try: ... Inputs("dem-never-opened.tif").prepare_inputs(missing, "out") ... except FileNotFoundError as exc: ... print("does not exist" in str(exc)) True
See Also
Inputs.create_lumped_inputs: Reduce the same rasters to catchment averages.
Source code in src/hapi/inputs.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | |