HmsGrid¶
HMS grid definition, HRAP cell mapping, and gridded precipitation helpers.
hms_commander.HmsGrid
¶
HmsGrid - HMS Grid Definition and Grid Cell Mapping Operations
Provides static methods for creating HMS grid definition files and mapping grid cells to subbasins for gridded precipitation workflows.
This module enables: - Creation of .grid files for HMS gridded precipitation - Generation of grid cell mapping files (hrapcells format) - Spatial intersection of AORC grid cells with subbasin boundaries - Travel length calculation for ModClark routing
Classes:
| Name | Description |
|---|---|
HmsGrid |
Static class for grid operations |
Key Functions
create_grid_definition: Generate HMS .grid file map_grid_to_subbasins: Create grid cell mapping file get_cell_polygons: Place a grid cell file's cells on the map (HRAP, SHG) remap_cell_file: Move a grid cell file to another lattice (HRAP to SHG) check_cells_on_grid: Check cells against a DSS grid record calculate_travel_lengths: Compute flow distances get_grid_info: Read .grid file metadata
Dependencies
Required: - geopandas: Spatial operations - shapely: Geometry operations - xarray: NetCDF grid handling - pandas: Data manipulation - numpy: Numerical operations
Install with: pip install hms-commander[gis] # OR pip install geopandas shapely xarray pandas numpy
Example
from hms_commander import HmsGrid, HmsHuc, HmsAorc
Download HUC12 watersheds¶
bounds = (-77.71, 41.01, -77.25, 41.22) watersheds = HmsHuc.get_huc12_for_bounds(bounds)
Download AORC data¶
aorc_nc = HmsAorc.download(bounds, "2020-05-01", "2020-05-15", "aorc.nc")
Create grid definition¶
HmsGrid.create_grid_definition( ... grid_name="AORC_Grid_1", ... dss_file="aorc_may2020.dss", ... pathname="/AORC/GRID/PRECIP////", ... output_file="grids/aorc.grid" ... )
Map AORC grid to each HUC12¶
for idx, ws in watersheds.iterrows(): ... HmsGrid.map_grid_to_subbasins( ... subbasin_geometries={ws['name']: ws['geometry']}, ... grid_coords=(lon_coords, lat_coords), ... output_hrapcells=f"regions/huc12_{ws['huc12']}" ... )
Notes
- All methods are static (no instantiation required)
- Grid cell mapping follows HMS hrapcells format
- Supports both user shapefiles and HUC boundaries
HmsGrid
¶
Static class for HMS grid operations.
Provides methods for creating HMS grid definition files and mapping grid cells to subbasins for gridded precipitation workflows.
All methods are static - do not instantiate this class.
Example
from hms_commander import HmsGrid
Create grid definition¶
HmsGrid.create_grid_definition( ... grid_name="AORC_Grid_1", ... dss_file="aorc.dss", ... pathname="/AORC/GRID/PRECIP////", ... output_file="grids/aorc.grid" ... )
Map grid cells to subbasin¶
HmsGrid.map_grid_to_subbasins( ... subbasin_geometries={"Sub1": polygon1, "Sub2": polygon2}, ... grid_coords=(lon_coords, lat_coords), ... output_hrapcells="regions/hrapcells" ... )
Source code in hms_commander/HmsGrid.py
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 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 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 | |
create_grid_definition(grid_name, dss_file, pathname, output_file, project_name=None, description='AORC Gridded Precipitation', version='4.13')
staticmethod
¶
Generate HMS .grid file for AORC precipitation.
Creates a .grid file that references DSS grid data for HMS gridded precipitation workflows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid_name
|
str
|
Name of the grid (e.g., "AORC_Grid_1", "Grid 1") |
required |
dss_file
|
Union[str, Path]
|
Path to DSS file (relative to HMS project folder) |
required |
pathname
|
str
|
DSS pathname for grid data (e.g., "/AORC/GRID/PRECIP////") |
required |
output_file
|
Union[str, Path]
|
Output .grid file path |
required |
project_name
|
Optional[str]
|
Project name for Grid Manager section. If None, uses grid_name. |
None
|
description
|
str
|
Description for the grid (default: "AORC Gridded Precipitation") |
'AORC Gridded Precipitation'
|
version
|
str
|
HMS version for format compatibility (default: "4.13") |
'4.13'
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created .grid file |
Example
from hms_commander import HmsGrid
Create grid definition¶
HmsGrid.create_grid_definition( ... grid_name="AORC_May2020", ... dss_file="precip/aorc_may2020.dss", ... pathname="/AORC/MAY2020/PRECIP////", ... output_file="grids/aorc_may2020.grid", ... description="AORC May 2020 Storm" ... )
Notes
- Output format follows HMS .grid file specification
- References external DSS grid data
- Grid Type: Precipitation
- Data Source Type: External DSS
- See tenk example project for reference format
Source code in hms_commander/HmsGrid.py
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 | |
map_grid_to_subbasins(subbasin_geometries, grid_coords, output_hrapcells, outlet_points=None, cell_size_km=None, grid_origin=None)
staticmethod
¶
Generate grid cell mapping file (hrapcells format).
Creates a file that maps grid cells to HMS subbasins with area weights and travel lengths for ModClark routing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subbasin_geometries
|
Dict[str, Polygon]
|
Dictionary mapping subbasin names to Shapely Polygon geometries |
required |
grid_coords
|
Tuple[ndarray, ndarray]
|
Tuple of (longitude_array, latitude_array) defining grid cell centers |
required |
output_hrapcells
|
Union[str, Path]
|
Output hrapcells file path |
required |
outlet_points
|
Optional[Dict[str, Tuple[float, float]]]
|
Dictionary mapping subbasin names to outlet coordinates (lon, lat). If None, uses centroid of lowest-elevation grid cells. |
None
|
cell_size_km
|
Optional[float]
|
Grid cell size in km. If None, calculated from coordinates. |
None
|
grid_origin
|
Optional[Tuple[int, int]]
|
Grid index origin (x_min, y_min). If None, calculated from coordinates. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created hrapcells file |
Example
from hms_commander import HmsGrid, HmsHuc import numpy as np
Get HUC12 watershed¶
bounds = (-77.71, 41.01, -77.25, 41.22) watersheds = HmsHuc.get_huc12_for_bounds(bounds)
Create geometry dict¶
geoms = {row['name']: row['geometry'] for _, row in watersheds.iterrows()}
Grid coordinates from AORC¶
lon = np.linspace(-77.71, -77.25, 50) lat = np.linspace(41.01, 41.22, 25)
Map AORC grid to subbasins¶
HmsGrid.map_grid_to_subbasins( ... subbasin_geometries=geoms, ... grid_coords=(lon, lat), ... output_hrapcells="regions/hrapcells" ... )
Notes
- Output format: HMS hrapcells file
- Header: "Parameter Order: xCoord yCoord TravelLength Area"
- Grid cells: "GRIDCELL: x y travel_length area"
- Travel length: Distance from grid cell centroid to subbasin outlet (km)
- Area: Grid cell area within subbasin (km²)
- See tenk/hrapcells for reference format
Source code in hms_commander/HmsGrid.py
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 | |
map_aorc_to_subbasins(basin_geometry, aorc_grid, output_hrapcells, subbasin_name=None, method='intersection')
staticmethod
¶
Generate grid cell mapping file from AORC NetCDF (hrapcells format).
Convenience method that extracts grid coordinates from an AORC NetCDF file and maps them to subbasin boundaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
basin_geometry
|
Union[str, Path, GeoDataFrame, Polygon]
|
Subbasin geometry, one of: - Path to shapefile - GeoDataFrame with geometry - Shapely Polygon (single subbasin) |
required |
aorc_grid
|
Union[str, Path]
|
Path to AORC NetCDF file |
required |
output_hrapcells
|
Union[str, Path]
|
Output hrapcells file path |
required |
subbasin_name
|
Optional[str]
|
Name of subbasin (for multi-subbasin files) |
None
|
method
|
str
|
Mapping method (default: "intersection"): - "intersection": Spatial intersection (exact, slow) - "centroid": Grid cell centroid within subbasin (fast) - "nearest": Nearest grid cell (approximate) |
'intersection'
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created hrapcells file |
Example
from hms_commander import HmsGrid, HmsHuc
Get HUC12 watershed¶
bounds = (-77.71, 41.01, -77.25, 41.22) watersheds = HmsHuc.get_huc12_for_bounds(bounds) huc12 = watersheds.iloc[0]
Map AORC grid to HUC12¶
HmsGrid.map_aorc_to_subbasins( ... basin_geometry=huc12['geometry'], ... aorc_grid="precip/aorc_may2020.nc", ... output_hrapcells=f"regions/huc12_{huc12['huc12']}", ... subbasin_name=huc12['name'] ... )
Notes
- Reads grid coordinates from AORC NetCDF file
- Uses map_grid_to_subbasins() internally
- See tenk/regions/hrapcells for reference format
Source code in hms_commander/HmsGrid.py
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 | |
calculate_travel_lengths(grid_cells, outlet_point, method='euclidean')
staticmethod
¶
Calculate flow distance from grid cells to outlet.
Computes travel lengths for ModClark time-area calculations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid_cells
|
GeoDataFrame
|
Grid cell geometries (polygons or points) as GeoDataFrame |
required |
outlet_point
|
Tuple[float, float]
|
Subbasin outlet coordinates (lon, lat) or (x, y) |
required |
method
|
str
|
Distance calculation method (default: "euclidean"): - "euclidean": Straight-line distance (fast) - "flow_path": Along DEM flow paths (requires DEM, accurate) |
'euclidean'
|
Returns:
| Type | Description |
|---|---|
Series
|
Travel lengths in kilometers as pd.Series |
Example
from hms_commander import HmsGrid
Calculate travel lengths¶
travel_lengths = HmsGrid.calculate_travel_lengths( ... grid_cells=grid_cells_gdf, ... outlet_point=(-77.5, 41.1), ... method="euclidean" ... )
Notes
- Euclidean: Simple, fast, approximate
- Flow path: Accurate, requires DEM (future implementation)
- Units: Always kilometers (HMS standard)
Source code in hms_commander/HmsGrid.py
get_grid_info(grid_file)
staticmethod
¶
Read metadata from HMS .grid file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid_file
|
Union[str, Path]
|
Path to .grid file |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Grid metadata dictionary including: - grid_manager: Grid manager name - version: HMS version - grids: List of grid definitions, each containing: - grid_name: Grid name - grid_type: Grid type (e.g., "Precipitation") - description: Grid description - dss_file: DSS file path - pathname: DSS pathname - last_modified: Last modification datetime |
Example
from hms_commander import HmsGrid
Read grid metadata¶
info = HmsGrid.get_grid_info("grids/aorc.grid") print(info['grids'][0]['grid_name']) 'AORC_Grid_1' print(info['grids'][0]['pathname']) '/AORC/GRID/PRECIP////'
Source code in hms_commander/HmsGrid.py
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 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 | |
read_hrapcells(hrapcells_file)
staticmethod
¶
Read grid cell mapping from hrapcells file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hrapcells_file
|
Union[str, Path]
|
Path to hrapcells file |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, List[dict]]
|
Dictionary mapping subbasin names to list of grid cells. |
Dict[str, List[dict]]
|
Each grid cell is a dict with: - x: X coordinate index - y: Y coordinate index - travel_length: Travel length in km - area: Area in km² |
Example
from hms_commander import HmsGrid
Read hrapcells¶
cells = HmsGrid.read_hrapcells("regions/hrapcells") print(f"Subbasins: {list(cells.keys())}") print(f"Cells in first subbasin: {len(cells['85'])}")
Source code in hms_commander/HmsGrid.py
get_cell_polygons(cell_file, lattice='HRAP', cell_size=None)
staticmethod
¶
Return the cells of a grid cell file (hrapcells format) as polygons.
A cell file gives each cell by its integer lattice index; cell (x, y) covers
x0 + x * cell_size to x0 + (x + 1) * cell_size east and the same north, in
the lattice's coordinates, where (x0, y0) is the lattice's cell_zero: the
corner of cell (0, 0). It is (0, 0) for HRAP and SHG. This places the cells of a file such as the tenk sample's
regions/hrapcells on the map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cell_file
|
Union[str, Path]
|
Grid cell file ( |
required |
lattice
|
Union[str, dict]
|
|
'HRAP'
|
cell_size
|
Optional[float]
|
Cell size for |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with |
GeoDataFrame
|
|
GeoDataFrame
|
the whole cell as |
Example
cells = HmsGrid.get_cell_polygons("tenk/regions/hrapcells", "HRAP") basins = cells.dissolve("subbasin") # the cells each subbasin uses
Source code in hms_commander/HmsGrid.py
remap_cell_file(cell_file, output_file, source_lattice='HRAP', target_lattice='SHG', target_cell_size=None, source_cell_size=None)
staticmethod
¶
Move a grid cell file onto another lattice, keeping each subbasin's area.
Each source cell's area inside its subbasin (the file's Area) is spread over
the target cells it overlaps, in proportion to the overlap, assuming that area is
spread evenly over the source cell. A file does not say where inside a partly
covered cell the subbasin lies, so boundary cells are approximate; whole cells
are exact. Overlaps are measured in EPSG:5070 (equal-area). Each subbasin's total
area is preserved to rounding. A target cell's travel length is the
area-weighted mean of the travel lengths of the source cells it receives area
from. Use it, for example, to run the tenk sample on SHG grids: the result has
SHG indexes, which the SHG grid records of HmsDssGrid.write_grid_timeseries(
target_crs="SHG") and HmsAorc.convert_to_dss_grid(target_crs="SHG") use.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cell_file
|
Union[str, Path]
|
Source grid cell file (hrapcells format). |
required |
output_file
|
Union[str, Path]
|
New cell file to write. An existing file is replaced. |
required |
source_lattice
|
Union[str, dict]
|
Lattice of |
'HRAP'
|
target_lattice
|
Union[str, dict]
|
Lattice of the output (default |
'SHG'
|
target_cell_size
|
Optional[float]
|
Target cell size ( |
None
|
source_cell_size
|
Optional[float]
|
Source cell size for a CRS lattice. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the new cell file. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file has no cells, or a lattice is not understood. |
Source code in hms_commander/HmsGrid.py
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 | |
check_cells_on_grid(cell_file, grid)
staticmethod
¶
Check that a grid cell file's cells fall on a DSS grid, and weight its values.
HEC-HMS looks each cell up by its index in the grid record. A cell outside the
record, or on a missing value, gets no precipitation, and HEC-HMS can still report
a successful run (look for WARNING 40503 in its log). Use this check before a
run, and its weighted_value to compare with the subbasin's PRECIP-INC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cell_file
|
Union[str, Path]
|
Grid cell file (hrapcells format), on the grid's lattice. |
required |
grid
|
dict
|
A grid dict from |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame, one row per subbasin: |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
area-weighted mean of the cells' values, in the grid's units, over the cells |
DataFrame
|
that have one; NaN when none has). |
Source code in hms_commander/HmsGrid.py
get_info()
staticmethod
¶
Get information about HMS grid operations.
Returns:
| Type | Description |
|---|---|
dict
|
Information about grid operations: - format: File format descriptions - supported_grids: Supported grid types - hrapcells_format: hrapcells file format description - references: Reference documentation |
Example
from hms_commander import HmsGrid
info = HmsGrid.get_info() print(info['format'])