HDF Modules¶
Classes for reading and processing HEC-RAS HDF result files.
Rivia provided the conceptual basis for HdfResultsQuery; pyHMT2D also
influenced HDF extraction and spatial probing workflows. See
Related libraries for author credit,
query semantics, and companion-library examples.
Exact native mesh dataset identity¶
Use HdfMesh.get_mesh_geometry_inventory(hdf_path) to inventory every native
dataset below Geometry/2D Flow Areas without modifying the file. The ordered
DataFrame contains dataset_path, dtype, shape, bytes and sha256.
Descriptors and metadata preserve the fixed-width native dtype; SHA-256 covers
the uncompressed C-order array bytes. HDF compression and storage chunking
therefore do not affect the dataset identity. Coordinates, units and CRS are
not converted.
reference = HdfMesh.get_mesh_geometry_inventory("child.g01.hdf")
result = HdfMesh.get_mesh_geometry_inventory(
"child.p09.hdf", dataset_paths=reference.dataset_path.tolist()
)
same_mesh_datasets = reference.to_dict("records") == result.to_dict("records")
Selecting the complete reference paths permits additional result property
datasets without asserting that those additions match. Missing, duplicate,
nonlocal or variable-width paths fail explicitly. An empty inventory cannot
pass. Reads use slabs bounded by max_chunk_bytes (default 8 MiB); a native
row that cannot fit that budget is rejected.
Bind both HDF file digests to fresh native preprocessing or execution receipts before using the comparison. Matching dataset rows does not establish whole HDF equality, matching attributes or projections, native boundary ownership, structure attachment, hydraulic equivalence or engineering approval. Verify those independent contracts through their corresponding public APIs. This reader performs no native execution and writes no artifact.
SA/2D native attachment evidence¶
Call HdfStruc.get_connection_attachments(hdf_path, connections_df=None,
ras_object=None) with an explicit HDF path or plan number. Plan numbers resolve
through plan_df to results; explicit geometry HDF paths are also accepted and
normally report unverified attachment after preprocessing alone. Supply the
expected Name, From, To inventory from GeomLateral.get_connection_data()
so a missing imported connection receives a failure row.
The return DataFrame contains those identities, from_cells, from_faces,
to_cells, to_faces, attachment_verified, reason_code,
orientation_verified, flux_sign_verified, evidence_paths, details,
source_hdf and native_version. IDs are tuples of zero-based mesh-local native
indices; repeated segment cells are preserved. The native headwater/tailwater
cell lists and face-point chains must map exactly to active cells and their
incident faces in the named areas. Geographic proximity never establishes
attachment. Absent, ambiguous, wrong-area, malformed, inactive or unsupported
native evidence reports CONNECTION_ATTACHMENT_UNVERIFIED.
Positive evidence is qualified on actual HEC-RAS 6.6 BaldEagleCrkMulti2D results. Three internal levees were verified on both sides. Its geometry-only preprocessing output lacked those persisted records. The storage-to-2D dam and unqualified versions remain unverified. A caller must establish that results are fresh for the authored geometry using input hashes and native compute receipts; this reader does not certify source currentness. Orientation and flow sign are separate and remain explicitly false in this interface.
Use scripts/qualify_sa2d_attachment.py in a fresh disposable workspace:
uv run python scripts/qualify_sa2d_attachment.py --project <source-copy> --workspace <new-workspace> --plan-number 04 --ras-exe <installed-Ras.exe> --max-wait 120 --compute-start 1999-01-01T12:00:00
The optional five-minute compute collects result-side native connectivity; it
does not qualify seam conveyance. Without it, the script records preprocessing
evidence and an explicit unverified outcome. Source hashes, runtime/TCU status,
elapsed time and native receipts are retained in sa2d_attachment_receipt.json.
Run the script under Wine Python in fim-hecras-wine:6.6-clb-v8 with the new
library installed for intended-runtime qualification. Mount source projects
read-only and choose a fresh output variant; fleet orchestration remains the
coordinator's responsibility.
Core Classes¶
HdfBase¶
Base functionality for HDF file operations.
get_dataset_info(file_path, group_path="/")- Print HDF structureget_attrs(hdf_file, attr_path)- Get attributes at pathget_projection(hdf_path)- Get coordinate systemget_result_unit_metadata(hdf_path, *, strict=True)- Read normalized unit metadata and source evidence from a standalone plan-result HDF
Datetime parsers are provided by HdfUtils.
get_result_unit_metadata() is deliberately a result-HDF fallback. When the
full project is available, use RasPrj.get_project_units() and treat the text
.prj marker as authoritative. The HDF reader never defaults missing metadata
to English units. It raises on missing, unrecognized, geometry-only, or
contradictory metadata unless strict=False, which returns the raw evidence
and an unresolved status for audit workflows.
HdfPlan¶
Plan-level information from HDF files.
HdfPlan.get_plan_met_precip_values(hdf_path) reads materialized precipitation
values, timestamps and attributes from a compiled plan without changing the file.
For a retained meteorology-only snapshot, select its group explicitly:
rain = HdfPlan.get_plan_met_precip_values(
"retained-meteorology.h5", group_path="Meteorology/Precipitation"
)
Arrays retain their stored units, numerical types and timestamp encodings. Missing datasets or inconsistent shapes raise errors; the reader does not search other groups or establish which model run used a snapshot.
get_plan_information(hdf_path)- Get plan metadataget_plan_start_time(hdf_path)/get_plan_end_time(hdf_path)- Get start/end timesget_plan_parameters(hdf_path)- Get computation parametersget_2d_flow_options(hdf_path)- Get 2D equation set, initial condition time, tolerances, and solver options from computed HDF output
HdfProject¶
Project-wide extent and coordinate-system helpers.
get_project_extent(hdf_path=None, include_1d=True, include_2d=True, include_storage=True, buffer_percent=50.0, buffer_x_percent=None, buffer_y_percent=None, geometry_type="footprint", fill_holes=True, *, geom_path=None, fallback_to_plaintext=True, ras_object=None)- Return a footprint or buffered bounding box and its project-coordinate bounds.get_project_bounds_latlon(hdf_path=None, buffer_percent=50.0, include_1d=True, include_2d=True, include_storage=True, project_crs=None, *, geom_path=None, fallback_to_plaintext=True, ras_object=None)- Return the project bounds in WGS84.export_extent_geojson(hdf_path, output_path, buffer_percent=50.0, *, geom_path=None, fallback_to_plaintext=True, ras_object=None)- Export the project extent as GeoJSON.
Extent extraction prefers usable HDF geometry independently for 1D reaches,
2D flow areas, and storage areas. With the default
fallback_to_plaintext=True, a matching plain-text .g## file supplies only
components unavailable from HDF; a text-only 1D footprint is constructed from
cross-section cut-line endpoints. Set fallback_to_plaintext=False for strict
HDF-only behavior. include_storage=True is also component-aware: HDF storage
polygons are preferred and companion text geometry is used only when needed.
Mesh Operations¶
HdfMesh¶
Mesh geometry data. See Meshing for the diagnostic-to-repair workflow and operation-specific failure limits.
get_mesh_perimeter_faces(hdf_path, mesh_name, ras_object=None) returns every
native perimeter face of a named 2D area as a GeoDataFrame, including faces
without an assigned BC line. It preserves native face_id, cell0, cell1,
interior_cell_id, exterior_cell_id, face-point endpoint IDs, face_length,
and complete face geometry. Physical cells use native Attributes/Cell Count;
ghost cell IDs are retained rather than classified from surface area.
Nullable bc_line_id, bc_line_name, and bc_line_type come from native BC
associations. The geometry BC type (for example External) is distinct from
the flow forcing type. Duplicate ownership, stale face/endpoints, non-perimeter
assignments, and missing association tables when BC lines exist raise errors.
It does not infer attachment from proximity. Inspect attrs['association_status']
and attrs['length_source']; native length is in model units. Interior-hole
boundary faces are included by topology, but rings are not classified.
from ras_commander.hdf import HdfMesh
faces = HdfMesh.get_mesh_perimeter_faces("child.g01.hdf", "Perimeter 1")
unassigned = faces.loc[faces.bc_line_id.isna()]
See scripts/validate_perimeter_bc.py for real-example native compilation and
source-preservation acceptance. Read only a current native compiled HDF after
editing geometry text.
Mesh corner elevations¶
get_mesh_corner_elevations(hdf_path, mesh_name=None, *, postprocessing_hdf=None, source="auto", engine="auto")
reads the static ground elevation of every mesh corner (face point). RASMapper's
depth-weighted sloping interpolation uses these terrain values. They are not
corner water surfaces, face water surfaces or node velocities, and turning on
more hydraulic output variables does not produce them. HEC-RAS stores them in
two places:
source layout |
Dataset | Written by |
|---|---|---|
"geometry" |
Geometry/2D Flow Areas/<mesh>/FacePoints Elevation in the geometry or plan HDF |
2D hydraulic-table preprocessing (HEC-RAS 7.0 and later; 6.x files do not have it) |
"mapping_cache" |
Results/Unsteady/Output/Output Blocks/Base Output/Summary Output/2D Flow Areas/<mesh>/Processed Data/Profile (Horizontal)/FacePoint Elevation in the result's PostProcessing.hdf (singular FacePoint) |
RASMapper, when it renders depth-weighted maps |
hdf_path names the meshes and gives each mesh's corner count (rows of
FacePoints Coordinate) and terrain metadata. Pass the cache with
postprocessing_hdf; it is usually <project folder>/<plan Short ID>/PostProcessing.hdf.
Values are float32 in FacePoints Coordinate row order, bit for bit as stored,
including NaN payloads and sentinels such as -9999. Nothing is interpolated,
reordered or filled. The method only reads: it never generates elevations from
terrain. Generating them needs the native terrain and belongs to a separate
preparation step.
Source selection is explicit and deterministic:
source="geometry"reads onlyhdf_path. Do not passpostprocessing_hdf.source="mapping_cache"reads only the cache (postprocessing_hdfrequired).source="auto"reads the geometry layout and, when given, the cache. Any candidate that is present but is not one float32 value per corner makes the result"invalid". When both are present they must be bit-identical (result"ok", values from the geometry), otherwise the result is"conflict"with no values. With only the geometry the result is"ok". With only the cache it is"ok"unless a staleness check failed ("stale"). With neither it is"missing".
A cache dataset existing does not show that it matches the mesh and terrain.
Every cache that reads successfully is checked, and each check is passed,
failed or not_checked (evidence not stored):
| Check | Passes when |
|---|---|
corner_count |
one value per corner of hdf_path's mesh (a mismatch makes the cache "invalid") |
terrain_file |
the cache's Terrain Filename (relative to the cache folder) is the mesh's terrain (relative to hdf_path) |
terrain_date |
the cache's Terrain File Date equals the mesh's Terrain File Date (the terrain the mesh was preprocessed against) |
terrain_current |
the terrain file's modification time still equals the cache's Terrain File Date |
cache_after_hdf |
the cache was written after hdf_path was last modified |
agreement |
(source="auto", both present) the two arrays are bit-identical |
A failed check makes a cache-only result "stale" with no values. Copying a
project can change file times and fail the date checks; the result then
reports a possibly stale cache instead of trusting it.
Each result (MeshCornerElevations) has status, values (read-only float32,
None unless "ok"), corner_count, source (the candidate used),
candidates (every source consulted, each with file, dataset, status,
detail, dataset attributes, terrain metadata and the sha256 of its
float32 bytes), checks and reason. require() returns the values or raises
CornerElevationError; as_dict() gives plain data.
engine follows RAS_COMMANDER_FAST_HDF (auto, h5py, native). The
native engine with the mesh_corner_elevations entry point (added after
published ras-commander-fast-hdf 0.2.2) and the h5py reader return
identical results; auto falls back to h5py on any native refusal, and native
raises FastHdfError instead.
from ras_commander.hdf import HdfMesh
result = HdfMesh.get_mesh_corner_elevations(
"Model.p01.hdf", "Perimeter 1",
postprocessing_hdf="Plan 01/PostProcessing.hdf",
)
elevations = result.require() # float32, FacePoints Coordinate order
print(result.source.layout, result.source.file, result.source.dataset)
print([(c.name, c.status) for c in result.checks])
get_mesh_area_names(hdf_path)- List 2D flow areasget_mesh_corner_elevations(hdf_path, mesh_name=None, *, postprocessing_hdf=None, source="auto", engine="auto")- Read the stored corner (face-point) ground elevations that RASMapper's depth-weighted sloping interpolation uses, with provenance. See Mesh corner elevations.get_mesh_areas(hdf_path)- Read named-area perimeters, with a strictly validated collection-level fallback for affected 6.2/6.3-era geometry HDFsdiagnose_mesh_layout(hdf_path, program_version=None)- Report version evidence, detected layout, dataset paths, and per-capability status for area names, perimeters, cell centers, face topology, and cell polygonsget_mesh_cell_polygons(hdf_path, *, strict=False, engine="auto", threads=None, diagnostics=False)- Get cell polygons as a GeoDataFrame; a warning names omitted cells. Withdiagnostics=Truethe equality-safe tuple of record dictionaries inresult.attrs["cell_polygon_diagnostics"]lists physical cells that were omitted or ambiguously polygonized (off by default since this release; it was always attached before). Usediagnose_mesh_cell_polygons()for a DataFrame.engine("auto","h5py","native") andthreadsselect and bound the native polygonizer; withengine="native"diagnostic labels can differ from the Python reference (see the docstring). See Native Rust HDF engine.diagnose_mesh_cell_polygons(hdf_path, *, engine="auto")- Report native cell IDs, face IDs, polygon counts, and reason codes for physical-cell reconstruction problems and expected boundary-only recordsget_mesh_cell_faces(hdf_path)- Get cell face lines (built in one vectorized call; natively inauto/nativemode). The face geometry to read once and join toinclude_geometry=Falseface results on["mesh_name", "face_id"]get_mesh_cell_points(hdf_path)- Get cell center points. The cell geometry to read once and join toinclude_geometry=Falsecell results on["mesh_name", "cell_id"]find_nearest_cell(point, cell_points_gdf, mesh_name=None)- Find nearest cell ID and distance using previously read cell centersfind_nearest_face(point, cell_faces_gdf, mesh_name=None)- Find nearest face ID and distance using previously read facesget_mesh_face_property_tables(hdf_path)- Read face elevation/area/wetted-perimeter/Manning tables
Some delivered geometries created across the HEC-RAS 6.2/6.3 timeframe store
valid 2D flow-area perimeters only in the collection-level Polygon Info,
Polygon Parts, and Polygon Points datasets. get_mesh_areas() can recover
those perimeters after validating every offset, count, part range, coordinate,
ring closure, and multipart association. It does not repair malformed rings or
change their topology.
The same files may report Complete Geometry=True while omitting the named-area
face-connectivity datasets. In that state, diagnose_mesh_layout() reports the
perimeter as collection_fallback and face/cell-polygon topology as
not_present. get_mesh_cell_faces() and get_mesh_cell_polygons() return an
empty GeoDataFrame with a warning. They never infer connectivity from cell
centers or collection-level Cell Info / Cell Points. Public USACE changelogs
do not identify the exact producer defect or establish its first fixed release,
so dataset inspection—not a blanket version rule—selects the safe reader.
Detailed face linework can also fail to produce exactly one polygon for an
individual physical cell. The default reader preserves its historical output
shape but warns, retains the native zero-based cell IDs, and attaches a
diagnostic table to the result. Use diagnose_mesh_cell_polygons() to inspect
the affected IDs or get_mesh_cell_polygons(..., strict=True) when incomplete
or ambiguous physical-cell geometry must stop the workflow. One- and two-face
boundary-only records are reported separately and do not fail strict mode.
Never assume the GeoDataFrame row index is an exhaustive physical-cell mask,
and do not silently replace failed detailed geometry with a convex hull,
endpoint ring, or selected repaired component.
EXPERIMENTAL — not recommended for production or any other non-experimental use. HEC-RAS 7.0 April 2026 has been tested in one Windows-preprocess/Linux-solve
*.p##.tmp.hdfworkflow. The exactHEC-RAS 7.0.1 June 2026andHEC-RAS 7.0.2 October 2026versions are also accepted after native temporary-file schema and write/readback qualification; their Linux solves after mutation remain untested. All other HEC-RAS versions and workflows are untested. These are not general land-cover or geometry-authoring APIs.
The methods require acknowledge_unsupported=True, validate the exact
temporary-result role and schema, retain a unique full-file backup, emit a
runtime warning, and verify readback:
write_linux_tmp_face_property_tables(...)- Replace selected temporary face tablesextend_linux_tmp_face_property_tables(...)- Extend temporary tables and return a structured reporttransform_linux_tmp_face_mannings_n(...)- Transform only the temporary-table Manning columnsample_linux_tmp_face_mannings_n_from_landcover_curves(...)- Apply the documented equal-class land-cover sampling heuristicset_mesh_pinned_attribute(...)- Set informationalPinnedmetadata; this does not protect edits from Windows preprocessing
The former names remain compatibility wrappers through v1.1.x and will not be removed before v1.2.0:
| Compatibility name | Canonical replacement |
|---|---|
set_mesh_face_property_tables() |
write_linux_tmp_face_property_tables() |
extend_face_property_tables() |
extend_linux_tmp_face_property_tables() |
set_face_mannings_n_values() |
transform_linux_tmp_face_mannings_n() |
recompute_face_mannings_n_from_landcover_curves() |
sample_linux_tmp_face_mannings_n_from_landcover_curves() |
pin_property_tables() |
set_mesh_pinned_attribute() |
HdfResultsMesh¶
2D mesh results.
get_mesh_max_ws(hdf_path, round_to="100ms")- GeoDataFrame withmaximum_water_surfaceand, when stored,maximum_water_surface_timeget_mesh_summary(hdf_path, var)- GeoDataFrame for a named HEC-RAS summary variable, with cell or face geometryget_mesh_summary_values(hdf_path, var)- Read summary values and identifiers without constructing Shapely geometryinclude_geometry=False(keyword-only) onget_mesh_max_ws,get_mesh_min_ws,get_mesh_max_face_v,get_mesh_min_face_v,get_mesh_max_ws_err,get_mesh_max_iter,get_mesh_last_iter,get_mesh_summary,get_mesh_summary_outputandget_mesh_max_depthis the fast output: a typed pandas DataFrame without geometry (stored value dtypes,int64IDs, stringmesh_name). The default GeoDataFrame is the convenient output; see Geometry: convenient or fast and Typed tables without geometryget_mesh_max_depth(hdf_path)- Maximum depth from stored HEC-RASDepthwhen present, otherwise derived in memory fromWater Surface - Cells Minimum Elevationget_mesh_max_face_v(hdf_path)- Maximum face velocityget_mesh_timeseries(hdf_path, mesh_name, var, truncate=True, *, time_selection=None, spatial_selection=None, return_type="xarray")- Eager time series with source-coordinate HDF slicing, or an opt-in lazyHdfResultViewiter_mesh_timeseries(hdf_path, mesh_name, var, *, time_selection=None, spatial_selection=None, batch_size=None, max_chunk_bytes=16777216)- Stream untruncated, bounded, time-major xarray batches-
inspect_mesh_series_raw(hdf_path, mesh_name, var, *, include_values=False)- Untyped diagnostic of one stored Base Output mesh series: dataset identity, shape, dtype, attributes, Time row match, geometry counts and the typed readers' refusal reason. Physical domain and units are always reported as unqualified; see Non-Newtonian rheology outputs -
get_mesh_cells_timeseries(hdf_path, mesh_names=None, var=None, truncate=False, ras_object=None)- Dictionary of mesh Datasets; select cells/faces afterward get_mesh_faces_timeseries(hdf_path, mesh_name, truncate=True)- Available face variables as one Dataset; selectface_velocityandface_idafterwardget_mesh_log_hydraulics(hdf_path, mesh_name)- Diagnostic DataFrame for the legacy HEC-RAS 6.0-6.3.x per-meshLog Hydraulicssolver log: ten named fields (iterations, corrections, residuals, volume balance, water surface extrema), Base Outputtime/timestampand per-field units/provenance inDataFrame.attrs. Other versions, unknownColumn Nlabels, a storedLocationor a row count that differs from Base Output time raiseValueError. Fixed-suffix labels (the producer always writesMin water surface elevation (m)) are not treated as unit evidence. The table is not a cell or face series;get_mesh_timeseries()still refuses it.get_profile_line_flow_timeseries(hdf_path, line_name, mesh_name=None, profile_lines_path=None, direction="absolute")- Native Mapper named-line flow; inspect returnedselection_sourceget_profile_line_peak_flow(hdf_path, line_name, mesh_name=None, profile_lines_path=None, direction="absolute")- Peak Q and time from the same native named-line extraction pathget_mesh_timeseries_availability(hdf_path, mesh_name=None)- Metadata-only report of whether each Base Output mesh dataset is readable as a series (status,rows,time_rows,stored_bytes,reason)
The canonical profile-line methods above require pythonnet/RasMapperLib. They
may return a native-associated precomputed hydrograph of unqualified provenance
or aggregate selected face flows; these have different signed/absolute-flow semantics. The native-associated
hydrograph is not independently established as solver-recorded and may be
observed data. Explicit solver-recorded Reference Lines HDF output is read with
HdfResultsXsec.get_ref_lines_timeseries().
See Profiles, hydrographs and reference locations for
method contracts and batch workflows
for plot/export examples. HDF storage should not be confused with the method
used to calculate the stored quantity.
get_mesh_max_depth() logs one INFO source message per mesh. Stored Depth is
read only. The fallback is computed only in memory and does not create or write
Depth in the HDF. Temporary synthetic test HDFs are test artifacts; they are
not producer output and are labeled separately from pre-existing HEC-RAS result
fixtures.
Non-Newtonian rheology outputs¶
Native HEC-RAS 6.6 and 7.0.1 Bingham runs can write three optional face-labelled
series. Face Yield Stress and Face Viscous Stress have one column per face and
are read by get_mesh_timeseries(), lazy views and iter_mesh_timeseries() as
(time, face_id) series with their stored lb/ft^2 units in US-Customary output.
Face Mixture Dynamic Viscosity is stored with Location=Faces and
Columns=Faces, but in the inspected outputs its width equals the stored cell
count (physical plus ghost cells), not the face count. No producer contract
establishes its physical domain or the meaning of its stored lb/ft^2*s label,
so the typed readers refuse it with ValueError and face/cell discovery skips it.
inspect_mesh_series_raw() reports the stored dataset and the refusal reason
without assigning cell or face identities, timestamps or converted units:
report = HdfResultsMesh.inspect_mesh_series_raw(
plan_hdf, "DebrisFlowArea", "Face Mixture Dynamic Viscosity"
)
report["typed_status"], report["refusal_reason"] # "refused", "...contradicts geometry count..."
report["shape"], report["geometry_counts"] # stored width vs stored cells/faces
report["physical_domain"], report["units_interpretation"] # always "unqualified"
Readable rheology series are a file-format result. They do not establish hydraulic convergence or engineering acceptance of a debris-flow model.
Ghost cells. HEC-RAS writes 2D cell results for the physical cells
followed by ghost cells outside the mesh perimeter. Geometry/2D Flow
Areas/Attributes Cell Count is the physical count; cell IDs at or above it
are ghost cells. Ghost values are placeholders, not solution results: summary
maximum and minimum water surface are 0.0, and minimum elevation is NaN. The
cell-result methods above therefore return physical cells only by default, so
their rows match the mesh polygons. Results carry an is_ghost_cell column
(DataFrames and GeoDataFrames) or coordinate along cell_id (xarray).
- Pass
include_ghost_cells=Trueto keep the ghost rows or columns. - In
get_mesh_timeseries()anditer_mesh_timeseries(),spatial_selectionis clipped to the physical cells. Negative positions count back from the last physical cell. - An HDF without
Cell Countkeeps every cell and logs a warning. - Face results are unaffected.
HdfMesh.get_mesh_cell_points(hdf_path, include_ghost_cells=False)returns the matching physical cell centers.
max_ws = HdfResultsMesh.get_mesh_max_ws(hdf_path) # physical cells only
everything = HdfResultsMesh.get_mesh_max_ws(hdf_path, include_ghost_cells=True)
The maximum methods have different temporal bases. get_mesh_max_ws() and
get_mesh_max_face_v() read native HEC-RAS Summary Output maxima, which are
tracked across the computation and can include peaks between saved
mapping/output timestamps. get_mesh_max_depth() instead reduces the retained
Depth series or derives depth from retained Water Surface; its maximum is
limited to those stored output times. See Maximum values
for an example and comparison with a time-series reduction.
Bounded and lazy result reads¶
Existing calls to get_mesh_timeseries() still return an eager
xarray.DataArray. The optional time_selection and spatial_selection
arguments are pushed into the HDF read before materialization. Integer
selections preserve a length-one dimension; forward slices preserve source
cell/face identifiers.
Set return_type="view" to receive an HdfResultView. Creating the view reads
only HDF metadata—not result values—and does not retain an open file handle.
Each operation reopens the source read-only and verifies its size and
nanosecond modification time before and after the read, detecting ordinary
source replacement or modification. Available operations are to_xarray(), to_numpy(),
to_pandas(), optional to_arrow(), iter_batches(), select(), and bounded
reduce("max"|"min"|"mean"|"argmax").
For truncate=True, eager conversion reads the selected HDF slab once and
trims zero-only leading/trailing rows in memory. Lazy shape, batching, and
reductions perform a bounded scan when the active window is needed. An all-zero
selection retains its full time extent, matching the historical eager API.
Truncation is evaluated over the selected spatial subset. select(time=None)
preserves a prior selection; pass slice(None) to reset it. NumPy and Python
integer indexes are both accepted. An explicit reduction dtype must be a
floating-point dtype so NaN/infinite filtering remains valid.
iter_mesh_timeseries() is intentionally untruncated: it emits every selected
source timestep once, in time-major batches. This makes batch reassembly
deterministic and avoids a hidden preliminary scan.
Series availability. A dataset whose stored rows differ from the Base
Output Time axis is never broadcast, padded, truncated or re-timed. Eager,
view and streamed reads all raise MeshSeriesAvailabilityError, a
ValueError subclass. They raise before any value is read. The error has
dataset_path, rows, time_rows, stored_bytes and disposition:
"unwritten_placeholder": the producer stored no data (stored_bytes == 0). Reading it would return HDF5 fill values, not results. HEC-RAS 6.6 and 7.0.1 plans without wind forcing leaveFace Wind Termthis way: an extendable one-row dataset withLocation=Faces,Rows=Timesand no stored chunks. It is created when governing-equation output terms are selected. HEC-RAS 6.6 Diffusion Wave runs leaveFace Water Surfacethis way too; 7.0.1 writes it in full. Treat these datasets as unavailable, not as a constant zero field."row_count_mismatch": stored data whose row count cannot be aligned with the clock.
get_mesh_timeseries_availability() reports the same qualification for every
dataset without reading values. get_mesh_faces_timeseries() and
get_mesh_cells_timeseries() skip such datasets during discovery and log the
same message.
from ras_commander import HdfResultsMesh, MeshSeriesAvailabilityError
report = HdfResultsMesh.get_mesh_timeseries_availability("BaldEagleDamBrk.p03.hdf")
print(report.loc[report.status != "available", ["mesh_name", "variable", "rows", "time_rows", "status"]])
try:
HdfResultsMesh.get_mesh_timeseries("BaldEagleDamBrk.p03.hdf", "BaldEagleCr", "Face Wind Term")
except MeshSeriesAvailabilityError as exc:
print(exc.disposition, exc.rows, exc.time_rows)
from ras_commander import HdfResultsMesh
view = HdfResultsMesh.get_mesh_timeseries(
"BaldEagleDamBrk.p03.hdf",
"BaldEagleCr",
"Water Surface",
truncate=False,
time_selection=slice(100, 200),
return_type="view",
)
# Only one selected timestep and the first 5,000 cells are materialized.
snapshot = view.select(time=150, spatial=slice(0, 5_000)).to_xarray()
# Batch sizing targets 16 MiB of result values by default.
for batch in view.iter_batches():
consume(batch)
# Geometry-free native summary output for database loading.
summary = HdfResultsMesh.get_mesh_summary_values(
"BaldEagleDamBrk.p03.hdf",
"Maximum Water Surface",
)
Prefer a native HEC-RAS summary dataset when it represents the requested
engineering statistic. A raw reduction over Water Surface is not always
semantically identical to HEC-RAS Maximum Water Surface; for example,
HEC-RAS may encode never-wet cells as zero in the summary while the time-series
array retains terrain-elevation values. Bounded reductions deliberately report
the selected raw dataset statistic and do not invent wet/dry semantics.
See the result-shape and availability contract for variable naming, coordinates, metadata, and missing-output behavior.
HdfResultsProducts¶
Inspection and deterministic product contracts for completed unsteady result HDFs.
inspect_result(hdf_path)- Read an existing result HDF without mutation and fail closed on incomplete or conflicting completion evidence, inconsistent time axes, missing CRS or units, and mesh/result/topology misalignmentexport(hdf_path, output_directory, *, resolution=None, max_dimension=2048, nodata=-9999.0, include_preview=True)- Generate a checksum-pinned hydraulic product package without modifying the producer HDF
Current HEC-RAS results can establish completion with
Event Conditions/Completed Successfully=True. Older producer HDFs that do
not contain that attribute can establish completion with their embedded
Complete Process compute-message marker. An explicit false or malformed
attribute is never overridden by messages.
The returned inspection identifies whether maximum depth will be read from the
stored HEC-RAS Depth time series or derived in memory from Water Surface -
Cells Minimum Elevation. It also records hydraulic_qaqc: not_evaluated:
mechanical completion and product readiness are not engineering acceptance.
from ras_commander import HdfResultsProducts
inspection = HdfResultsProducts.inspect_result("project.p02.hdf")
manifest = HdfResultsProducts.export(
"project.p02.hdf",
"project-p02-hydraulic-products",
)
export() supports completed unsteady HDFs with 2D flow areas. It writes a
common-grid trio of Cloud Optimized GeoTIFFs for maximum WSE, maximum depth, and
maximum adjacent-face velocity; a fixed-schema Arrow/Parquet boundary
hydrograph table; result metadata; numerical evidence; a WGS84 GeoJSON
footprint; and, by default, a depth preview. pyarrow>=14.0 is a required core
dependency because Arrow and Parquet are part of the modern geospatial product
contract, not an optional fallback.
Raster dimensions are bounded twice: neither width nor height may exceed
max_dimension, and the total raster contains at most 16,777,216 cells. The
nodata argument is normalized to float32 before collision checks so a nearby
double-precision value cannot silently become equal to valid stored data.
Pixels are square at the exact selected resolution; when a footprint span is
not evenly divisible, raster bounds expand by less than one pixel on the right
or bottom rather than silently changing the requested cell size.
The source HDF is opened read-only and protected by point-in-time digest checks.
The files in the output directory are newly generated ras-commander derivative
artifacts; they are not newly generated HEC-RAS model output. The output
directory must not already exist. Assets are published without overwriting and
hydraulic-products.json is linked last, so consumers must use that manifest as
the package-complete marker. A package that lacks the manifest is incomplete.
Publication requires same-filesystem hard-link support and fails closed when
the destination filesystem cannot provide it.
The exporter preserves valid negative-datum WSE and uses 2D flow-area
footprints as raster support. It does not infer hydraulic acceptability:
numerical-qaqc.json preserves evidence while the manifest remains
hydraulic_qaqc: not_evaluated. A result with no boundary-condition series gets
a valid, empty Parquet table with the same schema rather than losing the asset.
Synthetic HDFs created by focused tests are labeled test artifacts. Real-file integration uses pre-existing producer HDFs read-only and does not run HEC-RAS or generate model output; it generates only temporary derivative packages.
Plan Results¶
HdfResultsPlan¶
Plan-level results.
get_runtime_data(hdf_path)- Runtime statisticsget_volume_accounting(hdf_path)- Volume accounting dataget_compute_messages(hdf_path)- Computation messagesget_unsteady_info(hdf_path)- Unsteady result metadata; useHdfPlan.get_plan_parameters()for plan parametersis_steady_plan(hdf_path)- Check if steady stateget_steady_profile_names(hdf_path)- Get steady profile namesget_steady_wse(hdf_path)- Get steady water surface elevationsget_steady_info(hdf_path)- Get steady flow metadata
HdfResultsXsec¶
1D cross-section results.
get_xsec_timeseries(hdf_path)- All cross-section time seriesget_xsec_summary(hdf_path)- Cross-section summary data
1D Geometry¶
HdfXsec¶
Cross-section and river geometry extraction from HDF.
get_cross_sections(hdf_path, ras_object=None)- Extract cross-section geometries as a GeoDataFrame. Accepts a geometry HDF path or a plan selector; multipart cut lines are returned asMultiLineStringwithout synthetic connectors.get_xs_coords(hdf_path, river=None, reach=None, rs=None)- Extract native station/elevation points as XYZ with point/station order, cut-line distance, Manning's n, bank classification, coordinate metadata, and source provenanceget_river_centerlines(hdf_path)- Extract river centerlines asLineStringorMultiLineStringgeometriesget_river_stationing(hdf_path)- Calculate river stationing along centerlinesget_river_reaches(hdf_path)- Return model 1D river reach lines with stableriver_idand computedlengthcolumnsget_river_edge_lines(hdf_path)- Return river edge linesget_river_bank_lines(hdf_path)- Extract river bank lines
Structure Data¶
HdfStruc¶
HdfStruc.get_structures() treats a native empty Geometry/Structures group,
or one containing only an empty Property Tables subgroup, as an empty layer.
It returns typed Structure ID/geometry columns, source CRS/group attributes and
attrs["structure_status"]="empty_placeholder". Populated property tables,
unrecognized children, and incomplete nonempty layers remain hard errors; no
actual structure is silently skipped. Source files and native units are unchanged.
Structure geometry and SA/2D connections.
list_sa2d_connections(hdf_path, *, ras_object=None)- List SA/2D connections with time-series resultsget_structures(hdf_path, datetime_to_str=False)- Structure geometry and available attributes as a GeoDataFrameget_geom_structures_attrs(hdf_path)- Stored geometry structure attributes as a DataFrameget_storage_area_polygons(hdf_path, *, ras_object=None)- Extract storage area polygons and attributes from geometry or plan HDF files, including multi-ring polygons with interior rings; returns an empty GeoDataFrame when no storage areas are present.
HdfResultsBreach¶
Dam breach results.
get_breach_timeseries(hdf_path, structure)- Breach time seriesget_breach_summary(hdf_path, structure)- Breach summary statisticsget_breaching_variables(hdf_path, structure)- Breach geometry evolutionget_structure_variables(hdf_path, structure)- Structure flow variables
HdfStorageArea¶
Storage area volume-elevation curve extraction from HDF.
get_volume_elevation_curve(hdf_path, sa_name)- Get volume-elevation curve for a storage areaget_storage_area_names(hdf_path)- List storage areas in HDF
HdfChannelCapacity¶
1D channel capacity analysis (multi-AEP).
analyze_channel_capacity(...)- Run channel capacity analysis from geometry and result inputs; see the full signature belowcompare_conditions(existing_results, proposed_results, level="segments")- Compare previously analyzed channel conditions
HdfStruc1D¶
1D structure result extraction from plan HDF results.
get_structure_max_values(hdf_path, river, reach, rs)- Extract maximum headwater, tailwater, and flow for a bridge, culvert, inline weir, or inline control structure. Raises an actionableValueErrorwhen the plan HDF has no steady/unsteady results, required cross-section result datasets are absent, or the requested structure is not present in the results.list_1d_structures(hdf_path)- List 1D structures identified from result markers. Returns an empty DataFrame quietly when no structures are present in an otherwise readable HDF.
For steady plans, get_structure_max_values() can use the flanking cross sections when the structure is represented in HDF Node Info instead of Cross Section Attributes. The returned hw_source, tw_source, and flow_source fields identify the result locations used.
HdfHydraulicTables¶
Cross section property tables (HTAB).
get_xs_htab(hdf_path, river, reach, station)- Get HTAB data
Infrastructure¶
HdfPipe¶
Pipe network analysis.
get_pipe_conduits(hdf_path)- Get conduit geometryget_pipe_nodes(hdf_path)- Get node locationsget_pipe_network_timeseries(hdf_path, var)- Network time seriesget_pipe_network_summary(hdf_path)- Network summaryget_pipe_profile(hdf_path, conduit_id)- Get conduit profile
HdfPump¶
Pump station analysis.
get_pump_stations(hdf_path)- Get station locationsget_pump_groups(hdf_path)- Get pump groupsget_pump_station_timeseries(hdf_path, name)- Station time seriesget_pump_station_summary(hdf_path)- Station summaryget_pump_operation_timeseries(hdf_path, name)- Operation history
Analysis¶
HdfFluvialPluvial¶
Fluvial-pluvial boundary analysis.
Both fluvial/pluvial entry points log processing failures at ERROR with traceback, path, parameters and stage, then return an empty GeoDataFrame and discard partial geometry. Input/decorator validation exceptions remain unchanged. Cell identities and polygon dissolution stay scoped to each mesh, including repeated native IDs. A successful analysis with no qualifying boundary edges can also return empty. Polygon acreage thresholds use both projected horizontal CRS axis conversion factors. Missing or geographic CRS skips the filter with a warning. Unknown projected units fail processing: the method logs ERROR with traceback, path, parameters and stage, then returns an empty GeoDataFrame and discards partial geometry. Input/decorator validation exceptions remain unchanged; no result status attributes are added.
calculate_fluvial_pluvial_boundary(hdf_path, delta_t, min_line_length=None, *, engine="auto", diagnostics=False)- Calculate boundarygenerate_fluvial_pluvial_polygons(hdf_path, delta_t, temporal_tolerance_hours=1.0, min_polygon_area_acres=None, *, engine="auto", diagnostics=False)- Boundary polygons
engine selects the implementation. "h5py" is the reference described above
(failures are logged and an empty GeoDataFrame is returned). "native" uses the
native Rust graph kernels and raises FluvialNativeUnsupportedError (a
ValueError) when it cannot reproduce the reference result; other errors
propagate. "auto" (default) uses native when it can and otherwise the
reference, including on any native error, so its outcome is always the
reference outcome. The engine that produced the result is recorded in
result.attrs["fluvial_engine"] ("used": "native" or "h5py").
Native kernel timings and counts are attached as result.attrs["fluvial_native"]
only with diagnostics=True (default False), so results carry the same
attributes whichever engine ran.
FluvialNativeUnsupportedError is defined
in the module ras_commander.hdf.HdfFluvialPluvial (import it with
from ras_commander.hdf.HdfFluvialPluvial import FluvialNativeUnsupportedError).
How engine maps onto RAS_COMMANDER_FAST_HDF:
engine |
RAS_COMMANDER_FAST_HDF |
Behaviour |
|---|---|---|
"auto" (default) |
unset/auto |
Native when it reproduces the reference, otherwise the reference. |
"auto" |
h5py |
Reference; native is not attempted (attrs["fluvial_engine"]["used"] == "h5py"). |
"auto" |
native |
Native, or FastHdfError (never a silent fallback). |
"h5py" |
any (ignored) | Reference, with every read on h5py (native is never used, in any mode). |
"native" |
any (ignored) | Native, or FluvialNativeUnsupportedError; never falls back. |
The native engine is used only when fast_hdf.available() is true (the same
extension availability and API-version check as every other native read).
Every public selector uses engine= with "auto", "h5py" and "native".
Inputs the native fluvial engine does not reproduce (for example
min_polygon_area_acres, unprojected CRSs, delta_t=0) run on the reference
in auto mode.
HdfInfiltration¶
Native infiltration authoring and read-only inspection.
Geometry File Operations:
get_preprocessed_infiltration(hdf_path, mesh_name=None, variable=...)- Read solver-owned per-cell infiltration arraysget_infiltration_baseoverrides(hdf_path)- Retrieve the geometry-wide class-to-parameter fallback tableget_infiltration_calibration_regions(hdf_path)- Read every region table in the bulk variable-oriented HDF viewget_infiltration_region_overrides(hdf_path, region_name=..., hecras_version=...)- Read one selected region in the class-ordered native viewget_infiltration_region_names(hdf_path)- Read stable region namesget_infiltration_region_polygons(hdf_path)- Read stable region IDs, names, and polygon geometrycreate_infiltration_override_regions(hdf_path, region_names, hecras_version=...)- Create native geometry override regions from existing Manning-region polygonsset_infiltration_base_overrides(hdf_path, data, hecras_version=...)- Set the native geometry-wide Base Overrides fallbackscale_infiltration_base_overrides(hdf_path, data, scale_factors, hecras_version=...)- Scale active geometry-wide Base Overrides while preserving sentinel valuesset_infiltration_region_overrides(hdf_path, data, region_name=..., hecras_version=...)- Set one native region's parameter table without changing Base Overrides or other regionsscale_infiltration_region_overrides(hdf_path, data, scale_factors, region_name=..., hecras_version=...)- Scale one selected region while preserving sentinel values
Raster and Layer Operations:
get_infiltration_layer_data(hdf_path)- Get infiltration layer data from HDFset_infiltration_sidecar_parameters(hdf_path, data, hecras_version=...)- Set sidecar parameters through native RASMapper serializationscale_infiltration_sidecar_parameters(hdf_path, data, scale_factors, hecras_version=...)- Scale and save sidecar parameters nativelyget_classification_polygons(hdf_path)- Read infiltration sidecar classification polygon overridesget_infiltration_map(hdf_path=None, ras_object=None)- Read the infiltration raster map; without an explicit path, resolve the first usablerasmap_df["infiltration_hdf_path"]calculate_soil_statistics(hdf_path)- Process zonal statistics for soil analysisget_soils_raster_stats(geom_hdf_path, soil_hdf_path=None, ras_object=None)- Resolve the soil sidecar consistently; lookup failures retain the empty-frame recovery contractget_soil_raster_stats(...),get_infiltration_stats(...), andget_landcover_raster_stats(...)- Use the same status-aware sidecar resolver and empty-frame recovery contract
The compatibility names create_infiltration_group(),
set_infiltration_baseoverrides(), set_infiltration_layer_data(), and
scale_infiltration_baseoverrides() delegate to the canonical native APIs
through the v1.1.x compatibility window. The historical
scale_infiltration_data() name was ambiguous between a geometry HDF and an
infiltration sidecar and now fails closed with three explicit choices: the
geometry-wide, selected-region, or sidecar scaler.
These compatibility names will not be removed before v1.2.0.
Ras Commander never hand-authors or selectively deletes
/Geometry/Infiltration datasets.
Soil Analysis:
get_significant_mukeys(hdf_path, threshold)- Identify mukeys above percentage thresholdcalculate_total_significant_percentage(hdf_path)- Compute total coverageget_infiltration_parameters(hdf_path=None, mukey=None, ras_object=None)- Get theVariablesrow of one infiltration-layer class (a soil class, or"<land cover> : <soil>"for combined layers), keyed by the method's HEC-RAS parameter names, with the same optionalrasmap_dflookupcalculate_weighted_parameters(soil_stats, infiltration_params)- Compute weighted average parameters
Data Export:
save_statistics(data, path)- Export soil statistics to CSV
HdfLandCover¶
Land-cover sidecar and final Manning's n extraction.
get_landcover_raster_map(hdf_path)- Read land-cover class IDs, names, and Manning's n valuesset_landcover_mannings_n(hdf_path, mapping, hecras_version=...)- Set sidecar Manning's n through native RASMapper serializationsanitize_classification_names(hdf_path, raster_path=..., hecras_version="6.6")- Opt in to HEC-RAS 6.6's native labels-only sanitizer. It preserves IDs, numeric parameters, and exact companion-TIFF bytes; a legacy V1 sidecar is saved as native V2, with the returned result retaining before/after mappings and a durable backup path. This method is qualified only for6.6/6.6.0; it never rebuilds or resamples the raster.get_classification_polygons(hdf_path)- Read land-cover sidecar classification polygon overridesget_preprocessed_mannings_n(hdf_path)- Read preprocessed cell-center Manning's n values from geometry HDFaudit_final_mannings_n(hdf_path, ...)- Strictly audit solver-owned final cell/face Manning arraysestimate_final_mannings_raster(hdf_path, ...)- Build a non-authoritative visualization estimateexport_final_mannings_raster(hdf_path, output_tif_path, ...)- Write RAS Mapper's Final n Values raster without HEC-RAS (fast-hdf engine; pure 2D geometries, other layouts are refused)
Compatibility mappings are retained through v1.1.x and will not be removed before v1.2.0:
| Compatibility name | Canonical replacement |
|---|---|
set_landcover_raster_map() |
set_landcover_mannings_n() |
compute_final_mannings_raster() |
estimate_final_mannings_raster() for visualization, or audit_final_mannings_n() for solver evidence |
HdfBndry¶
Boundary condition geometry.
get_bc_lines(hdf_path)- Get BC linesget_breaklines(hdf_path)- Get breaklines. Zero- and one-point source records are excluded from line geometry and returned inresult.attrs["breakline_diagnostics"]. Each diagnostic preserves native zero-basedbl_id,Name, all decoded sourceattributes,point_start,point_count, exclusivepoint_end,part_start,part_count, andreason_code="BREAKLINE_TOO_FEW_POINTS". The list is empty for clean or absent layers and remains available when every record is degenerate. Persist diagnostics separately before GeoParquet/other tabular export because writers may discard attrs. Negative, truncated or out-of-range spans still raise; this read-only extraction does not change source geometry, units or CRS.
Utilities¶
HdfUtils¶
Utility class for HDF file operations.
Data Conversion:
convert_ras_string(value)- Convert RAS HDF strings to Python objectsconvert_ras_hdf_value(value)- Convert general HDF values to Python objectsconvert_df_datetimes_to_str(df)- Convert DataFrame datetime columns to stringsconvert_hdf5_attrs_to_dict(attrs)- Convert HDF5 attributes to dictionaryconvert_timesteps_to_datetimes(timesteps)- Convert timesteps to datetime objects
Spatial Operations:
perform_kdtree_query(source, target)- KDTree search between datasetsfind_nearest_neighbors(data, k)- Find nearest neighbors within dataset
DateTime Parsing:
parse_ras_datetime(datetime_str)- Parse RAS datetime (ddMMMYYYY HH:MM:SS)parse_ras_window_datetime(datetime_str)- Parse simulation window datetimeparse_duration(duration_str)- Parse duration strings (HH:MM:SS)parse_ras_datetime_ms(datetime_bytes)- Parse datetime with millisecondsparse_run_time_window(window_str)- Parse time window strings
Native Rust HDF engine¶
The native (Rust) engine is ras-commander's default HDF engine.
ras_commander.fast_hdf routes the Hdf* classes' numeric and text HDF reads
through it, and provides native mesh ring assembly and direct mesh-to-PMTiles
export. HdfResultsMesh, HdfMesh.get_mesh_cell_polygons and the other
routed Hdf* methods keep their established xarray, DataFrame and
GeoDataFrame outputs. Lazy result views push selected reads and bounded
batches through the same adapter. The engine provides HDF reads only; every
HDF write uses h5py. h5py is the reference implementation: in the default
auto mode any read the engine refuses uses h5py. Set
RAS_COMMANDER_FAST_HDF=h5py to select the h5py reference paths for every
read.
The engine is the open-source (MIT) distribution ras-commander-fast-hdf,
developed in
gpt-cmdr/ras-commander-fast-hdf
and published on PyPI. ras-commander 0.107.1 and later install it
automatically on Windows x64, Linux x64 (manylinux_2_28) and macOS arm64
(not yet qualified on the HEC-RAS corpus), the platforms with published
wheels; no Rust toolchain is needed:
On other platforms the engine is not installed and every read uses h5py. To
build it from source there, run pip install "ras-commander[fast]" (needs
Rust; see the extension repository's
building guide).
The fast and fast-hdf extras are otherwise no longer needed.
Geometry output requires GeoPandas and Shapely; direct PMTiles export requires
pyproj. See Native Rust HDF engine for modes,
qualification and limitations.
from ras_commander import fast_hdf
print(fast_hdf.available())
polygons = fast_hdf.mesh_polygons("model.g01.hdf", backend="native", threads=4)
fast_hdf.export_mesh_pmtiles(
"model.g01.hdf", "mesh.pmtiles", layer_name="mesh_cells",
min_zoom=10, max_zoom=14, backend="native", threads=4,
)
Explicit backend="native" requires native execution and reports unavailable or
unsupported operations. Automatic mode can use the compatibility path. Direct
export keeps polygons packed through a vectorized pyproj transformation and
passes them to freestiler's Rust core, without building per-cell Python geometry
objects. Each feature retains mesh_name and cell_id; IDs are not renumbered
when a source cell has no polygon. Tile feature identifiers are independently
unique across meshes.
HdfMesh.get_mesh_cell_polygons(strict=True) retains its diagnostic behavior.
Automatic mode returns the native result only when its diagnostic records,
warnings and strict-mode outcome are provably the Python polygonizer's: native
boundary_only records for one- and two-face cells, zero_faces records, and
no_polygon records for cells that the reference polygonizer also cannot
close. Any other case (an ambiguous or multi-polygon cell, an unassembled cell
that the reference would return, an invalid face span or face reference, an
unsupported layout) uses the Python polygonizer. Required Rust mode reports
unsupported cases explicitly and keeps the native records.
Use threads to bound native parallelism when calling from other worker pools.
The native engine refuses any single numeric read over 2 GiB before allocating,
so a damaged or crafted file cannot make it reserve memory the file does not
hold. Larger numeric reads (for example a whole 2D mesh time series) are served
natively as bounded 256 MiB hyperslab blocks, aligned to the stored chunks, into
one NumPy array, so the result is the same array h5py returns. Before allocating
the output, the declared size is checked against the storage the file really
holds: contiguous data must be allocated and inside the file; chunked data must
not decode to more than its stored bytes allow for its filters; and no more than
2 GiB may come from the fill value of unallocated chunks. A dataset that fails
this check reads through h5py in automatic mode and raises FastHdfError in
required mode. Big-endian datasets keep their existing h5py path at any size.
Coordinate transformation uses the HDF CRS, or an explicit source_crs override.
Missing CRS must be supplied rather than assumed to be WGS84. Result property
arrays passed to export_mesh_pmtiles(properties=...) are grouped by mesh and
indexed by original cell ID. Time-series ghost columns retain their existing
behavior; geometry extraction does not infer a different physical-cell count.
Property columns stay NumPy arrays when the installed engine reads them
natively: typed arrays (float64/32, signed and unsigned integers, bool),
(values, valid) pairs (False meaning null) and
{"codes": int array, "categories": [str, ...]} columns (-1 null) for
strings such as mesh_name. export_pmtiles(layers=...) accepts the same forms.
Support is detected by capability (ras-commander-fast-hdf with columnar
write_pmtiles properties); older engines receive the equivalent per-value
lists. Both give byte-identical archives. Lists and object arrays always keep
the list form, so mixed scalar columns are unchanged. On Bald Eagle p07
(87,039 cells, 15 columns, z10-14) the Python preparation drops from about
2.9 s to 0.4 s and peak working set by about 50 MiB.
Freestiler does not drop features by a configured density or area policy. The native export path repairs quantized rings on the integer tile grid. Very small cells can become one-pixel centroid squares at low zoom to preserve visibility. PMTiles are for visualization; use source polygons for analysis. The exporter retains source geometry in memory and spools encoded tile batches.
Environment variables, sessions and internal modules¶
| Variable | Values | Effect |
|---|---|---|
RAS_COMMANDER_FAST_HDF |
see the table in the next section | Backend policy for every routed reader. An unrecognised value (for example yes) is treated as auto and logs one warning per value, so a typo can never turn reads into empty results. |
RAS_COMMANDER_HDF_SESSION_CACHE |
unset or 1 (default), 0/off/false, persist |
Native session policy, below. |
RAS_COMMANDER_FAST_TEXT |
0/off/false/python, auto (default), required/rust |
Same policy for the optional native plain-text index in ras_commander.fast_text. It is not wired into any existing Geom*/Ras* method; only code that calls fast_text directly is affected, and there an unrecognised value raises ValueError. |
Native sessions and open files. The native engine reads through a session
that keeps the HDF open. By default a session is opened inside the first public
call that needs it, shared by every read of that call, and closed when that
public call returns (also when it raises). A read outside any public call
(direct use of fast_hdf, or a generator such as HdfResultsMesh.iter_mesh_timeseries
or HdfResultView.iter_batches iterated after its call returned) opens and closes
its own session. No HDF stays open after an Hdf*
method returns, so renaming, deleting, replacing or re-extracting a project
folder afterwards works exactly as without the extension (on Windows and on
network shares an open file would block these). Sessions are not carried from
one public call to the next; the measured cost of that is a few percent on
repeated reads of one file. Choose a different trade-off with
RAS_COMMANDER_HDF_SESSION_CACHE:
0: open and close the file around every individual native read (slowest).persist: keep up to four sessions across public calls (fastest for many repeated calls on the same files). The files stay open: callfast_hdf.close_sessions()(orclose_sessions(path)) before replacing, moving or deleting them, and before running HEC-RAS.RasCmdr.compute_plan()already does this.
Two small caches also exist: a cache of the engine's decoded layout
descriptions (at most 16 entries, keyed by file path, size and modification
time, never holding a file open), and fast_text.NATIVE_CALLS, a counter used
by the qualification tests.
Public and internal. ras_commander.fast_hdf is engine infrastructure.
Its supported names are available, close_sessions, FastHdfError,
FastHdfPanicError (a FastHdfError subclass for a panic inside the native
extension), mesh_polygons, packed_meshes and the export_* functions
(__all__; see the fast_hdf source reference).
Everything else in fast_hdf, fast_results, _fast_hdf_typed and
hdf/HdfFluvialNative is internal adapter code for the Hdf* classes and the
test suites: read_typed, read_attrs, read_attr, read_dataset,
read_datasets, mesh_series_domain, trace_reads, native_required,
reraise_required, backend_scope (applies an explicit backend to nested
reads of one call), release_native_sessions (used by writers before they
replace an HDF; call close_sessions(path) instead), the temporal-reduction
helpers of fast_results (whose __all__ is empty), and the native fluvial
adapter HdfFluvialNative (Analysis, LABELS, integer_milliseconds and
its NATIVE_CALLS counter; use HdfFluvialPluvial(engine=...)). These are
importable but may change in any release; use the Hdf* methods instead.
Routed HDF reads and backend modes¶
Public Hdf* readers whose data the pinned engine reads as a typed family call
fast_hdf.read_typed(dataset, selection) at their value reads. It returns
exactly what dataset[selection] returns, so public signatures, columns,
dtypes, index, CRS, attrs and exceptions do not change. The backend follows
RAS_COMMANDER_FAST_HDF:
| Mode | Values | Behavior |
|---|---|---|
| h5py | h5py (legacy: 0, off, false, python) |
h5py for every read. |
| Auto | unset, empty, auto (legacy: 1, on, true) |
Native read when the extension is installed and the function is qualified; any native failure, including Corrupt or checksum refusals, falls back to h5py, so the public result or exception is the h5py one. Functions the test corpus has not yet qualified (fast_hdf.UNQUALIFIED_NATIVE, marked with fast_hdf.h5py_until_qualified) run on h5py. |
| Native | native (legacy: required, rust) |
Native reads must succeed; a refusal raises FastHdfError, which routed readers surface unchanged instead of returning an empty result or wrapping it. |
Routing policy:
- Datasets in a typed engine family (2D mesh geometry and line families, 1D geometry, XS results, 1D summaries and structure series) are served by the typed reader, after the stored dtype layout and shape are checked.
- Wave 3 stored families (bridge API 10): pipes, reference lines and points,
breach, plan metadata tables, land-cover/infiltration sidecars, terrain,
sediment, encroachments, Event Conditions, steady output and the non-Base
output blocks (DSS Hydrograph/Profile, Computation Block). The engine's
stored_family_indexdecides membership; supported numeric, compound and byte-bitfield datasets are read typed. Geometry reference points come fromreference_point_geometry. Datasets the engine lists but does not qualify (for example pipe summaries without a storedLocation) keep their exact literal values through the generic reader. Compound text members stored NULLTERM or SPACEPAD receive HDF5's conversion into h5py's NULLPAD type. - Other numeric datasets use the generic native reader (
read_dataset). - Selections are validated with h5py's own selector before any native read. Invalid selections (for example a negative step) raise h5py's exception in every mode. Basic selections and single increasing integer vectors are read natively. Field names, boolean masks and non-integer vectors stay on h5py, and are refusals in required mode.
- Fixed-length text datasets (compute messages, time-stamp and profile-name
datasets) are read from the engine's
raw_fixed_stringswith h5py's byte rule applied: NULLPAD unchanged, NULLTERM cut at the first NUL, SPACEPAD without trailing spaces, each element zero-filled, in the dataset's own dtype (native-typed/fixed_stringsin the trace). Auto falls back to h5py on any engine refusal; required mode raisesFastHdfError. - Legacy single-part structure centerlines. When the engine refuses the
structure centerline family only because
Geometry/Structures/Centerline Partsis absent (a legal legacy layout), numeric Info/Points reads use the literal generic native reader. A missingPartsin any other packed family is damage and remains a refusal in required mode. - Required-mode metadata exception. Variable-length text datasets and
compound tables whose every member is text (identity tables such as XS
River/Reach/RSrows) are read through h5py in every mode (h5py-metadatain the trace). Group/key walks,inchecks and shape probes also stay on h5py. A compound with any numeric member is value data: without a typed engine route it is an h5py fallback in auto mode and aFastHdfErrorrefusal in required mode. Required mode therefore guarantees native numeric and attribute value reads, not that h5py is never opened. When the engine fails a whole read family (stored_family_indexfailures), the refusal message and the trace (diagnosticentries) say so. - Attributes.
fast_hdf.read_attrs(obj)returns{name: obj.attrs[name]}in h5py's key order andfast_hdf.read_attr(obj, name[, default])returns one attribute (obj.attrs[name]/obj.attrs.get(name, default)), with values rebuilt exactly from the engine's typed attributes (bridge API 11 or 12): numeric scalars/arrays in the stored dtype and byte order; bitfields as the unsigned integer of the same size and order; fixed strings with HDF5's NULLPAD conversion; an H5S_NULL dataspace ash5py.Empty(dtype), never a zero-length array. Groups use the engine's typed group attributes and every dataset its typed dataset attributes, inside or outside the read families. Values the engine cannot reproduce (variable-length text, compound, enum attributes) fall back to h5py in auto mode and raiseFastHdfErrorin required mode;read_attrsrefuses the whole object,read_attronly the requested attribute. Attributes of virtual, external or SWMR datasets are refused in required mode. AllHdf*readers qualified NATIVE read attributes through these two functions. - 2D mesh series domains.
fast_hdf.mesh_series_domain(dataset)returns the engine's typed domain of a Base Output 2D series:{id_dim, domain, domain_rule, capability}, wheredomain_ruleisstored_locationorlegacy_exact_name(HEC-RAS 5.0.7 series without a storedLocation:Depth/Water Surfacecells;Face Velocity,Face Shear Stress,Face Area,Face Manning's nfaces). It is the native counterpart of the h5py rule of ras-commander PR #565.HdfResultsMesh._mesh_series_id_dimtakes the domain from it when the engine qualifies one; otherwise (python mode, engine refusal in auto mode) the storedLocationis read throughread_attrand the #565 rule decides, so refusals keep theirValueError. Geometry-count checks run on both paths. HdfResultsMeshresult readers useread_dataset, which follows the same rule: in auto mode any native failure, Corrupt or checksum refusals included, falls back to h5py, so the public result or exception is the h5py one. Required mode raisesFastHdfError.- Since ROUTE-EXTENTS, project extents (
HdfProject), point/profile queries (HdfResultsQuery),get_mesh_max_depthand the depth raster exports, andHdfResultsProducts.exportread every value through these functions. Their broad exception handlers re-raise required-mode refusals instead of returning an empty extent or result. read_datasetreturns the literal stored selection. When the typed 2D mesh-result reader refuses to qualify a domain (for example a summary or series without a storedLocationattribute, refused since engine API 8), the exact values come from the generic native reader in every mode (native-generic/mesh_result-literalin the trace).
fast_hdf.trace_reads() records which backend served each read made through
read_typed and read_dataset. It is not a complete I/O audit. Reads a
caller makes directly with h5py do not appear in it. The route-1 qualification
gate therefore also intercepts h5py.Dataset.__getitem__ and read_direct
and, since PY-ROUTE-3, h5py.AttributeManager.__getitem__ in required mode. A method labelled NATIVE may read through h5py only the metadata
listed above.
In the coverage inventory, H5PY is an inventory (qualification) label, not an
enforced backend selection. It means a method was not qualified as an exact
native reader. Such a method can still use native helpers in auto mode; for
example, get_mesh_cell_polygons uses native ring assembly. Set
RAS_COMMANDER_FAST_HDF=0 to force h5py for everything.
Successful exports atomically replace the destination; failed exports preserve
an existing destination. Exporting over the source HDF file is rejected.
Run scripts/benchmark_fast_hdf.py --help for the reproducible benchmark driver.
Visualization¶
HdfPlot & HdfResultsPlot¶
Basic plotting utilities.
plot_results_max_wsel(gdf)- Plot maximum WSE map
Usage Example¶
from ras_commander import HdfResultsMesh, HdfResultsPlan, init_ras_project, ras
init_ras_project("/path/to/project", "6.5")
# Get HDF path
hdf_path = ras.plan_df.loc[ras.plan_df['plan_number'] == '01', 'HDF_Results_Path'].iloc[0]
# Extract max WSE
max_wse = HdfResultsMesh.get_mesh_max_ws(hdf_path)
# Get runtime stats
runtime = HdfResultsPlan.get_runtime_data(hdf_path)
Complete source reference¶
The sections above explain common operations. The source-derived reference below includes the remaining public methods and their full signatures. Method-specific prerequisites and return contracts take precedence over abbreviated summaries.
HdfBase source reference¶
Base class for HEC-RAS HDF file operations.
This class provides static methods for fundamental HDF file operations, including time parsing, attribute access, and geometric data extraction. All methods are designed to work with h5py.File objects or pathlib.Path inputs.
Note
This class is not meant to be instantiated. All methods are static and should be called directly from the class.
get_2d_flow_area_names_and_counts
staticmethod
¶
Get the names and cell counts of 2D flow areas from the HDF file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HDF file. |
required |
Returns:
| Type | Description |
|---|---|
List[Tuple[str, int]]
|
A list of tuples containing the name and cell count of each 2D flow area. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there's an error reading the HDF file or accessing the required data. |
get_attrs
staticmethod
¶
Get attributes from an HDF file at a specified path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_file
|
File
|
The opened HDF file. |
required |
attr_path
|
str
|
Path to the attributes in the HDF file. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary of attributes. |
get_dataset_info
staticmethod
¶
Recursively explore and print the structure of an HDF5 file.
Displays detailed information about groups, datasets, and their attributes in a hierarchical format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to the HDF5 file. |
required |
group_path
|
str
|
Starting group path to explore (default: root '/'). |
'/'
|
Prints
- Group and dataset names with hierarchical indentation
- Dataset shapes and data types
- All attributes for groups and datasets
get_polylines_from_parts
staticmethod
¶
get_polylines_from_parts(hdf_path: Path, path: str, info_name: str = 'Polyline Info', parts_name: str = 'Polyline Parts', points_name: str = 'Polyline Points') -> List[LineString]
Extract polylines from HDF file parts data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HDF file. |
required |
path
|
str
|
Internal HDF path to polyline data. |
required |
info_name
|
str
|
Name of polyline info dataset. |
'Polyline Info'
|
parts_name
|
str
|
Name of polyline parts dataset. |
'Polyline Parts'
|
points_name
|
str
|
Name of polyline points dataset. |
'Polyline Points'
|
Returns:
| Type | Description |
|---|---|
List[LineString]
|
List of Shapely LineString/MultiLineString geometries. |
Note
Expects HDF datasets containing: - Polyline information (start points and counts) - Parts information for multi-part lines - Point coordinates
get_projection
staticmethod
¶
Get the CRS of a HEC-RAS HDF file from consistent CRS evidence.
Evidence is collected by HdfUtils.collect_hdf_crs_evidence and
resolved by HdfUtils.resolve_crs_evidence. In precedence order:
- the HDF
Projectionattribute (root, elseGeometrygroup); - the projection file named by the matching
.rasmap(RASProjectionFilename); - every terrain layer HDF listed in that
.rasmap.
Every CRS found must be strictly equivalent (HdfUtils.crs_equivalent).
No coordinates are transformed and no authority code is guessed.
Behaviour changes from ras-commander <= 0.106.1:
- Conflicting evidence (for example an HDF attribute in one State
Plane zone and a
.rasmapprojection in another) now returnsNonewith a warning. Previously the HDF attribute was returned without checking the.rasmapor terrain. - Terrain layer HDFs are now consulted, so a project whose HDF and
.rasmapprojection are missing can resolve from terrain. "EPSG:n"is returned only when an EPSG definition is strictly equivalent (HdfUtils.get_equivalent_epsg); previouslypyproj.CRS.to_epsg()accepted a 70%-confidence match."ESRI:n"codes are never returned.- The
.rasmapis selected by matching the HDF project name when a folder holds several; parent (..) components of.rasmappaths are resolved instead of being stripped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HDF file. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
|
get_result_unit_metadata
staticmethod
¶
get_result_unit_metadata(hdf_path: Path, *, strict: bool = True, unit_system: Optional[str] = None, project_file: Optional[Union[str, Path]] = None) -> Dict[str, Any]
Read normalized units from a HEC-RAS result HDF.
If the full HEC-RAS project is available, pass its .prj as
project_file (or use :meth:RasPrj.get_project_units): the text
project marker is authoritative. A root /@Units System that
disagrees with it raises; a disagreeing /Geometry/@SI Units is
ignored with a warning (source="project_file").
For a standalone HDF the reader checks /Geometry/@SI Units and
/@Units System (source="plan_hdf"). Agreeing evidence
resolves. One disagreement is accepted: root SI Units with
/Geometry/@SI Units = False. RasMapper writes that geometry flag
from a False default and HEC-RAS 6.6 and 7.0 never update it from
the project units (seen on the Weise_2D sediment example). It resolves
to SI only when at least one result dataset Units label in the same
file is m and none is ft; the record then carries a warning
and keeps both attributes in evidence. Every other disagreement,
including root US Customary with /Geometry/@SI Units = True,
remains contradictory.
unit_system overrides all embedded and project evidence
(source="override"); disagreeing evidence is listed in
warnings.
With strict=True (default), missing, unrecognized, non-result, or
contradictory metadata raises :class:ValueError naming the
unit_system override. With strict=False, the same condition
returns a JSON-serializable unresolved record with evidence and
contradictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
HEC-RAS plan-result HDF path or plan selector. |
required |
strict
|
bool
|
Raise when the unit system cannot be resolved. |
True
|
unit_system
|
Optional[str]
|
Explicit |
None
|
project_file
|
Optional[Union[str, Path]]
|
HEC-RAS |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict containing status, normalized unit labels, provenance |
Dict[str, Any]
|
( |
get_simulation_start_time
staticmethod
¶
Extract the simulation start time from the HDF file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_file
|
Union[File, str, Path]
|
Open plan HDF handle, or a path ( |
required |
Returns:
| Type | Description |
|---|---|
datetime
|
Simulation start time as a datetime object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If Plan Information is not found or start time cannot be parsed. |
Note
HEC-RAS 6.x stores 'Simulation Start Time' as a 'Plan Data/Plan Information'
attribute. HEC-RAS 5.0.x does not write that attribute; it instead stores
'Time Window' ("
get_unsteady_timestamps
staticmethod
¶
Extract the list of unsteady timestamps from the HDF file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_file
|
Union[File, str, Path]
|
Open plan HDF handle, or a path ( |
required |
Returns:
| Type | Description |
|---|---|
List[datetime]
|
A list of datetime objects representing the unsteady timestamps. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the plan HDF has no unsteady output timestamps. |
Note
Reads 'Time Date Stamp (ms)' and falls back to 'Time Date Stamp' when a plan HDF does not write the millisecond dataset.
plan_vertex_ordinates
staticmethod
¶
Reduce an HDF vertex array to ordinates Shapely accepts.
HEC-RAS writes some geometry point tables with four ordinates per
vertex. Shapely's constructors take two or three and raise
ValueError: The ordinate (last) dimension should be 2 or 3, got 4
on anything wider, which aborts the whole layer for the caller.
Observed on the FEMA eBFE submittal for HUC8 12090106, model
MidCo_0601_A1: /Geometry/2D Flow Area Refinement Regions/Polygon
Points is (21592, 4) and the third and fourth columns are
entirely NaN. There they are padding, not Z and M, so keeping three
ordinates would manufacture NaN-Z geometry out of nothing and push the
failure downstream into whatever consumes the GeoDataFrame.
The rule is therefore: a real Z is kept, a padding or measure column is not.
- Fewer than four ordinates: returned unchanged. Two and three are what Shapely already accepts, so nothing that reads today changes.
- Four or more: the trailing ordinates past the third are dropped as M and beyond. The third is kept only when it holds at least one finite value; when it is entirely NaN or infinite it is padding and the result is planar XY.
Parameters¶
points : np.ndarray
A 2-D array of vertices, (n_vertices, n_ordinates), sliced
straight out of an HDF point dataset.
Returns¶
np.ndarray The same array when it already fits, otherwise a view holding its first two or three ordinates.
print_attrs
staticmethod
¶
Print the attributes of an HDF5 object (Dataset or Group).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the object |
required |
obj
|
Union[Dataset, Group]
|
HDF5 object whose attributes are to be printed |
required |
strip_results
staticmethod
¶
Remove the /Results group from a plan HDF file for clean re-execution.
This is used to prepare an HDF file for re-running RasUnsteady by removing previous simulation results while preserving geometry and plan configuration data.
Attribution: Implementation pattern derived from ras-agent (https://github.com/gheistand/ras-agent) by Glenn Heistand / CHAMP — Illinois State Water Survey. See runner.py:_prepare_run().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path]
|
Path to the plan HDF file. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the Results group was found and removed, False if no Results group existed. |
Example
from ras_commander.hdf import HdfBase removed = HdfBase.strip_results("model.p01.hdf") if removed: ... print("Results stripped, ready for re-execution")
HdfUtils source reference¶
Utility class for working with HEC-RAS HDF files.
This class provides general utility functions for HDF file operations, including attribute extraction, data conversion, and common HDF queries. It also includes spatial operations and helper methods for working with HEC-RAS specific data structures.
Note: - Use this class for general HDF utility functions that are not specific to plan or geometry files. - All methods in this class are static and can be called without instantiating the class.
convert_df_datetimes_to_str
staticmethod
¶
Convert any datetime64 columns in a DataFrame to strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
The DataFrame to convert. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
The DataFrame with datetime columns converted to strings. |
convert_hdf5_attrs_to_dict
staticmethod
¶
convert_hdf5_attrs_to_dict(attrs: Union[AttributeManager, Dict], prefix: Optional[str] = None) -> Dict
Convert HDF5 attributes to a Python dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attrs
|
Union[AttributeManager, Dict]
|
The attributes to convert. |
required |
prefix
|
Optional[str]
|
A prefix to add to the attribute keys. |
None
|
Returns:
| Type | Description |
|---|---|
Dict
|
A dictionary of converted attributes. |
convert_ras_hdf_value
staticmethod
¶
convert_ras_hdf_value(value: Any) -> Union[None, bool, str, List[str], int, float, List[int], List[float]]
Convert a value from a HEC-RAS HDF file into a Python object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The value to convert. |
required |
Returns:
| Type | Description |
|---|---|
Union[None, bool, str, List[str], int, float, List[int], List[float]]
|
The converted value. |
convert_ras_string
staticmethod
¶
convert_ras_string(value: Union[str, bytes]) -> Union[bool, datetime, List[datetime], timedelta, str]
Convert a string value from an HEC-RAS HDF file into a Python object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Union[str, bytes]
|
The value to convert. |
required |
Returns:
| Type | Description |
|---|---|
Union[bool, datetime, List[datetime], timedelta, str]
|
The converted value. |
convert_timesteps_to_datetimes
staticmethod
¶
convert_timesteps_to_datetimes(timesteps: ndarray, start_time: datetime, time_unit: str = 'days', round_to: str = '100ms') -> pd.DatetimeIndex
Convert RAS timesteps to datetime objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timesteps
|
ndarray
|
Array of timesteps. |
required |
start_time
|
datetime
|
Start time of the simulation. |
required |
time_unit
|
str
|
Unit of the timesteps. Default is "days". |
'days'
|
round_to
|
str
|
Frequency string to round the times to. Default is "100ms" (100 milliseconds). |
'100ms'
|
Returns:
| Type | Description |
|---|---|
DatetimeIndex
|
DatetimeIndex of converted and rounded datetimes. Preserves existing conversion precision and rounding for ordinary dates. If pandas cannot represent the full sequence (e.g. outside its nanosecond range, roughly 1677-2262), falls back to microsecond resolution throughout. Fallback offsets have at most half a microsecond of rounding error; finer round_to values cannot recover that information. Fallback dates beyond Python datetime bounds raise OverflowError instead of wrapping. Pandas versions with wider native date support retain their existing behavior. |
area_to_square_meters
staticmethod
¶
area_to_square_meters(area: Union[float, ndarray], crs: Any = None, units_system: Optional[str] = None) -> Union[float, np.ndarray]
Convert areas in model units squared to square metres using
linear_unit_to_meters (same arguments and errors).
collect_hdf_crs_evidence
staticmethod
¶
collect_hdf_crs_evidence(hdf_path: Union[str, Path], rasmap_path: Optional[Union[str, Path]] = None) -> List[CrsEvidence]
Collect ordered CRS evidence for a HEC-RAS HDF file.
Precedence (first is strongest): the HDF Projection attribute, the
RASMapper projection file, then each terrain layer HDF listed in the
.rasmap. Every checked location is returned, including missing and
absent ones, so callers can report exactly what was examined.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path]
|
Geometry or plan HDF file. |
required |
rasmap_path
|
Optional[Union[str, Path]]
|
RASMapper file. Defaults to the |
None
|
Returns:
| Type | Description |
|---|---|
List[CrsEvidence]
|
Ordered evidence, suitable for |
List[CrsEvidence]
|
|
collect_rasmap_crs_evidence
staticmethod
¶
Collect ordered CRS evidence named by a RASMapper (.rasmap) file.
Returns the RASProjectionFilename projection file evidence followed
by one evidence item per terrain layer HDF. This is the .rasmap
part of collect_hdf_crs_evidence for workflows without an HDF
(for example plain-text geometry).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rasmap_path
|
Union[str, Path]
|
RASMapper file. |
required |
Returns:
| Type | Description |
|---|---|
List[CrsEvidence]
|
Ordered evidence; a single |
List[CrsEvidence]
|
|
crs_equivalent
staticmethod
¶
Return True when two CRS definitions are strictly equivalent.
Equivalence ignores naming and WKT dialect (ESRI WKT1, OGC WKT2, authority codes) and axis order, but not datum realization, projection parameters or units. NAD83, NAD83(HARN) and NAD83(2011) State Plane zones are distinct; ftUS, international feet and metres are distinct.
Raises:
| Type | Description |
|---|---|
ValueError
|
If either input cannot be parsed as a CRS. |
find_nearest_neighbors
staticmethod
¶
Creates a self KDTree for dataset points and finds nearest neighbors excluding self, with distances above max_distance set to -1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
ndarray
|
The dataset to build the KDTree from and query against itself. |
required |
max_distance
|
float
|
The maximum distance threshold. Indices with distances greater than max_distance are set to -1. Defaults to 2.0. |
2.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of indices representing the nearest neighbor in points for each point in points. Indices with distances > max_distance or self-matches are set to -1. |
Example
points = np.array([[0, 0], [1, 1], [2, 2], [10, 10]]) result = HdfUtils.find_nearest_neighbors(points) print(result) array([1, 0, 1, -1])
format_crs
staticmethod
¶
Return the stable public string form of a CRS.
This is the single formatting rule used by HdfBase.get_projection,
HdfProject.get_project_crs and RasPrj.project_crs:
"EPSG:n"when an EPSG definition is strictly equivalent (get_equivalent_epsg);- otherwise the source WKT text unchanged (never an
"ESRI:n"code and never a guessed low-confidence EPSG code); NoneforNone/empty input.
Unparseable text is returned unchanged so callers keep the source definition for diagnosis.
get_crs_identity
staticmethod
¶
Describe a CRS without assigning a guessed authority code.
authority is set only for an exact (confidence 100) authority match
and may be any authority (EPSG, ESRI, ...). epsg is set
only when an EPSG definition is strictly equivalent (see
get_equivalent_epsg). Lower-confidence matches are reported in
authority_candidates for diagnostics and must not be used to label
data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
crs_input
|
Any
|
WKT1/WKT2 text, |
required |
candidate_min_confidence
|
int
|
Minimum confidence for listed candidates. |
20
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with keys |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input cannot be parsed as a CRS. |
get_equivalent_epsg
staticmethod
¶
Return an EPSG code whose definition is strictly equivalent to the CRS.
Candidate EPSG codes come from PROJ's authority matching; a candidate
is accepted only if it is equivalent under the crs_equivalent rule,
so a low-confidence match (for example a different NAD83 realization
or foot definition) is never used as a label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
crs_input
|
Any
|
Any input accepted by |
required |
Returns:
| Type | Description |
|---|---|
Optional[int]
|
The EPSG code, or |
Optional[int]
|
is equivalent or the input cannot be parsed. |
get_stored_ras_version
staticmethod
¶
Return the HDF root File Version attribute written by HEC-RAS
(e.g. "HEC-RAS 5.0.7 November 2018"), or None.
get_units_system
staticmethod
¶
Return the HDF root Units System attribute (e.g. "SI Units",
"US Customary"), or None when it is not stored.
linear_unit_to_meters
staticmethod
¶
Return metres per horizontal model unit.
The CRS unit is authoritative because US Customary does not
distinguish US survey feet from international feet. Without a CRS,
only SI Units resolves (to 1.0).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
crs
|
Any
|
CRS input accepted by |
None
|
units_system
|
Optional[str]
|
HDF |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the unit cannot be determined, the CRS is angular,
or the CRS unit contradicts |
parse_duration
staticmethod
¶
Parse a duration string into a timedelta object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
duration_str
|
str
|
The duration string to parse. |
required |
Returns:
| Type | Description |
|---|---|
timedelta
|
The parsed duration as a timedelta object. |
parse_ras_datetime
staticmethod
¶
Parse a RAS datetime string into a datetime object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datetime_str
|
str
|
The datetime string in format "ddMMMYYYY HH:MM:SS" |
required |
Returns:
| Type | Description |
|---|---|
datetime
|
The parsed datetime object. |
parse_ras_datetime_ms
staticmethod
¶
Parse a datetime string with milliseconds from a RAS file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datetime_str
|
str
|
The datetime string to parse. |
required |
Returns:
| Type | Description |
|---|---|
datetime
|
The parsed datetime object. |
parse_ras_file_version
staticmethod
¶
Parse "HEC-RAS 6.7 Beta 5 Development" to (6, 7, 0).
Returns None when no HEC-RAS version number is present.
parse_ras_window_datetime
staticmethod
¶
Parse a datetime string from a RAS simulation window into a datetime object.
HEC-RAS writes the end of a day as 2400 (02JAN1900 2400), which
is midnight at the start of the next day.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datetime_str
|
str
|
The datetime string to parse. |
required |
Returns:
| Type | Description |
|---|---|
datetime
|
The parsed datetime object. |
parse_run_time_window
staticmethod
¶
Parse a run time window string into a tuple of datetime objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
str
|
The run time window string to be parsed. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[datetime, datetime]
|
A tuple containing two datetime objects representing the start and end of the run |
datetime
|
time window. |
perform_kdtree_query
staticmethod
¶
perform_kdtree_query(reference_points: ndarray, query_points: ndarray, max_distance: float = 2.0) -> np.ndarray
Performs a KDTree query between two datasets and returns indices with distances exceeding max_distance set to -1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reference_points
|
ndarray
|
The reference dataset for KDTree. |
required |
query_points
|
ndarray
|
The query dataset to search against KDTree of reference_points. |
required |
max_distance
|
float
|
The maximum distance threshold. Indices with distances greater than this are set to -1. Defaults to 2.0. |
2.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of indices from reference_points that are nearest to each point in query_points. Indices with distances > max_distance are set to -1. |
Example
ref_points = np.array([[0, 0], [1, 1], [2, 2]]) query_points = np.array([[0.5, 0.5], [3, 3]]) result = HdfUtils.perform_kdtree_query(ref_points, query_points) print(result) array([ 0, -1])
read_crs_evidence
staticmethod
¶
Read CRS evidence from one HDF, projection (.prj) or raster
(.tif/.tiff/.vrt) file.
For HDF files the root Projection attribute is read; when the root
attribute is not stored, the Geometry group Projection
attribute is used. Never raises for missing or unreadable files; the
outcome is recorded in the returned evidence status.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[str, Path]
|
File to read. |
required |
source
|
Optional[str]
|
Label for the evidence (defaults to |
None
|
Returns:
| Type | Description |
|---|---|
CrsEvidence
|
CrsEvidence |
resolve_crs_evidence
staticmethod
¶
Resolve ordered CRS evidence without guessing.
resolved: at least one source has a CRS and every found CRS is strictly equivalent (seecrs_equivalent).crsis the highest-precedence source WKT;authorityis set only for an exact authority match;epsgis the first strictly equivalent EPSG code found across the agreeing evidence.missing: no source has a CRS. Unknown remains unknown.conflict: found CRSs are not equivalent.crsisNoneandcandidatesholds one WKT per distinct CRS, in precedence order.
Evidence with status invalid, unreadable, absent or
missing_file is kept for reporting but does not vote.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
evidence
|
Sequence[CrsEvidence]
|
Evidence in precedence order (strongest first). |
required |
Returns:
| Type | Description |
|---|---|
CrsResolution
|
CrsResolution |
resolve_hdf_paths
staticmethod
¶
resolve_hdf_paths(ras_folder: Path, plan_number: str, ras_object=None) -> Dict[str, Optional[Path]]
Resolve HDF plan and geometry file paths for a plan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ras_folder
|
Path
|
Path to HEC-RAS project folder |
required |
plan_number
|
str
|
Plan number (e.g., "01", "08") |
required |
ras_object
|
RasPrj
|
Optional RAS object instance |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Optional[Path]]
|
Dictionary with 'plan' and 'geometry' HDF paths (or None if not found) |
Examples:
resolve_ras_relative_path
staticmethod
¶
Resolve a path stored by RASMapper relative to base_folder.
RASMapper writes Windows separators (.\GIS\a.prj,
..\shared\a.prj) even when the project is read on Linux.
Separators are normalized and parent components are preserved;
textual removal of .\ would corrupt ..\ into ..
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_folder
|
Union[str, Path]
|
Folder the stored path is relative to (normally the
folder containing the |
required |
filename
|
str
|
Path text exactly as stored by RASMapper. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The resolved path. Drive-letter and UNC paths are returned |
Path
|
unchanged because they are not relative to |
scan_hdf_files
staticmethod
¶
Scan for HDF plan and geometry files in a RAS project folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ras_folder
|
Path
|
Path to HEC-RAS project folder containing .prj file |
required |
Returns:
| Type | Description |
|---|---|
Dictionary mapping HDF types to file paths
|
|
{'plan_01'
|
Path, 'geom_01': Path, ...} |
Examples:
CrsEvidence
dataclass
¶
One CRS observation from one source file.
status is one of found, absent (file readable, no CRS stored),
missing_file, invalid (CRS text present but unparseable) or
unreadable. wkt preserves the source definition with outer
whitespace stripped.
CrsResolution
dataclass
¶
Outcome of resolving ordered CRS evidence.
crs is the source WKT of the highest-precedence evidence only when
status == "resolved". Missing and conflicting evidence leave crs
as None; candidates lists one WKT per non-equivalent CRS found.
authority is an exact (confidence 100) authority code for crs;
epsg is an EPSG code strictly equivalent to the agreeing evidence.
to_crs_string() returns the public string form.
to_crs_string
¶
Return "EPSG:n" when an equivalent EPSG code exists, the
source WKT when only WKT exists, or None when not resolved.
HdfPlan source reference¶
A class for handling HEC-RAS plan HDF files.
Provides static methods for extracting data from HEC-RAS plan HDF files including simulation times, plan information, and geometry attributes. All methods use @standardize_input for handling different input types and @log_call for logging.
Note: This code is partially derived from the rashdf library (https://github.com/fema-ffrd/rashdf) under MIT license.
get_2d_flow_options
staticmethod
¶
Extract 2D unsteady computation options stored in a plan HDF output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS plan HDF file. |
required |
mesh_name
|
Optional[str]
|
Optional 2D flow area name to filter returned areas. |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Parsed 2D options using the same public option names
as |
get_geometry_information
staticmethod
¶
Get attributes stored on the Geometry group of a geometry HDF file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS geometry HDF file. String paths are also accepted. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with geometry attributes including Creation Date/Time, Version, Units, and Projection information. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If Geometry group is missing or there's an error reading attributes. |
get_plan_end_time
staticmethod
¶
Get the plan end time from the plan file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS plan HDF file. |
required |
Returns:
| Type | Description |
|---|---|
datetime
|
The plan end time. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there's an error reading the plan end time. |
get_plan_information
staticmethod
¶
Get plan information from a HEC-RAS HDF plan file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS plan HDF file. |
required |
Returns:
| Type | Description |
|---|---|
PlanInformationDict
|
Plan information including simulation times, flow regime, computation settings, etc. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there's an error retrieving the plan information. |
get_plan_met_precip
staticmethod
¶
Get precipitation attributes from a HEC-RAS HDF plan file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS plan HDF file. |
required |
Returns:
| Type | Description |
|---|---|
PlanMetPrecipDict
|
Precipitation attributes including method, time series data, and spatial distribution if available. Returns empty dict if no precipitation data exists. |
get_plan_met_precip_values
staticmethod
¶
get_plan_met_precip_values(hdf_path: Union[str, Path, int, File], *, ras_object: Optional[Any] = None, group_path: str = 'Event Conditions/Meteorology/Precipitation') -> Dict[str, Any]
Read materialized solver precipitation arrays without unit conversion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path, int, File]
|
Plan HDF path, plan identifier or open HDF handle accepted by the HDF input decorator. |
required |
ras_object
|
Optional[Any]
|
Optional RasPrj context for resolving plan identifiers. |
None
|
group_path
|
str
|
Exact HDF precipitation group. The default reads a
compiled plan. For a retained meteorology-only snapshot, pass
|
'Event Conditions/Meteorology/Precipitation'
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
byte strings are decoded; timestamp encodings and numerical values |
Dict[str, Any]
|
are preserved. Cell columns are precipitation-grid indexes, not |
Dict[str, Any]
|
hydraulic mesh-cell indexes. No depth/rate or time-unit inference |
Dict[str, Any]
|
is made. Native materialization was checked on HEC-RAS 6.6. |
Raises:
| Type | Description |
|---|---|
KeyError
|
Solver Values/Timestamp datasets are absent. An imported raster sidecar alone is not materialized solver precipitation. |
ValueError
|
The group path is empty or not a string, or dataset dimensions or time-axis lengths are inconsistent. |
Notes
Opens the source read-only and does not execute HEC-RAS. Snapshot arrays retain the same units, timestamp encodings and shape checks as compiled-plan arrays. This read does not establish that another plan used the retained precipitation.
get_plan_parameters
staticmethod
¶
Get plan parameter attributes from a HEC-RAS HDF plan file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS plan HDF file. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A DataFrame containing the plan parameters with columns: - Parameter: Name of the parameter - Value: Value of the parameter (decoded if byte string) - Plan: Plan number (01-99) extracted from the filename (ProjectName.pXX.hdf) |
DataFrame
|
Returns empty DataFrame if Plan Parameters not found (e.g., steady flow results). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there's an error retrieving the plan parameter attributes. |
get_plan_start_time
staticmethod
¶
Get the plan start time from the plan file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS plan HDF file. |
required |
Returns:
| Type | Description |
|---|---|
datetime
|
The plan start time in UTC format. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there's an error reading the plan start time. |
get_plan_timestamps_list
staticmethod
¶
Get the list of output timestamps from the plan simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS plan HDF file. |
required |
Returns:
| Type | Description |
|---|---|
List[datetime]
|
Chronological list of simulation output timestamps in UTC. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there's an error retrieving the plan timestamps. |
get_starting_wse_method
staticmethod
¶
Report how the computation's starting water surface is established.
HEC-RAS does not store a single "starting WSE method" attribute. This reads where HEC-RAS records it:
- Unsteady plans (the plan HDF has
Event Conditions/Unsteady/Boundary Conditions, written when the plan is computed): the starting water surface comes from the initialization, not from a boundary. HEC-RAS either reads a restart (initial conditions) file or computes water surfaces from the initial flows with a steady backwater pass, followed by the warm-up.methodis theStartup Modeattribute ofEvent Conditions/Unsteady/Initial Conditions. TheNormal Depths(friction slope),Rating CurvesandStage Hydrographsmembers are reported inboundariesonly. - Steady plans (
Event Conditions/Steady): HEC-RAS writes no boundary data to the HDF. The steady flow file named by the plan HDF'sPlan InformationFlow Filenameattribute is read from the HDF's folder (file name matched case-insensitively) with :meth:RasSteady.read_flow_file. The plan text file (Plan Filename) supplies the flow regime:Subcritical Flowselects the downstream (Dn) boundaries,Supercritical Flowthe upstream (Up) boundaries,Mixed Flowboth.
Parameters¶
hdf_path : Path Path to the HEC-RAS plan HDF file
Returns¶
StartingWSEMethodDict
- method, unsteady plans: the stored Startup Mode,
"Computed" (water surfaces computed from the initial flows,
then warm-up; every public corpus plan) or "Restart File"
(initial conditions read from restart_file); any other stored
value is returned verbatim. "Unknown" (with note) when no
Startup Mode is stored (HEC-RAS 5.0.x).
- method, steady plans: "Known WS", "Normal Depth",
"Critical Depth" or "Rating Curve" when every selected
boundary has that type; "Multiple" when they differ;
"Unknown" (with note) when no boundary could be read.
- method is "Error" (with error) when reading failed.
- slope: steady only; the normal-depth friction slope when the
method is "Normal Depth" and every selected boundary agrees.
Per-boundary slopes are always in boundaries.
- wse: steady only; the known water surface when the method is
"Known WS" and every selected boundary has the same value.
- regime: steady plans only, "Subcritical",
"Supercritical" or "Mixed" from the plan file.
- boundaries: one dict per selected boundary (type, location,
and its slope / known WS / rating-curve points when stored).
- source: the HDF group or flow file that was read.
- startup_mode: unsteady initial-condition startup mode.
- restart_file: unsteady Restart Filename when stored.
- warmup_steps: unsteady 1D-2D Number of Warmup Steps from
Plan Data/Plan Parameters when stored.
Notes¶
Values are not filled when they cannot be read: slope/wse are
omitted when boundaries disagree (see boundaries); regime is
omitted for unsteady plans and when the plan file or its regime line is
absent, in which case both boundary sides of a steady flow file are
reported. Unsteady boundary positions (upstream/downstream) are not
stored in the HDF and are not inferred. Quasi-unsteady (.q##) flow
files are not read. Earlier releases looked for plan attributes HEC-RAS
does not write and returned "Unknown" for every real plan.
HdfMesh source reference¶
A class for handling mesh-related operations on HEC-RAS HDF files.
This class provides methods to extract and analyze mesh data from HEC-RAS HDF files, including mesh area names, mesh areas, cell polygons, cell points, cell faces, and 2D flow area attributes.
Methods in this class are designed to work with the mesh geometry data stored in HEC-RAS HDF files, providing functionality to retrieve and process various aspects of the 2D flow areas and their associated mesh structures.
Note: This class relies on HdfBase and HdfUtils for some underlying operations.
combine_faces_to_linestring
staticmethod
¶
combine_faces_to_linestring(faces_gdf: GeoDataFrame, order_column: str = 'distance_along_profile') -> Optional[Any]
Combine ordered faces into a single LineString.
This is useful for creating a continuous line from selected profile faces.
Parameters¶
faces_gdf : GeoDataFrame GeoDataFrame of faces to combine, should be ordered. order_column : str, default 'distance_along_profile' Column to use for ordering faces.
Returns¶
Optional[shapely.geometry.LineString] A LineString combining all face geometries, or None if faces_gdf is empty or fewer than 2 coordinates found.
diagnose_mesh_cell_polygons
staticmethod
¶
Return cells not reconstructed as exactly one polygon.
The result contains the native mesh_name and zero-based cell_id,
face and polygon counts, a status and reason code, and the referenced
face IDs. boundary_only rows identify validated native one- or
two-face records and do not make strict reconstruction fail. omitted
and ambiguous rows identify physical-cell problems;
not_present and read_error distinguish unavailable or malformed
topology from a clean reconstruction. An empty result means every
named mesh supplied topology and every processed physical cell produced
exactly one polygon.
engine is as in :meth:get_mesh_cell_polygons. engine="auto"
falls back to the reference polygonizer on any native failure, and
whenever the native records cannot be proven equal to the reference's,
so its rows, statuses, reason codes and warnings are the reference
ones. engine="native" (or RAS_COMMANDER_FAST_HDF=native) never
falls back; there the native records can differ from the reference's
as described under diagnostics in :meth:get_mesh_cell_polygons.
diagnose_mesh_layout
staticmethod
¶
Inspect mesh-layout capabilities without modifying the HDF.
Parameters¶
hdf_path : Path
Geometry or plan HDF containing the Geometry/2D Flow Areas group.
program_version : str, optional
Program version read from the companion plan or geometry text file.
For example, HEC-RAS 6.2 commonly stores "6.20".
Returns¶
pandas.DataFrame
One row per 2D flow area. Capability status columns use
standard, collection_fallback, not_present,
malformed, or read_error. Dataset-path columns identify the
evidence used for each decision.
Notes¶
Collection-level Cell Info and Cell Points are reported as
evidence only. They are never promoted to face connectivity or cell
polygon topology.
extend_face_property_tables
staticmethod
¶
extend_face_property_tables(hdf_path: Union[str, Path], mesh_name: str, extension_elevation: float, mannings_n_func: Callable[[float, float], float], elevation_step: float = 0.5, face_ids: Optional[List[int]] = None, polygon=None, region_name: Optional[str] = None, pin_tables: bool = True, *, acknowledge_unsupported: bool = False) -> Dict[int, int]
Deprecated wrapper for guarded Linux temporary-table extension.
extend_linux_tmp_face_property_tables
staticmethod
¶
extend_linux_tmp_face_property_tables(hdf_path: Union[str, Path], mesh_name: str, extension_elevation: float, mannings_n_func: Callable[[float, float], float], elevation_step: float = 0.5, face_ids: Optional[List[int]] = None, polygon=None, region_name: Optional[str] = None, pin_tables: bool = True, *, acknowledge_unsupported: bool = False) -> Dict[str, Any]
Extend guarded Linux temporary face tables to higher elevations.
For each target face, appends rows from the current table maximum up
to extension_elevation. Area is extrapolated above the terrain
maximum using the native face length when available, falling back to
the last Wetted Perimeter value. Wetted Perimeter is held at the last
tabulated value. Manning's n at each new elevation is computed via
mannings_n_func.
.. warning::
EXPERIMENTAL. Not recommended for production or any other
non-experimental use. Tested only with HEC-RAS 7.0 April 2026 in
the workflow below; all other versions and workflows are untested.
Edits are overwritten by the Windows HEC-RAS geometry preprocessor
on the next plan execution. The tested Linux two-phase workflow is:
(1) preprocess on Windows via
RasPreprocess.preprocess_plan() to generate the .tmp.hdf,
(2) apply edits to the .tmp.hdf, (3) execute with
RasCmdr.compute_plan_linux(). This is an undocumented and
unsupported method of injecting modified HDF inputs into the
solver and may produce erroneous results.
Parameters¶
hdf_path : Union[str, Path]
Guarded HEC-RAS 7.0 *.p##.tmp.hdf result artifact.
mesh_name : str
Name of the 2D flow area.
extension_elevation : float
Target maximum elevation for the extended tables.
mannings_n_func : Callable[[float, float], float]
Function (depth, base_n) -> n where depth is the water
depth above the face's minimum elevation and base_n is the
Manning's n from the last existing table row.
elevation_step : float, default 0.5
Elevation increment between new rows.
face_ids : Optional[List[int]]
List of face IDs to extend. None extends all faces whose
current maximum is below extension_elevation.
polygon : shapely Polygon/MultiPolygon or GeoDataFrame, optional
If provided and face_ids is None, only extend faces whose
midpoint falls within this polygon.
region_name : str, optional
If provided and face_ids is None, only extend faces within
the named Manning's n calibration region from the geometry HDF.
Precedence: face_ids > region_name > polygon.
pin_tables : bool, default True
Pin tables after modification.
Returns¶
Dict[str, Any]
Structured mutation report with rows_added,
faces_modified, total_rows_added, and backup_path.
find_nearest_cell
staticmethod
¶
find_nearest_cell(point, cell_points_gdf: GeoDataFrame, mesh_name: str = None) -> Optional[Tuple[int, float]]
Find the nearest mesh cell center to a given point.
This is useful for locating cell elements near a point of interest, such as when extracting water surface elevations at a specific location.
Parameters¶
point : shapely.geometry.Point or tuple The query point. Can be a shapely Point or (x, y) tuple. cell_points_gdf : GeoDataFrame GeoDataFrame containing cell center points, typically from get_mesh_cell_points(). mesh_name : str, optional If provided, filter to only cells in this mesh area.
Returns¶
Optional[Tuple[int, float]] A tuple containing: - cell_id (int): The ID of the nearest cell - distance (float): The distance to the nearest cell center Returns (None, None) if no cells found to search.
Example¶
cell_points = HdfMesh.get_mesh_cell_points(hdf_path) cell_id, dist = HdfMesh.find_nearest_cell((500000, 4000000), cell_points) if cell_id is not None: ... print(f"Nearest cell: {cell_id}, Distance: {dist:.2f}")
find_nearest_face
staticmethod
¶
find_nearest_face(point, cell_faces_gdf: GeoDataFrame, mesh_name: str = None) -> Optional[Tuple[int, float]]
Find the nearest mesh cell face to a given point.
This is useful for locating face elements near a point of interest, such as when extracting timeseries data at a specific location.
Parameters¶
point : shapely.geometry.Point or tuple The query point. Can be a shapely Point or (x, y) tuple. cell_faces_gdf : GeoDataFrame GeoDataFrame containing cell face geometries, typically from get_mesh_cell_faces(). mesh_name : str, optional If provided, filter to only faces in this mesh area.
Returns¶
Optional[Tuple[int, float]] A tuple containing: - face_id (int): The ID of the nearest cell face - distance (float): The distance to the nearest cell face Returns (None, None) if no faces found to search.
Example¶
cell_faces = HdfMesh.get_mesh_cell_faces(hdf_path) face_id, dist = HdfMesh.find_nearest_face((500000, 4000000), cell_faces) if face_id is not None: ... print(f"Nearest face: {face_id}, Distance: {dist:.2f}")
get_face_ids_in_calibration_region
staticmethod
¶
get_face_ids_in_calibration_region(hdf_path: Union[str, Path], mesh_name: str, region_name: str, method: str = 'midpoint') -> List[int]
Return face IDs within a named Manning's n calibration region.
Reads the calibration region polygon from the geometry HDF via
HdfLandCover.get_mannings_region_polygons() and delegates
to get_face_ids_in_polygon().
Parameters¶
hdf_path : Union[str, Path]
Path to the HEC-RAS geometry HDF file (.g##.hdf).
mesh_name : str
Name of the 2D flow area / mesh.
region_name : str
Name of the calibration region as defined in RASMapper GUI.
method : str, default 'midpoint'
Spatial test method (see get_face_ids_in_polygon).
Returns¶
List[int] Sorted list of face IDs within the named calibration region.
Raises¶
ValueError If the named region is not found in the geometry HDF.
get_face_ids_in_polygon
staticmethod
¶
get_face_ids_in_polygon(hdf_path: Union[str, Path], mesh_name: str, polygon, method: str = 'midpoint') -> List[int]
Return face IDs whose geometry falls within a polygon boundary.
Parameters¶
hdf_path : Union[str, Path]
Path to the HEC-RAS geometry HDF file (.g##.hdf).
mesh_name : str
Name of the 2D flow area / mesh.
polygon : shapely.geometry.Polygon, shapely.geometry.MultiPolygon, or GeoDataFrame
The masking polygon. If a GeoDataFrame is provided, all
geometries are unioned into a single polygon.
method : str, default 'midpoint'
How to test each face against the polygon:
- 'midpoint': face midpoint must be within the polygon
- 'any_vertex': at least one face vertex must be within
Returns¶
List[int] Sorted list of face IDs (0-indexed) that satisfy the spatial filter.
get_faces_along_profile_line
staticmethod
¶
get_faces_along_profile_line(profile_line, cell_faces_gdf: GeoDataFrame, distance_threshold: float = 10.0, angle_threshold: float = 60.0, mesh_name: str = None, order_by_distance: bool = True) -> GeoDataFrame
Get mesh cell faces that align with a profile line.
This function finds faces that are: 1. Within a distance threshold of the profile line 2. Oriented perpendicular to the profile line (within angle threshold)
This is useful for extracting cross-sectional flow data along a transect or profile line.
Parameters¶
profile_line : shapely.geometry.LineString The profile line to find faces along. cell_faces_gdf : GeoDataFrame GeoDataFrame containing cell face geometries, typically from get_mesh_cell_faces(). distance_threshold : float, default 10.0 Maximum distance from profile line to include a face. angle_threshold : float, default 60.0 Maximum angle deviation from perpendicular (degrees). A value of 90 would include faces parallel to the profile. mesh_name : str, optional If provided, filter to only faces in this mesh area. order_by_distance : bool, default True If True, order faces by distance along the profile line.
Returns¶
GeoDataFrame A GeoDataFrame containing selected faces with additional columns: - distance_along_profile: Distance from profile start - angle_to_profile: Angle deviation from perpendicular
Example¶
from shapely.geometry import LineString profile = LineString([(500000, 4000000), (501000, 4000000)]) cell_faces = HdfMesh.get_mesh_cell_faces(hdf_path) profile_faces = HdfMesh.get_faces_along_profile_line( ... profile, cell_faces, distance_threshold=15, angle_threshold=45 ... ) print(f"Found {len(profile_faces)} faces along profile")
get_mannings_calibration_table
staticmethod
¶
Retrieve the Manning's n calibration table from a HEC-RAS geometry HDF file.
Reads the compound dataset at
Geometry/Land Cover (Manning's n)/Calibration Table which contains
land cover names, base Manning's n values, and per-region calibration
factors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS geometry HDF file. |
required |
Returns:
| Type | Description |
|---|---|
Optional[DataFrame]
|
A DataFrame with columns for each field in the calibration table |
Optional[DataFrame]
|
(land cover name, base Manning's n, and one column per calibration |
Optional[DataFrame]
|
region), or |
Example¶
df = HdfMesh.get_mannings_calibration_table("model.g01.hdf") print(df.columns.tolist()[:3]) ['Land Cover Name', "Base Manning's n Value", ...]
get_mesh_area_attributes
staticmethod
¶
Return geometry 2D flow area attributes from a HEC-RAS HDF file.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file.
Returns¶
pd.DataFrame A DataFrame containing the 2D flow area attributes with: - Index: str - Attribute names (e.g., 'Name', 'Cell Count', 'Face Count') - Value: varies - Attribute values (decoded from HDF bytes)
get_mesh_area_names
staticmethod
¶
get_mesh_areas
staticmethod
¶
Return 2D flow area perimeter polygons.
Collection-level Parts offsets are feature-local and valid when every part lies within the feature's point count. Legacy global offsets are accepted only when all parts together cover the feature point range exactly; any other layout fails closed.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file.
Returns¶
GeoDataFrame A GeoDataFrame containing the 2D flow area perimeter polygons if 2D areas exist.
get_mesh_cell_faces
staticmethod
¶
Return 2D flow mesh cell faces.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file.
Returns¶
GeoDataFrame A GeoDataFrame containing the 2D flow mesh cell faces with columns: - mesh_name: str - Name of the 2D flow area - face_id: int - Unique face identifier (0-indexed) - geometry: LineString - Face edge geometry (may include intermediate perimeter points)
Notes¶
Each face is its start point, its Faces Perimeter Values rows (the
intermediate points of a curved or perimeter face) and its end point,
in stored order. All lines of a mesh are built in one vectorized
Shapely call from packed coordinate buffers: the native engine builds
the buffers where it proves the layout (auto and native
modes), NumPy builds them otherwise, and a per-face loop handles any
layout neither accepts. The geometry is identical (WKB) in every case.
This is the face geometry to read once per model and join to the fast
include_geometry=False face results of :class:HdfResultsMesh
on ["mesh_name", "face_id"]:
faces = HdfMesh.get_mesh_cell_faces(plan_hdf) vmax = HdfResultsMesh.get_mesh_max_face_v(plan_hdf, include_geometry=False) located = faces.merge(vmax, on=["mesh_name", "face_id"])
get_mesh_cell_points
staticmethod
¶
get_mesh_cell_points(hdf_path: Path, include_ghost_cells: bool = True, *, include_geometry: bool = True) -> Union[GeoDataFrame, pd.DataFrame]
Return 2D flow mesh cell center points.
Parameters¶
hdf_path : Path
Path to the HEC-RAS geometry HDF file.
include_ghost_cells : bool, optional
Cells Center Coordinate lists the physical cells followed by
ghost cells outside the perimeter (IDs at or above the area's
Attributes Cell Count). Default True returns every entry.
Pass False to return physical cells only, matching mesh polygons
and the default ghost-free HdfResultsMesh cell results. A mesh
whose Cell Count is not recorded keeps every entry.
include_geometry : bool, optional, keyword-only
Default True returns the GeoDataFrame below. False returns a
DataFrame with the same rows and order and the stored coordinates
as two columns instead of Shapely points (no GeoPandas/Shapely,
no CRS lookup): mesh_name (pandas str/string), cell_id
(int64), x and y (the stored coordinate dtype,
float64 in HEC-RAS files).
Returns¶
GeoDataFrame A GeoDataFrame containing the 2D flow mesh cell center points with columns: - mesh_name: str - Name of the 2D flow area - cell_id: int - Unique cell identifier (0-indexed) - geometry: Point - Cell center point geometry
Notes¶
This is the cell-center geometry to read once per model and join to
the fast include_geometry=False cell results of
:class:HdfResultsMesh on ["mesh_name", "cell_id"]. Pass
include_ghost_cells=False to match their default ghost-free rows.
get_mesh_cell_polygons
staticmethod
¶
get_mesh_cell_polygons(hdf_path: Path, *, strict: bool = False, engine: str = 'auto', threads: Optional[int] = None, diagnostics: bool = False) -> GeoDataFrame
Return 2D flow mesh cell polygons.
Parameters¶
hdf_path : Path
Path to the HEC-RAS geometry HDF file.
strict : bool, default False
Raise :class:MeshCellPolygonError when a native cell produces no
polygon or more than one polygon. The default preserves the legacy
return behavior and emits a warning for omitted cells.
engine : str, default "auto"
"auto": native first, with the Python reference polygonizer on
any native refusal or failure, so results and exceptions are the
reference ones. "h5py": the reference polygonizer only.
"native": native execution or
:class:~ras_commander.fast_hdf.FastHdfError.
threads : int, optional
Maximum threads for native extraction and polygon construction.
diagnostics : bool, default False
Attach anomaly rows to result.attrs["cell_polygon_diagnostics"]
as an equality-safe tuple of record dictionaries. Off by default
(behaviour change from ras-commander 0.106.1, which always attached
them); :meth:diagnose_mesh_cell_polygons returns them as a
DataFrame.
Native and Python diagnostics: with engine="auto" the records
are always the Python reference's (native results are used only
when every record is proven equal, else the Python polygonizer
runs). With engine="native" (or
RAS_COMMANDER_FAST_HDF=native) the native records are returned
as produced and can differ: the engine labels a cell it did not
assemble omitted/no_polygon only when it detected an invalid
ring, otherwise boundary_only/insufficient_faces even if the
cell has three or more faces; it never reports ambiguous/
multiple_polygons, invalid_face_span or
missing_face_reference (the reference polygonizes the faces
and can). The polygons themselves are unaffected.
Returns¶
GeoDataFrame A GeoDataFrame containing the 2D flow mesh cell polygons with columns: - mesh_name: str - Name of the 2D flow area - cell_id: int - Unique cell identifier (0-indexed) - geometry: Polygon - Cell polygon geometry constructed from face edges Returns an empty GeoDataFrame if no 2D areas exist or if there's an error.
Notes¶
Cell IDs are native, zero-based IDs within each mesh. The returned row
index must not be treated as a complete or positional cell identifier.
Use :meth:diagnose_mesh_cell_polygons or strict=True whenever an
exhaustive physical-cell mask is required.
get_mesh_cell_property_tables
staticmethod
¶
Extract Cell Property Tables for each Cell in all 2D Flow Areas.
Returns elevation-volume relationships for each cell, which define how cell volume changes with water surface elevation. This data is used internally by HEC-RAS for 2D hydraulic computations.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file.
Returns¶
Dict[str, pd.DataFrame] A dictionary where: - keys: mesh area names (str) - values: DataFrames with columns: - Cell ID: unique identifier for each cell - Elevation: water surface elevation (float) - Volume: cell volume at that elevation (float) Returns an empty dictionary if no 2D areas exist or if there's an error.
Notes¶
The HDF path for this data is 'Geometry/2D Flow Areas/{mesh_name}/Cells Volume Elevation Info' and 'Geometry/2D Flow Areas/{mesh_name}/Cells Volume Elevation Values'.
Cell surface area is stored separately in 'Cells Surface Area' dataset (one value per cell), not in the elevation-volume table.
get_mesh_corner_elevations
staticmethod
¶
get_mesh_corner_elevations(hdf_path: Path, mesh_name: Optional[str] = None, *, postprocessing_hdf: Optional[Union[str, Path]] = None, source: str = 'auto', engine: str = 'auto', ras_object=None)
Return stored 2D mesh corner ground elevations with their provenance.
RASMapper's depth-weighted sloping interpolation uses one static terrain elevation per mesh corner (face point). They are not corner water surfaces, face water surfaces or node velocities, and enabling more hydraulic output variables does not produce them. HEC-RAS stores them in two places:
"geometry":Geometry/2D Flow Areas/<mesh>/FacePoints Elevationin the geometry or plan HDF, written by 2D hydraulic-table preprocessing (HEC-RAS 7.0 and later; absent from 6.x files)."mapping_cache":Results/Unsteady/Output/Output Blocks/Base Output/ Summary Output/2D Flow Areas/<mesh>/Processed Data/Profile (Horizontal)/ FacePoint Elevationin the result'sPostProcessing.hdf(note the singularFacePoint), written by RASMapper when it renders depth-weighted maps. It is usually in the plan's output folder,<project folder>/<plan Short ID>/PostProcessing.hdf; pass it explicitly.
This method only reads. Values are float32 in FacePoints Coordinate
row order, bit for bit as stored (NaN payloads and sentinels such as
-9999 included). It never interpolates, reorders or fills values, and it
never generates missing elevations from terrain.
Parameters¶
hdf_path : Path
Geometry or plan HDF. It names the meshes and gives each mesh's
corner count (FacePoints Coordinate rows) and terrain metadata.
mesh_name : str, optional
One mesh. When omitted, every 2D flow area is returned.
postprocessing_hdf : str or Path, optional
The result's PostProcessing.hdf mapping cache to consult.
source : {"auto", "geometry", "mapping_cache"}, default "auto"
"geometry" reads only hdf_path (postprocessing_hdf must be
omitted). "mapping_cache" reads only the cache (required); the
geometry layout is not consulted. "auto" reads the geometry layout
and, when given, the cache:
1. Any candidate that is present but not one float32 value per
corner makes the result ``"invalid"``.
2. Both present: they must be bit-identical (result ``"ok"``, values
from the geometry), otherwise ``"conflict"`` with no values.
3. Only the geometry: ``"ok"``.
4. Only the cache: ``"ok"`` unless a staleness check failed
(``"stale"``, no values).
5. Neither: ``"missing"``.
With ``"mapping_cache"`` a cache that fails a staleness check is
``"stale"`` with no values.
engine : {"auto", "h5py", "native"}, default "auto"
Read backend, as for the other HdfMesh readers and
RAS_COMMANDER_FAST_HDF. "auto" uses the native engine and
falls back to h5py on any native refusal or failure; "h5py" uses
only h5py; "native" raises
:class:~ras_commander.fast_hdf.FastHdfError instead of falling
back. Both backends return identical results.
ras_object : RasPrj, optional
Project used to resolve a plan number to its HDF.
Returns¶
MeshCornerElevations or dict[str, MeshCornerElevations]
One result for mesh_name, else {mesh_name: result} in mesh
order. Each result has status ("ok", "missing",
"invalid", "conflict" or "stale"), values (read-only
float32 array, None unless "ok"), corner_count,
source (the candidate the values come from), candidates
(every source consulted, each with file, dataset,
status, detail, dataset attributes, terrain
metadata and the sha256 of its float32 bytes), checks and
reason. result.require() returns the values or raises
:class:CornerElevationError; result.as_dict() gives plain data.
Raises¶
ValueError
Invalid source/engine/argument combination, an unknown
mesh, or a mesh without FacePoints Coordinate.
FastHdfError
Only with engine="native" (or RAS_COMMANDER_FAST_HDF=native)
when the native engine is unavailable or refuses the data.
Notes¶
Staleness: a cache dataset existing does not show it matches the mesh
and terrain. Each cache that reads successfully gets these checks
(passed, failed or not_checked when the evidence is not
stored):
corner_count: one value per corner ofhdf_path's mesh (a mismatch makes the cache"invalid");terrain_file: the cache'sTerrain Filename(relative to the cache folder) is the mesh's terrain (relative tohdf_path);terrain_date: the cache'sTerrain File Dateequals the date the mesh was preprocessed against (meshTerrain File Date);terrain_current: the terrain file's modification time still equals the cache'sTerrain File Date;cache_after_hdf: the cache was written afterhdf_pathwas last modified;agreement("auto"with both present): bit-identical values.
Copying a project can change file times and fail the date checks; the result then reports a stale cache rather than trusting it.
Examples¶
result = HdfMesh.get_mesh_corner_elevations("model.p01.hdf", "Perimeter 1") elevations = result.require() # float32, FacePoints Coordinate order result.source.file, result.source.dataset, result.source.terrain
get_mesh_face_hydraulic_properties_at_stage
staticmethod
¶
get_mesh_face_hydraulic_properties_at_stage(hdf_path: Path, mesh_name: str, face_ids, water_surface, unit_system: str = 'us')
Interpolate 2D face hydraulic properties at supplied water-surface stages.
Parameters¶
hdf_path : Path
Path to the HEC-RAS geometry HDF file.
mesh_name : str
2D flow area name.
face_ids : scalar or array-like
Face IDs to evaluate.
water_surface : scalar, 1D array, or 2D array
Water-surface elevation(s). Scalars are broadcast to every face.
1D arrays must contain one value per face. 2D arrays are interpreted
as time-by-face.
unit_system : str, default 'us'
'us'/'customary' uses 1.486 in Manning's conveyance;
'metric'/'si' uses 1.0.
Returns¶
xarray.Dataset
Dataset with dimensions time and face_id containing:
area, wetted_perimeter, mannings_n,
hydraulic_radius, and conveyance.
Notes¶
This helper is sourced from the geometry preprocessor face property tables stored in the geometry HDF. It is therefore a geometry-derived/interpolated view of face hydraulic properties, not the canonical native unsteady-results calculation path.
When native face results such as Face Area or Face Manning's n
are available in the plan/results HDF, prefer
HdfResultsMesh.get_mesh_faces_timeseries() for QAQC and direct
comparison to native HEC-RAS output. Those values reflect the solver's
canonical results path, including aggregation from computational time
steps to output time steps.
Conveyance is derived from face property tables using:
K = C * A * (A / P) ** (2 / 3) / n.
Stages below the lowest tabulated elevation are treated as dry faces with zero area, wetted perimeter, hydraulic radius, and conveyance.
get_mesh_face_property_tables
staticmethod
¶
Extract Face Property Tables for each Face in all 2D Flow Areas.
Returns elevation-area-wetted perimeter relationships for each face, which define the hydraulic properties at different water surface elevations. This data is used internally by HEC-RAS for 2D hydraulic computations.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file.
Returns¶
Dict[str, pd.DataFrame] A dictionary where: - keys: mesh area names (str) - values: DataFrames with columns: - Face ID: unique identifier for each face (int) - Elevation: water surface elevation (float) - Area: face area at that elevation (float) - Wetted Perimeter: wetted perimeter length at that elevation (float) - Manning's n: Manning's roughness coefficient (float) Returns an empty dictionary if no 2D areas exist or if there's an error. Returns an empty DataFrame with correct columns for meshes where property tables don't exist.
Notes¶
The HDF path for this data is 'Geometry/2D Flow Areas/{mesh_name}/Faces Area Elevation Info' and 'Geometry/2D Flow Areas/{mesh_name}/Faces Area Elevation Values'.
get_mesh_perimeter_faces
staticmethod
¶
get_mesh_perimeter_faces(hdf_path: str | Path, mesh_name: str, *, ras_object=None, on_duplicate_ownership: Literal['raise', 'report'] = 'raise') -> GeoDataFrame
Read every perimeter face of a named 2D area, including unassigned faces.
hdf_path accepts geometry/plan HDF paths, open HDF handles, or
project numbers resolved by the standard HDF decorator. ras_object
selects the project used for number resolution. No files are modified.
Returns a GeoDataFrame with mesh_name, face_id, cell0,
cell1, interior_cell_id, exterior_cell_id,
fp_start_index, fp_end_index, face_length, bc_line_id,
bc_line_name, bc_line_type, and geometry. IDs retain their
native zero-based numbering. Exterior cells retain ghost IDs (or -1).
Length is the native Faces NormalUnitVector and Length value in
model units, falling back to complete face geometry length if absent.
BC columns are nullable for confirmed unassigned faces.
on_duplicate_ownership="report" keeps one row per face and adds
duplicate_ownership (bool), owning_bc_line_ids and
owning_bc_line_names (parallel lists in native encounter order).
Duplicate-owned faces have null scalar BC ID, name and type; unassigned
faces have empty owner lists. Repeated native associations are also
marked, even for the same owner. Default "raise" retains strict
validation and the original columns. Other validations remain active.
attrs['duplicate_ownership'] lists duplicate faces and owners for
the requested mesh, with duplicate face and association-row counts.
Physical cells are identified by collection Attributes/Cell Count;
higher cell IDs identify native ghost cells. Surface area and the
sometimes stale Cell Maximum Index attribute are not used.
Faces with one physical cell and one exterior cell form the inventory,
including any mesh interior-hole boundary faces. It does not classify
perimeter rings or infer associations from geometric proximity.
Raises KeyError for an unknown mesh or missing required native tables.
Raises ValueError for malformed topology, duplicate BC ownership,
stale BC face/endpoints, or missing native association evidence when
the selected area has boundary lines. Missing preprocessing is never
reported as confirmed unassigned ownership. Association availability
is also retained in attrs['association_status'].
get_mesh_sloped_topology
staticmethod
¶
Extract all mesh topology needed for sloped water surface interpolation.
This function performs a single HDF read to extract all geometric and topological data required for RASMapper's "Sloped (Cell Corners)" water surface rasterization algorithm.
Parameters¶
hdf_path : Path Path to the HEC-RAS plan HDF file. mesh_name : str, optional Name of the specific mesh area to extract. If None, uses the first mesh area found.
Returns¶
Dict[str, Any] Dictionary containing all topology data:
- 'mesh_name': str - Name of the mesh area
- 'n_cells': int - Number of cells
- 'n_faces': int - Number of faces
- 'n_facepoints': int - Number of facepoints (vertices)
Coordinates:
- 'cell_centers': ndarray (n_cells, 2) float64 - Cell center X, Y
- 'facepoint_coords': ndarray (n_facepoints, 2) float64 - Vertex X, Y
Minimum elevations:
- 'cell_min_elev': ndarray (n_cells,) float32 - Min terrain per cell
- 'face_min_elev': ndarray (n_faces,) float32 - Min terrain per face
Face connectivity:
- 'face_cells': ndarray (n_faces, 2) int32 - [cell_a, cell_b] per face
(-1 indicates perimeter/boundary)
- 'face_facepoints': ndarray (n_faces, 2) int32 - [fp_a, fp_b] per face
Facepoint-to-face connectivity (CSR-like):
- 'facepoint_face_info': ndarray (n_facepoints, 2) int32 - [start, count]
- 'facepoint_face_values': ndarray (n_connections, 2) int32 - [face_idx, orientation]
Cell-to-face connectivity (CSR-like):
- 'cell_face_info': ndarray (n_cells, 2) int32 - [start, count]
- 'cell_face_values': ndarray (n_connections, 2) int32 - [face_idx, orientation]
Notes¶
The CSR-like format for variable-length connectivity uses: - info array: [start_index, count] per element - values array: actual connections, accessed as values[start:start+count]
The orientation value indicates which side of the face the element is on: - 0: "a" side (first cell in face_cells) - 1: "b" side (second cell in face_cells)
Example¶
>>> topology = HdfMesh.get_mesh_sloped_topology(plan_hdf_path)
>>> print(f"Mesh: {topology['mesh_name']}")
>>> print(f"Cells: {topology['n_cells']}, Faces: {topology['n_faces']}")
>>>
>>> # Access faces connected to facepoint 0
>>> start, count = topology['facepoint_face_info'][0]
>>> connected_faces = topology['facepoint_face_values'][start:start+count, 0]
get_reference_line_internal_faces
staticmethod
¶
get_reference_line_internal_faces(hdf_path: Path, mesh_name: Optional[str] = None) -> pd.DataFrame
Return internal mesh faces associated with native HEC-RAS reference lines.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file. mesh_name : Optional[str], optional If provided, return only reference-line faces for this 2D flow area.
Returns¶
pd.DataFrame
Rows keyed by reference line and face with columns such as
reference_line_id, profile_name, mesh_name, face_id,
fp_start_index, fp_end_index, station_start,
station_end, station_length, face_length, and
station_fraction where source fields are available. Returns an
empty DataFrame when reference lines or internal faces are absent.
station_fraction is the raw HDF-derived fraction and may be
outside [0, 1] for unusual station data; consumers should validate
or clip it before using it as a multiplier.
pin_property_tables
staticmethod
¶
pin_property_tables(hdf_path: Union[str, Path], mesh_name: str, pinned: bool = True, *, acknowledge_unsupported: bool = False) -> None
Deprecated wrapper for :meth:set_mesh_pinned_attribute.
recompute_face_mannings_n_from_landcover_curves
staticmethod
¶
recompute_face_mannings_n_from_landcover_curves(hdf_path: Union[str, Path], mesh_name: str, curves: DataFrame, landcover_hdf_path: Optional[Union[str, Path]] = None, face_ids: Optional[List[int]] = None, sample_spacing: float = 10.0, pin_tables: bool = True, *, acknowledge_unsupported: bool = False) -> int
Deprecated wrapper for the equal-class Linux temporary-table API.
sample_linux_tmp_face_mannings_n_from_landcover_curves
staticmethod
¶
sample_linux_tmp_face_mannings_n_from_landcover_curves(hdf_path: Union[str, Path], mesh_name: str, curves: DataFrame, landcover_hdf_path: Optional[Union[str, Path]] = None, face_ids: Optional[List[int]] = None, sample_spacing: float = 10.0, pin_tables: bool = True, *, acknowledge_unsupported: bool = False) -> Dict[str, Any]
Sample land-cover curves into guarded Linux temporary face tables.
The land-cover raster is sampled along each target face. For each face table elevation, class-specific roughness values are interpolated by depth and combined with an equal-class power mean (exponent 1.5). Repeated samples do not add weight: this is a class-presence heuristic, not fraction-, length-, area-, or conveyance-weighted roughness. Faces outside the raster or containing only nodata retain their original values.
.. warning::
EXPERIMENTAL. Not recommended for production or any other
non-experimental use. Tested only with HEC-RAS 7.0 April 2026 in
the workflow below; all other versions and workflows are untested.
Edits are overwritten by the Windows HEC-RAS geometry preprocessor
on the next plan execution. The tested Linux two-phase workflow is:
(1) preprocess on Windows via
RasPreprocess.preprocess_plan() to generate the .tmp.hdf,
(2) apply edits to the .tmp.hdf, (3) execute with
RasCmdr.compute_plan_linux(). This is an undocumented and
unsupported method of injecting modified HDF inputs into the
solver and may produce erroneous results.
Parameters¶
hdf_path : Union[str, Path]
Guarded HEC-RAS 7.0 *.p##.tmp.hdf result artifact.
mesh_name : str
Name of the 2D flow area.
curves : pd.DataFrame
Depth-varying roughness curves with pixel_value, depth, and
mannings_n columns.
landcover_hdf_path : Optional[Union[str, Path]]
Land-cover HDF path. The sidecar .tif raster is sampled.
face_ids : Optional[List[int]]
Faces to recompute. None recomputes all faces with sampled
land-cover classes.
sample_spacing : float, default 10.0
Maximum spacing for additional samples along each face.
pin_tables : bool, default True
Pin tables after modification.
Returns¶
Dict[str, Any]
Structured mutation report with faces_modified and the
full-file backup_path.
set_face_mannings_n_values
staticmethod
¶
set_face_mannings_n_values(hdf_path: Union[str, Path], mesh_name: str, mannings_n_func: Callable[[float, float, float], float], face_ids: Optional[List[int]] = None, polygon=None, region_name: Optional[str] = None, pin_tables: bool = True, *, acknowledge_unsupported: bool = False) -> int
Deprecated wrapper for guarded Linux temporary Manning transforms.
set_mesh_face_property_tables
staticmethod
¶
set_mesh_face_property_tables(hdf_path: Union[str, Path], mesh_name: str, face_tables: Dict[int, DataFrame], pin_tables: bool = True, *, acknowledge_unsupported: bool = False) -> None
Deprecated wrapper for :meth:write_linux_tmp_face_property_tables.
set_mesh_pinned_attribute
staticmethod
¶
set_mesh_pinned_attribute(hdf_path: Union[str, Path], mesh_name: str, pinned: bool = True, *, acknowledge_unsupported: bool = False) -> Path
Set or clear guarded Linux temporary-HDF Pinned metadata.
Warning
EXPERIMENTAL. Not recommended for production or any other non-experimental use. HEC-RAS 7.0 April 2026 is qualified for the Windows-preprocess/Linux-solve workflow. HEC-RAS 7.0.1 June 2026 and 7.0.2 October 2026 are qualified for temporary-HDF schema and write/readback only; their Linux solves after mutation are untested. All other versions and workflows are untested.
Pinned is informational metadata that may be recognized by
RASMapper. It is ignored by Windows HEC-RAS preprocessing and does not
protect modified face tables. This method therefore accepts only the
guarded 7.0 Linux two-phase *.p##.tmp.hdf role, requires explicit
acknowledgement, creates a full-file backup, and verifies readback.
Returns:
| Type | Description |
|---|---|
Path
|
Path to the full-file pre-write backup. |
transform_linux_tmp_face_mannings_n
staticmethod
¶
transform_linux_tmp_face_mannings_n(hdf_path: Union[str, Path], mesh_name: str, mannings_n_func: Callable[[float, float, float], float], face_ids: Optional[List[int]] = None, polygon=None, region_name: Optional[str] = None, pin_tables: bool = True, *, acknowledge_unsupported: bool = False) -> Dict[str, Any]
Transform Manning's n in guarded Linux temporary face tables.
Preserves Elevation, Area, and Wetted Perimeter columns. Only the Manning's n column is recomputed.
.. warning::
EXPERIMENTAL. Not recommended for production or any other
non-experimental use. Tested only with HEC-RAS 7.0 April 2026 in
the workflow below; all other versions and workflows are untested.
Edits are overwritten by the Windows HEC-RAS geometry preprocessor
on the next plan execution. The tested Linux two-phase workflow is:
(1) preprocess on Windows via
RasPreprocess.preprocess_plan() to generate the .tmp.hdf,
(2) apply edits to the .tmp.hdf, (3) execute with
RasCmdr.compute_plan_linux(). This is an undocumented and
unsupported method of injecting modified HDF inputs into the
solver and may produce erroneous results.
Parameters¶
hdf_path : Union[str, Path]
Guarded HEC-RAS 7.0 *.p##.tmp.hdf result artifact.
mesh_name : str
Name of the 2D flow area.
mannings_n_func : Callable[[float, float, float], float]
Function (elevation, depth, current_n) -> new_n where
elevation is the row elevation, depth is elevation minus
the face minimum elevation, and current_n is the existing
Manning's n value.
face_ids : Optional[List[int]]
Faces to modify. None modifies all faces.
polygon : shapely Polygon/MultiPolygon or GeoDataFrame, optional
If provided and face_ids is None, only modify faces whose
midpoint falls within this polygon.
region_name : str, optional
If provided and face_ids is None, only modify faces within
the named Manning's n calibration region from the geometry HDF.
Precedence: face_ids > region_name > polygon.
pin_tables : bool, default True
Pin tables after modification.
Returns¶
Dict[str, Any]
Structured mutation report with faces_modified and the
full-file backup_path.
write_linux_tmp_face_property_tables
staticmethod
¶
write_linux_tmp_face_property_tables(hdf_path: Union[str, Path], mesh_name: str, face_tables: Mapping[int, DataFrame], pin_tables: bool = True, *, acknowledge_unsupported: bool = False) -> Path
Write face tables to a guarded HEC-RAS Linux .tmp.hdf.
Warning
EXPERIMENTAL. Not recommended for production or any other non-experimental use. HEC-RAS 7.0 April 2026 is qualified for the Windows-preprocess/Linux-solve workflow. HEC-RAS 7.0.1 June 2026 and 7.0.2 October 2026 are qualified for temporary-HDF schema and write/readback only; their Linux solves after mutation are untested. All other versions and workflows are untested.
This API is limited to the proven two-phase workflow: preprocess a plan
into *.p##.tmp.hdf, modify that temporary result, then pass it to
RasCmdr.compute_plan_linux(). The exact root file role/version,
mesh schema, face IDs, and hydraulic values are checked before a unique
full-file backup is created. The file is reopened after writing for
exact Info/Values readback verification.
pin_tables=True only sets the mesh Pinned metadata attribute.
It does not protect edits from Windows HEC-RAS preprocessing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path]
|
Qualified HEC-RAS |
required |
mesh_name
|
str
|
Exact 2D flow-area name. |
required |
face_tables
|
Mapping[int, DataFrame]
|
Face ID to DataFrame mapping. Required columns are
|
required |
pin_tables
|
bool
|
Set the informational |
True
|
acknowledge_unsupported
|
bool
|
Must be explicitly |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the full-file pre-write backup. |
HdfXsec source reference¶
Handles cross-section and river geometry data extraction from HEC-RAS HDF files.
This class provides static methods to extract and process: - Cross-section geometries and attributes - River centerlines and reaches - River edge and bank lines - Station-elevation profiles
All methods are designed to return GeoDataFrames with standardized geometries and attributes following the HEC-RAS data structure.
Note
Requires HEC-RAS geometry HDF files with standard structure and naming conventions. All methods use proper error handling and logging.
generate_river_edge_lines
staticmethod
¶
Generate river edge lines from cross-section cut-line end points.
Pure-Python equivalent of RASMapper's "Create Edge Lines at XS Limits".
For each (River, Reach), the left end points of consecutive cross-section
cut lines are connected into a left edge line and the right end points
into a right edge line. HEC-RAS stores cut lines left(start) -> right(end)
looking downstream, so coords[0] is the left limit and coords[-1]
is the right limit of each cross section.
Use this when a geometry has no stored Geometry/River Edge Lines
(e.g. the XS interpolation surface has not been computed) or to derive a
1D footprint boundary directly from cross sections. This is a simplified
XS-endpoint construction; for HEC-RAS's own bank-line-anchored
offset-curve edge lines (written to the geometry HDF with the group-level
Source Data Hash), use RasGeometryCompute.generate_edge_lines().
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file. ras_object : RasPrj, optional RAS project object for path resolution context.
Returns¶
GeoDataFrame
Generated edge lines with columns matching get_river_edge_lines:
- edge_id : int
- River : str
- Reach : str
- bank_side : str ('Left' or 'Right')
- geometry : LineString
- length : float (project units)
Empty GeoDataFrame when no cross sections are available.
get_1d_footprint
staticmethod
¶
get_1d_footprint(hdf_path: Path, edge_source: str = 'auto', dissolve: bool = False, close_with_end_xs: bool = True, ras_object=None) -> gpd.GeoDataFrame
Build the 1D model footprint polygon(s) from river edge lines.
For each (River, Reach) the left and right edge lines are closed into a polygon ring: left edge, downstream cross section, reversed right edge, upstream cross section. The end caps follow the real cut-line geometry of the end cross sections, including their interior vertices, so a bent cut line is reproduced instead of chorded. This is the true 1D study footprint, not a bounding box.
Parameters¶
hdf_path : Path
Path to the HEC-RAS geometry HDF file.
edge_source : {'auto', 'stored', 'generate'}, default 'auto'
- 'stored' : use Geometry/River Edge Lines only.
- 'generate' : always generate edge lines from XS end points.
- 'auto' : use stored edge lines when present, otherwise generate.
dissolve : bool, default False
If True, dissolve the per-reach polygons into a single (multi)polygon
row. If False, return one polygon row per (River, Reach).
close_with_end_xs : bool, default True
Close each ring on the end cross-section cut-line geometry. Set False
for the legacy behavior, a straight chord between the edge-line end
points. When an edge-line end point does not land on a cut-line limit
(possible for stored edge lines), that end cap falls back to the
straight chord regardless of this setting.
ras_object : RasPrj, optional
RAS project object for path resolution context.
Returns¶
GeoDataFrame
Columns River, Reach, source, geometry (Polygon). When
dissolve=True, a single row with a (Multi)Polygon and
source='1d_footprint'. Empty GeoDataFrame when no 1D geometry is
available.
get_cross_sections
staticmethod
¶
get_cross_sections(hdf_path: Union[str, Path], datetime_to_str: bool = True, *, ras_object=None) -> gpd.GeoDataFrame
Extracts cross-section geometries and attributes from a HEC-RAS geometry HDF file.
Parameters¶
hdf_path : str or Path
HEC-RAS geometry HDF path or supported geometry selector. String
and numeric selectors are resolved against ras_object.
datetime_to_str : bool, optional
Convert datetime objects to strings, defaults to True
ras_object : RasPrj, optional
Project used to resolve plan/geometry selectors. When omitted, the
initialized global project is used. Must be passed by keyword.
Returns¶
gpd.GeoDataFrame Cross-section data with columns: - geometry: LineString or MultiLineString - Cross-section polyline geometry - station_elevation: ndarray - Station-elevation profile (Nx2 array: [station, elevation]) - mannings_n: dict - Raw Manning's n data with keys 'Station' and 'Mann n' (lists) - n_lob: float - Left overbank Manning's n (computed from bank stations) - n_channel: float - Main channel Manning's n (computed from bank stations) - n_rob: float - Right overbank Manning's n (computed from bank stations) - ineffective_blocks: list - List of dicts with keys: 'Left Sta', 'Right Sta', 'Elevation', 'Permanent' - River: str - River name - Reach: str - Reach name - RS: str - River station identifier - Name: str - Cross-section name - Description: str - Cross-section description - Len Left: float - Left overbank flow path length - Len Channel: float - Main channel flow path length - Len Right: float - Right overbank flow path length - Left Bank: float - Left bank station location - Right Bank: float - Right bank station location - Friction Mode: str - Friction method used - Contr: float - Contraction coefficient - Expan: float - Expansion coefficient - Left Levee Sta: float - Left levee station (if exists) - Left Levee Elev: float - Left levee elevation (if exists) - Right Levee Sta: float - Right levee station (if exists) - Right Levee Elev: float - Right levee elevation (if exists) - HP Count: int - Hydraulic table point count - HP Start Elev: float - Hydraulic table starting elevation - HP Vert Incr: float - Hydraulic table vertical increment - HP LOB Slices: int - Left overbank slices count - HP Chan Slices: int - Main channel slices count - HP ROB Slices: int - Right overbank slices count - Ineff Block Mode: int - Ineffective area block mode - Obstr Block Mode: int - Obstruction block mode - Default Centerline: int - Default centerline flag - Last Edited: str - Last edit timestamp
Notes¶
The returned GeoDataFrame includes the coordinate system from the HDF file when available. All byte strings are converted to regular strings.
Raises¶
FileNotFoundError If the path or project selector cannot be resolved to an existing geometry HDF file.
get_river_bank_lines
staticmethod
¶
Extract river bank lines from HDF geometry file.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file datetime_to_str : bool, optional Convert datetime objects to strings, by default False
Returns¶
GeoDataFrame River bank line data with columns: - geometry: LineString - River bank line geometry - bank_id: int - Unique identifier for each bank line (0-indexed) - bank_side: str - Bank side indicator ('Left' or 'Right') - length: float - Length of the bank line in project coordinate units (computed)
Note: Bank lines are assumed to be in pairs (left/right). If odd number of geometries
exist, the bank_side pattern may not align perfectly.
get_river_centerlines
staticmethod
¶
Extracts river centerline geometries and attributes from HDF geometry file.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file datetime_to_str : bool, optional Convert datetime objects to strings, defaults to False
Returns¶
GeoDataFrame River centerline data with columns: - geometry: LineString or MultiLineString - River centerline geometry - River Name: str - Name of the river - Reach Name: str - Name of the reach - US Type: str - Upstream connection type (e.g., 'Junction', 'External') - US Name: str - Upstream connection name - DS Type: str - Downstream connection type (e.g., 'Junction', 'External') - DS Name: str - Downstream connection name - length: float - Centerline length in project coordinate units (computed)
Note: Additional HDF attributes may be included depending on HEC-RAS version.
Use datetime_to_str=True to convert any datetime columns to ISO format strings.
Notes¶
Returns an empty GeoDataFrame if no centerlines are found. All string attributes are stripped of whitespace.
get_river_edge_lines
staticmethod
¶
Return the model river edge lines.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file. datetime_to_str : bool, optional If True, convert datetime objects to strings. Default is False.
Returns¶
GeoDataFrame River edge line data with columns: - geometry: LineString - River edge line geometry - edge_id: int - Unique identifier for each edge line (0-indexed) - bank_side: str - Bank side indicator ('Left' or 'Right') - length: float - Length of edge line in project coordinate units (computed) - Last Edited: datetime or str - Last edit timestamp (str if datetime_to_str=True, if available)
Note: Each row represents one river bank (left or right). Additional HDF attributes
may be included depending on HEC-RAS version.
get_river_flow_paths
staticmethod
¶
Return the model river flow paths (Geometry/River Flow Paths).
RASMapper's Create Flow Paths from XS Layout artifact: the flow-path
polylines (left overbank, channel, right overbank) that drive 1D reach
lengths. Pure h5py read; the group must already exist. Generate it with
RasGeometryCompute.generate_flow_paths() when absent.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file. datetime_to_str : bool, optional Accepted for signature parity with the other river-layer readers; flow paths carry no timestamp attribute, so this is a no-op.
Returns¶
GeoDataFrame
Columns flow_path_id (int), geometry (LineString), and
length (project units). Empty GeoDataFrame when no flow paths
are stored.
get_river_reaches
staticmethod
¶
Return the model 1D river reach lines.
This method extracts river reach data from the HEC-RAS geometry HDF file, including attributes and geometry information.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file. datetime_to_str : bool, optional If True, convert datetime objects to strings. Default is False.
Returns¶
GeoDataFrame River reach data with columns: - geometry: LineString or MultiLineString - River reach line geometry - river_id: int - Unique identifier for each reach (0-indexed) - River Name: str - Name of the river - Reach Name: str - Name of the reach - US Type: str - Upstream connection type - US Name: str - Upstream connection name - DS Type: str - Downstream connection type - DS Name: str - Downstream connection name - Last Edited: datetime or str - Last edit timestamp (str if datetime_to_str=True) - length: float - Reach length in project coordinate units (computed)
Note: Additional HDF attributes may be included depending on HEC-RAS version.
get_river_stationing
staticmethod
¶
Calculates stationing along river centerlines with interpolated points.
Parameters¶
centerlines_gdf : GeoDataFrame River centerline geometries from get_river_centerlines()
Returns¶
GeoDataFrame Original centerlines with additional columns: - station_start: float - Starting station value (0.0 or total_length, depends on US/DS connections) - station_end: float - Ending station value (total_length or 0.0, depends on US/DS connections) - stations: ndarray - Array of 100 evenly-spaced station values along centerline - points: list - List of shapely Point geometries at each station location
All original columns from centerlines_gdf are preserved (geometry, River Name, Reach Name, etc.).
Notes¶
Station direction (increasing/decreasing) is determined by upstream/downstream junction connections. Stations are calculated at 100 evenly spaced points along each centerline.
get_xs_coords
staticmethod
¶
get_xs_coords(hdf_path: Path, river: Optional[str] = None, reach: Optional[str] = None, rs: Optional[str] = None, horizontal_crs: Any = None, vertical_units: Optional[str] = None, vertical_datum: Optional[str] = None, ras_object=None) -> pd.DataFrame
Extract point-level XYZ cross-section geometry from a geometry HDF.
This is the HDF equivalent of
:meth:GeomCrossSection.get_xs_coords. Station/elevation rows are
projected onto each stored GIS cut line, in native order, and enriched
with Manning's n and bank metadata. Elevations are returned exactly as
stored; this method never performs a vertical transformation.
Parameters¶
hdf_path:
Geometry .g##.hdf path (or a supported geometry-HDF selector).
river, reach, rs:
Optional exact, case-sensitive filters.
horizontal_crs:
Explicit CRS override. Otherwise the embedded or adjacent RASMapper
projection is used when available.
vertical_units, vertical_datum:
Explicit metadata overrides. Direct HDF extraction uses only
genuinely explicit vertical-unit metadata; generic unit-system
flags are not treated as authoritative. A vertical datum is
reported only when explicitly provided or stored in the HDF; it is
never inferred from the horizontal CRS.
Returns¶
pandas.DataFrame One row per native station/elevation point. Stable columns include identifiers, native/station order, cut-line relative distance, XYZ, Manning's n, bank classification, CRS/units, and source provenance.
get_xs_interpolation_surface
staticmethod
¶
Return the cross-section interpolation surface.
RASMapper's Compute XS Interpolation Surface artifact
(Geometry/Cross Section Interpolation Surfaces): the triangulated
surface HEC-RAS builds between each pair of adjacent cross sections. The
stored TIN is returned as one dissolved polygon per XS-to-XS segment,
tagged with the upstream/downstream cross-section ids and the stored
area. Pure h5py read; the group must already exist. Generate it with
RasGeometryCompute.generate_interpolation_surface() when absent.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file.
Returns¶
GeoDataFrame
One row per interpolation segment with columns surface_id (int),
us_xs_id / ds_xs_id (int, when XSIDs present), area
(float, when Areas present), and geometry ((Multi)Polygon of
the segment's TIN triangles). Empty GeoDataFrame when no surface is
stored.
HdfBndry source reference¶
A class for handling boundary-related data from HEC-RAS HDF files.
This class provides methods to extract and process various boundary elements such as boundary condition lines, breaklines, refinement regions, and reference lines/points from HEC-RAS geometry HDF files.
Methods in this class return data primarily as GeoDataFrames, making it easy to work with spatial data in a geospatial context.
Note
This class relies on the HdfBase and HdfUtils classes for some of its functionality. Ensure these classes are available in the same package.
get_bc_external_faces
staticmethod
¶
get_bc_external_faces(hdf_path: Union[str, Path], include_geometry: bool = False, validate_unique_faces: bool = True, *, on_duplicate_ownership: Literal['raise', 'report'] = 'raise') -> Union[pd.DataFrame, gpd.GeoDataFrame]
Return native BC-line-to-external-face associations.
The association is read directly from
Geometry/Boundary Condition Lines/External Faces. It is the
authoritative HEC-RAS native boundary-connectivity result; this method
does not infer faces from proximity to a BC line.
Parameters¶
hdf_path : str or Path
Path to a HEC-RAS geometry or plan HDF containing geometry data.
include_geometry : bool, default False
If True, return a GeoDataFrame whose LineString geometry is
built from only the natively associated faces. Selected face
rows, face-point coordinates, and any intermediate Faces
Perimeter Values are indexed directly when the external-face
endpoints agree with the referenced mesh face. HEC-RAS can retain
stale face IDs after remeshing while writing valid native endpoint
IDs; those rows fall back to endpoint-only segments and are
reported in DataFrame.attrs. The full mesh face network is
never materialized.
validate_unique_faces : bool, default True
Require each mesh-local face to be owned by exactly one native BC
association. Set to False only for diagnostics: all native rows
are returned and duplicate counts are reported in DataFrame.attrs.
This legacy switch retains the original column shape.
on_duplicate_ownership : {"raise", "report"}, default "raise"
With "report", suppress only duplicate-ownership errors, even
when validate_unique_faces=True. Preserve every association
and add duplicate_ownership (bool), owning_bc_line_ids and
owning_bc_line_names (parallel lists in native encounter order,
deduplicated by owner ID/name pair; missing values are None).
Repeated associations to the same owner are also marked.
attrs['duplicate_ownership'] lists duplicate keys and their
owner lists, using mesh_name=None when mesh metadata is unknown.
No files are modified; other validation remains active.
Returns¶
pandas.DataFrame or geopandas.GeoDataFrame
A GeoDataFrame when include_geometry=True, otherwise a
DataFrame. One row per native external-face association with columns
bc_line_id, bc_line_name, mesh_name,
bc_line_type, face_id, fp_start_index,
fp_end_index, station_start, and station_end.
DataFrame.attrs['association_status'] is 'present',
'empty', or 'absent'. An empty-but-present native dataset
is therefore distinguishable from geometry that has not been
preprocessed to create the association.
When include_geometry=True, the result also has a
geometry column and the native HDF projection. The
topology_match_count and topology_mismatch_count metadata
distinguish rows that could and could not reuse mesh-face
perimeter values.
Raises¶
ValueError If the native dataset has an unsupported schema, contains invalid BC/face identifiers, or (by default) assigns one external face more than once.
Notes¶
BC Line ID is the zero-based row index into the adjacent
Attributes dataset. Name, mesh, and type remain nullable when the
Attributes dataset or an optional attribute field is unavailable.
get_bc_lines
staticmethod
¶
get_breaklines
staticmethod
¶
Return 2D mesh area breaklines.
Parameters¶
hdf_path : Path or str Path to the HEC-RAS geometry HDF file.
Returns¶
gpd.GeoDataFrame A GeoDataFrame containing the breaklines.
Notes¶
Read-only: coordinates retain the source CRS and horizontal units.
Missing layers return an empty frame. Records with zero or one point
are skipped and retained in result.attrs["breakline_diagnostics"]
(an empty list when none are skipped), including all-degenerate layers.
Each diagnostic contains the zero-based native bl_id, Name,
decoded source attributes, point_start, point_count,
exclusive point_end, part_start, part_count, and
reason_code="BREAKLINE_TOO_FEW_POINTS". Persist these attrs explicitly
when writing artifacts; tabular writers may not retain them.
Negative, out-of-range or truncated spans and read errors remain hard
errors; no partial layer is returned for corrupted source records.
get_reference_lines
staticmethod
¶
Return the reference lines geometry and attributes.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file. mesh_name : Optional[str], optional Name of the mesh to filter by. Default is None.
Returns¶
gpd.GeoDataFrame A GeoDataFrame containing the reference lines. If mesh_name is provided, returns only lines for that mesh.
get_reference_points
staticmethod
¶
Return the reference points geometry and attributes.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file. mesh_name : Optional[str], optional Name of the mesh to filter by. Default is None.
Returns¶
gpd.GeoDataFrame A GeoDataFrame containing the reference points. If mesh_name is provided, returns only points for that mesh.
get_refinement_regions
staticmethod
¶
Return 2D mesh area refinement regions.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file.
Returns¶
gpd.GeoDataFrame A GeoDataFrame containing the refinement regions. Missing layers return an empty frame; malformed present layers raise an exception.
Notes¶
Multipart Polygon Parts offsets are relative to each feature's
point slice, as HEC-RAS writes them. Legacy global offsets are
accepted only when all of the feature's parts together cover its
point slice exactly; otherwise out-of-range parts raise.
HdfStruc source reference¶
Handles 2D structure geometry data extraction from HEC-RAS HDF files.
This class provides static methods for extracting and analyzing structure geometries and their attributes from HEC-RAS geometry HDF files. All methods are designed to work without class instantiation.
Notes¶
- 1D Structure data should be accessed via the HdfResultsXsec class
- All methods use @standardize_input for consistent file handling
- All methods use @log_call for operation logging
- Returns GeoDataFrames with both geometric and attribute data
get_connection_attachments
staticmethod
¶
get_connection_attachments(hdf_path: str | Path, connections_df: DataFrame | None = None, *, ras_object=None) -> pd.DataFrame
Verify both SA/2D ends from native result cell and face receipts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
str | Path
|
Geometry or result HDF path (str or Path), or a plan number resolved to result HDF by the input decorator. Geometry-only preprocessing normally lacks solver receipts. |
required |
connections_df
|
DataFrame | None
|
Expected Name/From/To inventory. Every expected connection receives a row, including missing native ones. |
None
|
ras_object
|
RasPrj
|
Explicit project context for resolving plan numbers. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with Name, From, To, from_cells, from_faces, to_cells, |
DataFrame
|
to_faces, attachment_verified, reason_code, orientation_verified, |
DataFrame
|
flux_sign_verified, evidence_paths, details, source_hdf and |
DataFrame
|
native_version. IDs are zero-based mesh-local native indices; |
DataFrame
|
repeated segment cell IDs are preserved. No mutation is performed. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
The resolved HDF is absent. |
ValueError
|
Expected identity columns are missing or input cannot be resolved by the HDF decorator. |
OSError
|
Native HDF cannot be read. |
Notes¶
The supported result layout is qualified against HEC-RAS 6.6 native
BaldEagleCrkMulti2D output. Other versions fail closed until qualified.
Storage-area ends, missing/ambiguous identities, absent native datasets,
and invalid cell/face incidence return
CONNECTION_ATTACHMENT_UNVERIFIED. No distance or geometric proximity
establishes attachment. Exact native face-point IDs map to mesh faces;
cells must be active and incident to those faces. Attachment alone does
not qualify hydraulic equivalence, flow sign, or head loss. Orientation
and flux sign remain explicitly unverified by this method.
get_culvert_hydraulics
staticmethod
¶
Extract culvert hydraulic properties from geometry HDF.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file datetime_to_str : bool, optional If True, converts datetime objects to ISO format strings, by default False
Returns¶
pd.DataFrame Culvert hydraulic data with columns: - Structure_ID: unique culvert identifier - Flow_Regime: flow regime setting (e.g., "Pressure Flow", "Open Channel") - Entrance_Coefficient: entrance loss coefficient (Ke) - Exit_Coefficient: exit loss coefficient (Kx) - Scale_Factor: culvert scale factor - Chart: chart selection for culvert analysis - Additional culvert-specific hydraulic attributes
Notes¶
Returns empty DataFrame if no culverts found in geometry file. Includes flow regime setting and all hydraulic coefficients. All byte strings are decoded to UTF-8.
get_geom_structures_attrs
staticmethod
¶
Extracts structure attributes from a HEC-RAS geometry HDF file.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file
Returns¶
pd.DataFrame DataFrame containing structure attributes from the Geometry/Structures group. Returns empty DataFrame if no structures are found.
Notes¶
Attributes are extracted from the HDF5 group 'Geometry/Structures'. All byte strings in attributes are automatically decoded to UTF-8.
get_sa2d_breach_info
staticmethod
¶
Get information about which SA/2D connection structures have breach capability.
Parameters¶
hdf_path : Path Path to HEC-RAS plan HDF file or plan number ras_object : RasPrj, optional RAS object for multi-project workflows
Returns¶
pd.DataFrame DataFrame with columns: - structure: Structure name - has_breach: Boolean, True if "Breaching Variables" dataset exists - breach_at_time: Time of breach initiation (if available) - breach_at_date: Date/time of breach (if available) - centerline_breach: Centerline station for breach (if available)
Examples¶
>>> info = HdfStruc.get_sa2d_breach_info("02")
>>> breach_dams = info[info['has_breach']]['structure'].tolist()
>>> print(f"Breach structures: {breach_dams}")
Notes¶
- Returns empty DataFrame if no SA/2D connections found
- Only structures with "Breaching Variables" have has_breach=True
- Use in conjunction with RasBreach for reading/modifying breach parameters
get_storage_area_polygons
staticmethod
¶
Extract storage area polygon geometry from HEC-RAS HDF file.
Works on both geometry HDF (.g##.hdf) and plan HDF (.p##.hdf) —
both contain identical /Geometry/Storage Areas/ data.
Pass a geometry number string (e.g. "12") to resolve via
geom_df; pass a full Path object to use directly.
Parameters¶
hdf_path : Path Path to geometry or plan HDF file (str, Path, or geometry number). ras_object : RasPrj, optional RAS object for multi-project workflows.
Returns¶
GeoDataFrame GeoDataFrame with columns: - Name (str): Storage area name - geometry (Polygon): Perimeter polygon in project CRS - avg_area (float): Average surface area from HDF attributes - min_elev (float): Minimum elevation from HDF attributes - mode (str): Storage area mode
Returns empty GeoDataFrame if no storage areas found in file.
Notes¶
Multi-part polygons (rings/holes) are fully supported via the
Polygon Parts dataset; the first ring is the exterior, subsequent
rings are interiors (holes).
The available project CRS is attached without transforming coordinates;
the CRS remains unset when no projection can be resolved.
get_structures
staticmethod
¶
Extracts structure data from a HEC-RAS geometry HDF5 file.
Missing structure layers return an empty frame. A present empty group,
or one containing only an empty Property Tables subgroup, returns
a typed empty GeoDataFrame preserving source CRS/group attributes with
attrs["structure_status"]="empty_placeholder". Populated property
tables, unknown child layouts, missing required datasets in nonempty
layers and read errors are logged and raised. This is read-only; native
coordinate/elevation units are unchanged.
Parameters¶
hdf_path : Path or str Path to the HEC-RAS geometry HDF5 file datetime_to_str : bool, optional If True, converts datetime objects to ISO format strings, by default False
Returns¶
GeoDataFrame Structure data with columns: - Structure ID: unique identifier - Geometry: LineString of structure centerline, or a MultiLineString when the stored Centerline Info Part Count is greater than 1 (one line per stored part, no connecting segment between parts), or None when the structure stores an empty (zero-point) centerline - Various attribute columns from the HDF file - Profile_Data: list of station/elevation dictionaries - Bridge coefficient attributes (if present) - Table info attributes (if present)
Notes¶
- Group-level attributes are stored in GeoDataFrame.attrs['group_attributes']
- Invalid centerline geometry raises an exception. A zero-point centerline (Centerline Info Point Count 0, as HEC-RAS stores for some lateral structures) is a valid empty range and yields None geometry, the missing-geometry convention of the other hdf readers; its start index and Parts must still be in range.
- Centerline Parts offsets are relative to each structure's point slice; legacy global offsets are accepted only when all parts together cover that slice exactly. Single-part centerlines are unchanged LineStrings.
- All byte strings are decoded to UTF-8
- CRS is preserved from the source file
- Public Structure IDs remain one-based. Bridge coefficients are joined by their native zero-based Attributes row IDs, not the display IDs. Duplicate or out-of-range coefficient IDs raise ValueError.
list_sa2d_connections
staticmethod
¶
List all SA/2D Area Connection structures in HDF results file.
This includes both breach structures and regular SA/2D connections with time series results.
Parameters¶
hdf_path : Path Path to HEC-RAS plan HDF file or plan number ras_object : RasPrj, optional RAS object for multi-project workflows
Returns¶
List[str] Names of all SA/2D Area Connection structures with time series results. Returns empty list if no SA/2D connections found.
Examples¶
structures = HdfStruc.list_sa2d_connections("02") print(structures) ['Laxton_Dam', 'PineCreek#1_Dam', 'US_2DArea_Res2']
Notes¶
- Not all structures returned have breach capability
- Use get_sa2d_breach_info() to determine which have "Breaching Variables"
- Empty list returned if no SA/2D connections in results
HdfStorageArea source reference¶
Static helpers for HEC-RAS storage-area HDF data.
Methods accept geometry HDF paths directly or the flexible geometry inputs
supported by standardize_input(file_type="geom_hdf").
compute_stage_storage_curve
staticmethod
¶
compute_stage_storage_curve(hdf_path: Path, sa_name: str, elevation_interval: float = 5.0, min_elevation: Optional[float] = None, max_elevation: Optional[float] = None, progress_callback: Optional[Callable[[int, int, str], None]] = None, *, ras_object=None) -> Tuple[pd.DataFrame, Dict[str, Any]]
Compute a stage-storage curve from the storage-area terrain footprint.
Parameters¶
hdf_path : Path
Geometry HDF file path.
sa_name : str
Storage area name.
elevation_interval : float
Elevation step between volume samples (project vertical units).
min_elevation, max_elevation : float, optional
Override the automatic range derived from terrain statistics.
progress_callback : callable, optional
(current, total, message) progress reporter.
ras_object : RasPrj, optional
RAS object for multi-project workflows.
Returns¶
Tuple[pandas.DataFrame, dict]
DataFrame columns are stage and storage. storage is in
acre-feet for US Customary projects, cubic meters for SI projects,
or cubic project units when the HDF unit system is unknown.
Metadata is also copied to df.attrs.
compute_volume_below_elevation
staticmethod
¶
Compute volume below a water-surface elevation inside a storage polygon.
The returned volume is in cubic project units, matching the horizontal and vertical units of the terrain raster.
get_storage_area_for_breach_structure
staticmethod
¶
get_storage_area_for_breach_structure(hdf_path: Path, breach_structure_id: str, *, ras_object=None) -> Optional[str]
Return the upstream SA/2D area associated with a structure.
If no upstream SA/2D value exists, the downstream SA/2D field is used as a fallback because many lateral connections store the storage area there.
get_storage_area_names
staticmethod
¶
Return storage area names from a geometry HDF file.
Parameters¶
hdf_path : Path Path to a HEC-RAS geometry HDF file. ras_object : RasPrj, optional RAS object for multi-project workflows.
get_storage_area_properties
staticmethod
¶
get_storage_area_properties(hdf_path: Path, sa_name: str, *, ras_object=None) -> Dict[str, Any]
Extract attributes for a storage area from a geometry HDF file.
The returned dictionary includes the original HDF field names and common snake_case aliases where the fields are present.
get_terrain_path_from_geom_hdf
staticmethod
¶
Resolve the terrain path referenced by a geometry HDF file.
HEC-RAS stores the terrain HDF path in the /Geometry attributes.
When a companion .vrt exists, this returns the VRT so rasterio can
sample the underlying terrain rasters directly.
get_volume_elevation_curve
staticmethod
¶
Read the HEC-RAS pre-computed elevation-volume curve from a geometry HDF.
Parameters¶
hdf_path : Path
Path to a HEC-RAS geometry HDF file.
sa_name : str
Storage area name (e.g. "190").
ras_object : RasPrj, optional
RAS object for multi-project workflows.
Returns¶
pd.DataFrame
Columns elevation and volume. Volume is in acre-feet as
stored by HEC-RAS. Returns an empty DataFrame if the storage area
or curve data is not found.
HdfStruc1D source reference¶
Extract 1D structure results from HEC-RAS HDF files.
This class provides static methods for extracting max headwater, tailwater, and flow values from 1D hydraulic structures (bridges, culverts, inline weirs) in HEC-RAS plan HDF files.
All methods are static and designed to be used without instantiation.
Notes¶
- Direct unsteady family results take precedence over cross-section estimates.
- Structure Variables, Bridge Variables and Culvert Variables use Variable_Unit.
- Legacy BR U/BR D and steady flanking cross-section behavior is retained.
get_structure_max_values
staticmethod
¶
get_structure_max_values(hdf_path: Path, river: str, reach: str, rs: str, *, ras_object=None) -> Dict[str, Any]
Extract maximum headwater, tailwater, and flow values for a 1D structure.
This method searches for structure results in the HDF file and extracts the maximum values needed for HTAB optimization. Direct unsteady inline, bridge, culvert and pump results take precedence over legacy cross-section output. Stage HW, Stage TW and Total Flow (inline) or Flow (other families) are selected by their stored Variable_Unit labels, in native units.
Parameters¶
hdf_path : Path Path to HEC-RAS plan HDF file or plan number river : str River name (case-sensitive) reach : str Reach name (case-sensitive) rs : str River station of the structure (as string, e.g., "5600") For a pumping station, use its exact Name with river=reach="". ras_object : RasPrj, optional RAS object for multi-project workflows
Returns¶
Dict[str, Any] Dictionary containing: - 'max_hw': Maximum headwater (water surface at upstream face) - 'max_tw': Maximum tailwater (water surface at downstream face) - 'max_flow': Maximum flow through structure - 'hw_source': Source location for headwater data - 'tw_source': Source location for tailwater data - 'flow_source': Source location for flow data - 'found': True if structure results were found
Raises¶
FileNotFoundError If HDF file doesn't exist ValueError If structure not found in results
Examples¶
max_vals = HdfStruc1D.get_structure_max_values( ... "Muncie.p01.hdf", "White River", "Muncie", "5600" ... ) print(f"Max HW: {max_vals['max_hw']:.2f}") print(f"Max Flow: {max_vals['max_flow']:.0f}")
Notes¶
- For bridges: BR U = headwater (upstream face), BR D = tailwater (downstream)
- Direct family identities require an exact, unique geometry match; no nearest-station matching or estimated TW is used for these results.
- Missing/all-NaN direct quantities remain None, with no source assigned.
- Malformed family identity, time/column layout or labels raises ValueError.
- Legacy cross-section fallback can search nearby BR U/BR D markers
- For unsteady results, uses time series max values
- For steady results, uses max across all profiles
list_1d_structures
staticmethod
¶
List all 1D structures with results in HDF file.
Parameters¶
hdf_path : Path Path to HEC-RAS plan HDF file or plan number ras_object : RasPrj, optional RAS object for multi-project workflows
Returns¶
pd.DataFrame DataFrame with columns: - River: River name - Reach: Reach name - RS: River station; pump Name for pumping stations - Name: Cross section name (may include BR U/BR D markers) - Type: Structure type indicator (Bridge, Culvert, etc.) if detectable
Notes¶
Unsteady Base Output Inline Structures, Bridges, Culverts and Pumping Stations are linked to exact, unique geometry identities and validated primary datasets/Variable_Unit labels. Pumps have empty River/Reach and use their Name as RS (pass these values to get_structure_max_values). Direct family records take precedence over duplicate legacy BR U/BR D markers or generic Structures records. Malformed direct layouts raise ValueError; an empty inventory retains the five documented columns.
HdfHydraulicTables source reference¶
Extract hydraulic property tables (HTAB) from HEC-RAS geometry HDF files.
All methods are static and designed to be used without instantiation.
Property tables provide preprocessed hydraulic properties (area, conveyance, wetted perimeter, etc.) as functions of elevation for cross sections and structures.
get_all_xs_htabs
staticmethod
¶
Extract hydraulic property tables for ALL cross sections in geometry.
Batch extraction of property tables for all cross sections, returned as a dictionary keyed by (river, reach, rs) tuples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path]
|
Path to geometry HDF file (.g##.hdf) |
required |
Returns:
| Type | Description |
|---|---|
Dict[Tuple[str, str, str], DataFrame]
|
Dictionary mapping (river, reach, rs) tuples to property table DataFrames |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If HDF file doesn't exist |
IOError
|
If HDF read fails |
Example
from ras_commander import HdfHydraulicTables from pathlib import Path
Extract all property tables¶
hdf_file = Path("BaldEagle.g01.hdf") all_htabs = HdfHydraulicTables.get_all_xs_htabs(hdf_file)
print(f"Extracted {len(all_htabs)} property tables")
Access specific cross section¶
htab = all_htabs[("Bald Eagle", "Loc Hav", "1")]
Calculate statistics across all cross sections¶
max_areas = {} for (river, reach, rs), htab in all_htabs.items(): ... max_area = htab['Area_Total'].max() ... max_areas[rs] = max_area
Find cross section with largest area¶
largest_rs = max(max_areas, key=max_areas.get) print(f"Largest XS: RS {largest_rs} with area {max_areas[largest_rs]:.1f} sq ft")
Notes
- More efficient than calling get_xs_htab() repeatedly
- Returns all cross sections in single HDF file read
- Dictionary keys are (river, reach, rs) tuples for easy lookup
get_xs_htab
staticmethod
¶
Extract hydraulic property table (HTAB) for a cross section.
Reads preprocessed hydraulic properties from geometry HDF file, including area, conveyance, wetted perimeter, top width, and other properties as functions of elevation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path]
|
Path to geometry HDF file (.g##.hdf) |
required |
river
|
str
|
River name (case-sensitive) |
required |
reach
|
str
|
Reach name (case-sensitive) |
required |
rs
|
str
|
River station (as string, e.g., "1") |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Property table with columns: - Elevation: Water surface elevation (ft or m) - Area_LOB: Left overbank area (sq ft or sq m) - Area_Chan: Channel area - Area_ROB: Right overbank area - Area_Total: Total flow area (computed) - Area_Ineff_LOB: Ineffective area left overbank - Area_Ineff_Chan: Ineffective area channel - Area_Ineff_ROB: Ineffective area right overbank - Conv_LOB: Conveyance left overbank (cfs or cms) - Conv_Chan: Conveyance channel - Conv_ROB: Conveyance right overbank - Conveyance_Total: Total conveyance (computed) - WP_LOB: Wetted perimeter left overbank (ft or m) - WP_Chan: Wetted perimeter channel - WP_ROB: Wetted perimeter right overbank - Wetted_Perimeter_Total: Total wetted perimeter (computed) - Mann_N_LOB: Manning's n left overbank - Mann_N_Chan: Manning's n channel - Mann_N_ROB: Manning's n right overbank - Top_Width: Total top width (ft or m) - Top_Width_LOB: Top width left overbank - Top_Width_Chan: Top width channel - Top_Width_ROB: Top width right overbank - Alpha: Velocity distribution coefficient - Storage_Area: Storage area (sq ft or sq m) - Beta: Momentum coefficient |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If HDF file doesn't exist |
ValueError
|
If cross section not found |
IOError
|
If HDF read fails |
Example
from ras_commander import HdfHydraulicTables from pathlib import Path import matplotlib.pyplot as plt
Extract property table¶
hdf_file = Path("BaldEagle.g01.hdf") htab = HdfHydraulicTables.get_xs_htab(hdf_file, "Bald Eagle", "Loc Hav", "1")
print(f"Property table: {len(htab)} elevations") print(f"Elevation range: {htab['Elevation'].min():.2f} to {htab['Elevation'].max():.2f}")
Plot area-elevation curve¶
plt.figure(figsize=(10, 6)) plt.plot(htab['Area_Total'], htab['Elevation'], 'b-', linewidth=2) plt.xlabel('Flow Area (sq ft)') plt.ylabel('Elevation (ft)') plt.title('Cross Section Area-Elevation Curve') plt.grid(True, alpha=0.3) plt.show()
Calculate hydraulic radius¶
htab['Hydraulic_Radius'] = htab['Area_Total'] / htab['Wetted_Perimeter_Total'] print(f"Max hydraulic radius: {htab['Hydraulic_Radius'].max():.2f} ft")
Notes
- Property tables are in GEOMETRY HDF (.g##.hdf), not plan HDF
- Tables computed during geometry preprocessing in HEC-RAS
- Use for rating curves, stage-discharge, hydraulic analysis
- Total values (area, conveyance, WP) computed from LOB + Chan + ROB
- See HdfXsec.get_cross_sections() for XS geometry
HdfResultsPlan source reference¶
Handles extraction of results data from HEC-RAS plan HDF files.
This class provides static methods for accessing and analyzing
- Unsteady flow results
- Volume accounting data
- Runtime statistics
- Reference line/point time series outputs
All methods use
- @standardize_input decorator for consistent file path handling
- @log_call decorator for operation logging
- HdfUtils class for common HDF operations
Note
No instantiation required - all methods are static.
get_compute_messages
staticmethod
¶
Read computation messages from HDF file with fallback to .txt file.
Extracts computation messages from the HDF Results/Summary structure. This includes detailed information about the computation process, warnings, errors, convergence information, and performance metrics.
If HDF path not found, falls back to .txt file extraction using RasControl.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to plan HDF file (or plan number string if using standardize_input decorator, which resolves to HDF path) |
required |
Returns:
| Type | Description |
|---|---|
str
|
String containing computation messages, or empty string if unavailable |
Example
from ras_commander import init_ras_project, HdfResultsPlan init_ras_project(r"/path/to/project", "6.5") msgs = HdfResultsPlan.get_compute_messages("01") print(msgs)
Note
Modern HEC-RAS versions (6.x+) store computation messages in HDF: /Results/Summary/Compute Messages (text)
Older versions (pre-6.x) use .txt files which are accessed via fallback to RasControl.get_comp_msgs()
Function naming follows HDF structure conventions (get_compute_messages) vs RasControl legacy naming (get_comp_msgs) to reflect technological lineage.
get_compute_messages_hdf_only
staticmethod
¶
Extract compute messages from HDF file or .txt files (no RasControl fallback).
This method reads computation messages without using RasControl/COM interface, making it suitable for automated workflows where COM locking is problematic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to plan HDF file (or plan number string if using standardize_input decorator, which resolves to HDF path) |
required |
Returns:
| Type | Description |
|---|---|
str
|
Compute messages text, or empty string if unavailable |
Example
from ras_commander import init_ras_project, HdfResultsPlan init_ras_project(r"/path/to/project", "6.5") msgs = HdfResultsPlan.get_compute_messages_hdf_only("01") print(msgs)
Note
Falls back to .txt files on disk but NEVER uses RasControl. Order of attempts: 1. HDF Results/Summary/Compute Messages (text) 2. {plan_file}.computeMsgs.txt (HEC-RAS 6.x+) 3. {plan_file}.comp_msgs.txt (HEC-RAS 5.x)
get_reference_summary
staticmethod
¶
Summarize reference line or point results from their stored time series.
HEC-RAS writes no reference summary table: Base Output/Summary
Output holds only groups such as 2D Flow Areas, Cross
Sections, Storage Areas and Pipe Networks, and no
Reference Lines/Reference Points group (checked on 6.3.1, 6.6,
7.0 and 7.0.1 plans). Reference results are stored only as time series
under Base Output/Unsteady Time Series/Reference Lines|Points
(Name = "<name>|<2D area>" plus one (time, feature) dataset
per variable). The per-area copies under 2D Flow Areas/<area>/
Reference Lines|Points hold a subset of the same variables with
identical values, so they are not read.
This method derives the summary from exactly the series
:meth:get_reference_timeseries returns (the same native-capable
reader, Base Output time axis and variable selection: numeric
(time, feature) datasets except names containing Unit,
Index or String, so e.g. Depth Unit is omitted). For every
reference feature and variable it reports the largest stored value
(Statistic='Maximum') and the smallest ('Minimum'), each with
the stored timestamp of its first occurrence. Values are stored
samples, never interpolated; a peak between output times is not
represented. Non-finite samples are ignored; a series with no finite
sample gets NaN and NaT.
Note
The input decorator accepts keyword-only ras_object for
project-number resolution; it is not in the underlying signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to HEC-RAS plan HDF file |
required |
reftype
|
str
|
Type of reference data ('lines' or 'points') |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per feature, variable and statistic, in stored feature order, then stored variable order, then Maximum before Minimum, with columns:
Returns an empty DataFrame when the plan has no global reference time-series group of that type, or when an error is caught (including an invalid reftype); inspect log diagnostics. |
get_reference_timeseries
staticmethod
¶
Get reference-line or reference-point time series as a tidy DataFrame.
Modern HEC-RAS HDF files store a Name vector plus shared
(time, feature) matrices such as Flow, Velocity, and Water Surface.
This compatibility method delegates schema handling to
:class:HdfResultsXsec and converts its native xarray Dataset to one
row per time/feature pair. It therefore supports all numeric variables
present in the HDF instead of assuming one dataset per feature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to HEC-RAS plan HDF file |
required |
reftype
|
str
|
Type of reference data ('lines' or 'points') |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Tidy frame containing time, reference ID/name, mesh name, and every numeric native result variable. Returns an empty frame when the requested reference output is absent or an error is caught, including an invalid reftype. Inspect log diagnostics; an empty result is not a zero-valued hydrograph. |
get_runtime_data
staticmethod
¶
Extract detailed runtime and computational performance metrics from HDF file.
Note
The input decorator accepts keyword-only ras_object for
project-number resolution; it is not in the underlying signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to HEC-RAS plan HDF file |
required |
Returns:
| Type | Description |
|---|---|
Optional[DataFrame]
|
DataFrame containing runtime statistics or None if data cannot be extracted |
Notes
- Times are reported in multiple units (ms, s, hours)
- Compute speeds are calculated as simulation-time/compute-time ratios
- Process times include: geometry, preprocessing, event conditions, and unsteady flow computations
get_steady_info
staticmethod
¶
Get steady flow attributes and metadata from HEC-RAS HDF plan file.
Note
The input decorator accepts keyword-only ras_object for
project-number resolution; it is not in the underlying signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to HEC-RAS plan HDF file |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing steady flow attributes including: - Program Name - Program Version - Type of Run - Run Time Window - Solution status - And other metadata attributes |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified HDF file is not found |
KeyError
|
If steady state results are not found |
ValueError
|
If the plan is not a steady state plan |
Example
info_df = HdfResultsPlan.get_steady_info('01') print(info_df['Solution'].values[0]) 'Steady Finished Successfully'
get_steady_profile_names
staticmethod
¶
Extract profile names from steady state results.
Note
The input decorator accepts keyword-only ras_object for
project-number resolution; it is not in the underlying signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to HEC-RAS plan HDF file |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
List of profile names (e.g., ['50Pct', '10Pct', '1Pct']) |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified HDF file is not found |
KeyError
|
If steady state results or profile names are not found |
ValueError
|
If the plan is not a steady state plan |
Example
from ras_commander import HdfResultsPlan, init_ras_project init_ras_project(Path('/path/to/project'), '6.6') profiles = HdfResultsPlan.get_steady_profile_names('01') print(profiles) ['50Pct', '20Pct', '10Pct', '4Pct', '2Pct', '1Pct', '0.2Pct']
get_steady_results
staticmethod
¶
Extract steady state profile results from HEC-RAS HDF file.
This function extracts all key hydraulic results for steady state profiles in a single call, matching the schema of RasControl.get_steady_results() for consistency between COM and HDF-based workflows.
Parameters¶
hdf_path : Path Path to HEC-RAS plan HDF file (.p##.hdf)
Returns¶
pd.DataFrame Steady state results with one row per cross-section per profile.
**Schema:**
+----------------+----------+---------------------------------------+
| Column | Type | Description |
+================+==========+=======================================+
| river | str | River name |
+----------------+----------+---------------------------------------+
| reach | str | Reach name |
+----------------+----------+---------------------------------------+
| node_id | str | Cross section river station |
+----------------+----------+---------------------------------------+
| profile | str | Profile name (e.g., "PF 1", "1Pct") |
+----------------+----------+---------------------------------------+
| wsel | float | Water surface elevation (ft or m) |
+----------------+----------+---------------------------------------+
| velocity | float | Channel velocity (ft/s or m/s) |
+----------------+----------+---------------------------------------+
| flow | float | Total flow (cfs or cms) |
+----------------+----------+---------------------------------------+
| froude | float | Channel Froude number (dimensionless) |
+----------------+----------+---------------------------------------+
| energy | float | Energy grade elevation (ft or m) |
+----------------+----------+---------------------------------------+
| max_depth | float | Maximum total depth (ft or m) |
+----------------+----------+---------------------------------------+
| hydraulic_depth| float | Channel hydraulic depth (ft or m) |
+----------------+----------+---------------------------------------+
| channel_length | float | Downstream channel reach length |
+----------------+----------+---------------------------------------+
| min_ch_el | float | Minimum channel elevation (ft or m) |
+----------------+----------+---------------------------------------+
| top_width | float | Total top width (ft or m) |
+----------------+----------+---------------------------------------+
| area | float | Total flow area (sq ft or sq m) |
+----------------+----------+---------------------------------------+
| eg_slope | float | Energy grade slope (ft/ft or m/m) |
+----------------+----------+---------------------------------------+
| friction_slope | float | Friction slope (ft/ft or m/m) |
+----------------+----------+---------------------------------------+
Raises¶
ValueError If the HDF file does not contain steady state results.
Notes¶
Comparison with RasControl.get_steady_results():
This HDF-based method provides the same schema as the COM-based RasControl.get_steady_results(), plus channel reach length and additional hydraulic variables (hydraulic_depth, top_width, area, eg_slope, friction_slope) that are readily available in the HDF file.
max_depth is read from HEC-RAS Maximum Depth Total. Older HDFs
without that dataset fall back to Hydraulic Depth Channel and
record the selected dataset in df.attrs['max_depth_source'].
energy uses the primary Cross Sections/Energy Grade dataset, with
Additional Variables/Energy Grade as a fallback only when the primary
dataset is absent. Optional profile outputs, including froude and
min_ch_el, remain NaN when their datasets are not stored. No Froude
number or minimum channel elevation is inferred from other quantities.
df.attrs['column_sources'] maps optional profile-output columns to
their selected HDF dataset paths, or None when no source is available.
df.attrs['unavailable_columns'] lists those columns with no source;
one summarized warning names the missing datasets. A stored array that
contains only NaNs still has a source and is not listed as unavailable.
Existing max_depth_source and channel_length_source attributes
are retained. Present datasets with incorrect shapes raise ValueError.
Performance:
This method is significantly faster than COM-based extraction since it reads directly from the HDF file without opening HEC-RAS.
Examples¶
Extract all steady results:
from ras_commander import init_ras_project, HdfResultsPlan init_ras_project("/path/to/project", "7.0") df = HdfResultsPlan.get_steady_results("01") df.to_csv('steady_results.csv', index=False)
Filter by profile:
profile_1 = df[df['profile'] == 'PF 1']
Plot water surface profile:
import matplotlib.pyplot as plt plt.plot(profile_1['node_id'].astype(float), profile_1['wsel']) plt.xlabel('Station') plt.ylabel('Water Surface Elevation (ft)')
See Also¶
RasControl.get_steady_results : COM-based steady results extraction is_steady_plan : Check if plan contains steady results get_steady_profile_names : Get list of profile names
get_steady_wse
staticmethod
¶
get_steady_wse(hdf_path: Path, profile_index: Optional[int] = None, profile_name: Optional[str] = None) -> pd.DataFrame
Extract water surface elevation (WSE) data for steady state profiles.
Note
The input decorator accepts keyword-only ras_object for
project-number resolution; it is not in the underlying signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to HEC-RAS plan HDF file |
required |
profile_index
|
int
|
Index of profile to extract (0-based). If None, extracts all profiles. |
None
|
profile_name
|
str
|
Name of profile to extract (e.g., '1Pct'). If specified, overrides profile_index. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing WSE data with columns: - River: River name - Reach: Reach name - Station: Cross section river station - Profile: Profile name (if multiple profiles) - WSE: Water surface elevation (ft) |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified HDF file is not found |
KeyError
|
If steady state results or WSE data are not found |
ValueError
|
If profile_index or profile_name is invalid |
get_unsteady_info
staticmethod
¶
Get unsteady attributes from a HEC-RAS HDF plan file.
Note
The input decorator accepts keyword-only ras_object for
project-number resolution; it is not in the underlying signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS plan HDF file. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A DataFrame containing the decoded unsteady attributes. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified HDF file is not found. |
KeyError
|
If the "Results/Unsteady" group is not found in the HDF file. |
get_unsteady_summary
staticmethod
¶
Get results unsteady summary attributes from a HEC-RAS HDF plan file.
Note
The input decorator accepts keyword-only ras_object for
project-number resolution; it is not in the underlying signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS plan HDF file. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A DataFrame containing the decoded results unsteady summary attributes. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified HDF file is not found. |
KeyError
|
If the "Results/Unsteady/Summary" group is not found in the HDF file. |
get_volume_accounting
staticmethod
¶
Get volume accounting attributes from a HEC-RAS HDF plan file.
Note
The input decorator accepts keyword-only ras_object for
project-number resolution; it is not in the underlying signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS plan HDF file. |
required |
Returns:
| Type | Description |
|---|---|
Optional[DataFrame]
|
DataFrame containing the decoded volume accounting attributes, or None if the group is not found. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified HDF file is not found. |
is_steady_plan
staticmethod
¶
Check if HDF file contains steady state results.
Note
The input decorator accepts keyword-only ras_object for
project-number resolution; it is not in the underlying signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to HEC-RAS plan HDF file |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the HDF contains steady state results, False otherwise |
Notes
- Checks for existence of Results/Steady group
- Does not guarantee results are complete or valid
list_steady_variables
staticmethod
¶
List all available steady state variables in the HDF file.
This is a diagnostic function useful for exploring what data is available in a particular steady state results file.
Parameters¶
hdf_path : Path Path to HEC-RAS plan HDF file
Returns¶
Dict[str, List[str]] Dictionary with keys: - 'cross_sections': Variables in Cross Sections group - 'additional': Variables in Additional Variables group - 'structures': Variables in Structures group (if present)
Example¶
vars = HdfResultsPlan.list_steady_variables('01') print(vars['additional']) ['Area Flow Channel', 'Velocity Channel', 'Top Width Total', ...]
HdfResultsMesh source reference¶
Handles mesh-related results from HEC-RAS HDF files.
Provides methods to extract and analyze: - Mesh summary outputs - Timeseries data - Water surface elevations - Velocities - Error metrics
Works with HEC-RAS 6.0+ plan HDF files.
export_depth_rasters_at_times
staticmethod
¶
export_depth_rasters_at_times(hdf_path: Path, timestamps: Union[str, Timestamp, List[Union[str, Timestamp]]], output_dir: Union[str, Path], mesh_name: Optional[str] = None, geom_hdf_path: Optional[Union[str, Path]] = None, resolution: Optional[float] = None, max_dimension: int = 600, method: str = 'nearest', nodata: float = -9999.0) -> Dict[str, Path]
Export per-timestep 2D depth rasters from a computed plan HDF.
The method reads cell-centered HEC-RAS results through the plan HDF. If the Depth dataset is not present, it computes depth as Water Surface minus Cells Minimum Elevation and clips negative values to zero. This is useful when RAS Mapper stored-map export cannot create GeoTIFFs for every requested timestep but the plan HDF contains the needed hydraulic results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Plan HDF path. |
required |
timestamps
|
Union[str, Timestamp, List[Union[str, Timestamp]]]
|
One or more simulation timestamps. Strings may use
RAS format such as |
required |
output_dir
|
Union[str, Path]
|
Folder where GeoTIFFs will be written. |
required |
mesh_name
|
Optional[str]
|
2D flow area name. Required when the plan has multiple 2D flow areas. |
None
|
geom_hdf_path
|
Optional[Union[str, Path]]
|
Optional geometry HDF path. Defaults to |
None
|
resolution
|
Optional[float]
|
Optional output cell size in the model CRS units. If
omitted, a resolution is chosen so the longest raster dimension
is approximately |
None
|
max_dimension
|
int
|
Target maximum raster width/height when
|
600
|
method
|
str
|
Rasterization method. |
'nearest'
|
nodata
|
float
|
GeoTIFF nodata value. |
-9999.0
|
Returns:
| Type | Description |
|---|---|
Dict[str, Path]
|
Mapping from the original timestamp label to the |
Dict[str, Path]
|
exported GeoTIFF path. |
export_max_depth_raster
staticmethod
¶
export_max_depth_raster(hdf_path: Path, output_path: Union[str, Path] = None, resolution_m: float = 3.0, crs=None, method: str = 'linear', nodata: float = -9999.0) -> Path
Export maximum depth as a Cloud-Optimized GeoTIFF raster.
Attribution: Implementation pattern derived from ras-agent (https://github.com/gheistand/ras-agent) by Glenn Heistand / CHAMP — Illinois State Water Survey. See results.py:cells_to_raster().
Reads cell centers and max depth from the HDF file, interpolates onto a regular grid using a SciPy interpolator evaluated in bounded blocks, and writes a COG in windows with LZW compression and overviews. Output values and interpolation queries are bounded by the window size; the input mesh and GDAL write buffers still consume memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HDF file. |
required |
output_path
|
Union[str, Path]
|
Output GeoTIFF path. If None, writes to a temporary file. |
None
|
resolution_m
|
float
|
Grid cell size in CRS units (default 3.0). |
3.0
|
crs
|
CRS or str
|
Output CRS. If None, uses the CRS from the HDF file. |
None
|
method
|
str
|
Interpolation method for griddata (default "linear"). |
'linear'
|
nodata
|
float
|
Nodata value for the raster (default -9999.0). |
-9999.0
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the written GeoTIFF file. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no depth rows exist or no rows have both a finite maximum depth and finite point coordinates. |
get_boundary_conditions_timeseries
staticmethod
¶
Get timeseries output for all boundary conditions as a single combined xarray Dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HDF file. |
required |
Returns:
| Type | Description |
|---|---|
Dataset
|
Multiple variables with shared structure. Use Dataset when returning MULTIPLE variables that share common dimensions. Data variables: - stage: Water surface elevation at each BC - flow: Flow at each BC - flow_per_face: Flow distribution across faces (3D) - stage_per_face: Stage distribution across faces (3D) Dimensions: - time: Timestamps - bc_name: Boundary condition names - face_id: Face IDs (for per-face variables) Coordinates:
Metadata from HDF attributes (BC types, locations, etc.).
Ordinary metadata retains its legacy lowercase spelling,
including spaces. HEC-RAS When to use: Boundary condition analysis across model. All BCs combined in single Dataset for easy comparison. |
get_flood_extent_polygon
staticmethod
¶
get_flood_extent_polygon(plan_number: str, profile: str = 'Max', ras_object=None, ras_version: str = None, timeout: int = 600) -> gpd.GeoDataFrame
Generate the canonical RASMapper inundation boundary polygon via RasProcess.exe StoreAllMaps.
This uses the same algorithm RASMapper uses in the GUI to produce inundation boundary shapefiles — the authoritative HEC-RAS flood extent. Requires an initialized ras-commander project and HEC-RAS installed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plan_number
|
str
|
Plan number (e.g., "01"). |
required |
profile
|
str
|
Profile to map — "Max", "Min", or timestamp string. |
'Max'
|
ras_object
|
RasPrj
|
Optional RAS project object. |
None
|
ras_version
|
str
|
Optional HEC-RAS version for RasProcess.exe. |
None
|
timeout
|
int
|
RasProcess.exe timeout in seconds (default 600). |
600
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
Inundation boundary polygon(s) read from the shapefile generated by RASMapper. Returns empty GeoDataFrame if generation fails or no flood extent is produced. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If RasProcess.exe or plan HDF not found. |
RuntimeError
|
If RasProcess.exe command fails. |
Example
from ras_commander import init_ras_project from ras_commander.hdf import HdfResultsMesh init_ras_project("/path/to/project", "7.0") flood_gdf = HdfResultsMesh.get_flood_extent_polygon("01")
get_mesh_cells_timeseries
staticmethod
¶
get_mesh_cells_timeseries(hdf_path: Path, mesh_names: Optional[Union[str, List[str]]] = None, var: Optional[str] = None, truncate: bool = False, ras_object: Optional[Any] = None, include_ghost_cells: bool = False) -> Dict[str, xr.Dataset]
Get mesh cells timeseries output.
With var=None, discover actual numeric cell and face datasets using
authoritative stored Location (Cells/Cell/Faces) or the
exact-name stable-core legacy schema when Location is absent (see
get_mesh_timeseries), matching geometry counts and Base Output Time.
Time-only diagnostics are available by explicit selection. This can return more variables
and use more memory than a fixed convenience list; select var for
focused reads. Unqualified datasets are skipped with diagnostics.
An explicitly selected malformed dataset raises ValueError. No times
are invented for one-row outputs. Hydraulic depth remains distinct
from Depth. Ghost-cell defaults and flags apply after validation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to HDF file |
required |
mesh_names
|
str | List[str]
|
Mesh name(s). If None, processes all meshes |
None
|
var
|
str
|
Variable name. If None, retrieves all variables |
None
|
truncate
|
bool
|
Remove trailing zeros if True |
False
|
ras_object
|
Any
|
RAS object if available |
None
|
include_ghost_cells
|
bool
|
Keep the ghost-cell columns HEC-RAS
writes after the physical cells (default False). Cell
variables always carry an |
False
|
Returns:
| Type | Description |
|---|---|
Dict[str, Dataset]
|
Multiple mesh areas with multiple variables. Use Dict[str, Dataset] when extracting data for MULTIPLE mesh areas. Structure: { 'Mesh1': Dataset(vars=['Water Surface', 'Velocity', ...]), 'Mesh2': Dataset(vars=['Water Surface', 'Velocity', ...]), ... } Each Dataset contains: Data variables: All cell/face variables for that mesh Dimensions: time, cell_id/face_id (specific to each mesh) Attributes: mesh_name, start_time When to use: Model-wide analysis across multiple mesh areas. For single mesh, use get_mesh_faces_timeseries() → Dataset. For single variable, use get_mesh_timeseries() → DataArray. Why dictionary: Different meshes may have different: - Number of cells/faces - Available variables - Time series lengths |
get_mesh_faces_timeseries
staticmethod
¶
get_mesh_faces_timeseries(hdf_path: Path, mesh_name: str, truncate: bool = True) -> xr.Dataset
Get timeseries output for all face-based variables of a specific mesh.
Discover numeric datasets qualified by authoritative Location=Faces
or the exact-name legacy face schema when Location is absent, with
validated time/face counts. Unqualified entries are skipped with diagnostics;
one-row datasets are never broadcast onto the full Time axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HDF file. |
required |
mesh_name
|
str
|
Name of the mesh. |
required |
truncate
|
bool
|
Whether to truncate leading/trailing zero-only timesteps for each variable. Defaults to True for backward compatibility with the previous behavior. |
True
|
Returns:
| Type | Description |
|---|---|
Dataset
|
Multiple variables for ONE mesh. Use Dataset when extracting MULTIPLE variables for a SINGLE mesh area. Data variables: Any qualified face-based HDF time-series outputs, normalized to lowercase names such as face_velocity, face_flow, face_water_surface, face_area, and face_mannings_n. Each variable shares common dimensions. Dimensions: - time: Timestamps - face_id: Face IDs When to use: Combined face analysis for single mesh. For single variable, use get_mesh_timeseries() → DataArray. For multiple meshes, use get_mesh_cells_timeseries() → Dict[str, Dataset]. |
get_mesh_last_iter
staticmethod
¶
get_mesh_last_iter(hdf_file: Path, include_ghost_cells: bool = False, *, include_geometry: bool = True) -> Union[gpd.GeoDataFrame, pd.DataFrame]
Get last iteration count for each mesh cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_file
|
Path
|
Path to the HDF file. |
required |
include_ghost_cells
|
bool
|
Keep rows for the ghost cells HEC-RAS
writes outside the mesh perimeter (default False). Rows always
carry an |
False
|
include_geometry
|
bool
|
Keyword-only. Default True is the
convenient output: a GeoDataFrame with cell-center points.
False is the fast output: the typed DataFrame of
:meth: |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing last iteration counts. |
get_mesh_log_hydraulics
staticmethod
¶
Read the legacy per-mesh 2D solver log table Log Hydraulics.
HEC-RAS 6.0 through 6.3.x can write Results/Unsteady/Output/Output
Blocks/Base Output/Unsteady Time Series/2D Flow Areas/<mesh>/Log
Hydraulics: one row per Base Output time and one column per solver
diagnostic, labelled by Column 0 ... Column N attributes. It has
no Location; its columns are fields, never cells or faces, so
get_mesh_timeseries() keeps refusing it. This is a diagnostic
reader only. It does not establish hydraulic convergence or result
quality.
Accepted schema (all checked; any deviation raises ValueError):
- root
File Versionis HEC-RAS 6.0 through 6.3.x. These bounds come from producer strings in the HEC-RAS 6.0-6.3.1 solver binaries (absent from 5.0.x and 6.4.1+) and one authentic 6.3.1 result. - a rank-2 numeric dataset at the canonical path with no
Location. - exactly one
Column ilabel per stored column, each one of the producer label strings for that position (10 columns). - rows equal the length of the canonical Base Output
Timeand itsTime Date Stamp (ms)(orTime Date Stamp) datasets. The table is never aligned to any other clock or resampled.
Units are taken only from a label suffix that the producer varies by
unit system and that agrees with the root Units System. Fixed-suffix
labels (Inner-loop max volume residual divided by wet area (ft),
Min water surface elevation (m)) and conflicting suffixes get
units=None; values are never converted. Cell-location columns are
stored float values of a solver cell location whose index base is
unqualified; they are not joined to mesh geometry.
Row semantics within each output interval (instantaneous step at the
output time versus an interval aggregate) are not established. In the
inspected 6.3.1 output the first row (simulation start) is all zero, and
the max/min water surface columns repeat the Water Surface dataset's
stored Maximum/Minimum Value of Data Set attributes rather than the
per-row extrema of the stored Water Surface rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Plan number, plan-result HDF path, or open HDF handle. |
required |
mesh_name
|
str
|
Name of the 2D flow area. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per Base Output time with columns |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
dtype. |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
and |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the mesh has no |
ValueError
|
If the file version, labels, shape, Location or clock fall outside the accepted schema. |
get_mesh_max_depth
staticmethod
¶
get_mesh_max_depth(hdf_path: Path, include_ghost_cells: bool = False, *, include_geometry: bool = True) -> Union[gpd.GeoDataFrame, pd.DataFrame]
Get the maximum depth for each 2D mesh cell.
The preferred source is the stored Depth time series. HEC-RAS can
omit that optional output while retaining Water Surface and
Cells Minimum Elevation. In that case, depth is derived at every
timestep as water surface minus minimum cell elevation, clipped at
zero, and then reduced to the temporal maximum.
Non-finite samples are ignored when a cell has at least one finite
sample. A cell with no finite samples is returned with a NaN maximum.
Both stored and derived time series are reduced in bounded time
chunks rather than materialized as a complete (time, cell) array;
HDF5 still decompresses each whole storage chunk that a read touches.
One INFO message per mesh identifies provenance. If the HDF contains
Depth, that stored HEC-RAS dataset is read only. Otherwise, depth
is derived in memory from Water Surface minus Cells Minimum
Elevation; the method does not create or write a Depth dataset.
Attribution: Implementation pattern derived from ras-agent (https://github.com/gheistand/ras-agent) by Glenn Heistand / CHAMP — Illinois State Water Survey. See results.py:extract_max_depth().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HDF file. |
required |
include_ghost_cells
|
bool
|
Keep rows for the ghost cells HEC-RAS writes outside the mesh perimeter (default False). |
False
|
include_geometry
|
bool
|
Keyword-only. Default True is the
convenient output: the GeoDataFrame below. False is the fast
output: a DataFrame with the same
rows, order and values but no |
True
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with columns:
- mesh_name (str): Name of the 2D flow area
- cell_id (int): Cell index
- maximum_depth (float): Maximum depth at that cell
- is_ghost_cell (bool): True for ghost cells outside the
perimeter (cell IDs at or above the area's |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the HDF file cannot be read, a declared mesh is missing required geometry or result datasets, or their dimensions and cell counts are inconsistent. |
get_mesh_max_face_v
staticmethod
¶
get_mesh_max_face_v(hdf_path: Path, round_to: str = '100ms', *, include_geometry: bool = True) -> Union[gpd.GeoDataFrame, pd.DataFrame]
Get maximum face velocity for each mesh face.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HDF file. |
required |
round_to
|
str
|
Time rounding specification (default "100ms"). |
'100ms'
|
include_geometry
|
bool
|
Keyword-only. Default True is the
convenient output: a GeoDataFrame with face lines.
False is the fast output: the typed DataFrame of
:meth: |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing maximum face velocities. |
get_mesh_max_iter
staticmethod
¶
get_mesh_max_iter(hdf_path: Path, round_to: str = '100ms', include_ghost_cells: bool = False, *, include_geometry: bool = True) -> Union[gpd.GeoDataFrame, pd.DataFrame]
Get maximum iteration count for each mesh cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HDF file. |
required |
round_to
|
str
|
Time rounding specification (default "100ms"). |
'100ms'
|
include_ghost_cells
|
bool
|
Keep rows for the ghost cells HEC-RAS
writes outside the mesh perimeter (default False). Rows always
carry an |
False
|
include_geometry
|
bool
|
Keyword-only. Default True is the
convenient output: a GeoDataFrame with cell-center points.
False is the fast output: the typed DataFrame of
:meth: |
True
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame containing maximum iteration counts with geometry. Includes columns: - mesh_name: Name of the mesh - cell_id: ID of the cell - cell_last_iteration: Maximum number of iterations - cell_last_iteration_time: Time when max iterations occurred - geometry: Point geometry representing cell center |
get_mesh_max_ws
staticmethod
¶
get_mesh_max_ws(hdf_path: Path, round_to: str = '100ms', include_ghost_cells: bool = False, *, include_geometry: bool = True) -> Union[gpd.GeoDataFrame, pd.DataFrame]
Get maximum water surface elevation for each mesh cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HDF file. |
required |
round_to
|
str
|
Time rounding specification (default "100ms"). |
'100ms'
|
include_ghost_cells
|
bool
|
Keep rows for the ghost cells HEC-RAS
writes outside the mesh perimeter (default False). Rows always
carry an |
False
|
include_geometry
|
bool
|
Keyword-only. Default True is the
convenient output: a GeoDataFrame with cell-center points.
False is the fast output: the typed DataFrame of
:meth: |
True
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame containing maximum water surface elevations with geometry. |
get_mesh_max_ws_err
staticmethod
¶
get_mesh_max_ws_err(hdf_path: Path, round_to: str = '100ms', include_ghost_cells: bool = False, *, include_geometry: bool = True) -> Union[gpd.GeoDataFrame, pd.DataFrame]
Get maximum water surface error for each mesh cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HDF file. |
required |
round_to
|
str
|
Time rounding specification (default "100ms"). |
'100ms'
|
include_ghost_cells
|
bool
|
Keep rows for the ghost cells HEC-RAS
writes outside the mesh perimeter (default False). Rows always
carry an |
False
|
include_geometry
|
bool
|
Keyword-only. Default True is the
convenient output: a GeoDataFrame with cell-center points.
False is the fast output: the typed DataFrame of
:meth: |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing maximum water surface errors. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there's an error processing the maximum water surface error data. |
get_mesh_min_face_v
staticmethod
¶
get_mesh_min_face_v(hdf_path: Path, round_to: str = '100ms', *, include_geometry: bool = True) -> Union[gpd.GeoDataFrame, pd.DataFrame]
Get minimum face velocity for each mesh cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HDF file. |
required |
round_to
|
str
|
Time rounding specification (default "100ms"). |
'100ms'
|
include_geometry
|
bool
|
Keyword-only. Default True is the
convenient output: a GeoDataFrame with face lines.
False is the fast output: the typed DataFrame of
:meth: |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing minimum face velocities. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there's an error processing the minimum face velocity data. |
get_mesh_min_ws
staticmethod
¶
get_mesh_min_ws(hdf_path: Path, round_to: str = '100ms', include_ghost_cells: bool = False, *, include_geometry: bool = True) -> Union[gpd.GeoDataFrame, pd.DataFrame]
Get minimum water surface elevation for each mesh cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HDF file. |
required |
round_to
|
str
|
Time rounding specification (default "100ms"). |
'100ms'
|
include_ghost_cells
|
bool
|
Keep rows for the ghost cells HEC-RAS
writes outside the mesh perimeter (default False). Rows always
carry an |
False
|
include_geometry
|
bool
|
Keyword-only. Default True is the
convenient output: a GeoDataFrame with cell-center points.
False is the fast output: the typed DataFrame of
:meth: |
True
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame containing minimum water surface elevations with geometry. |
get_mesh_summary
staticmethod
¶
get_mesh_summary(hdf_path: HdfInput, var: str, round_to: str = '100ms', include_ghost_cells: bool = False, *, include_geometry: bool = True) -> Union[gpd.GeoDataFrame, pd.DataFrame]
Get spatial summary output for a mesh variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
HdfInput
|
Plan number, plan-result HDF path, or open HDF handle. |
required |
var
|
str
|
HEC-RAS summary-output variable name, such as
|
required |
round_to
|
str
|
Time rounding specification for paired time rows. |
'100ms'
|
include_ghost_cells
|
bool
|
Keep rows for the ghost cells HEC-RAS writes
outside the mesh perimeter (default False). Ghost values are
placeholders, not solution results. Cell results always carry
an |
False
|
include_geometry
|
bool
|
Keyword-only. Default True is the convenient
output: a GeoDataFrame with cell/face geometry. False is the
fast output: the typed table of
:meth: |
True
|
Returns:
| Type | Description |
|---|---|
Union[GeoDataFrame, DataFrame]
|
GeoDataFrame with mesh name, cell or face identifier, summary |
Union[GeoDataFrame, DataFrame]
|
values, optional summary times, and cell/face geometry; or the |
Union[GeoDataFrame, DataFrame]
|
typed DataFrame when |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the summary or geometry cannot be read. |
get_mesh_summary_output
staticmethod
¶
get_mesh_summary_output(hdf_file: File, var: str, round_to: str = '100ms', include_ghost_cells: bool = False, *, include_geometry: bool = True) -> Union[gpd.GeoDataFrame, pd.DataFrame]
Get the summary output data for a given variable from the HDF file.
Parameters¶
hdf_path : h5py.File
Open HDF file object.
var : str
The summary output variable to retrieve.
round_to : str, optional
The time unit to round the datetimes to. Default is "100ms".
include_ghost_cells : bool, optional
Cell results include an is_ghost_cell column. HEC-RAS writes
values for ghost cells outside the mesh perimeter after the
physical cells. Default False drops those rows; pass True to
keep them.
include_geometry : bool, optional, keyword-only
Default True is the convenient output: a GeoDataFrame with a
cell-center point (cell variables) or face line (face variables)
on every row. The geometry is built from packed coordinate
buffers in one vectorized Shapely call (natively, where the
engine proves the layout), but it is still most of the call.
False is the fast output: the typed table described in
Returns, read straight from the stored arrays without building
geometry (no GeoPandas/Shapely). Use it when you only need the
values, or when you read several results of one model: read the
geometry once with :meth:HdfMesh.get_mesh_cell_faces or
:meth:HdfMesh.get_mesh_cell_points and join each table to it on
["mesh_name", "face_id"] or ["mesh_name", "cell_id"].
Returns¶
gpd.GeoDataFrame or pd.DataFrame A GeoDataFrame containing the summary output data with decoded attributes as metadata. Returns empty GeoDataFrame if variable is not found.
With ``include_geometry=False``: a DataFrame with the same rows,
order, columns (except ``geometry``), values and ``attrs``.
``mesh_name`` is pandas ``str``/``string``; ``cell_id``/``face_id`` are
``int64`` keys; the value column keeps the stored dtype; the
``*_time`` column is ``datetime64``; ``is_ghost_cell`` is
``bool``. Join geometry on ``(mesh_name, face_id)`` from
:meth:`HdfMesh.get_mesh_cell_faces`, or on ``(mesh_name, cell_id)``
from :meth:`HdfMesh.get_mesh_cell_points` (``x``/``y`` columns with
``include_geometry=False``). Returns an empty DataFrame if the
variable is not found.
Examples¶
Read the face lines once, then join any number of face results:
faces = HdfMesh.get_mesh_cell_faces(plan_hdf) vmax = HdfResultsMesh.get_mesh_max_face_v(plan_hdf, include_geometry=False) located = faces.merge(vmax, on=["mesh_name", "face_id"]) # GeoDataFrame
get_mesh_summary_output_group
staticmethod
¶
get_mesh_summary_output_group(hdf_file: File, mesh_name: str, var: str) -> Union[h5py.Group, h5py.Dataset]
Return the HDF group for a given mesh and summary output variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_file
|
File
|
Open HDF file object. |
required |
mesh_name
|
str
|
Name of the mesh. |
required |
var
|
str
|
Name of the summary output variable. |
required |
Returns:
| Type | Description |
|---|---|
Union[Group, Dataset]
|
The HDF group or dataset for the specified mesh and variable. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the specified group or dataset is not found in the HDF file. |
get_mesh_summary_values
staticmethod
¶
get_mesh_summary_values(hdf_path: HdfInput, var: str, round_to: str = '100ms', include_ghost_cells: bool = False) -> pd.DataFrame
Return mesh summary values without constructing geometry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
HdfInput
|
Path to the plan result HDF. |
required |
var
|
str
|
HEC-RAS summary-output variable name. |
required |
round_to
|
str
|
Time rounding specification for paired time rows. |
'100ms'
|
include_ghost_cells
|
bool
|
Keep rows for the ghost cells HEC-RAS writes
outside the mesh perimeter (default False). Ghost values are
placeholders, not solution results. Cell results always carry
an |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with mesh name, cell or face identifier, value, and an |
DataFrame
|
optional time column. Cell results add |
DataFrame
|
dataset attributes are retained in |
DataFrame
|
Shapely geometry is constructed. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the summary data cannot be read or has an unexpected shape. |
get_mesh_timeseries
staticmethod
¶
get_mesh_timeseries(hdf_path: HdfInput, mesh_name: str, var: str, truncate: bool = True, *, time_selection: Selection = None, spatial_selection: Selection = None, return_type: Literal['xarray', 'view'] = 'xarray', include_ghost_cells: bool = False) -> Union[xr.DataArray, HdfResultView]
Get timeseries output for a specific mesh and variable.
Numeric series must match canonical Base Output Time rows. Rank-one
time-only series return (time,) without ghost or spatial coordinates.
Rank-two series use authoritative scalar Location (Cells,
Cell or Faces). Only absent Location permits the immutable
exact-name legacy schema: Depth/Water Surface are cells; Face Velocity,
Face Shear Stress, Face Area and Face Manning's n are faces. These
canonical stable-core names support observed 5.0.7 and compatible
6.x/7.x output, including excerpts without File Version. Both paths
require matching stored geometry counts. Invalid present Location,
unknown legacy names and contradictory axes raise ValueError; shape
and name substrings never select a domain. Cell Hydraulic Depth is
a literal variable distinct from Depth; no alias is applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
HdfInput
|
Plan number, plan-result HDF path, or open HDF handle. |
required |
mesh_name
|
str
|
Name of the 2D flow area. |
required |
var
|
str
|
HEC-RAS time-series variable to retrieve. |
required |
truncate
|
bool
|
Whether to truncate leading/trailing zero-only rows (default True). An all-zero selection retains its full time extent. Eager materialization reads once and trims in memory; lazy views defer the bounded scan until needed. |
True
|
time_selection
|
Selection
|
Source-coordinate integer or forward slice applied before materialization. |
None
|
spatial_selection
|
Selection
|
Source-coordinate integer or forward slice of cells/faces applied before materialization. Truncation is evaluated over this selected spatial subset. |
None
|
return_type
|
Literal['xarray', 'view']
|
|
'xarray'
|
include_ghost_cells
|
bool
|
Keep the ghost-cell columns HEC-RAS writes
after the physical cells of a cell variable (default False).
Ghost values are placeholders, not solution results. When
False, |
False
|
Returns:
| Type | Description |
|---|---|
DataArray or HdfResultView
|
Single variable time series data.
Use DataArray when extracting ONE variable for ONE mesh.
Dimensions: - time: Timestamps - face_id/cell_id: IDs for faces/cells Coordinates (cell variables, xarray only):
- is_ghost_cell: True for ghost cells outside the mesh
perimeter (cell IDs at or above the area's
Attributes: - units: Variable units - mesh_name: Name of mesh - variable: Variable name When to use: Single variable extraction for focused analysis.
For multiple variables, use |
Raises:
| Type | Description |
|---|---|
MeshSeriesAvailabilityError
|
If the stored rows differ from the
Base Output Time axis (a |
ValueError
|
If the variable or return type is invalid. |
TypeError
|
If a selection is not integer-like or a slice. |
IndexError
|
If an integer selection is outside the source extent. |
FileNotFoundError
|
If a lazy view's source is moved before use. |
RuntimeError
|
If a lazy view's source changes after creation. |
Valid variables include
"Water Surface", "Face Velocity", "Cell Velocity - Velocity X"...
get_mesh_timeseries_availability
staticmethod
¶
get_mesh_timeseries_availability(hdf_path: HdfInput, mesh_name: Optional[str] = None) -> pd.DataFrame
Report whether each Base Output mesh dataset is readable as a series.
Reads metadata only (no result values). Each dataset directly under
Base Output/Unsteady Time Series/2D Flow Areas/<mesh> is qualified
by the same rule as :meth:get_mesh_timeseries, so status predicts
whether an eager, view or streamed read of that variable succeeds.
Subgroups (for example Boundary Conditions) are not series and are
omitted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
HdfInput
|
Plan number, plan-result HDF path, or open HDF handle. |
required |
mesh_name
|
Optional[str]
|
Optional 2D flow area name; all meshes when omitted. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per dataset with columns |
DataFrame
|
|
DataFrame
|
(None when the Time axis is missing or malformed), |
DataFrame
|
|
or None), ``status`` and ``reason``. ``status`` is
|
|
- ``"available"``
|
readable; |
- ``"unwritten_placeholder"``
|
rows differ from the clock and the
producer stored no data ( |
- ``"row_count_mismatch"``
|
stored data whose rows differ from the clock. |
- ``"unqualified"``
|
any other refusal (invalid Location, unknown
legacy name, non-numeric data, malformed Time or geometry);
|
- ``"native_refused"``
|
only with |
DataFrame
|
|
DataFrame
|
rows match the clock but that stores no data still reads as fill |
DataFrame
|
values; check |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
get_profile_line_flow_timeseries
staticmethod
¶
get_profile_line_flow_timeseries(hdf_path: Path, line_name: str, mesh_name: Optional[str] = None, profile_lines_path: Optional[Union[str, Path]] = None, direction: str = 'absolute', truncate: bool = False, ras_object: Optional[Any] = None) -> pd.DataFrame
Return a flow time series across a RAS Mapper profile/reference line.
Recorded computed reference-line Flow is read first through
HdfResultsXsec.get_ref_lines_timeseries(), without pythonnet or
face-output requirements. Observed Event Conditions data is not used.
Otherwise native reference-line faces and ad-hoc profile lines are read through
RASResults.ReadUnsteadyTimeSeries() after selecting ad-hoc faces
with MeshFV2D.PerimeterFacesAlongPolyline().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Completed plan HDF, with the matching geometry available. |
required |
line_name
|
str
|
Exact reference-line or profile-layer feature name. |
required |
mesh_name
|
Optional[str]
|
Optional 2D flow area selector. |
None
|
profile_lines_path
|
Optional[Union[str, Path]]
|
Optional external profile-line layer. Coordinates must match the model CRS; project metadata can resolve this path. |
None
|
direction
|
str
|
|
'absolute'
|
truncate
|
bool
|
Trim leading and trailing zero-flow samples when true. |
False
|
ras_object
|
RasPrj
|
Optional initialized project context. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with |
DataFrame
|
|
include units, variable and face IDs. Preserve this provenance
|
|
DataFrame
|
|
DataFrame
|
reference matrix, with its dataset path and reference ID in attrs; |
DataFrame
|
face-selection routes identify |
DataFrame
|
aggregation of stored face output, not a new solver calculation. |
DataFrame
|
Missing units are not inferred. |
Notes
Face fallbacks require pythonnet and compatible RasMapperLib. For an
offline approximation use get_profile_line_flow_timeseries_legacy.
To read recorded reference matrices directly without native mapping,
use HdfResultsXsec.get_ref_lines_timeseries. Reading an HDF cannot
create reference output that was not recorded by the model run.
get_profile_line_flow_timeseries_legacy
staticmethod
¶
get_profile_line_flow_timeseries_legacy(hdf_path: Path, line_name: str, mesh_name: Optional[str] = None, profile_lines_path: Optional[Union[str, Path]] = None, direction: str = 'absolute', truncate: bool = False, ras_object: Optional[Any] = None) -> pd.DataFrame
Return a legacy pure-Python profile/reference-line flow time series.
This method predates the pythonnet/RasMapperLib profile API. It selects
native reference-line internal faces when available, otherwise reads a
RAS Mapper Profile Lines feature file and uses
HdfMesh.get_faces_along_profile_line() plus direct HDF Face Flow
time series. Keep using it for offline analysis without a HEC-RAS
install or to reproduce pre-CLB-852 results; it is retained for
backward compatibility.
Parameters¶
hdf_path : Path
Plan HDF path, plan number, or other input accepted by
@standardize_input(file_type='plan_hdf').
line_name : str
Profile/reference line name to extract.
mesh_name : Optional[str], optional
2D flow area name. Required when the line resolves to more than one
mesh area.
profile_lines_path : Optional[Union[str, Path]], optional
Explicit RAS Mapper Profile Lines feature path. If omitted, the
method attempts to use ras_object.rasmap_df.profile_lines_path.
direction : str, default "absolute"
"absolute" sums absolute face flows to avoid face-normal sign
cancellation. "signed" preserves native HEC-RAS face-flow signs;
orientation is controlled by the underlying face normals.
truncate : bool, default False
Passed to get_mesh_timeseries().
ras_object : Optional[Any], optional
RAS project object used for plan-number and rasmap path resolution.
Returns¶
pd.DataFrame
Columns: time, flow, line_name, mesh_name,
direction, face_count, and selection_source.
get_profile_line_peak_flow
staticmethod
¶
get_profile_line_peak_flow(hdf_path: Path, line_name: str, mesh_name: Optional[str] = None, profile_lines_path: Optional[Union[str, Path]] = None, direction: str = 'absolute', ras_object: Optional[Any] = None) -> pd.DataFrame
Return peak flow across a RAS Mapper profile/reference line.
For direction="absolute", the peak is the maximum of the selected
extraction route's absolute-flow series: absolute recorded reference
hydrograph flow or a sum of absolute face flows. Preserve selection_source to
distinguish these quantities. For direction="signed", the peak timestep is selected by
maximum signed-flow magnitude and the returned peak_flow preserves
the native sign at that timestep. A peak from saved output times need
not equal a peak over every computational timestep.
inspect_mesh_series_raw
staticmethod
¶
inspect_mesh_series_raw(hdf_path: HdfInput, mesh_name: str, var: str, *, include_values: bool = False) -> Dict[str, Any]
Describe one Base Output mesh series exactly as stored, without typing it.
This is a diagnostic accessor for series that the typed readers refuse,
such as a dataset whose stored Location contradicts its width. It
reports the stored identity, shape, dtype and attributes, the canonical
Time row count, the stored geometry counts, and the typed-reader outcome
with its refusal reason. It never assigns a physical domain or a unit
interpretation: physical_domain and units_interpretation are
always "unqualified", and a rank-two dataset's axes are
("raw_row", "raw_column"). time_axis["matches_rows"] reports
whether the row count equals the canonical Base Output Time axis; no
timestamps are attached. Column positions are not cell or face
identifiers. No values are
converted, relabelled, filtered, broadcast or reconstructed. Use
get_mesh_timeseries() or iter_mesh_timeseries() for qualified
spatial series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
HdfInput
|
Plan number, plan-result HDF path, or open HDF handle. |
required |
mesh_name
|
str
|
Name of the 2D flow area. |
required |
var
|
str
|
Exact dataset name under the mesh's Base Output Unsteady Time Series group. |
required |
include_values
|
bool
|
Return a copy of the stored array under |
False
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
dict with keys |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
( |
Dict[str, Any]
|
( |
Dict[str, Any]
|
|
Dict[str, Any]
|
(the typed readers' |
Dict[str, Any]
|
None when refused), |
Dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset is absent or is not an HDF dataset. |
iter_mesh_timeseries
staticmethod
¶
iter_mesh_timeseries(hdf_path: HdfInput, mesh_name: str, var: str, *, time_selection: Selection = None, spatial_selection: Selection = None, batch_size: Optional[int] = None, max_chunk_bytes: int = 16 * 1024 * 1024, include_ghost_cells: bool = False) -> Iterator[xr.DataArray]
Yield untruncated, bounded time-major batches for one mesh variable.
The returned iterator owns one read-only HDF handle for the duration of iteration. Each batch uses the established xarray DataArray schema. Geometry is not constructed. The iterator deliberately does not trim leading or trailing zero-only rows so every selected source timestep is emitted exactly once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
HdfInput
|
Plan number, plan-result HDF path, or open HDF handle. |
required |
mesh_name
|
str
|
Name of the 2D flow area. |
required |
var
|
str
|
HEC-RAS time-series variable name. |
required |
time_selection
|
Selection
|
Source-coordinate integer or forward slice. |
None
|
spatial_selection
|
Selection
|
Source-coordinate integer or forward slice of cells or faces. |
None
|
batch_size
|
Optional[int]
|
Optional explicit number of timesteps per batch. |
None
|
max_chunk_bytes
|
int
|
Byte target used when |
16 * 1024 * 1024
|
include_ghost_cells
|
bool
|
Keep the ghost-cell columns of a cell
variable (default False). When False, |
False
|
Returns:
| Type | Description |
|---|---|
Iterator[DataArray]
|
Iterator of labeled xarray DataArray batches. |
Raises:
| Type | Description |
|---|---|
MeshSeriesAvailabilityError
|
If the stored rows differ from the Base Output Time axis; raised before any batch is produced. |
ValueError
|
If the variable, selection, or batch sizing is invalid. |
TypeError
|
If a selection is not integer-like or a slice. |
IndexError
|
If an integer selection is outside the source extent. |
FileNotFoundError
|
If the source is moved before iteration. |
RuntimeError
|
If the source changes after iterator creation. |
HdfResultView source reference¶
Serializable lazy view that reopens its HDF source for each operation.
The view stores dataset metadata and selections but no open HDF handle and no result values. This makes file ownership explicit: each materialization, reduction, or batch iterator opens the source read-only and closes it when that operation completes. A size/mtime fingerprint detects ordinary source replacement and modification before or during an operation.
iter_batches
¶
iter_batches(*, batch_size: Optional[int] = None, max_chunk_bytes: int = 16 * 1024 * 1024, dtype: Optional[DTypeLike] = None) -> Iterator[xr.DataArray]
Return a generator of time-major batches from one HDF handle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
Optional[int]
|
Optional explicit number of selected timesteps per batch. |
None
|
max_chunk_bytes
|
int
|
Target value bytes per batch when |
16 * 1024 * 1024
|
dtype
|
Optional[DTypeLike]
|
Optional NumPy-compatible output dtype used in byte sizing and conversion. |
None
|
Returns:
| Type | Description |
|---|---|
Iterator[DataArray]
|
Generator yielding labeled xarray DataArray batches. The generator |
Iterator[DataArray]
|
logs and validates completion when exhausted or closed. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a batch limit is nonpositive. |
FileNotFoundError
|
If the source path no longer exists. |
RuntimeError
|
If the source changes before or during consumption. |
reduce
¶
reduce(operation: str, *, max_chunk_bytes: int = 16 * 1024 * 1024, dtype: Optional[DTypeLike] = None) -> xr.DataArray
Reduce the selected time axis with bounded memory.
Supported operations are max, min, mean, and argmax.
NaN and infinite samples are ignored. argmax returns source time
indexes and uses -1 for a spatial element with no finite samples.
An explicit dtype must be floating point so NaN/infinite filtering
cannot be destroyed by a pre-reduction integer cast.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
operation
|
str
|
One of |
required |
max_chunk_bytes
|
int
|
Maximum target value bytes per source batch. |
16 * 1024 * 1024
|
dtype
|
Optional[DTypeLike]
|
Optional floating-point computation/output dtype. |
None
|
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray over the selected spatial dimension, or a scalar |
DataArray
|
DataArray for a one-dimensional source. Argmax values are source |
DataArray
|
time indexes and use |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the operation or chunk target is invalid. |
TypeError
|
If the source is nonnumeric or |
FileNotFoundError
|
If the source path no longer exists. |
RuntimeError
|
If the source changes after view creation. |
select
¶
Return a new view with source-coordinate time/spatial selections.
Integer selections preserve their dimension as a length-one slice.
Selections use source indexes rather than indexes relative to a prior
selection, which keeps serialized views unambiguous. Passing None
preserves an existing selection; use a full slice(None) to reset
that dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time
|
Selection
|
Python/NumPy integer or positive-step slice in source time coordinates. |
None
|
spatial
|
Selection
|
Python/NumPy integer or positive-step slice in source cell/face coordinates. |
None
|
Returns:
| Type | Description |
|---|---|
'HdfResultView'
|
A new immutable view over the same fingerprinted source. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If a selection is not integer-like or a slice. |
IndexError
|
If an integer selection is outside the source extent. |
ValueError
|
If a slice step is nonpositive or a spatial selection is supplied for a one-dimensional dataset. |
to_arrow
¶
Materialize the selection as an optional PyArrow table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
Optional[DTypeLike]
|
Optional NumPy-compatible output dtype. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A PyArrow Table in long form, with time, optional spatial |
Any
|
identifier, and value columns. |
Any
|
annotation so importing ras-commander does not require PyArrow. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If PyArrow is not installed. |
FileNotFoundError
|
If the source path no longer exists. |
RuntimeError
|
If the source changed after view creation. |
to_numpy
¶
Materialize only the selected values as a NumPy array.
The eager path reads the selected HDF slab once. When truncation is enabled, leading and trailing zero-only rows are trimmed in memory; an all-zero selection retains its full time extent for compatibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
Optional[DTypeLike]
|
Optional NumPy-compatible output dtype. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Selected result values with a stable time dimension. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the source path no longer exists. |
KeyError
|
If the source dataset was removed. |
RuntimeError
|
If the source fingerprint, shape, or dtype changed. |
to_pandas
¶
Materialize the selection using xarray's pandas representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
Optional[DTypeLike]
|
Optional NumPy-compatible output dtype. |
None
|
Returns:
| Type | Description |
|---|---|
Union[Series, DataFrame]
|
Series for one-dimensional sources or DataFrame for two-dimensional |
Union[Series, DataFrame]
|
sources. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the source path no longer exists. |
RuntimeError
|
If the source changed after view creation. |
to_xarray
¶
Materialize the selection as a labeled xarray DataArray.
Result values are read once. Truncation is evaluated over the selected spatial subset, so a subset can have a narrower active time window than the complete mesh.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
Optional[DTypeLike]
|
Optional NumPy-compatible output dtype. |
None
|
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray labeled by timestamps and source cell/face identifiers. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the source path no longer exists. |
KeyError
|
If a required source dataset was removed. |
RuntimeError
|
If the source fingerprint, shape, or dtype changed. |
HdfResultsXsec source reference¶
A static class for extracting and processing 1D results data from HEC-RAS HDF files.
This class provides methods to extract and process unsteady flow simulation results for cross-sections, reference lines, and reference points. All methods are static and designed to be used without class instantiation.
The class handles: - Cross-section timeseries (water surface, velocity, flow) - Reference line timeseries - Reference point timeseries
Dependencies
- HdfBase: Core HDF file operations
- HdfUtils: Utility functions for HDF processing
get_ref_lines_timeseries
staticmethod
¶
get_ref_lines_timeseries(hdf_path: Path, variables: Optional[Union[str, Sequence[str]]] = None) -> xr.Dataset
Extract timeseries output data for reference lines from HEC-RAS HDF file.
Parameters:¶
hdf_path : Path Path to the HEC-RAS results HDF file variables : str or sequence of str, optional HDF dataset names to include. If omitted, all numeric datasets with shape (time, reference_line) are returned.
Returns:¶
xr.Dataset Dataset containing numeric native HDF time-series data for reference lines. Returns empty dataset if reference line data not found.
Raises:¶
FileNotFoundError If the specified HDF file is not found KeyError If required datasets are missing from the HDF file
get_ref_points_timeseries
staticmethod
¶
get_ref_points_timeseries(hdf_path: Path, variables: Optional[Union[str, Sequence[str]]] = None) -> xr.Dataset
Extract timeseries output data for reference points from HEC-RAS HDF file.
This method extracts flow, velocity, and water surface elevation data for all reference points defined in the model. Reference points are user-defined locations where detailed output is desired.
Parameters:¶
hdf_path : Path Path to the HEC-RAS results HDF file variables : str or sequence of str, optional HDF dataset names to include. If omitted, all numeric datasets with shape (time, reference_point) are returned.
Returns:¶
xr.Dataset Dataset containing numeric native HDF time-series variables for each reference point.
The dataset includes coordinates:
- time: Simulation timesteps
- refpt_id: Unique identifier for each reference point
- refpt_name: Name of each reference point
- mesh_name: Associated 2D mesh area name
Returns empty dataset if reference point data not found.
Raises:¶
FileNotFoundError If the specified HDF file is not found KeyError If required datasets are missing from the HDF file
Examples:¶
ds = HdfResultsXsec.get_ref_points_timeseries("path/to/plan.hdf")
Get water surface timeseries for first reference point¶
ws = ds['Water Surface'].isel(refpt_id=0)
Get all data for a specific reference point by name¶
point_data = ds.where(ds['refpt_name'] == 'Point1', drop=True)
get_xsec_summary
staticmethod
¶
get_xsec_summary(hdf_path: Path, variables: Optional[Union[str, Sequence[str]]] = None, chunk_rows: int = 4096) -> pd.DataFrame
Summarize unsteady 1D cross-section results with bounded memory.
One row is returned for each cross section. river, reach, and
node_id preserve the native HEC-RAS identity used to join result
attributes to cross-section geometry. Every available numeric
time-series variable contributes minimum, maximum, and time-of-maximum
columns. Missing optional variables are ignored.
Parameters¶
hdf_path : Path Path to the HEC-RAS plan results HDF. variables : str or sequence of str, optional Native HDF variable names to summarize. Matching is case-insensitive. By default, all numeric cross-section time-series variables are included. chunk_rows : int, default 4096 Maximum number of timesteps read from one HDF dataset at a time.
Returns¶
pandas.DataFrame Attribute-only summary rows. An empty frame indicates that the plan contains no unsteady cross-section output.
get_xsec_timeseries
staticmethod
¶
Extract Water Surface, Velocity Total, Velocity Channel, Flow Lateral, and Flow data from HEC-RAS HDF file. Includes Cross Section Only and Cross Section Attributes as coordinates in the xarray.Dataset. Also calculates maximum values for key parameters.
Parameters:¶
hdf_path : Path Path to the HEC-RAS results HDF file
Returns:¶
xr.Dataset Xarray Dataset containing the extracted cross-section results with appropriate coordinates and attributes. Includes maximum values for Water Surface, Flow, Channel Velocity, Total Velocity, and Lateral Flow.
HdfResultsBreach source reference¶
Handles dam breach results extraction from HEC-RAS HDF files.
This class provides comprehensive breach results extraction including: - Time series data (flow, water levels, breach geometry) - Summary statistics (peak values, timing) - Structure-level flow variables
All methods are static and designed for plan-number-based access via the @standardize_input decorator.
Architectural Note
- Use HdfResultsBreach for extracting breach RESULTS from HDF files
- Use RasBreach for reading/writing breach PARAMETERS in plan files
- Use HdfStruc for structure listings and metadata
get_breach_summary
staticmethod
¶
get_breach_summary(hdf_path: Path, structure_name: str = None, *, ras_object=None) -> pd.DataFrame
Extract breach summary statistics (peak values, timing, final geometry).
Provides quick overview of breach performance without full time series.
Parameters¶
hdf_path : Path Path to HEC-RAS plan HDF file or plan number structure_name : str, optional Specific structure. If None, returns all breach structures. ras_object : RasPrj, optional RAS object for multi-project workflows
Returns¶
pd.DataFrame Summary statistics with columns: - structure: Structure name - breach_initiated: Boolean, True if breach formed - breach_at_time: Time of breach initiation (days) - breach_at_date: Date/time of breach - max_total_flow: Maximum total flow (cfs) - max_total_flow_time: Time of max total flow - max_breach_flow: Maximum breach flow (cfs) - max_breach_flow_time: Time of max breach flow - final_breach_width: Final breach width (ft) - final_breach_depth: Final breach depth (ft) - max_hw: Maximum headwater elevation (ft) - max_tw: Maximum tailwater elevation (ft)
Examples¶
summary = HdfResultsBreach.get_breach_summary("02") print(summary[['structure', 'max_total_flow', 'final_breach_width']])
Notes¶
- Returns summary even if breach didn't fully form (NaN for incomplete data)
- Times are pandas datetime objects
- If only 1 timestep available, "max" values are that single value
get_breach_timeseries
staticmethod
¶
get_breach_timeseries(hdf_path: Path, structure_name: str = None, *, ras_object=None) -> pd.DataFrame
Extract combined breach and structure time series (primary user function).
This is a convenience function that combines data from both: - Structure Variables (total flow, weir flow) - Breaching Variables (breach geometry and breach-specific flow)
Provides a complete picture of dam breach behavior over time.
Parameters¶
hdf_path : Path Path to HEC-RAS plan HDF file or plan number structure_name : str, optional Specific structure name. If None, returns all breach structures. ras_object : RasPrj, optional RAS object for multi-project workflows
Returns¶
pd.DataFrame Combined time series with columns: - datetime: Timestamp - structure: Structure name (if multiple structures) - total_flow: Total flow through structure (cfs) - weir_flow: Flow over remaining weir (cfs) - breach_flow: Flow through breach opening (cfs) - hw: Headwater elevation (ft) - tw: Tailwater elevation (ft) - bottom_width: Breach width (ft) - bottom_elevation: Breach bottom elevation (ft) - left_slope: Left side slope - right_slope: Right side slope - breach_velocity: Breach velocity (ft/s) - breach_flow_area: Breach flow area (ft²)
Examples¶
Extract all breach data for plan 02¶
df = HdfResultsBreach.get_breach_timeseries("02")
Get specific dam¶
df = HdfResultsBreach.get_breach_timeseries("02", "Laxton_Dam")
Visualize¶
import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8))
Flow hydrograph¶
ax1.plot(df['datetime'], df['total_flow'], label='Total Flow') ax1.plot(df['datetime'], df['breach_flow'], label='Breach Flow') ax1.set_ylabel('Flow (cfs)') ax1.legend()
Breach width evolution¶
ax2.plot(df['datetime'], df['bottom_width']) ax2.set_ylabel('Breach Width (ft)') ax2.set_xlabel('Time') plt.tight_layout()
Notes¶
- Only returns structures with breach capability
- For non-breach SA/2D connections, use get_structure_variables()
- NaN values in breach columns indicate breach not yet formed
See Also¶
get_structure_variables : Structure-level data only get_breaching_variables : Breach-specific data only
get_breaching_variables
staticmethod
¶
get_breaching_variables(hdf_path: Path, structure_name: str = None, *, ras_object=None) -> pd.DataFrame
Extract breach-specific geometry progression and flow data.
Only available for structures with breach capability. This dataset shows how the breach evolves over time (width, depth, flow, etc.).
Parameters¶
hdf_path : Path Path to HEC-RAS plan HDF file or plan number structure_name : str, optional Specific structure name. If None, returns all breach structures. ras_object : RasPrj, optional RAS object for multi-project workflows
Returns¶
pd.DataFrame Breach progression data with columns: - datetime: Timestamp - structure: Structure name (if multiple structures) - hw: Headwater stage at breach (ft or m) - tw: Tailwater stage at breach (ft or m) - bottom_width: Current breach bottom width (ft or m) - bottom_elevation: Current breach bottom elevation (ft or m) - left_slope: Left side slope (feet/feet or m/m) - right_slope: Right side slope (feet/feet or m/m) - breach_flow: Flow through breach opening (cfs or m³/s) - breach_velocity: Average velocity through breach (ft/s or m/s) - breach_flow_area: Flow area of breach (ft² or m²)
Examples¶
Get breach progression for specific dam¶
df = HdfResultsBreach.get_breaching_variables("02", "Laxton_Dam")
Plot breach width evolution¶
import matplotlib.pyplot as plt plt.plot(df['datetime'], df['bottom_width']) plt.ylabel('Breach Width (ft)')
Get all breach structures¶
df = HdfResultsBreach.get_breaching_variables("02")
Notes¶
- Returns empty DataFrame if structure has no breach capability
- NaN values indicate breach not yet formed at that timestep
- Units depend on project unit system
- For total structure flow, use get_structure_variables()
Raises¶
ValueError If specified structure_name doesn't exist in HDF
get_structure_variables
staticmethod
¶
get_structure_variables(hdf_path: Path, structure_name: str = None, *, ras_object=None) -> pd.DataFrame
Extract structure-level flow variables (Total Flow, Weir Flow, HW, TW).
This is the primary time series for overall structure performance. Available for all SA/2D connections (with or without breach).
Parameters¶
hdf_path : Path Path to HEC-RAS plan HDF file or plan number structure_name : str, optional Specific structure name. If None, returns all structures. ras_object : RasPrj, optional RAS object for multi-project workflows
Returns¶
pd.DataFrame Time series data with columns: - datetime: Timestamp - structure: Structure name (if multiple structures) - total_flow: Total flow through structure (cfs or m³/s) - weir_flow: Flow over weir (cfs or m³/s) - hw: Headwater elevation at representative station (ft or m) - tw: Tailwater elevation at representative station (ft or m)
Examples¶
Get all structures¶
df = HdfResultsBreach.get_structure_variables("02")
Get specific structure¶
df = HdfResultsBreach.get_structure_variables("02", "Laxton_Dam")
Plot flow hydrograph¶
import matplotlib.pyplot as plt plt.plot(df['datetime'], df['total_flow']) plt.ylabel('Flow (cfs)')
Notes¶
- HW and TW are at representative stations defined in structure attributes
- For breach structures, use get_breaching_variables() for breach-specific data
- Units depend on project unit system (US Customary or SI)
HdfResultsSediment source reference¶
Static reader for 2D mobile-bed (sediment) plan-HDF results.
get_active_layer_grain_class
staticmethod
¶
get_active_layer_grain_class(hdf_path: Path, percentile: str = 'D50', mesh_name: Optional[str] = None, time_index: int = -1, ras_object: Optional[Any] = None, unit_system: Optional[str] = None, *, include_geometry: bool = True)
Return per-cell active-layer grain diameter (mm) at a time index.
HEC-RAS stores these diameters in mm in SI and US Customary projects
alike. The reader validates the dataset's own Units attribute and
raises if it is not mm; an unlabelled dataset is read as mm with a
warning. The model unit system is not needed for the diameters, so
unresolvable or contradictory model units no longer block this reader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
percentile
|
str
|
One of |
'D50'
|
mesh_name
|
Optional[str]
|
2D area name; defaults to the sole sediment area. |
None
|
time_index
|
int
|
Sediment output time index (default -1 = final). |
-1
|
ras_object
|
Optional[RasPrj]
|
Project whose |
None
|
unit_system
|
Optional[str]
|
|
None
|
include_geometry
|
bool
|
Keyword-only. Default True returns the
GeoDataFrame below. False returns the typed table described in
:meth: |
True
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
Columns |
get_bed_change_volumes
staticmethod
¶
get_bed_change_volumes(hdf_path: Path, mesh_name: Optional[str] = None, time_index: int = -1, ras_object: Optional[Any] = None, unit_system: Optional[str] = None) -> pd.DataFrame
Summarize bed-change volumes per 2D sediment area at a time index.
Integrates Cell Bed Change against Cells Surface Area over the
physical cells (ghost cells are dropped). One row per area with columns:
mesh_name, length_unit, n_cells, net_bed_volume, erosion_volume,
deposition_volume, max_scour, max_deposition.
Volumes are in native cubic length units (ft^3 or m^3, per
length_unit); max_scour/max_deposition are in the native
length unit. Negative values indicate net scour. Callers convert to
ac-ft / cubic yards only when length_unit == 'ft'. The length unit
resolves as in :meth:get_cell_bed_change.
get_cell_bed_change
staticmethod
¶
get_cell_bed_change(hdf_path: Path, mesh_name: Optional[str] = None, time_index: int = -1, ras_object: Optional[Any] = None, unit_system: Optional[str] = None, *, include_geometry: bool = True)
Return per-cell bed change at a time index as a GeoDataFrame.
Columns: mesh_name, cell_id, bed_change, surface_area, geometry.
bed_change is in the model length unit (ft or m; see
gdf.attrs['length_unit']). Negative = scour, positive = deposition.
time_index indexes the sediment output series (default -1 = final).
The length unit comes from unit_system ("SI" or
"US Customary") when given, else from the project .prj marker
when the project is known (ras_object, or the initialized global
project that contains the HDF), else from the embedded HDF metadata
(see :meth:HdfBase.get_result_unit_metadata). Unresolvable or
contradictory units raise ValueError.
include_geometry=False (keyword-only) returns a DataFrame with the
same rows, order, values and attrs but no geometry column and
no GeoPandas/Shapely dependency: mesh_name (pandas str/string),
cell_id (int64), and bed_change/surface_area in their
stored dtypes (the GeoDataFrame casts them to float64).
get_cell_bed_change_timeseries
staticmethod
¶
get_cell_bed_change_timeseries(hdf_path: Path, mesh_name: Optional[str] = None, ras_object: Optional[Any] = None, unit_system: Optional[str] = None)
Return the full (time, cell) bed-change series as an xarray.DataArray.
Dimensions (time, cell_id); time is the model output time vector
(days). Units are the model length unit (ft or m; see da.attrs['units']),
resolved as in :meth:get_cell_bed_change; negative = scour.
get_cell_bed_elevation
staticmethod
¶
get_cell_bed_elevation(hdf_path: Path, mesh_name: Optional[str] = None, time_index: int = -1, ras_object: Optional[Any] = None, unit_system: Optional[str] = None, *, include_geometry: bool = True)
Return per-cell bed elevation at a time index as a GeoDataFrame.
Columns: mesh_name, cell_id, bed_elevation, surface_area, geometry
(bed_elevation in the model length unit; see gdf.attrs['length_unit']).
The length unit resolves as in :meth:get_cell_bed_change
(unit_system override, project .prj, embedded metadata).
include_geometry=False returns the typed table described in
:meth:get_cell_bed_change.
get_sediment_mesh_areas
staticmethod
¶
Return the 2D flow area names that have Sediment Bed results.
Returns an empty list if the plan has no 2D mobile-bed results.
is_sediment_plan
staticmethod
¶
Return True if the plan HDF contains 2D mobile-bed (Sediment Bed) results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Number, Path]
|
Plan number, prefixed plan number, path to the plan HDF, or open HDF handle. |
required |
ras_object
|
Optional[RasPrj]
|
RAS project object for multi-project workflows. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the plan contains 2D mobile-bed results. |
HdfResultsProducts source reference¶
Static namespace for deterministic hydraulic product packages.
export
staticmethod
¶
export(hdf_path: Union[str, Path], output_directory: Union[str, Path], *, resolution: float | None = None, max_dimension: int = 2048, nodata: float = -9999.0, include_preview: bool = True) -> dict[str, Any]
Generate a deterministic hydraulic product package.
The source is an existing HEC-RAS producer HDF opened read-only. The COG, Parquet, GeoJSON, JSON, and optional PNG files are newly generated ras-commander product artifacts; they are not HEC-RAS model output. The source digest is checked before and after inspection, rendering, and publication.
The output directory must not exist. It is claimed atomically, assets
are hard-linked from a same-parent staging directory without
overwriting names, and the checksum-pinned manifest is published last.
Consumers must treat the package as complete only when
:attr:MANIFEST_FILENAME exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path]
|
Completed HEC-RAS unsteady plan-result HDF. |
required |
output_directory
|
Union[str, Path]
|
New directory for the generated product package. |
required |
resolution
|
float | None
|
Optional raster cell size in model CRS units. |
None
|
max_dimension
|
int
|
Maximum raster width and height. Defaults to 2048; total raster cells are also bounded for memory safety. |
2048
|
nodata
|
float
|
Finite float32 nodata value for all three COGs. Inputs are normalized to the value that will actually be stored. |
-9999.0
|
include_preview
|
bool
|
Generate |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The JSON-serializable manifest also written to the package. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the source HDF does not exist. |
FileExistsError
|
If the output directory already exists or is claimed concurrently. |
ValueError
|
If inputs, the result HDF, spatial support, or rendered metadata are invalid or inconsistent. |
RuntimeError
|
If the source changes, asset verification fails, or publication cannot preserve the no-overwrite contract. |
OSError
|
If source reads, staging, hard links, or publication fail. |
inspect_result
staticmethod
¶
Inspect whether an HDF can support the hydraulic product contract.
Completion is accepted from the current HEC-RAS
Event Conditions/Completed Successfully=True attribute or, for
older producer files that do not contain that attribute, an embedded
compute-message Complete Process marker. An explicit false or
malformed completion attribute is never overridden by messages.
The method reads the existing result HDF without creating or changing
any HDF dataset. It validates the time axes, embedded CRS and units,
cell/face topology, and all mesh result arrays required by
:meth:export.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path]
|
Existing HEC-RAS unsteady plan-result HDF. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A JSON-serializable inspection record. |
dict[str, Any]
|
|
dict[str, Any]
|
readiness do not constitute engineering acceptance. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If completion evidence, time axes, CRS, units, mesh geometry, topology, or required result arrays are incomplete or inconsistent. |
OSError
|
If the HDF cannot be opened or read. |
HdfPipe source reference¶
Static methods for handling pipe network data from HEC-RAS HDF files.
Contains methods for: - Geometry retrieval (nodes, conduits, networks, profiles) - Results retrieval (timeseries and summary data)
All methods use @standardize_input for path validation and @log_call
extract_timeseries_for_conduit
staticmethod
¶
extract_timeseries_for_conduit(plan_hdf_path: Union[str, Path, int, File], conduit_id: int, pipe_network_name: Optional[str] = None, output_block: str = 'DSS Hydrograph Output', *, ras_object=None) -> Dict[str, xr.DataArray]
Extract time series data for a specific conduit.
Parameters:¶
plan_hdf_path : str, Path, int or h5py.File Results HDF path, open file, or plan number resolved against ras_object. conduit_id : int Stored conduit ID from Conduit Indices, not a network column position. pipe_network_name : Optional[str] Network name (default: first geometry network). output_block : str Base Output or DSS Hydrograph Output (default). ras_object : RasPrj, optional Project used to resolve plan numbers; defaults to the global project.
Returns:¶
Dict[str, xr.DataArray]: Dictionary containing time series data for: - Pipe Flow (US/DS) - Velocity (US/DS)
Raises:
| Type | Description |
|---|---|
KeyError
|
If the stored conduit ID, network, or variable is missing. |
ValueError
|
If the output block, domain, or timestamps are invalid. |
Example
series = HdfPipe.extract_timeseries_for_conduit("model.p02.hdf", 85)
extract_timeseries_for_node
staticmethod
¶
extract_timeseries_for_node(plan_hdf_path: Union[str, Path, int, File], node_id: int, pipe_network_name: Optional[str] = None, output_block: str = 'DSS Hydrograph Output', *, ras_object=None) -> Dict[str, xr.DataArray]
Extract time series data for a specific node.
Parameters:¶
plan_hdf_path : str, Path, int or h5py.File Results HDF path, open file, or plan number resolved against ras_object. node_id : int Stored node ID from Node Indices, not a network column position. pipe_network_name : Optional[str] Network name (default: first geometry network). output_block : str Base Output or DSS Hydrograph Output (default). ras_object : RasPrj, optional Project used to resolve plan numbers; defaults to the global project.
Returns:¶
Dict[str, xr.DataArray]: Dictionary containing time series data for: - Depth - Drop Inlet Flow - Water Surface
Raises:
| Type | Description |
|---|---|
KeyError
|
If the stored node ID, network, or variable is missing. |
ValueError
|
If the output block, domain, or timestamps are invalid. |
Example
series = HdfPipe.extract_timeseries_for_node("model.p02.hdf", 121)
get_pipe_conduits
staticmethod
¶
get_pipe_conduits(hdf_path: Union[str, Path, int, File], crs: Optional[str] = None) -> gpd.GeoDataFrame
Extracts pipe conduit geometries and attributes from HDF5 file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path, int, File]
|
HDF path (str or Path), open h5py.File, or plan number |
required |
crs
|
Optional[str]
|
Coordinate Reference System override (default: stored projection) |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame with columns
|
|
GeoDataFrame
|
|
-Polyline
|
LineString geometries |
-Terrain_Profiles
|
List of (station, elevation) tuples |
Raises:
| Type | Description |
|---|---|
KeyError
|
If required geometry or one terrain-profile table is missing. |
ValueError
|
If geometry rows or profile slices are inconsistent. |
Example
conduits = HdfPipe.get_pipe_conduits("model.p02.hdf")
get_pipe_inlets
staticmethod
¶
Reads top and side inlet attributes from a HEC-RAS geometry HDF file.
Reads Geometry/Pipe Nodes/Top Inlets/Attributes and
Geometry/Pipe Nodes/Side Inlets/Attributes and combines them into a
single DataFrame with an inlet_type column indicating 'top' or
'side'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path, int, File]
|
HDF path, open file, or plan number. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing inlet attributes with an
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If a group exists but its Attributes dataset is missing. |
Example
inlets_df = HdfPipe.get_pipe_inlets("path/to/plan.hdf")
get_pipe_network
staticmethod
¶
get_pipe_network(hdf_path: Union[str, Path, int, File], pipe_network_name: Optional[str] = None, crs: Optional[str] = None) -> gpd.GeoDataFrame
Creates a GeoDataFrame for a pipe network's geometry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path, int, File]
|
HDF path (str or Path), open h5py.File, or plan number |
required |
pipe_network_name
|
Optional[str]
|
Name of network (uses first if None) |
None
|
crs
|
Optional[str]
|
Coordinate Reference System override (default: stored projection) |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame containing
|
|
GeoDataFrame
|
|
GeoDataFrame
|
|
GeoDataFrame
|
|
GeoDataFrame
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If required network geometry is missing. |
ValueError
|
If the network name, stored IDs, or geometry slices are invalid. |
Example
cells = HdfPipe.get_pipe_network("model.p02.hdf")
get_pipe_network_summary
staticmethod
¶
get_pipe_network_summary(hdf_path: Union[str, Path, int, File], pipe_network_name: Optional[str] = None) -> pd.DataFrame
Read literal Base summary rows and pipe-network volume-accounting attributes.
Select the first geometry network when pipe_network_name is omitted. Return long-form columns network, source, path, row, location, row_variable, units, value. Each stored summary row is retained; a one-row minimum never receives an invented time row. Labels/units are literal source metadata, even where the file's labels appear inconsistent. Summary datasets without Location do not claim a node/conduit domain or stored-ID mapping. Volume-accounting attributes use null row/location/units: the group's 'Vol Accounting in' attribute (itself returned as a row) names the volume unit and is not applied per attribute (e.g. 'Error Percent' is a percentage). DataFrame.attrs retains source shapes and complete dataset/group attributes. Missing both sources raises KeyError; malformed present datasets raise ValueError. A legacy Summary/Pipe Network table without geometry identities retains its original DataFrame shape when no network name is requested.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path, int, File]
|
HDF path (str or Path), open h5py.File, or plan number. |
required |
pipe_network_name
|
Optional[str]
|
Network name; defaults to the first geometry network. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Literal summary rows and volume-accounting attributes. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the network or both summary sources are missing. |
ValueError
|
If a stored summary or volume attribute is malformed. |
Example
summary = HdfPipe.get_pipe_network_summary("model.p02.hdf")
get_pipe_network_timeseries
staticmethod
¶
get_pipe_network_timeseries(hdf_path: Union[str, Path, int, File], variable: str, pipe_network_name: Optional[str] = None, output_block: str = 'DSS Hydrograph Output') -> xr.DataArray
Extracts timeseries data for a pipe network variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path, int, File]
|
HDF path (str or Path), open h5py.File, or plan number |
required |
variable
|
str
|
Variable name to extract. Valid options: - Cell: Courant, Water Surface - Face: Flow, Velocity, Water Surface - Pipes: Pipe Flow (DS/US), Vel (DS/US) - Nodes: Depth, Drop Inlet Flow, Water Surface |
required |
pipe_network_name
|
Optional[str]
|
Pipe network to read. When omitted, the first Geometry/Pipe Networks/Attributes entry is selected. |
None
|
output_block
|
str
|
Base Output or DSS Hydrograph Output. DSS remains the default for compatibility. Timestamps come only from that block; absent or mismatched timestamps raise ValueError. location remains positional; node_id/conduit_id are stored IDs. attrs records domain, stored_location, network and output_block. |
'DSS Hydrograph Output'
|
Returns:
| Type | Description |
|---|---|
DataArray
|
xarray.DataArray with dimensions (time, location). |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the network geometry or requested results are missing. |
ValueError
|
If the variable, output block, domain, or timestamps are invalid. |
Example
depth = HdfPipe.get_pipe_network_timeseries( ... "model.p02.hdf", "Nodes/Depth", output_block="Base Output")
get_pipe_nodes
staticmethod
¶
get_pipe_nodes(hdf_path: Union[str, Path, int, File], crs: Optional[str] = None) -> gpd.GeoDataFrame
Creates a GeoDataFrame for Pipe Node points and their attributes from an HDF5 file.
Reads Geometry/Pipe Nodes/Attributes (compound dtype) and
Geometry/Pipe Nodes/Points (x, y, z coordinates), merging them into a
single GeoDataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path, int, File]
|
HDF path, open file, or plan number. |
required |
crs
|
Optional[str]
|
Coordinate Reference System override (default: stored projection). |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame containing pipe node attributes and Point geometries. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the required pipe node geometry datasets are missing. |
Example
nodes_gdf = HdfPipe.get_pipe_nodes("path/to/plan.hdf")
get_pipe_profile
staticmethod
¶
Extract the profile data for a specific pipe conduit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path, int, File]
|
HDF path, open file, or plan number. |
required |
conduit_id
|
int
|
Stored conduit ID (global Geometry/Pipe Conduits row, not network position). |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing the pipe profile data. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the required datasets are not found in the HDF file. |
IndexError
|
If the specified conduit_id is out of range. |
ValueError
|
If the terrain profile slice is out of bounds. |
Example
profile = HdfPipe.get_pipe_profile("model.p02.hdf", 0)
HdfPump source reference¶
A class for handling pump station related data from HEC-RAS HDF files.
This class provides static methods to extract and process pump station data, including: - Pump station locations and attributes - Pump group configurations and efficiency curves - Time series results for pump operations - Summary statistics for pump stations
All methods are static and designed to work with HEC-RAS HDF files containing pump data.
get_pump_groups
staticmethod
¶
Extract pump group data from the HDF file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS HDF file. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing pump group data with columns: - efficiency_curve_start: Starting index of efficiency curve data - efficiency_curve_count: Number of points in efficiency curve - efficiency_curve: List of efficiency curve values - Additional attributes from the HDF file. Returns an empty DataFrame when the HDF file contains no pump station group. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the pump group exists but required datasets are missing. |
get_pump_operation_timeseries
staticmethod
¶
Extract detailed pump operation results data for a specific pump station.
Time comes only from DSS Profile Output: stored timestamps, or its numeric Time in days when timestamps are absent (attrs['time_units']='days'). Missing or malformed axes raise; Base Output and integer row indexes are never substituted. DSS timestamp text may have seconds or milliseconds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS HDF file. |
required |
pump_station
|
str
|
Name or identifier of the pump station. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing pump operation data with columns: - Time: Stored simulation timestamps, or elapsed days if absent - Flow: Pump flow rate - Stage HW: Headwater stage - Stage TW: Tailwater stage - Pump Station: Station identifier - Pumps on: Number of active pumps |
Raises:
| Type | Description |
|---|---|
KeyError
|
If required datasets are not found in the HDF file. |
ValueError
|
If the station is absent or its block-local time axis is malformed or has a different row count from the results. |
get_pump_station_summary
staticmethod
¶
Summarize each pump station's stored DSS Hydrograph Output results.
HEC-RAS (verified 6.6 and 7.0.1) writes no pump station summary table:
/Results/Unsteady/Summary holds only run and volume-accounting data,
and Base Output/Summary Output has no pump station group. Pump
results are stored only as time series in each output block under
Unsteady Time Series/Pumping Stations/<station>/Structure Variables
(columns named by its Variable_Unit attribute). This method derives
the summary from the DSS Hydrograph Output block, the same block
and time axis :meth:get_pump_station_timeseries returns.
Every statistic is derived exactly from the stored samples (no interpolation): the maximum/minimum is the largest/smallest stored finite value, and its time is the stored time of its first occurrence. Only output-interval samples are stored, so a peak between samples is not represented. Non-finite samples are ignored; a variable with no finite sample gets NaN values and times.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS HDF file. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per pump station (stored group order) with:
- Pump Station: station name (the result group name)
- Output Block: always |
DataFrame
|
Times are timestamps parsed from the block's stored |
DataFrame
|
|
DataFrame
|
dataset when no timestamps are stored (then |
DataFrame
|
|
DataFrame
|
summarized variable to its stored unit. HEC-RAS does not store |
DataFrame
|
pumped volume, pump run time or energy, so they are not reported. |
DataFrame
|
Returns an empty DataFrame (with a debug log) when the file has no |
DataFrame
|
DSS Hydrograph Output pump station results. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a station's stored layout is not the proven one
(2-D float data whose |
KeyError
|
If a station has no Structure Variables dataset or the block stores no time axis. |
get_pump_station_timeseries
staticmethod
¶
Extract timeseries results data for a specific pump station.
Time comes only from DSS Hydrograph Output: stored timestamps, or its numeric Time in days when timestamps are absent (time.units='days'). Missing or malformed axes raise; Base Output and integer row indexes are never substituted. DSS timestamp text may have seconds or milliseconds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS HDF file. |
required |
pump_station
|
str
|
Name or identifier of the pump station. |
required |
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray containing the timeseries data with dimensions: - time: Stored simulation timestamps, or elapsed days if absent - variable: Variables including ['Flow', 'Stage HW', 'Stage TW', 'Pump Station', 'Pumps on'] |
DataArray
|
Attributes include units and pump station name. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If required datasets are not found in the HDF file. |
ValueError
|
If the station is absent or its block-local time axis is malformed or has a different row count from the results. |
get_pump_stations
staticmethod
¶
get_pump_stations(hdf_path: Path, *, include_geometry: bool = True) -> Union[gpd.GeoDataFrame, pd.DataFrame]
Extract pump station data from the HDF file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS HDF file. |
required |
include_geometry
|
bool
|
Keyword-only. Pump stations are point
features, so the default True returns the GeoDataFrame below.
False is a table-only convenience without GeoPandas/Shapely or
a CRS lookup: |
True
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame containing pump station data with columns: - geometry: Point geometry of pump station location - station_id: Unique identifier for each pump station - Additional attributes from the HDF file. Returns an empty GeoDataFrame when the HDF file contains no pump station group. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the pump station group exists but required datasets are missing. |
HdfInfiltration source reference¶
A class for handling infiltration-related operations on HEC-RAS HDF geometry files.
This class provides methods to extract and modify infiltration data from HEC-RAS HDF geometry files, including base overrides of infiltration parameters.
calculate_soil_statistics
staticmethod
¶
calculate_soil_statistics(zonal_stats: list, raster_map: dict, cell_area_sqm: Optional[float] = None, no_data: Any = None) -> pd.DataFrame
Calculate soil statistics from zonal statistics
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zonal_stats
|
list
|
List of zonal statistics |
required |
raster_map
|
dict
|
Dictionary mapping raster values to mukeys |
required |
cell_area_sqm
|
Optional[float]
|
Area represented by one raster cell in square meters. Must be provided by the caller. |
None
|
no_data
|
Any
|
Optional NoData raster value to exclude. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with soil statistics including percentages and areas |
calculate_total_significant_percentage
staticmethod
¶
Calculate total percentage covered by significant mukeys
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
significant_mukeys
|
DataFrame
|
DataFrame of significant mukeys |
required |
Returns:
| Type | Description |
|---|---|
float
|
Total percentage covered by significant mukeys |
calculate_weighted_parameters
staticmethod
¶
Calculate weighted infiltration parameters based on soil statistics
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
soil_stats
|
DataFrame
|
DataFrame with soil statistics |
required |
infiltration_params
|
dict
|
Dictionary of infiltration parameters by mukey,
e.g. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary of weighted average infiltration parameters, keyed like |
dict
|
the first entry of |
dict
|
a |
dict
|
are its |
dict
|
is left out of the result (and a warning names it) when any |
contributing class does not have it
|
the key is missing, the value |
dict
|
is NaN, or it is |
dict
|
with |
dict
|
|
dict
|
attribute declares it, and it is the only negative value they |
dict
|
store. When no class contributes ( |
dict
|
empty, no mukey matches, or the total |
positive) the result is an empty dict and a warning is logged
|
|
dict
|
no value is supplied that the layer does not hold. |
create_infiltration_group
staticmethod
¶
create_infiltration_group(hdf_path: Union[str, Path], region_names: Optional[Sequence[str]] = None, hecras_version: Optional[str] = None, ras_object=None) -> pd.DataFrame
Deprecated wrapper for native infiltration-region creation.
create_infiltration_override_regions
staticmethod
¶
create_infiltration_override_regions(geometry_hdf_path: Union[str, Path], region_names: Optional[Sequence[str]] = None, hecras_version: Optional[str] = None, ras_object=None) -> pd.DataFrame
Create geometry infiltration regions through native RasMapperLib.
The polygons are copied from the geometry's native Land Cover
(Manning's n) regions. HEC-RAS authors the complete geometry
infiltration HDF schema, including the geometry-wide Base Overrides
fallback and separate per-region parameter tables. The result is
reloaded and validated.
Qualified runtimes are HEC-RAS 6.x and 7.0.x. The returned DataFrame
exposes geometry_hdf_path, backup_path, and
recompute_required in .attrs.
get_classification_polygons
staticmethod
¶
Read classification polygon overrides from an infiltration sidecar HDF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to an infiltration HDF file. |
required |
ras_object
|
RasPrj
|
Optional RasPrj object for API consistency. |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with |
get_infiltration_baseoverrides
staticmethod
¶
Retrieve current infiltration parameters from a HEC-RAS geometry HDF file. Dynamically reads whatever columns are present in the table.
Parameters¶
hdf_path : Path Path to the HEC-RAS geometry HDF file
Returns¶
Optional[pd.DataFrame] DataFrame containing infiltration parameters if successful, None if operation fails
get_infiltration_calibration_regions
staticmethod
¶
Retrieve infiltration calibration region data from a HEC-RAS geometry HDF file.
Reads compound datasets from Geometry/Infiltration/Variables (e.g.
Curve Number, Abstraction Ratio, Minimum Infiltration Rate) and builds
a DataFrame for each, indexed by the infiltration region names from
Geometry/Infiltration/Attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS geometry HDF file. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Dict[str, DataFrame]]
|
A dictionary mapping variable names (e.g. |
Optional[Dict[str, DataFrame]]
|
DataFrames where rows are regions and columns are land cover / soil |
Optional[Dict[str, DataFrame]]
|
combinations, or |
Example¶
regions = HdfInfiltration.get_infiltration_calibration_regions("model.g01.hdf") print(regions.keys()) dict_keys(['Curve Number', 'Abstraction Ratio', 'Minimum Infiltration Rate'])
get_infiltration_layer_data
staticmethod
¶
Retrieve current infiltration parameters from a HEC-RAS infiltration layer HDF file. Extracts the Variables dataset which contains the layer data.
Parameters¶
hdf_path : Path Path to the HEC-RAS infiltration layer HDF file
Returns¶
Optional[pd.DataFrame] DataFrame containing infiltration parameters if successful, None if operation fails
get_infiltration_map
staticmethod
¶
Read the infiltration raster map from HDF file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Optional path to the HDF file. If not provided, uses first infiltration_hdf_path from rasmap_df |
None
|
ras_object
|
RasPrj
|
Optional RAS object. If not provided, uses global ras instance |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary mapping raster values to mukeys |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
get_infiltration_parameters
staticmethod
¶
get_infiltration_parameters(hdf_path: Path = None, mukey: str = None, ras_object: Any = None) -> Optional[Dict[str, float]]
Get the infiltration parameters stored for one class of an infiltration layer.
Reads the Variables table of a RASMapper infiltration layer HDF
(the file referenced by the project's .rasmap; for example
Soils Data/Infiltration.hdf). HEC-RAS keys that table by the class
Name column: one row per class with one float column per parameter.
The row whose Name equals mukey exactly is returned.
What mukey must be depends on how the layer was built:
- Layers that depend on a soils layer only (one column in
Dependency Classifications) and legacy layers that carry their ownRaster Mapkey rows by the soil class name, e.g."167"or"329910_Docena"(theNameof the soils/infiltrationRaster Map). - Layers that depend on a land cover and a soils layer key rows by
the combined class, e.g.
"Mixed Forest : B". Parameters then vary by land cover, so a bare soil (or land cover) class does not identify one row and aValueErroris raised; pass the combined name (theNamevalues are listed by :meth:get_infiltration_layer_data).
The returned keys depend on the infiltration method (LC Type of
the layer):
- Deficit and Constant:
Maximum Deficit,Initial Deficit,Potential Percolation Rate. - Green-Ampt:
Wetting Front Suction,Saturated Hydraulic Conductivity,Initial Soil Water Content,Saturated Soil Water Content,Residual Soil Water Content,Pore Size Distribution Index(column order as stored). - SCS Curve Number:
Curve Number,Abstraction Ratio,Minimum Infiltration Rate.
Values are returned exactly as stored, in the project's unit system
(the layer does not record units), including the -9999.0 that
HEC-RAS 7.0.1 Green-Ampt layers store in Residual Soil Water
Content and Pore Size Distribution Index. Layer-wide
Properties (e.g. SCS Initial Loss Reset Time) are not per-class
parameters and are not included.
The keys returned by earlier versions (Initial Loss (in),
Constant Loss Rate (in/hr), Impervious Area (%)) cannot be
filled: HEC-RAS infiltration layers do not store them (impervious
percentage belongs to the land cover layer's Percent Impervious),
so they are not returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Optional path to the infiltration layer HDF. If not
provided, uses the first |
None
|
mukey
|
str
|
Class name to look up ( |
None
|
ras_object
|
RasPrj
|
Optional RAS object. If not provided, uses global ras instance. |
None
|
Returns:
| Type | Description |
|---|---|
Optional[Dict[str, float]]
|
The parameter columns of the matching |
Optional[Dict[str, float]]
|
|
Optional[Dict[str, float]]
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If the HDF has no |
ValueError
|
If |
get_infiltration_region_names
staticmethod
¶
Retrieve infiltration region names from a HEC-RAS geometry HDF file.
Reads the Name field from the structured array at
Geometry/Infiltration/Attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS geometry HDF file. |
required |
Returns:
| Type | Description |
|---|---|
Optional[List[str]]
|
A list of infiltration region name strings, or |
Optional[List[str]]
|
dataset does not exist. |
Example¶
names = HdfInfiltration.get_infiltration_region_names("model.g01.hdf") print(names) ['Grass', 'Paving - Concrete', 'Detention Pond']
get_infiltration_region_overrides
staticmethod
¶
get_infiltration_region_overrides(geometry_hdf_path: Union[str, Path], *, region_name: Optional[str] = None, region_id: Optional[int] = None, hecras_version: Optional[str] = None, ras_object=None) -> pd.DataFrame
Read one native infiltration-region parameter table.
Exactly one selector is required. region_id is zero-based.
Returned rows follow the associated native classification order.
get_infiltration_region_polygons
staticmethod
¶
Retrieve infiltration region polygons from a HEC-RAS geometry HDF file.
Reads polygon geometry from Geometry/Infiltration/Polygon Info,
Polygon Parts, Polygon Points, and region names from
Geometry/Infiltration/Attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS geometry HDF file. |
required |
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
A GeoDataFrame with columns |
GeoDataFrame
|
|
GeoDataFrame
|
layer is absent; missing siblings in a present layer raise. |
Read errors and malformed present polygon layers are logged and raised.
Example¶
gdf = HdfInfiltration.get_infiltration_region_polygons("model.g01.hdf") print(gdf[['Name', 'geometry']].head())
get_infiltration_stats
staticmethod
¶
get_infiltration_stats(geom_hdf_path: Path, landcover_hdf_path: Path = None, soil_hdf_path: Path = None, ras_object: Any = None) -> pd.DataFrame
Calculate combined land cover and soil infiltration statistics for each 2D flow area.
This function processes both land cover and soil data to calculate statistics for each combination (Land Cover : Soil Type) within each 2D flow area.
Parameters¶
geom_hdf_path : Path Path to the HEC-RAS geometry HDF file containing the 2D flow areas landcover_hdf_path : Path, optional Path to the land cover HDF file. If None, uses landcover_hdf_path from rasmap_df soil_hdf_path : Path, optional Path to the soil HDF file. If None, uses soil_layer_path from rasmap_df ras_object : Any, optional Optional RAS object. If not provided, uses global ras instance
Returns¶
pd.DataFrame DataFrame with combined statistics for each 2D flow area, including: - mesh_name: Name of the 2D flow area - combined_type: Combined land cover and soil type (e.g. "Mixed Forest : B") - percentage: Percentage of 2D flow area covered by this combination - area_sqm: Area in square meters - area_acres: Area in acres - area_sqmiles: Area in square miles - curve_number: Curve number for this combination - abstraction_ratio: Abstraction ratio for this combination - min_infiltration_rate: Minimum infiltration rate for this combination
Notes¶
Requires the rasterstats package to be installed.
get_landcover_raster_stats
staticmethod
¶
get_landcover_raster_stats(geom_hdf_path: Path, landcover_hdf_path: Path = None, ras_object: Any = None) -> pd.DataFrame
Calculate land cover statistics for each 2D flow area using the area's perimeter.
Parameters¶
geom_hdf_path : Path Path to the HEC-RAS geometry HDF file containing the 2D flow areas landcover_hdf_path : Path, optional Path to the land cover HDF file. If None, uses landcover_hdf_path from rasmap_df ras_object : Any, optional Optional RAS object. If not provided, uses global ras instance
Returns¶
pd.DataFrame DataFrame with land cover statistics for each 2D flow area, including: - mesh_name: Name of the 2D flow area - land_cover: Land cover classification name - percentage: Percentage of 2D flow area covered by this land cover type - area_sqm: Area in square meters - area_acres: Area in acres - area_sqmiles: Area in square miles - mannings_n: Manning's n value for this land cover type - percent_impervious: Percent impervious for this land cover type
Notes¶
Requires the rasterstats package to be installed. Area outputs are derived from categorical pixel counts scaled by raster cell area.
get_preprocessed_infiltration
staticmethod
¶
get_preprocessed_infiltration(hdf_path: Path, mesh_name: Optional[str] = None, variable: str = 'Curve Number', ras_object=None) -> pd.DataFrame
Read preprocessed per-cell infiltration values from geometry HDF.
Returns the exact per-cell infiltration parameter values that HEC-RAS
uses in computation, from
/Geometry/2D Flow Areas/{mesh}/Infiltration/{variable}.
These reflect all overrides (base + calibration regions) as resolved
during geometry preprocessing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Geometry HDF path, plan number ("01"), or geometry number ("g01"). |
required |
mesh_name
|
Optional[str]
|
Specific 2D flow area. If None, reads all. |
None
|
variable
|
str
|
Infiltration variable name. Common values: 'Curve Number', 'Abstraction Ratio', 'Minimum Infiltration Rate' |
'Curve Number'
|
ras_object
|
RasPrj
|
Optional RasPrj object for path resolution. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
mesh_name, cell_id, value |
Example
cn = HdfInfiltration.get_preprocessed_infiltration("01", variable='Curve Number')
get_preprocessed_infiltration_stats
staticmethod
¶
get_preprocessed_infiltration_stats(hdf_path: Path, mesh_name: Optional[str] = None, variable: str = 'Curve Number', ras_object=None) -> pd.DataFrame
Compute statistics on preprocessed per-cell infiltration values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Geometry HDF path, plan number ("01"), or geometry number ("g01"). |
required |
mesh_name
|
Optional[str]
|
Specific 2D flow area. If None, computes for all. |
None
|
variable
|
str
|
Infiltration variable name. |
'Curve Number'
|
ras_object
|
RasPrj
|
Optional RasPrj object. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
mesh_name, variable, n_cells, |
DataFrame
|
min_val, max_val, mean_val, median_val, std_val |
get_significant_mukeys
staticmethod
¶
Get mukeys with percentage greater than threshold
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
soil_stats
|
DataFrame
|
DataFrame with soil statistics |
required |
threshold
|
float
|
Minimum percentage threshold (default 1.0) |
1.0
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with significant mukeys and their statistics |
get_soil_raster_stats
staticmethod
¶
get_soil_raster_stats(geom_hdf_path: Path, landcover_hdf_path: Path = None, soil_hdf_path: Path = None, ras_object: Any = None) -> pd.DataFrame
Calculate combined land cover and soil infiltration statistics for each 2D flow area.
This function processes both land cover and soil data to calculate statistics for each combination (Land Cover : Soil Type) within each 2D flow area.
Parameters¶
geom_hdf_path : Path Path to the HEC-RAS geometry HDF file containing the 2D flow areas landcover_hdf_path : Path, optional Path to the land cover HDF file. If None, uses landcover_hdf_path from rasmap_df soil_hdf_path : Path, optional Path to the soil HDF file. If None, uses soil_layer_path from rasmap_df ras_object : Any, optional Optional RAS object. If not provided, uses global ras instance
Returns¶
pd.DataFrame DataFrame with combined statistics for each 2D flow area, including: - mesh_name: Name of the 2D flow area - combined_type: Combined land cover and soil type (e.g. "Mixed Forest : B") - percentage: Percentage of 2D flow area covered by this combination - area_sqm: Area in square meters - area_acres: Area in acres - area_sqmiles: Area in square miles - curve_number: Curve number for this combination - abstraction_ratio: Abstraction ratio for this combination - min_infiltration_rate: Minimum infiltration rate for this combination
Notes¶
Requires the rasterstats package to be installed.
get_soils_raster_stats
staticmethod
¶
get_soils_raster_stats(geom_hdf_path: Path, soil_hdf_path: Path = None, ras_object: Any = None) -> pd.DataFrame
Calculate soil group statistics for each 2D flow area using the area's perimeter.
Parameters¶
geom_hdf_path : Path Path to the HEC-RAS geometry HDF file containing the 2D flow areas soil_hdf_path : Path, optional Path to the soil HDF file. If None, uses soil_layer_path from rasmap_df ras_object : Any, optional Optional RAS object. If not provided, uses global ras instance
Returns¶
pd.DataFrame DataFrame with soil statistics for each 2D flow area, including: - mesh_name: Name of the 2D flow area - mukey: Soil mukey identifier - percentage: Percentage of 2D flow area covered by this soil type - area_sqm: Area in square meters - area_acres: Area in acres - area_sqmiles: Area in square miles
Notes¶
Requires the rasterstats package to be installed. Area outputs are derived from categorical pixel counts scaled by raster cell area.
save_statistics
staticmethod
¶
Save soil statistics to CSV
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
soil_stats
|
DataFrame
|
DataFrame with soil statistics |
required |
output_path
|
Path
|
Path to save CSV file |
required |
include_timestamp
|
bool
|
Whether to include timestamp in filename |
True
|
scale_infiltration_base_overrides
staticmethod
¶
scale_infiltration_base_overrides(geometry_hdf_path: Union[str, Path], infiltration_df: DataFrame, scale_factors: Mapping[str, float], hecras_version: Optional[str] = None, ras_object: Any = None) -> pd.DataFrame
Scale geometry-wide Base Overrides through native RasMapperLib.
scale_infiltration_baseoverrides
staticmethod
¶
scale_infiltration_baseoverrides(hdf_path: Union[str, Path], infiltration_df: DataFrame, scale_factors: Dict[str, float], hecras_version: Optional[str] = None, ras_object: Any = None) -> pd.DataFrame
Deprecated spelling alias for scale_infiltration_base_overrides.
scale_infiltration_data
staticmethod
¶
scale_infiltration_data(hdf_path: Union[str, Path], infiltration_df: DataFrame, scale_factors: Dict[str, float], hecras_version: Optional[str] = None, ras_object: Any = None) -> pd.DataFrame
Fail closed because the historical path type was ambiguous.
scale_infiltration_region_overrides
staticmethod
¶
scale_infiltration_region_overrides(geometry_hdf_path: Union[str, Path], infiltration_df: DataFrame, scale_factors: Mapping[str, float], *, region_name: Optional[str] = None, region_id: Optional[int] = None, hecras_version: Optional[str] = None, ras_object: Any = None) -> pd.DataFrame
Scale one region table and delegate exclusively to its setter.
region_id is zero-based. Sentinel values of -9999 remain
unchanged so that HEC-RAS continues to fall back to Base Overrides.
scale_infiltration_sidecar_parameters
staticmethod
¶
scale_infiltration_sidecar_parameters(infiltration_hdf_path: Union[str, Path], infiltration_df: DataFrame, scale_factors: Mapping[str, float], geometry_hdf_path: Union[str, Path, None] = None, hecras_version: Optional[str] = None, ras_object: Any = None) -> pd.DataFrame
Scale sidecar parameters and save through native RasMapperLib.
set_infiltration_base_overrides
staticmethod
¶
set_infiltration_base_overrides(geometry_hdf_path: Union[str, Path], infiltration_df: DataFrame, hecras_version: Optional[str] = None, ras_object=None) -> pd.DataFrame
Set geometry-wide Base Overrides through native RasMapperLib.
HEC's internal base ParameterSet is guarded by an exact ABI
fingerprint, serialized with InterpretationOverrideLayer.Save(), and
validated through a fresh native geometry reload. Qualified runtimes
are HEC-RAS 6.x and 7.0.x. The returned DataFrame exposes
geometry_hdf_path, backup_path, and recompute_required in
.attrs. Named region polygons do not constrain this table; use
:meth:set_infiltration_region_overrides for spatially bounded values.
set_infiltration_baseoverrides
staticmethod
¶
set_infiltration_baseoverrides(hdf_path: Union[str, Path], infiltration_df: DataFrame, hecras_version: Optional[str] = None, ras_object=None) -> pd.DataFrame
Deprecated spelling wrapper for the native Base Overrides setter.
set_infiltration_layer_data
staticmethod
¶
set_infiltration_layer_data(hdf_path: Union[str, Path], infiltration_df: DataFrame, geom_hdf_path: Union[str, Path, None] = None, hecras_version: Optional[str] = None, ras_object: Any = None) -> pd.DataFrame
Compatibility alias for :meth:set_infiltration_sidecar_parameters.
.. warning::
If the associated geometry HDF contains a
``/Geometry/Infiltration/Base Overrides`` dataset, values written
here are **ignored** by HEC-RAS during preprocessing. Use
``HdfInfiltration.set_infiltration_base_overrides()`` instead when
Base Overrides are present.
Parameters¶
hdf_path : Path Path to the HEC-RAS infiltration layer HDF file (sidecar). infiltration_df : pd.DataFrame DataFrame containing infiltration parameters with columns: - Name (string) - Curve Number (float) - Abstraction Ratio (float) - Minimum Infiltration Rate (float) geom_hdf_path : str, Path, or None Optional path to the geometry HDF (.g##.hdf). When provided, the function checks for Base Overrides and emits a warning if they exist.
Returns¶
pd.DataFrame The native table reloaded after RASMapper saves it.
set_infiltration_region_overrides
staticmethod
¶
set_infiltration_region_overrides(geometry_hdf_path: Union[str, Path], infiltration_df: DataFrame, *, region_name: Optional[str] = None, region_id: Optional[int] = None, hecras_version: Optional[str] = None, ras_object=None) -> pd.DataFrame
Set one native infiltration-region parameter table.
Exactly one selector is required. region_id is zero-based.
HEC-RAS serializes the selected public ParameterSet; fresh native
reload validation proves that global Base Overrides, region geometry,
names, and unrelated region tables were not changed.
set_infiltration_sidecar_parameters
staticmethod
¶
set_infiltration_sidecar_parameters(infiltration_hdf_path: Union[str, Path], infiltration_df: DataFrame, geometry_hdf_path: Union[str, Path, None] = None, hecras_version: Optional[str] = None, ras_object: Any = None) -> pd.DataFrame
Set infiltration sidecar parameters through native RasMapperLib.
This method preserves the native Variables schema, unknown
metadata, classification IDs, and RASMapper save semantics. The
returned DataFrame exposes classification_hdf_path,
backup_path, and recompute_required in .attrs.
HdfLandCover source reference¶
Final Manning's n computation from land cover, base values, and calibration regions.
Provides two access patterns: - Preprocessed cell values: Read the exact per-cell n-values that HEC-RAS computed during geometry preprocessing (fast, authoritative). - Raster composition: Combine base land cover raster + calibration table + region polygons to produce the full-resolution Final Manning's N raster (exportable, enables before/after comparison).
All methods are static - call directly without instantiation
HdfLandCover.get_preprocessed_mannings_n("project.g01.hdf")
audit_final_mannings_n
staticmethod
¶
audit_final_mannings_n(hdf_path: Union[str, Path], mesh_name: Optional[str] = None, tolerance: float = 0.0001, minimum_distinct_values: int = 2, expected_values: Optional[List[float]] = None, require_complete_geometry: bool = True, raise_on_failure: bool = True, ras_object: Any = None, minimum_cell_distinct_values: Optional[int] = None, expected_cell_values: Optional[List[float]] = None, minimum_face_distinct_values: Optional[int] = None, expected_face_values: Optional[List[float]] = None) -> pd.DataFrame
Audit the final Manning values embedded by HEC-RAS.
This reads the solver-owned geometry copied into either a geometry HDF
or a plan-result HDF. HEC-RAS 5.x is validated from column four of
Faces Area Elevation Values; 6.x and newer are also validated from
Cells Center Manning's n. Values closer than tolerance are
treated as the same class, preventing floating-point noise around one
default value from masquerading as spatial diversity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Union[str, Path]
|
Explicit |
required |
mesh_name
|
Optional[str]
|
Optional 2D flow-area name. |
None
|
tolerance
|
float
|
Minimum difference between materially distinct values. |
0.0001
|
minimum_distinct_values
|
int
|
Backward-compatible required number of face Manning values. |
2
|
expected_values
|
Optional[List[float]]
|
Backward-compatible values that must appear in the face array within tolerance. |
None
|
require_complete_geometry
|
bool
|
Require HEC-RAS's |
True
|
raise_on_failure
|
bool
|
Raise |
True
|
ras_object
|
Any
|
Reserved for API consistency. |
None
|
minimum_cell_distinct_values
|
Optional[int]
|
Optional required number of cell-
center Manning values. Use this to validate the solver's
|
None
|
expected_cell_values
|
Optional[List[float]]
|
Optional values that must appear in the cell-center array within tolerance. |
None
|
minimum_face_distinct_values
|
Optional[int]
|
Explicit face-array requirement;
overrides |
None
|
expected_face_values
|
Optional[List[float]]
|
Explicit face-array values; overrides
|
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One-row-per-area DataFrame with associations, cell and face value |
DataFrame
|
summaries, and a strict |
build_landcover_depth_roughness_curves
staticmethod
¶
build_landcover_depth_roughness_curves(landcover_hdf_path: Union[str, Path], depths: List[float], mannings_n_func: Callable[[float, float, str], float]) -> pd.DataFrame
Build depth-varying Manning's n curves from a land-cover sidecar HDF.
Parameters¶
landcover_hdf_path : Union[str, Path]
Path to the land-cover HDF containing IDs, Names, and
ManningsN datasets.
depths : List[float]
Depth values used to evaluate mannings_n_func.
mannings_n_func : Callable
Function (depth, base_n, class_name) -> n.
Returns¶
pd.DataFrame
Columns: pixel_value, class_name, depth,
base_mannings_n, and mannings_n.
compare_base_vs_calibrated
staticmethod
¶
Compare base Manning's n vs calibrated values per land cover class per region.
Shows the effect of calibration: which regions override which classes, and by how much. Only includes entries where the region has a non-zero override (actual calibration changes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Geometry HDF path, plan number ("01"), or geometry number ("g01"). |
required |
ras_object
|
Any
|
Optional RasPrj object for path resolution. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
land_cover_class, base_n, region_name, |
Optional[DataFrame]
|
calibrated_n, delta_n, pct_change. |
Optional[DataFrame]
|
None if calibration table not found. |
Example
comp = HdfLandCover.compare_base_vs_calibrated("project.g01.hdf") biggest = comp.nlargest(5, 'pct_change') print(biggest[['land_cover_class', 'region_name', 'base_n', 'calibrated_n', 'pct_change']])
compute_final_mannings_raster
staticmethod
¶
compute_final_mannings_raster(hdf_path: Path, landcover_hdf_path: Optional[Union[str, Path]] = None, output_tif_path: Optional[Union[str, Path]] = None, ras_object: Any = None) -> Optional[np.ndarray]
Deprecated alias for the non-authoritative raster estimate.
estimate_final_mannings_raster
staticmethod
¶
estimate_final_mannings_raster(hdf_path: Path, landcover_hdf_path: Optional[Union[str, Path]] = None, output_tif_path: Optional[Union[str, Path]] = None, ras_object: Any = None) -> Optional[np.ndarray]
Estimate Manning's n raster from base + calibration overrides.
Combines the base land cover raster with the calibration table and
region polygons to produce a full-resolution visualization estimate.
This is not the authoritative RASMapper FinalNValueLayer and must
not be used as proof of solver input. Use audit_final_mannings_n on
a completed geometry or plan HDF for that gate.
The land cover HDF is auto-resolved from the geometry's Land Cover Filename
attribute (set via RASMapper's Manage Associations menu), or can be overridden.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Geometry HDF path, plan number ("01"), or geometry number ("g01"). |
required |
landcover_hdf_path
|
Optional[Union[str, Path]]
|
Path to land cover HDF file. If None (default), auto-resolves from the geometry HDF's association attribute. |
None
|
ras_object
|
Any
|
Optional RasPrj object for path resolution. |
None
|
output_tif_path
|
Optional[Union[str, Path]]
|
If provided, writes result to GeoTIFF. |
None
|
Returns:
| Type | Description |
|---|---|
Optional[ndarray]
|
2D numpy array of final Manning's n values (same shape as land cover raster). |
0.0 marks no data
|
pixels whose class is not in the raster map, and |
Optional[ndarray]
|
classes whose stored Manning's n is a no-data value (NaN, -9999 in |
Optional[ndarray]
|
current layers, float32 max in legacy layers such as the NoData |
Optional[ndarray]
|
class or every class of a legacy combined layer). The written |
Optional[ndarray]
|
GeoTIFF stores those pixels as its nodata value, -9999. |
Optional[ndarray]
|
None if inputs cannot be resolved. |
Example
arr = HdfLandCover.estimate_final_mannings_raster("01") arr = HdfLandCover.estimate_final_mannings_raster( ... "project.g01.hdf", ... landcover_hdf_path="custom_landcover.hdf", # override ... output_tif_path="final_mannings_n.tif" ... )
export_final_mannings_raster
staticmethod
¶
export_final_mannings_raster(hdf_path: Path, output_tif_path: Union[str, Path], landcover_hdf_path: Optional[Union[str, Path]] = None, ras_object: Any = None, *, rasmapper_tile_corner: bool = True, compress: str = 'DEFLATE', writer: str = 'auto') -> Path
Write RAS Mapper's "Final n Values" raster without HEC-RAS.
Reproduces RAS Mapper 7.0.1's Export Raster of the geometry's "Final n Values" layer with its default options (original extent = the geometry extent, cell size = the land-cover TIFF cell size): 2D flow area default n, then the land-cover class n (calibration-table base values replace the land-cover values when valid), then calibration region overrides, with RAS Mapper's nearest-pixel class sampling and polygon rules. Pixel-identical to RAS Mapper 7.0.1 on the qualified models; see the fast-hdf documentation for the evidence.
Pure 2D geometries only: geometries with cross sections, river
centerlines or pipe networks, virtual (merged) land-cover layers and
multi-part polygons raise UnsupportedError (from the engine) rather
than produce a different raster. estimate_final_mannings_raster
remains available as the older estimate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Geometry HDF path, plan number or geometry number. |
required |
output_tif_path
|
Union[str, Path]
|
GeoTIFF to write (float32, nodata -9999, 256 x 256 tiles, the land-cover TIFF's CRS). |
required |
landcover_hdf_path
|
Optional[Union[str, Path]]
|
Land-cover HDF; default: the geometry's
|
None
|
ras_object
|
Any
|
Optional RasPrj object for path resolution. |
None
|
rasmapper_tile_corner
|
bool
|
|
True
|
compress
|
str
|
GeoTIFF compression ( |
'DEFLATE'
|
writer
|
str
|
|
'auto'
|
Returns:
| Type | Description |
|---|---|
Path
|
The output path. |
get_classification_polygons
staticmethod
¶
get_classification_polygons(landcover_hdf_path: Union[str, Path], ras_object: Any = None) -> gpd.GeoDataFrame
Read classification polygon overrides from a land-cover sidecar HDF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
landcover_hdf_path
|
Union[str, Path]
|
Path to a land-cover HDF file. |
required |
ras_object
|
Any
|
Optional RasPrj object for API consistency. |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with |
get_landcover_association
staticmethod
¶
Get the land cover HDF path associated with a geometry.
Reads the Land Cover Filename attribute from the geometry HDF
and resolves it to an absolute path. This is set via RASMapper's
"Manage Associations" menu.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Geometry HDF path, plan number ("01"), or geometry number ("g01"). |
required |
ras_object
|
Any
|
Optional RasPrj object. |
None
|
Returns:
| Type | Description |
|---|---|
Optional[Path]
|
Absolute path to the land cover HDF file, or None if not found. |
get_landcover_raster_map
staticmethod
¶
get_landcover_raster_map(landcover_hdf_path: Union[str, Path], ras_object: Any = None) -> Optional[pd.DataFrame]
Read the raster classification map from a land cover .hdf file.
Returns the mapping of integer pixel values to land cover class names and their associated Manning's n values.
Reads //Raster Map and //Variables from the land cover HDF.
Legacy RAS Mapper layers (still shipped in the HEC-RAS 7.0 example
projects, e.g. Muncie and Weise_2D) have no Raster Map; they store
the classes as parallel IDs, Names and ManningsN arrays,
where the stored ID is the class's pixel value. Those are read as
stored (Manning's n unconverted, including no-data values); arrays of
different lengths are refused (None).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
landcover_hdf_path
|
Union[str, Path]
|
Path to land cover HDF file (from rasmap_df['landcover_hdf_path']) |
required |
ras_object
|
Any
|
Optional RasPrj object for path resolution. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
pixel_value, class_name, mannings_n. |
Optional[DataFrame]
|
None if file cannot be read. |
Example
rmap = HdfLandCover.get_landcover_raster_map("LandCover.hdf") print(rmap[['class_name', 'mannings_n']].head())
get_mannings_calibration_table
staticmethod
¶
get_mannings_calibration_table(hdf_path: Path, ras_object: Any = None) -> Optional[pd.DataFrame]
Read the Manning's n calibration table from geometry HDF.
Returns the full calibration table showing base n-values and per-region overrides. Each row is a land cover class, each column after the first two is a calibration region. Values > 0 indicate an override; 0 means use the base value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Geometry HDF path, plan number ("01"), or geometry number ("g01"). |
required |
ras_object
|
Any
|
Optional RasPrj object for path resolution. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
Land Cover Name, Base Manning's n Value, |
Optional[DataFrame]
|
plus one column per calibration region. None if not found. |
Example
cal = HdfLandCover.get_mannings_calibration_table("01")
get_mannings_region_cell_mapping
staticmethod
¶
get_mannings_region_cell_mapping(hdf_path: Path, ras_object: Any = None) -> Optional[pd.DataFrame]
Read the cell-to-region mapping for Manning's n calibration regions.
Returns which cells fall within which calibration regions, from the preprocessed datasets in the geometry HDF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Geometry HDF path, plan number ("01"), or geometry number ("g01"). |
required |
ras_object
|
Any
|
Optional RasPrj object for path resolution. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
region_id, cell_index. |
Optional[DataFrame]
|
None if datasets not found. |
get_mannings_region_polygons
staticmethod
¶
Read Manning's n calibration region polygons from geometry HDF.
Returns the polygon geometries used for spatial override of Manning's n values. Each polygon defines a calibration region that can override base n-values for specific land cover classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Geometry HDF path, plan number ("01"), or geometry number ("g01"). |
required |
ras_object
|
Any
|
Optional RasPrj object for path resolution. |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame with columns
|
region_id, Name, 2D_Area_Name, geometry |
Read errors and malformed present polygon layers are logged and raised.
Example
regions = HdfLandCover.get_mannings_region_polygons("01")
get_preprocessed_mannings_n
staticmethod
¶
get_preprocessed_mannings_n(hdf_path: Path, mesh_name: Optional[str] = None, ras_object: Any = None) -> pd.DataFrame
Read preprocessed per-cell Manning's n from geometry HDF.
Returns the exact per-cell n-values that HEC-RAS uses in computation,
from /Geometry/2D Flow Areas/{mesh}/Cells Center Manning's n.
These values reflect the full override chain (base + calibration regions)
as resolved during geometry preprocessing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Geometry HDF path, plan number ("01"), or geometry number ("g01"). Resolved via @standardize_input to the geometry HDF file. |
required |
mesh_name
|
Optional[str]
|
Specific 2D flow area name. If None, reads all areas. |
None
|
ras_object
|
Any
|
Optional RasPrj object for path resolution. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
mesh_name, cell_id, mannings_n |
Example
df = HdfLandCover.get_preprocessed_mannings_n("01") # by plan number df = HdfLandCover.get_preprocessed_mannings_n("project.g01.hdf") # by path
get_preprocessed_mannings_stats
staticmethod
¶
get_preprocessed_mannings_stats(hdf_path: Path, mesh_name: Optional[str] = None, ras_object: Any = None) -> pd.DataFrame
Compute statistics on preprocessed per-cell Manning's n values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Geometry HDF path, plan number ("01"), or geometry number ("g01"). |
required |
mesh_name
|
Optional[str]
|
Specific 2D flow area. If None, computes for all. |
None
|
ras_object
|
Any
|
Optional RasPrj object. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
mesh_name, n_cells, min_n, max_n, |
DataFrame
|
mean_n, median_n, std_n |
Example
stats = HdfLandCover.get_preprocessed_mannings_stats("project.g01.hdf") print(stats)
set_landcover_mannings_n
staticmethod
¶
set_landcover_mannings_n(landcover_hdf_path: Union[str, Path], class_mapping: Mapping[str, float], hecras_version: Optional[str] = None, ras_object: Any = None) -> dict
Update Manning values through RASMapper's native table editor.
Direct h5py edits of Variables/ManningsN are intentionally not
supported: HEC-RAS owns the sidecar schema and may maintain additional
state when the classification table is saved.
HEC-RAS 5.x does not expose a native sidecar table writer. For 5.x,
use :meth:GeomLandCover.set_base_mannings_n or rebuild the native
layer with :meth:RasMap.add_landcover_layer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
landcover_hdf_path
|
Union[str, Path]
|
Native RASMapper land-cover sidecar. |
required |
class_mapping
|
Mapping[str, float]
|
Class-name to Manning-value mapping. |
required |
hecras_version
|
Optional[str]
|
Explicit HEC-RAS version. Required when
|
None
|
ras_object
|
Any
|
Initialized project object used to infer |
None
|
set_landcover_raster_map
staticmethod
¶
set_landcover_raster_map(hdf_path: Union[str, Path], class_mapping: Dict[str, float], ras_object: Any = None, *, hecras_version: Optional[str] = None) -> dict
Deprecated compatibility alias for set_landcover_mannings_n.
sanitize_classification_names
staticmethod
¶
sanitize_classification_names(landcover_hdf_path: Union[str, Path], raster_path: Optional[Union[str, Path]] = None, hecras_version: Optional[str] = None, ras_object: Any = None) -> LandCoverSanitizationResult
Sanitize land-cover labels through the native HEC-RAS 6.6 editor.
This labels-only operation preserves classification IDs, all numeric class parameters, and the companion TIFF. It is qualified only for HEC-RAS 6.6/6.6.0 because it calls RASMapper's native sanitizer and writes a legacy V1 sidecar back in the current V2 schema. It does not recreate or resample the raster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
landcover_hdf_path
|
Union[str, Path]
|
Native RASMapper land-cover sidecar. |
required |
raster_path
|
Optional[Union[str, Path]]
|
Exact companion TIFF path. When omitted, the wrapper resolves the path registered by RASMapper and records it in the result; supplied paths must match that native association. |
None
|
hecras_version
|
Optional[str]
|
Explicit HEC-RAS 6.6 or 6.6.0 version. Required when
|
None
|
ras_object
|
Any
|
Initialized project object used to infer |
None
|
Returns:
| Type | Description |
|---|---|
LandCoverSanitizationResult
|
A |
LandCoverSanitizationResult
|
complete before/after class-parameter snapshots, sidecar schema |
LandCoverSanitizationResult
|
versions, a durable backup path, and matching companion-TIFF |
LandCoverSanitizationResult
|
SHA-256 values. |
HdfPlot source reference¶
A class containing static methods for plotting general HDF data from HEC-RAS models.
This class provides plotting functionality for HDF data, focusing on geometric elements like cell polygons and time series data.
Note
matplotlib and geopandas are lazy-loaded when plotting methods are called.
plot_mesh_cells
staticmethod
¶
plot_mesh_cells(cell_polygons_df: DataFrame, projection: str, title: str = '2D Flow Area Mesh Cells', figsize: Tuple[int, int] = (12, 8)) -> gpd.GeoDataFrame
Plots the mesh cells from the provided DataFrame and returns the GeoDataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cell_polygons_df
|
DataFrame
|
DataFrame containing cell polygons. |
required |
projection
|
str
|
The coordinate reference system to assign to the GeoDataFrame. |
required |
title
|
str
|
Plot title. Defaults to '2D Flow Area Mesh Cells'. |
'2D Flow Area Mesh Cells'
|
figsize
|
Tuple[int, int]
|
Figure size. Defaults to (12, 8). |
(12, 8)
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame containing the mesh cells. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input DataFrame is empty. |
plot_time_series
staticmethod
¶
plot_time_series(df: DataFrame, x_col: str, y_col: str, title: str = None, figsize: Tuple[int, int] = (12, 6)) -> None
Plots time series data from HDF results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing the time series data |
required |
x_col
|
str
|
Name of the column containing x-axis data (usually time) |
required |
y_col
|
str
|
Name of the column containing y-axis data |
required |
title
|
str
|
Plot title. Defaults to None. |
None
|
figsize
|
Tuple[int, int]
|
Figure size. Defaults to (12, 6). |
(12, 6)
|
HdfResultsPlot source reference¶
A class containing static methods for plotting HEC-RAS results data.
This class provides visualization methods for various types of HEC-RAS results, including maximum water surface elevations and timing information.
plot_results_max_wsel
staticmethod
¶
Plots the maximum water surface elevation per cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_ws_df
|
DataFrame
|
DataFrame containing merged data with coordinates and max water surface elevations. |
required |
plot_results_max_wsel_time
staticmethod
¶
plot_results_max_wsel_time(max_ws_df: DataFrame, show_stats: bool = False) -> Optional[Dict[str, Any]]
Plots the time of the maximum water surface elevation (WSEL) per cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_ws_df
|
DataFrame
|
DataFrame containing merged data with coordinates and max water surface timing information. |
required |
show_stats
|
bool
|
If True, return concise timing statistics. |
False
|
plot_results_mesh_variable
staticmethod
¶
plot_results_mesh_variable(variable_df: DataFrame, variable_name: str, colormap: str = 'viridis', point_size: int = 10) -> None
Plot any mesh variable with consistent styling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variable_df
|
DataFrame
|
DataFrame containing the variable data |
required |
variable_name
|
str
|
Name of the variable (for labels) |
required |
colormap
|
str
|
Matplotlib colormap to use. Default: 'viridis' |
'viridis'
|
point_size
|
int
|
Size of the scatter points. Default: 10 |
10
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Raises:
| Type | Description |
|---|---|
ImportError
|
If matplotlib is not installed |
ValueError
|
If required columns are missing from variable_df |
fast_hdf source reference¶
The supported names of the native engine adapter (ras_commander.fast_hdf.__all__).
Adapter for ras-commander's default HDF engine, the native (Rust) extension.
The ras-commander-fast-hdf extension is a core dependency on the platforms
with published wheels (CPython on Windows x64, Linux x64 and macOS arm64). This
module routes the Hdf* classes' value reads through it and provides native
mesh assembly and direct PMTiles export. h5py is the reference implementation
and the public contract: in the default auto mode any native failure
(Corrupt/checksum refusals included) falls back to the h5py read, so callers see
the h5py outcome. Metadata and unsupported HDF types use h5py. Where the
extension is not installed or has an incompatible API_VERSION, every read
uses h5py.
RAS_COMMANDER_FAST_HDF=h5py (legacy 0) turns the native engine off;
native (legacy required) raises :class:FastHdfError instead of falling
back, which proves native execution in qualification runs. Explicit
backend='python' or 'rust' overrides the environment.
Public surface: __all__ lists the supported names (available,
close_sessions, FastHdfError, FastHdfPanicError, mesh_polygons,
packed_meshes and the export_* functions). Everything else here, in
particular read_typed/read_attrs/read_attr/read_dataset(s),
mesh_series_domain, trace_reads, native_required,
reraise_required, backend_scope and release_native_sessions (use
close_sessions(path)), is internal adapter plumbing for the Hdf*
classes and the qualification suites; it may change without notice.
Environment: RAS_COMMANDER_FAST_HDF (backend policy; an unrecognised value
is auto with one logged warning) and RAS_COMMANDER_HDF_SESSION_CACHE
(native session policy). See docs/api/hdf.md, "Native Rust HDF engine", and
docs/native-engine.md.
FastHdfError
¶
Bases: RuntimeError
The explicitly requested native operation could not be completed.
FastHdfPanicError
¶
Bases: FastHdfError
A Rust panic inside the native extension: an engine bug, not bad input.
The extension contains panics at every Python entry point and raises this
class while ras_commander.fast_hdf is imported (the standalone module
raises its own NativePanicError(RuntimeError)). Unlike PyO3's
PanicException it is an Exception, so auto mode falls back to
h5py and rust mode reports it as a :class:FastHdfError. A panic does
not poison a cached session; later reads and close() keep working.
available
¶
Whether a compatible extension can be imported, independently of policy.
close_sessions
¶
Release cached native file mappings before replacing HDFs or running RAS.
Omit path to close all cached files. Explicit HdfSession objects are owned by their caller and must be closed separately.
packed_meshes
¶
Return native packed polygon buffers keyed by mesh name.
Each entry contains coordinates (N, 2), ring offsets (C+1), and original cell IDs (C). Unsupported topology raises; no ring or cell is invented. This task API requires the optional extension, including in auto mode.
mesh_polygons
¶
Extract the established mesh GeoDataFrame, with explicit backend control.
backend takes the public engine values (auto/h5py/native);
see :meth:HdfMesh.get_mesh_cell_polygons for diagnostics.
export_pmtiles
¶
export_pmtiles(output_path, layers: Mapping, *, source_crs='EPSG:4326', min_zoom=0, max_zoom=12, backend='auto', threads=None)
Atomically export packed polygon layers through pyproj and freestiler.
layers maps source-layer names to coordinates, offsets, cell_ids and
optional property columns. Properties are aligned with the supplied IDs.
A property column is a sequence of scalars, a typed 1-D NumPy array, a
(values, valid) pair (False meaning null) or a
{"codes": int array, "categories": [str, ...]} dict (-1 null).
Engines that read columns natively (detected by capability) receive the
arrays without a Python object per value; others receive the equivalent
lists. Both give byte-identical archives.
Each layer may override source_crs. No feature-dropping is requested.
Legacy offsets describes one closed exterior ring per feature.
For holes/multipart, replace it with ring_offsets (coordinate spans),
polygon_offsets (ring spans: exterior first, then holes), and
feature_offsets (polygon spans). All are integer arrays starting at zero
with terminal sentinels. Components must be nonempty; an empty layer uses
[0] at each level. IDs/properties remain per feature. Coordinates must
describe valid polygons; ring winding is handled by freestiler.
export_mesh_pmtiles
¶
export_mesh_pmtiles(hdf_path, output_path, *, mesh_names=None, properties=None, layer_name='mesh_cells', source_crs=None, min_zoom=0, max_zoom=12, backend='auto', threads=None)
Write selected HDF meshes as one layer without per-cell Python geometry.
properties maps mesh name -> column name -> source-cell-indexed array.
Original mesh_name/cell_id properties are always retained; native
feature IDs are sequential and unique across the selected meshes. Ghost
result columns may exist, but only constructed cell IDs are exported.
export_arrow
¶
Export a typed Arrow table/reader through optional native source writers.
Required columns: nonnullable mesh_name:string and cell_id:int64, and geometry:binary (XY OGC WKB). Attributes: int64/uint64/float64/bool/string/ binary/timestamp[ms]. Nulls are explicit. CRS is required and compared with existing GeoArrow metadata. GeoJSON is transformed using pyproj always_xy; large integer attributes become decimal strings, times remain integer ms. Existing outputs reject. IPC staging adds disk I/O; Rust callers can feed RecordBatch iterators directly. No implicit Python fallback.
export_arrow_pmtiles
¶
export_arrow_pmtiles(output, batches, *, source_crs, min_zoom=0, max_zoom=12, max_batch_rows=65536, layer_name='features', threads=None, timestamp_ms=False, reuse_from=None)
Export an Arrow/WKB rendering bundle using freestiler and reversible IDs.
Output is a new directory containing tiles.pmtiles, identities.arrow and manifest.json. Existing bundles reject. Reuse a previous bundle to retain its composite identity mapping. Timestamps reject unless timestamp_ms=True; UInt64 must fit signed int64, binary properties reject. No custom tile repair.
HdfFluvialPluvial source reference¶
A class for analyzing and visualizing fluvial-pluvial boundaries in HEC-RAS 2D model results.
This class provides methods to process and visualize HEC-RAS 2D model outputs, specifically focusing on the delineation of fluvial and pluvial flood areas. It includes functionality for calculating fluvial-pluvial boundaries based on the timing of maximum water surface elevations.
Key Concepts: - Fluvial flooding: Flooding from rivers/streams - Pluvial flooding: Flooding from rainfall/surface water - delta_t: Time threshold (in hours) used to distinguish between fluvial and pluvial cells. Cells with max WSE time differences greater than delta_t are considered boundaries.
Data Requirements: - HEC-RAS plan HDF file containing: - 2D mesh cell geometry (accessed via HdfMesh) - Maximum water surface elevation times (accessed via HdfResultsMesh)
Usage Example
from ras_commander import HdfFluvialPluvial hdf_path = Path("path/to/plan.hdf")
To get just the boundary lines¶
boundary_lines_gdf = HdfFluvialPluvial.calculate_fluvial_pluvial_boundary( ... hdf_path, ... delta_t=12 ... )
To get classified flood polygons¶
flood_polygons_gdf = HdfFluvialPluvial.generate_fluvial_pluvial_polygons( ... hdf_path, ... delta_t=12, ... temporal_tolerance_hours=1.0 ... )
calculate_fluvial_pluvial_boundary
staticmethod
¶
calculate_fluvial_pluvial_boundary(hdf_path: Path, delta_t: float = 12, min_line_length: Optional[float] = None, *, engine: str = 'auto', diagnostics: bool = False) -> gpd.GeoDataFrame
Calculate the fluvial-pluvial boundary lines based on cell polygons and maximum water surface elevation times.
This function is useful for visualizing the line of transition between flooding mechanisms.
Cell identity is scoped by (mesh_name, cell_id). Adjacency never
crosses mesh boundaries, even when coordinates or native IDs coincide.
Processing failures log contextual ERROR with traceback and return an empty
GeoDataFrame, discarding partial output. A successful analysis with no
qualifying edges also returns empty. Input/decorator validation can raise.
The result depends only on the stored mesh and results, never on cell
polygon row order, ring direction or ring start vertex. Adjacency comes
from the stored Faces Cell Indexes topology (with an order-invariant
shared-ring-segment fallback when that dataset is absent). There is one
line per boundary cell pair, in sorted (mesh_name, cell_id) pair
order. Each line holds every face the two cells share, with the stored
face coordinates (a MultiLineString if the shared faces are not
contiguous).
Behavior change (after v0.106.1): earlier releases kept only the last ring segment of a shared face, so a curved face could yield a fragment that varied with polygon order, and coordinates were rounded to 8 decimals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS plan HDF file. |
required |
delta_t
|
float
|
Threshold time difference in hours. Cells with time differences greater than this value are considered boundaries. Default is 12 hours. |
12
|
min_line_length
|
float
|
Minimum length (in CRS units) for boundary lines to be included. Lines shorter than this will be dropped. Default is None (no filtering). |
None
|
engine
|
str
|
"auto" (default): the native Rust graph and threshold kernels when
they reproduce the reference result, otherwise the reference
implementation; which one ran is recorded in
|
'auto'
|
diagnostics
|
bool
|
Attach |
False
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame containing the fluvial-pluvial boundary lines. |
generate_fluvial_pluvial_polygons
staticmethod
¶
generate_fluvial_pluvial_polygons(hdf_path: Path, delta_t: float = 12, temporal_tolerance_hours: float = 1.0, min_polygon_area_acres: Optional[float] = None, *, engine: str = 'auto', diagnostics: bool = False) -> gpd.GeoDataFrame
Generates dissolved polygons representing fluvial, pluvial, and ambiguous flood zones.
This function classifies each wetted cell and merges them into three distinct regions based on the timing of maximum water surface elevation.
Times, adjacency and classifications retain (mesh_name, cell_id)
identity. Dissolved regions remain separate per mesh and classification;
native cell IDs are not renumbered. Processing failures log contextual ERROR
with traceback and return an empty GeoDataFrame, discarding partial output.
Existing input/decorator validation exceptions can still raise.
Classification depends only on the stored mesh and results, never on cell polygon row order, ring direction or ring start vertex:
- Adjacency comes from the stored
Faces Cell Indexestopology, with an order-invariant shared-ring-segment fallback when it is absent. - Seeding: for each adjacent pair whose max-WSE times differ by at least
delta_t, the later-peaking cell is evidence forfluvialand the earlier one forpluvial. A cell with evidence for both (it is in several competing pairs) is seededambiguousand does not grow. Equal times (possible only whendelta_t <= 0) seed nothing. - Region growth is simultaneous per iteration; a cell reached by both
fronts in the same iteration is
ambiguous. - Cells are dissolved in sorted
(mesh_name, cell_id)order with normalized rings, so thecell_idcolumn (the smallest cell in the class) and the geometry are reproducible.
Behavior change (after v0.106.1): earlier releases seeded pairs in adjacency
order and let the last pair win, so a cell in competing pairs took an
arbitrary label. Reordering identical polygons moved up to 55,000 sq ft
between classes on AustinOyster at delta_t=1. Results now change
once to the order-invariant rule; see the release notes.
Optionally, for polygons classified as fluvial or pluvial, if their area is less than min_polygon_area_acres, they are reclassified to the opposite type and merged with adjacent polygons of that type. Ambiguous polygons are exempt from this logic. Acreage uses the projected CRS axis units converted to square meters. Missing or geographic CRS skips filtering with a warning. Unresolved projected units or other processing failures log a contextual ERROR with traceback and return an empty GeoDataFrame; partial geometry is discarded. Input validation performed by the input decorator can still raise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Path to the HEC-RAS plan HDF file. |
required |
delta_t
|
float
|
The time difference (in hours) between adjacent cells that defines the initial boundary between fluvial and pluvial zones. Default is 12. |
12
|
temporal_tolerance_hours
|
float
|
The maximum time difference (in hours) for a cell to be considered part of an expanding region. Default is 1.0. |
1.0
|
min_polygon_area_acres
|
float
|
Minimum polygon area (in acres). For fluvial or pluvial polygons smaller than this, reclassify to the opposite type and merge with adjacent polygons of that type. Ambiguous polygons are not affected. |
None
|
engine
|
str
|
"auto" (default): the native Rust graph and threshold kernels when
they reproduce the reference result, otherwise the reference
implementation; which one ran is recorded in
|
'auto'
|
diagnostics
|
bool
|
Attach |
False
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
A GeoDataFrame with dissolved polygons for 'fluvial', 'pluvial', and 'ambiguous' zones. Processing failure returns an empty GeoDataFrame; partial geometry is never returned as complete. |
Raises:
| Type | Description |
|---|---|
Exception
|
Existing input/decorator validation errors are not suppressed. |
FastHdfError
|
Only under |
HdfBenefitAreas source reference¶
Analysis of benefit and rise areas from HEC-RAS 2D plan comparisons.
IMPORTANT: This module currently supports 2D mesh areas only. Analysis uses mesh cell polygons and maximum WSE at cell centers. For 1D cross section benefit analysis, see roadmap feature request.
This class provides methods to compare maximum water surface elevations between existing and proposed conditions, identifying areas where WSE is reduced (benefit) or increased (rise/adverse impact).
The analysis produces five GeoDataFrames: - benefit_polygons: Contiguous areas with WSE reduction - rise_polygons: Contiguous areas with WSE increase - existing_points: Max WSE points from existing plan - proposed_points: Max WSE points from proposed plan - difference_points: Matched points with WSE differences
Example
from ras_commander import init_ras_project, HdfBenefitAreas
Initialize project¶
init_ras_project("/path/to/project", "7.0")
Compare existing vs proposed using plan numbers¶
results = HdfBenefitAreas.identify_benefit_areas( ... existing_hdf_path="01", ... proposed_hdf_path="02", ... min_delta=0.1 ... )
OR use file paths directly (no project init needed)¶
results = HdfBenefitAreas.identify_benefit_areas( ... existing_hdf_path="/path/to/existing.p01.hdf", ... proposed_hdf_path="/path/to/proposed.p02.hdf", ... min_delta=0.1 ... )
Access results¶
benefit = results['benefit_polygons'] print(f"Benefit area: {benefit.geometry.area.sum() / 43560:.1f} acres")
identify_benefit_areas
staticmethod
¶
identify_benefit_areas(existing_hdf_path: Union[str, Path], proposed_hdf_path: Union[str, Path], min_delta: float = 0.1, match_precision: int = 6, adjacency_method: str = 'polygon_edges', dissolve: bool = True, ras_object: Optional[Any] = None) -> Dict[str, gpd.GeoDataFrame]
Identify benefit and rise areas by comparing two HEC-RAS 2D plans.
2D Models Only: This method analyzes 2D mesh areas. For 1D cross section benefit analysis, see roadmap feature request.
Compares maximum water surface elevations between existing and proposed conditions to identify areas where WSE is reduced (benefit) or increased (rise/adverse impact). Creates contiguous polygons using mesh cell adjacency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
existing_hdf_path
|
Union[str, Path]
|
Path to existing condition HDF file. Can be: - Plan number (e.g., "01") - HDF filename (e.g., "plan.p01.hdf") - Full path (e.g., "/path/to/plan.p01.hdf") |
required |
proposed_hdf_path
|
Union[str, Path]
|
Path to proposed condition HDF file. Can be: - Plan number (e.g., "02") - HDF filename (e.g., "plan.p02.hdf") - Full path (e.g., "/path/to/plan.p02.hdf") |
required |
min_delta
|
float
|
Minimum WSE difference threshold (feet). Points with |wse_difference| < min_delta are excluded from polygon creation. Default: 0.1 feet |
0.1
|
match_precision
|
int
|
Decimal precision for coordinate matching between plans. Points are matched by rounding x,y to this many decimals. Default: 6 (sub-millimeter precision) |
6
|
adjacency_method
|
str
|
Method for building cell adjacency ("polygon_edges" or "topology"). - "polygon_edges": Uses shared polygon edges (default, matches QGIS) - "topology": Uses face_cells from mesh topology (more robust) Default: "polygon_edges" |
'polygon_edges'
|
dissolve
|
bool
|
Whether to dissolve polygons by contiguous group. If False, returns individual mesh cell polygons. Default: True |
True
|
ras_object
|
RasPrj
|
Optional RAS project object (for multi-project workflows). If None, uses global ras object. |
None
|
Returns:
| Type | Description |
|---|---|
Dictionary with five GeoDataFrames
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If plan HDF files not found |
ValueError
|
If plans have incompatible mesh structures or no matching points |
Notes
- WSE difference = proposed - existing
- Negative difference = benefit (WSE reduced)
- Positive difference = rise (WSE increased)
- Area calculations assume coordinates are in feet (area_sqft = polygon.area)
- area_acres = area_sqft / 43560
Example
from ras_commander import init_ras_project, HdfBenefitAreas
Initialize project¶
init_ras_project("/path/to/project", "7.0")
Option 1: Use plan numbers¶
results = HdfBenefitAreas.identify_benefit_areas( ... existing_hdf_path="01", ... proposed_hdf_path="02", ... min_delta=0.1 ... )
Option 2: Use file paths directly (no project initialization needed)¶
results = HdfBenefitAreas.identify_benefit_areas( ... existing_hdf_path="/path/to/existing.p01.hdf", ... proposed_hdf_path="/path/to/proposed.p02.hdf", ... min_delta=0.1 ... )
Print summary¶
benefit = results['benefit_polygons'] rise = results['rise_polygons'] print(f"Benefit area: {benefit.geometry.area.sum() / 43560:.1f} acres") print(f"Rise area: {rise.geometry.area.sum() / 43560:.1f} acres")
Export to GeoPackage¶
benefit.to_file("benefit_areas.gpkg", layer="benefit", driver="GPKG") rise.to_file("benefit_areas.gpkg", layer="rise", driver="GPKG")
HdfChannelCapacity source reference¶
1D channel capacity analysis for HEC-RAS models.
Compares maximum water surface elevations from multiple AEP storm simulations against bank elevations to determine channel capacity at each cross section. Results are aggregated into segments and summarized as a system-wide capacity distribution.
All methods are static — do not instantiate this class.
Example
from ras_commander import HdfChannelCapacity banks = HdfChannelCapacity.extract_bank_elevations("g01.hdf") wse = HdfChannelCapacity.extract_max_wse(["p01.hdf", "p02.hdf"]) capacity = HdfChannelCapacity.determine_capacity(banks, wse)
analyze_channel_capacity
staticmethod
¶
analyze_channel_capacity(geom_hdf: Union[str, Path], plan_inputs: Union[str, Path, List[Union[str, Path]]], storm_order: Optional[List[str]] = None, profile_names: Optional[List[str]] = None, segment_length: float = DEFAULT_SEGMENT_LENGTH, ras_object: Optional[Any] = None) -> Dict[str, Any]
Complete channel capacity analysis pipeline.
Orchestrates all steps: bank elevation extraction, WSE extraction, capacity determination, segment aggregation, and system summary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geom_hdf
|
Union[str, Path]
|
Geometry HDF path, number, or filename |
required |
plan_inputs
|
Union[str, Path, List[Union[str, Path]]]
|
List of plan HDF paths/numbers (one per storm) |
required |
storm_order
|
Optional[List[str]]
|
Storm names in order from smallest to largest. Must match profile_names if provided. |
None
|
profile_names
|
Optional[List[str]]
|
Names for WSE columns. If None but storm_order is provided, uses storm_order as profile_names. |
None
|
segment_length
|
float
|
Segment length for aggregation (default 1320 ft) |
DEFAULT_SEGMENT_LENGTH
|
ras_object
|
Optional[Any]
|
Optional RAS project object |
None
|
Returns:
| Type | Description |
|---|---|
Dict with keys
|
xs_capacity: DataFrame — per-XS capacity levels segments: DataFrame — aggregated segment capacities summary: DataFrame — system capacity distribution (Table 2) bank_elevations: DataFrame — bank elevations at each XS max_wse: DataFrame — max WSE from each plan |
compare_conditions
staticmethod
¶
compare_conditions(existing_results: Union[Dict[str, Any], DataFrame], proposed_results: Union[Dict[str, Any], DataFrame], level: str = 'segments') -> pd.DataFrame
Compare channel capacity between existing and proposed conditions.
Produces a side-by-side segment-level comparison showing capacity level changes between two analysis results. A positive level change is an improvement because higher capacity levels contain larger events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
existing_results
|
Union[Dict[str, Any], DataFrame]
|
Dict from analyze_channel_capacity() or a capacity DataFrame for existing conditions. |
required |
proposed_results
|
Union[Dict[str, Any], DataFrame]
|
Dict from analyze_channel_capacity() or a capacity DataFrame for proposed conditions. |
required |
level
|
str
|
"segments" for default segment-level comparison, or "xs" for cross-section comparison. |
'segments'
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
River, Reach, segment_id (or RS for level="xs"), existing_level, existing_category, proposed_level, proposed_category, level_change, classification |
determine_capacity
staticmethod
¶
determine_capacity(bank_elevations: DataFrame, max_wse: DataFrame, storm_order: Optional[List[str]] = None) -> pd.DataFrame
Determine capacity level at each cross section.
Tests storms from smallest (most frequent) to largest (least frequent). For each XS, the capacity level corresponds to the largest storm the channel can contain without the WSE exceeding the controlling bank elevation. The sweep stops at the first overtopping event for each cross section, which is the conservative interpretation of channel capacity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bank_elevations
|
DataFrame
|
DataFrame from extract_bank_elevations() with columns: River, Reach, RS, controlling_bank_elev, Len Channel |
required |
max_wse
|
DataFrame
|
DataFrame from extract_max_wse() with columns: River, Reach, RS, plus one WSE column per storm |
required |
storm_order
|
Optional[List[str]]
|
Ordered list of storm column names in max_wse, from smallest to largest. If None, uses non-key columns in order. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
River, Reach, RS, controlling_bank_elev, Len Channel, capacity_level, capacity_category, last_contained_storm, plus one boolean overtop column per storm |
extract_bank_elevations
staticmethod
¶
extract_bank_elevations(geom_hdf: Union[str, Path], ras_object: Optional[Any] = None) -> pd.DataFrame
Extract bank elevations at each 1D cross section.
Uses np.interp() on station-elevation arrays at the Left Bank and Right Bank station positions from HdfXsec.get_cross_sections(). The controlling (higher) bank elevation is also computed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geom_hdf
|
Union[str, Path]
|
Path to geometry HDF file, geometry number (e.g., "01"), or HDF filename. Uses @_standardize_hdf_input resolution. |
required |
ras_object
|
Optional[Any]
|
Optional RAS project object for multi-project workflows. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
River, Reach, RS, Left Bank, Right Bank, left_bank_elev, right_bank_elev, controlling_bank_elev, thalweg_elev, channel_depth, Len Channel |
extract_max_wse
staticmethod
¶
extract_max_wse(plan_inputs: Union[str, Path, Dict[str, Union[str, Path, Tuple[Union[str, Path], str]]], List[Union[str, Path]]], profile_names: Optional[List[str]] = None, steady_profile_names: Optional[Union[str, List[Optional[str]], Dict[str, str]]] = None, ras_object: Optional[Any] = None) -> pd.DataFrame
Extract maximum water surface elevation at each XS from one or more plans.
Auto-detects format using the following fallback chain: 1. RAS 6.x unsteady summary output (Maximum Water Surface) 2. RAS 5.x/6.x unsteady time series (Water Surface -> max across time) 3. Steady-state profiles (selected profile or max across profiles)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plan_inputs
|
Union[str, Path, Dict[str, Union[str, Path, Tuple[Union[str, Path], str]]], List[Union[str, Path]]]
|
Single plan path/number or list of plan paths/numbers. A dict may be used as {output_column: plan_input}; dict values may also be (plan_input, steady_profile_name). |
required |
profile_names
|
Optional[List[str]]
|
Optional list of profile/storm names corresponding to each plan input. If None, uses "Plan_01", "Plan_02", etc. |
None
|
steady_profile_names
|
Optional[Union[str, List[Optional[str]], Dict[str, str]]]
|
Optional steady-state profile name(s) to select from plan HDF files. Use a string for one input, a list matching plan_inputs, or a dict keyed by output column. |
None
|
ras_object
|
Optional[Any]
|
Optional RAS project object for multi-project workflows. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
River, Reach, RS, plus one WSE column per plan (named by profile_names or "Plan_XX") |
extract_steady_profile_wse
staticmethod
¶
extract_steady_profile_wse(plan_hdf: Union[str, Path], profile_names: Optional[List[str]] = None, ras_object: Optional[Any] = None) -> pd.DataFrame
Extract individual steady-state profile WSE from a single plan HDF.
Unlike extract_max_wse() which collapses all profiles to a single max, this method preserves each profile as a separate column — required for channel capacity analysis on steady-state plans with multiple AEP profiles.
Typical use case: FEMA BLE models with 7 steady-state profiles (10-yr, 25-yr, 50-yr, etc.) stored in one plan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plan_hdf
|
Union[str, Path]
|
Path to plan HDF file, plan number, or HDF filename. |
required |
profile_names
|
Optional[List[str]]
|
Optional list of names for the WSE columns. If None, reads profile names from the HDF file (e.g., ['10-year', '25-year', '50-year', ...]). If provided, must match the number of profiles in the HDF. |
None
|
ras_object
|
Optional[Any]
|
Optional RAS project object for multi-project workflows. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
River, Reach, RS, plus one WSE column per steady-state profile |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the HDF file does not exist. |
ValueError
|
If the HDF contains no steady-state results, or profile_names length doesn't match profile count. |
segment_channel
staticmethod
¶
segment_channel(capacity_df: DataFrame, segment_length: float = DEFAULT_SEGMENT_LENGTH) -> pd.DataFrame
Aggregate cross section capacity into fixed-length channel segments.
Groups XS by River/Reach and creates segments of the specified length. Each segment's capacity is the weighted average of its constituent XS capacities (weighted by Len Channel), rounded DOWN (FLOOR) for conservative assessment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
capacity_df
|
DataFrame
|
DataFrame from determine_capacity() with columns: River, Reach, RS, capacity_level, Len Channel |
required |
segment_length
|
float
|
Segment length in model units (default 1320 ft = 0.25 mi) |
DEFAULT_SEGMENT_LENGTH
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
River, Reach, segment_id, segment_start_rs, segment_end_rs, weighted_capacity, capacity_level (floored), capacity_category, channel_length, xs_count |
system_capacity_summary
staticmethod
¶
Generate system-wide capacity distribution summary (Table 2).
Groups cross sections or channel segments by capacity level and computes the total channel length and percentage at each level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
capacity_df
|
DataFrame
|
DataFrame from segment_channel() with columns capacity_level and segment_length_ft/channel_length, or from determine_capacity() with capacity_level and Len Channel. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
capacity_level, capacity_category, channel_length_ft, percent_of_total |
DataFrame
|
Sorted by capacity_level (1-7). Percentages sum to 100%. |
HdfResultsAnalysis source reference¶
Cross-plan comparison and critical duration analysis for HEC-RAS results.
This class follows the HdfBenefitAreas pattern — a standalone analysis class in the hdf/ subpackage that compares results across multiple plan HDF files.
All methods are static — no instantiation required.
Example
from ras_commander import HdfResultsAnalysis
Compare peaks across storm duration plans¶
result = HdfResultsAnalysis.analyze_critical_duration( ... plan_numbers=['01', '02', '03'], ... plan_labels={'01': '6hr', '02': '12hr', '03': '24hr'}, ... threshold_pct=5.0 ... ) print(result[['location', 'critical_plan', 'max_peak']])
analyze_critical_duration
staticmethod
¶
analyze_critical_duration(plan_numbers: List[str], locations: Optional[List[str]] = None, threshold_pct: float = 5.0, plan_labels: Optional[Dict[str, str]] = None, reftype: str = 'lines', variable: str = 'Water Surface', ras_object: Optional[Any] = None) -> pd.DataFrame
Identify critical storm duration by comparing peaks across multiple plans.
For each reference location, extracts peak values from each plan's HDF file and identifies which plan produces the highest peak. Computes percentage differences and flags locations exceeding the threshold.
Parameters¶
plan_numbers : list of str Plan numbers to compare (e.g., ['01', '02', '03']) locations : list of str, optional Subset of reference locations to analyze. If None, uses all locations found in the HDF files. threshold_pct : float, default 5.0 Percentage difference threshold for flagging (e.g., R7's 5% rule). Locations where the difference between max and second-max peak exceeds this threshold are flagged. plan_labels : dict, optional Mapping of plan_number → descriptive label (e.g., {'01': '6hr'}). Used for column naming in output. If None, plan numbers are used. reftype : str, default 'lines' Reference type for HDF extraction ('lines' or 'points') variable : str, default 'Water Surface' Native HDF reference output variable to compare across plans. ras_object : optional Custom RAS object to use instead of the global one
Returns¶
pd.DataFrame One row per location with columns: - location: Reference name - peak_{label}: Peak value for each plan - critical_plan: Plan label with highest peak - max_peak: Highest peak value across plans - second_peak: Second highest peak value - pct_diff: Percentage difference between max and second peak - exceeds_threshold: Boolean flag if pct_diff > threshold_pct
Example¶
from ras_commander import HdfResultsAnalysis result = HdfResultsAnalysis.analyze_critical_duration( ... plan_numbers=['01', '02', '03'], ... plan_labels={'01': '6hr', '02': '12hr', '03': '24hr'} ... ) critical = result[result['exceeds_threshold']] print(f"{len(critical)} locations exceed {5.0}% threshold")
HdfProject source reference¶
Extract project-level geometry and metadata from HEC-RAS HDF files.
This class provides methods to calculate combined project extents from all model elements (2D areas, cross sections, river centerlines, storage areas) with configurable buffering for precipitation and terrain data downloads.
All methods are static. Extent methods can combine HDF and plain-text geometry.
export_extent_geojson
staticmethod
¶
export_extent_geojson(hdf_path: Union[str, Path], output_path: Union[str, Path], buffer_percent: float = 50.0, *, geom_path: Optional[Union[str, Path]] = None, fallback_to_plaintext: bool = True, ras_object=None) -> Path
Export project extent to GeoJSON file.
Parameters¶
hdf_path : str or Path Path to HEC-RAS geometry HDF file output_path : str or Path Path for output GeoJSON file buffer_percent : float, default 50.0 Buffer percentage to apply geom_path : path-like, optional Explicit companion plain-text geometry path. fallback_to_plaintext : bool, default True Use companion plain-text geometry when requested geometry is unavailable in HDF. Set False to require HDF-derived geometry only. ras_object : RasPrj, optional Project context for path and CRS resolution.
Returns¶
Path Path to created GeoJSON file
Examples¶
path = HdfProject.export_extent_geojson( ... "BaldEagle.g01.hdf", ... "project_extent.geojson", ... buffer_percent=50.0 ... )
get_project_bounds_latlon
staticmethod
¶
get_project_bounds_latlon(hdf_path: Optional[Union[str, Path, File]] = None, buffer_percent: float = 50.0, include_1d: bool = True, include_2d: bool = True, include_storage: bool = True, project_crs: Optional[str] = None, *, geom_path: Optional[Union[str, Path]] = None, fallback_to_plaintext: bool = True, ras_object=None) -> Tuple[float, float, float, float]
Get project bounds in WGS84 lat/lon coordinates.
Calculates project extent and transforms to WGS84 (EPSG:4326) for use with web services like AORC that expect lat/lon coordinates.
Parameters¶
hdf_path : path-like, optional Path to a geometry HDF, plain-text geometry, or plan number. buffer_percent : float, default 50.0 Buffer percentage to apply to extent include_1d : bool, default True Include 1D elements include_2d : bool, default True Include 2D elements include_storage : bool, default True Include storage areas from HDF or companion text geometry project_crs : str, optional Override CRS for projects without embedded projection. Use EPSG codes like "EPSG:26918" (UTM Zone 18N) or "EPSG:2271" (PA State Plane North). If None, attempts to read CRS from HDF file. geom_path : path-like, optional Explicit companion plain-text geometry path. ras_object : RasPrj, optional Project context for plan-number, geometry-path, and CRS resolution. fallback_to_plaintext : bool, default True Use plain-text geometry when requested geometry is unavailable in HDF. Set False to require HDF-derived geometry only.
Returns¶
Tuple[float, float, float, float] (west, south, east, north) in decimal degrees (WGS84)
Examples¶
west, south, east, north = HdfProject.get_project_bounds_latlon( ... "BaldEagle.g01.hdf", ... buffer_percent=50.0 ... ) print(f"Lat/Lon bounds: W={west}, S={south}, E={east}, N={north}")
For projects without embedded CRS, specify manually:¶
west, south, east, north = HdfProject.get_project_bounds_latlon( ... "BaldEagle.g01.hdf", ... buffer_percent=50.0, ... project_crs="EPSG:26918" # UTM Zone 18N ... )
get_project_crs
staticmethod
¶
Get the coordinate reference system from HDF file.
Parameters¶
hdf_path : Path Path to HEC-RAS geometry HDF file
Returns¶
str or None
Same value as HdfBase.get_projection: "EPSG:n" when an
EPSG code is strictly equivalent, otherwise WKT; None when the HDF,
.rasmap projection and terrain evidence is missing or conflicts.
Examples¶
crs = HdfProject.get_project_crs("BaldEagle.g01.hdf") print(f"Project CRS: {crs}")
get_project_extent
staticmethod
¶
get_project_extent(hdf_path: Optional[Union[str, Path, File]] = None, include_1d: bool = True, include_2d: bool = True, include_storage: bool = True, buffer_percent: float = 50.0, buffer_x_percent: Optional[float] = None, buffer_y_percent: Optional[float] = None, geometry_type: str = 'footprint', fill_holes: bool = True, *, geom_path: Optional[Union[str, Path]] = None, fallback_to_plaintext: bool = True, ras_object=None) -> Tuple[GeoDataFrame, Tuple[float, float, float, float]]
Calculate the combined project extent from all model elements.
With geometry_type='footprint' (default) this returns the true model
extent as a (multi)polygon: the union of 2D flow-area perimeters and 1D
reach footprints (built from river edge lines, see
HdfXsec.get_1d_footprint). With geometry_type='bbox' it returns
the legacy buffered bounding box.
In both modes the returned bounds tuple is the (optionally buffered)
bounding box of the geometry, so downstream callers that only use the
bounds (lat/lon conversion, data downloads) are unaffected.
Parameters¶
hdf_path : path-like, optional
Path to a geometry HDF (.g##.hdf), its plain-text geometry
file (.g##), or an existing plan-number input.
include_1d : bool, default True
Include 1D river reach footprints (footprint mode) or 1D cross
sections and river centerlines (bbox mode). Set include_2d=False to
get the 1D-only extent.
include_2d : bool, default True
Include 2D flow area perimeters. Set include_1d=False to get the
2D-only extent.
include_storage : bool, default True
Include storage area extents from HDF or companion text geometry.
buffer_percent : float, default 50.0
Buffer percentage. In bbox mode it expands the bounding box on each
axis (recommended 50% for precipitation to capture contributing
areas). In footprint mode it buffers the footprint polygon outward by
an equivalent distance. Pass buffer_percent=0 for the raw,
unbuffered footprint.
buffer_x_percent : float, optional
Override buffer for X axis (bbox mode). If None, uses buffer_percent.
buffer_y_percent : float, optional
Override buffer for Y axis (bbox mode). If None, uses buffer_percent.
geometry_type : {'footprint', 'bbox'}, default 'footprint'
'footprint' returns the true extent polygon; 'bbox' returns the
legacy buffered bounding box.
fill_holes : bool, default True
Footprint mode only. Remove interior sliver gaps (holes) from the
combined 1D + 2D footprint. Unioning 1D reach footprints with 2D
flow-area perimeters leaves thin interior rings wherever the two
boundaries overlap without aligning exactly (clearly visible on
Muncie). Set False to keep those holes. Ignored in 'bbox' mode. Only
interior rings are dropped; disconnected parts of a genuinely
multipart model (e.g. separate 2D flow areas) are always preserved.
geom_path : path-like, optional
Explicit plain-text geometry path. When omitted, the companion
.g## file is inferred from hdf_path. When its compiled HDF
sibling exists, usable HDF components remain preferred.
ras_object : RasPrj, optional
Project context for plan-number, geometry-path, and CRS resolution.
fallback_to_plaintext : bool, default True
Use the matching plain-text geometry when requested geometry is
unavailable in HDF. Set False to require HDF-derived geometry only.
Returns¶
Tuple[GeoDataFrame, Tuple[float, float, float, float]] - GeoDataFrame with the extent geometry (footprint polygon or box) and project CRS - Bounding box (minx, miny, maxx, maxy) in project CRS
Examples¶
True model footprint (raw, unbuffered)¶
gdf, bounds = HdfProject.get_project_extent( ... "BaldEagle.g01.hdf", buffer_percent=0.0 ... )
2D-only footprint¶
gdf_2d, _ = HdfProject.get_project_extent( ... "BaldEagle.g01.hdf", include_1d=False, buffer_percent=0.0 ... )
Legacy buffered bounding box (for precipitation download)¶
box_gdf, box_bounds = HdfProject.get_project_extent( ... "BaldEagle.g01.hdf", geometry_type='bbox', buffer_percent=50.0 ... )