Skip to content

Geometry Modules

Classes for parsing and modifying HEC-RAS geometry files.

Native property tables and regional mapping recovery

Use RasMap.recompute_property_tables(project, geometry, hecras_version="6.6") on a disposable model copy. For modern HEC-RAS versions, the computation runs in a separate Python process launched with -I to ignore PYTHONPATH and user-site startup hooks. It rejects preloaded foreign HDF5 DLLs, loads the selected installation's bin64 DLLs by absolute path, and checks their module handles and filenames. A native object probe verifies that managed HDF calls share reference-count changes with that exact DLL; version and thread-safety checks also run before computation. Installation, geometry, and recovery-source paths become absolute in the caller before the worker changes directories; mapped drive letters are preserved. The call raises on a native process failure or a 1,800-second timeout, then checks the existing complete-geometry and nonempty table-pair postconditions. It preserves the geometry's source CRS and units and does not establish hydraulic acceptance. The HEC-RAS 5.x route is unchanged. The isolated worker requires Windows Python, either on Windows or under Wine, and the mesh extra (pythonnet>=3.0.5). Native run qualification here covers HEC-RAS 6.6; other modern releases require their own qualification.

A compiled child with regional roughness polygons but no calibration table can fail in the native land-cover resampler. Recover a missing regional mapping from a same-source geometry whose native region attributes and polygon datasets are byte-identical:

Python
from ras_commander import GeomLandCover, RasMap

recovery = GeomLandCover.restore_mannings_region_mappings(
    "reference.g02.hdf", "child.g02.hdf", hecras_version="6.6"
)
RasMap.recompute_property_tables("study.prj", "child.g02", hecras_version="6.6")

The recovery is qualified with HEC-RAS 6.6. The caller must use geometries from the same source CRS and unit system; the method performs no coordinate or unit conversion. It refuses an existing target calibration table, changed region identities, duplicate class names, or finite base-table overrides. The method accepts only float32 numeric calibration columns. HEC-RAS writes the original regional mappings through its native mapping methods; the method verifies class names and float32 value bytes afterward. Native string storage widths may differ, so the returned source/target table hashes need not match. The receipt dictionary records those hashes, the backup path, class count, identity checks, and recompute_required=True. Native writing may also resize region-name storage and add an empty 2D Area Name attribute. Existing attribute values and all polygon datasets must remain unchanged; other attribute additions fail verification and roll back. Postwrite verification also preserves Complete Geometry, permits only the new calibration dataset, and compares every unrelated dataset with the backup.

The source remains read-only. The target is backed up and restored if recovery fails. No cell or face hydraulic dataset is copied, and recovery does not mark an incomplete geometry complete. Run native geometry/property computation and normal QA before accepting the child. These operations do not repair a changed mesh or establish equivalence between full and cropped terrains.

Unified Cross-Section Points

RasCrossSections.get_points(project, geometry) exports the same stable point schema from a plain-text .g## geometry or compiled .g##.hdf. Pass a RasPrj, project folder, or .prj file for project; pass a geometry number, title, text path, or HDF path for geometry. source="auto" prefers an available HDF for project geometry selectors, while an explicit source path keeps its source type.

Python
from ras_commander import RasCrossSections

points = RasCrossSections.get_points("Muncie.prj", "01")
points.to_csv("muncie-xs-points.csv", index=False)

The frame includes model/geometry/reach/XS identifiers; exact river, reach, and river-station strings; native and station order; cut-line relative distance; XYZ; Manning's n and bank fields; horizontal CRS/units; vertical units/datum; vertical_units_source; and source/extraction provenance. Native elevations are preserved by default. A vertical datum is never inferred from a horizontal CRS or a model centroid. When the source does not store a datum, pass vertical_datum= explicitly; vertical_units= is the highest-priority override, followed by the full project's text .prj marker. A direct HdfXsec.get_xs_coords() call uses only genuinely explicit HDF vertical-unit metadata and does not infer units from generic HDF unit-system flags. The source column reports explicit, project_text, geometry_hdf_explicit, or unknown.

The identifiers are deterministic within one export; collection-wide model identity remains the responsibility of the consuming catalog. Prefer Parquet for large exports because the complete transform-provenance JSON is repeated per point and can make CSV files unnecessarily large.

Vertical conversion is opt-in through VerticalTransform. Use either an exact PROJ pipeline or explicit source and target 3D/compound CRSs. The operation is run against every point's own X/Y/Z coordinate, and the requested operation, resolved PROJ definition, datum/unit labels, and PROJ/pyproj versions are stored in vertical_transform_provenance and DataFrame.attrs.

Python
from ras_commander import RasCrossSections, VerticalTransform

transform = VerticalTransform(
    source_vertical_datum="NAVD88",
    target_vertical_datum="Local project datum",
    source_vertical_units="ft",
    target_vertical_units="ft",
    pipeline="+proj=pipeline +step +proj=affine +zoff=1.25",
)

adjusted = RasCrossSections.get_points(
    "Muncie.prj",
    "01",
    vertical_datum="NAVD88",
    vertical_transform=transform,
)

An affine offset is shown only to make the explicit operation easy to inspect. For geodetic vertical transformations, use the project-approved PROJ pipeline or full compound CRS definitions and confirm required grid files are installed.

RAS Mapper Reach-Length QA

RasGeometryCompute.assess_flow_path_policy() determines whether a joined 1D reach may safely regenerate its overbank flow paths. It copies the whole project, forces RAS Mapper to regenerate flow paths on the copy, recomputes LOB/channel/ROB reach lengths, and compares them with the stored values. The source project is never modified.

Python
from ras_commander import RasGeometryCompute

policy = RasGeometryCompute.assess_flow_path_policy(
    "JoinedModel.g01.hdf",
    tolerance_fraction=0.01,
)

print(policy.recommended_policy)
display(policy.reach_metrics_df)
display(policy.xs_metrics_df)

The recommendation is regenerate_and_recompute only when every usable LOB and ROB interval reproduces its stored length within 1%. Otherwise it is preserve_and_recompute_only_at_join_boundary. The preserve policy is also selected when no source flow paths span a reach but its stored overbank lengths differ from the channel lengths. This prevents an automatically generated path from silently replacing evidence of intentionally different overbank routing.

For a provisional joined reach, pass the two cross sections adjacent to the join. The method returns exactly one regenerated left and right segment clipped between those cut lines. Save the review evidence directly as GeoParquet when desired:

Python
policy = RasGeometryCompute.assess_flow_path_policy(
    "JoinedModel.g01.hdf",
    join_upstream_xs=("Walnut", "Main", "5304.8"),
    join_downstream_xs=("Walnut", "Main", "4884.4"),
    review_segments_path="working/walnut_join_flow_paths.parquet",
)

display(policy.join_segments_gdf[["side", "length", "geometry"]])

Join selectors may use the full-precision restationed values returned by RasBreakout1D.assemble_network_edge().seams_gdf. Compiled geometry HDF files can store those values at a shorter displayed precision; the selector accepts a unique match within one unit of that displayed precision and still fails closed when more than one cross section could match.

The clipped segment lengths supply only the new join interval's LOB/ROB values; the remaining stored source lengths stay unchanged under the preserve policy. The returned geometries should be retained for visual review.

audit_main_channel_lengths() is the independent, read-only informative QA check. It accepts either a plain-text .g## geometry or a compiled .g##.hdf, measures the distance between adjacent cross-section intersections along the river centerline, and compares that distance with the stored channel reach length. It flags non-terminal intervals outside the supplied relative tolerance or with an invalid centerline intersection.

Python
channel_audit = RasGeometryCompute.audit_main_channel_lengths(
    "WALNUT 0229.g01",
    tolerance_fraction=0.01,
)
display(channel_audit[channel_audit["main_channel_flagged"]])

These APIs follow HEC's documented distinction: channel length comes from the river line, while LOB/ROB lengths come from flow paths. Automatically generated flow paths are review starting points rather than reconstructions of engineering judgment. See the official HEC-RAS Mapper pages for Cross Sections Rivers, River Station Markers, and Flow Path Lines.

GeomProjection

Model geometry reprojection helpers for copied HEC-RAS projects and plain-text geometry files.

Methods

  • reproject_model_geometry(project_path, source_crs, destination_crs, dest_folder=None, ...) - Copy a project folder, transform authored .g## model geometry coordinates, write a destination ESRI projection file, update copied .rasmap RASProjectionFilename references, and return terrain / compiled-geometry rebuild requirements.
  • reproject_geometry(geom_file, source_crs, destination_crs, output_geom=None, ...) - Transform one plain-text .g## file. By default writes a sibling copied geometry named *_reprojected.g##.

Both methods accept CRS inputs supported by pyproj.CRS.from_user_input(), plus ESRI .prj file paths or WKT text. Datum shifts are rejected by default because HEC-RAS project reprojection cannot reproduce geodetic datum transformations. Set allow_datum_shift=True only after a project-specific engineering review.

reproject_model_geometry() always works on a copied project folder. The destination cannot be the source project folder or a child of it, even with overwrite=True.

Python
from ras_commander import GeomProjection

report = GeomProjection.reproject_model_geometry(
    project_path="Muncie.prj",
    source_crs="EPSG:5070",
    destination_crs="EPSG:26915",
    dest_folder="Muncie_reprojected",
)

print(report["projection_file"])
print(report["terrain_requirements"])

The reprojection writer transforms authored text geometry such as river reach XY lines, cross-section GIS cut lines, storage-area and 2D perimeters, 2D seed points, breaklines, SA/2D connection lines, BC lines, reference lines, and IC point positions. It intentionally does not transform station/elevation tables, bank stations, compiled .g##.hdf geometry, refinement-region HDF datasets, terrain HDF/raster pixels, land-cover rasters, infiltration rasters, or sediment bed-material rasters. The returned report identifies compiled geometry preprocessing requirements, refinement-region HDF integrity findings, and terrain layers whose CRS no longer matches the destination project CRS.

Use existing CRS inspection and validation APIs with the returned report:

  • RasPrj.refresh_project_crs() to refresh the active project's inferred CRS.
  • RasMap.parse_rasmap() to inspect .rasmap projection and terrain paths.
  • RasMapValidation.check_layer_crs() to validate GIS/raster layers against an expected EPSG code.
  • HdfBase.get_projection() to inspect HDF or rasmap-associated projection metadata.

RasGeometry

Comprehensive 1D geometry parsing and modification.

Cross Section Methods

  • get_cross_sections(geom) - List all cross sections
  • build_cross_section(input_spec=None, **kwargs) - Build a complete Type 1 cross-section geometry entry from station/elevation, terrain, adjacent XS, bank, Manning's n, and reach-length inputs
  • get_station_elevation(geom, river, reach, station) - Get station-elevation pairs
  • set_station_elevation(geom, river, reach, station, sta_elev) - Modify station-elevation
  • get_mannings_n(geom, river, reach, station) - Get Manning's n values
  • get_bank_stations(geom, river, reach, station) - Get bank station locations

Cross Section Builder

GeomCrossSection.build_cross_section() returns a CrossSectionBuildResult with resolved station/elevation, bank stations, Manning's n breakpoints, reach lengths, fallback messages, and formatted .g## geometry lines. The method accepts either keyword arguments or a CrossSectionBuildInput dataclass.

Python
from ras_commander import (
    CrossSectionBankStations,
    CrossSectionManningsN,
    CrossSectionReachLengths,
    GeomCrossSection,
)

result = GeomCrossSection.build_cross_section(
    river="Example River",
    reach="Main",
    rs="1000",
    terrain_profile=terrain_df,  # columns: station/elevation or Station/Elevation
    cut_line=[(0.0, 0.0), (500.0, 0.0)],
    river_centerline=[(250.0, -50.0), (250.0, 50.0)],
)

entry_text = result.text

Fallback behavior is intentionally visible. Every fallback logs at ERROR level with river|reach|RS and also appears in result.fallback_messages. The builder always writes required Bank Sta=, #Sta/Elev=, and #Mann= records when enough station/elevation data can be resolved.

Resolution order:

  • Station/elevation: explicit station_elevation, terrain profile or RasTerrainMod.get_terrain_profile(), then adjacent XS interpolation.
  • Bank stations: explicit station/elevation, explicit stations with terrain elevations, river-centerline intersection with default 20-unit main-channel width, then profile-interpolated bank elevations when terrain is unavailable.
  • Manning's n: controlled by mannings_strategy. auto prefers land cover, neighboring XS interpolation, user values, then defaults (MC=0.06, LOB=ROB=0.08). Strategies landcover, neighbor, user, and default make a source preferred.
  • Point count: station/elevation output is capped at 500 points using a Douglas-Peucker-style reducer that preserves endpoints, banks, the thalweg, and major slope breaks.

Fully specified inputs avoid fallbacks:

Python
result = GeomCrossSection.build_cross_section(
    river="Example River",
    reach="Main",
    rs="1000",
    station_elevation=survey_df,
    bank_stations=CrossSectionBankStations(120.0, 180.0, 534.2, 533.8),
    mannings_n=CrossSectionManningsN(lob=0.08, channel=0.05, rob=0.08),
    reach_lengths=CrossSectionReachLengths(left=400.0, channel=390.0, right=410.0),
)
assert result.fallback_messages == []

Storage Area Methods

  • get_storage_areas(geom) - List storage areas
  • get_storage_elevation_volume(geom, name) - Get elevation-volume curve

Lateral Structure Methods

  • get_lateral_structures(geom) - List lateral structures
  • get_lateral_weir_profile(geom, name) - Get weir profile

Connection Methods

  • get_connections(geom) - List SA/2D connections
  • get_connection_weir_profile(geom, name) - Get connection weir profile
  • get_connection_gates(geom, name) - Get gate data

RasGeometryUtils

Parsing utilities for HEC-RAS geometry files.

Methods

  • parse_fixed_width(line, width=8) - Parse fixed-width formatted line
  • parse_count_line(line) - Parse count header line
  • interpolate_bank_station(sta_elev, bank) - Interpolate bank station elevation

GeomReferenceFeatures

Reference line and reference point helpers for 2D calibration and native reference-line output.

Reference Line Methods

  • add_reference_lines(geom_file, lines, storage_area) - Insert manually supplied reference lines into a .g## file
  • replace_reference_lines(geom_file, storage_area, reference_lines, *, expected_existing_names=..., create_backup=True) - Atomically replace or remove one existing 2D area's complete reference-line collection while preserving other areas; returns the backup path, or None when backups are disabled
  • generate_reference_lines_from_longitudinal_line(...) - Generate transverse reference-line dictionaries at regular station intervals along a named longitudinal line
  • add_reference_lines_from_longitudinal_line(...) - Generate and write transverse reference lines through the existing .g## writer
  • get_reference_lines(geom_file) - Read reference lines from a .g## file

Automated Reference Lines

Python
from ras_commander import GeomReferenceFeatures

reference_lines = GeomReferenceFeatures.generate_reference_lines_from_longitudinal_line(
    centerlines_gdf,
    longitudinal_line_name="Main River",
    spacing=500.0,
    line_length=1500.0,
    name_template="MainRiver_{station_int}",
)

GeomReferenceFeatures.add_reference_lines(
    "MyModel.g01",
    reference_lines,
    storage_area="Perimeter 1",
)

For result-guided orientation, pass orientation="velocity" or orientation="depth_velocity" with orientation_plan_hdf. Generated lines fall back to normal-to-line orientation unless orientation_fallback="raise" is set.

GeomMesh

See Meshing: Generation, Diagnostics and Repair for the complete method reference, runtime matrix, diagnostics, and repair evidence.

The repair contract, version support, and refinement caveats retain the existing qualification and failure limits.

Structure APIs

Inline structures are exposed through the public GeomInlineWeir, GeomBridge, and GeomCulvert classes. There is no public RasStruct class.

Inline Weir Methods

  • GeomInlineWeir.get_weirs(geom, river=None, reach=None) - List inline weirs
  • GeomInlineWeir.get_profile(geom, river, reach, station) - Get weir profile
  • GeomInlineWeir.get_gates(geom, river, reach, station) - Get gate data

Bridge Methods

  • GeomBridge.get_bridges(geom) - List bridges
  • GeomBridge.get_deck(geom, river, reach, station) - Get deck profile
  • GeomBridge.get_piers(geom, river, reach, station) - Get pier data
  • GeomBridge.get_abutment(geom, river, reach, station) - Get abutment data
  • GeomBridge.get_approach_sections(geom, river, reach, station) - Get approach sections
  • GeomBridge.get_coefficients(geom, river, reach, station) - Get coefficients
  • GeomBridge.get_hydraulic_methods(geom, river, reach, station) - Get bridge low-flow/high-flow method selections from Bridge Culvert-, Deck Dist Width WeirC, BR Coef=, and WSPro= records
  • GeomBridge.set_hydraulic_methods(geom, river, reach, station, low_flow_method=..., high_flow_method=..., weir_coefficient=...) - Set bridge modeling approach method selections and related coefficients
  • GeomBridge.get_htab(geom, river, reach, station) - Get HTAB settings

Accepted low_flow_method values are energy, momentum, yarnell, and wspro. Accepted high_flow_method values are energy and pressure_weir. Optional compute flags are use_energy, use_momentum, use_yarnell, and use_wspro. Optional coefficient fields include momentum_cd, yarnell_k, pressure_flow_submerged_inlet_cd, pressure_flow_submerged_inlet_outlet_cd, and positive weir_coefficient. Unsupported combinations, such as disabling the selected low-flow method or selecting Momentum/Yarnell without an existing or supplied coefficient, raise ValueError.

Culvert Methods

  • GeomCulvert.get_culverts(geom, river, reach, station) - Get all culverts at a bridge/culvert structure
  • GeomCulvert.get_all(geom, river=None, reach=None) - Get all culverts in a geometry file
  • GeomCulvert.set_culverts(geom, river, reach, station, culverts) - Replace culvert records at an existing bridge/culvert structure
  • GeomCulvert.set_culvert(geom, river, reach, station, culvert=None, culvert_index=None, culvert_name=None, **kwargs) - Update one culvert by index/name or append a new one
  • GeomCulvert.get_adjacent_cross_sections(geom, river, reach, station) - Find the nearest upstream and downstream cross sections around a structure
  • GeomCulvert.set_adjacent_ineffective_flow(geom, river, reach, station, upstream_ineffective=None, downstream_ineffective=None, ...) - Coordinate ineffective-flow writes on adjacent cross sections

set_culverts() accepts a DataFrame, list of dictionaries, or one dictionary. Shape can be supplied as Shape code or ShapeName for any taxonomy-backed HEC-RAS culvert shape: Circular, Box, Pipe Arch, Ellipse, Arch, Semi-Circle, Low Profile Arch, High Profile Arch, or Con Span. Required fields are validated against culvert_taxonomy.json, including shape-specific dimensions, positive/nonnegative numeric ranges, Chart #/Scale# combinations, a maximum of 10 culvert groups per crossing, and a maximum of 25 identical barrels per group. The API preserves legacy field names InletType and OutletType for HEC-RAS Chart # and Scale#; ChartID and ScaleID aliases are also accepted. Single-barrel records require UpstreamStation and DownstreamStation. Multi-barrel records require NumBarrels and matching BarrelStations pairs.

Python
from ras_commander.geom.GeomCulvert import GeomCulvert

GeomCulvert.set_culverts(
    "model.g01",
    "River",
    "Reach",
    "1000",
    [
        {
            "ShapeName": "Circular",
            "Span": 6,
            "Length": 50,
            "ManningsN": 0.013,
            "EntranceLoss": 0.5,
            "ExitLoss": 1.0,
            "InletType": 1,
            "OutletType": 1,
            "UpstreamInvert": 25.1,
            "UpstreamStation": 996,
            "DownstreamInvert": 25.0,
            "DownstreamStation": 996,
            "CulvertName": "Culvert #1",
        },
        {
            "ShapeName": "Pipe Arch",
            "Span": 7,
            "Rise": 5,
            "Length": 48,
            "ManningsN": 0.024,
            "EntranceLoss": 0.4,
            "ExitLoss": 1.0,
            "ChartID": 34,
            "ScaleID": 1,
            "UpstreamInvert": 26.2,
            "UpstreamStation": 1000,
            "DownstreamInvert": 25.8,
            "DownstreamStation": 1000,
            "CulvertName": "Pipe Arch",
        },
        {
            "ShapeName": "Box",
            "Span": 4,
            "Rise": 4,
            "Length": 55,
            "ManningsN": 0.015,
            "EntranceLoss": 0.3,
            "ExitLoss": 1.0,
            "InletType": 8,
            "OutletType": 1,
            "UpstreamInvert": 27.5,
            "DownstreamInvert": 27.0,
            "NumBarrels": 2,
            "BarrelStations": [(980, 980), (1020, 1020)],
            "CulvertName": "Twin Box",
        },
    ],
)

GeomCrossSection

Cross-section authoring and blocked-obstruction management.

Cross Section Builder

  • build_cross_section(input_spec=None, **kwargs) - Build complete cross-section geometry entry from terrain, survey, or adjacent XS data
  • get_blocked_obstructions(geom_file, river, reach, rs) - Read blocked obstructions for a cross section
  • set_blocked_obstructions(geom_file, river, reach, rs, obstructions) - Write blocked obstructions

See the Cross Section Builder section above for resolution order and fallback behavior.

GeomBridge

Bridge geometry authoring (deck profiles, piers, abutments, approach sections).

Methods

  • get_bridges(geom_file, river=None, reach=None) - List bridges
  • get_deck(geom_file, river, reach, rs) - Read bridge deck profile
  • set_deck(geom_file, river, reach, rs, deck_data, ...) - Write bridge deck profile

GeomBcLines

Read and author boundary condition line geometry.

GeomBcLines.get_bc_lines(geom_file) reads a plain-text .g## file into a DataFrame with name, storage_area, coordinates, and coordinate_count columns, in file order. Each coordinates value is a list of (x, y) tuples in the source coordinate system and units. The reader preserves stored precision, strips surrounding name padding, and rejects missing headers, invalid arc counts, truncated or non-finite coordinates, and missing text-position terminators. A file without BC lines returns an empty frame with the same columns. The call leaves the file unchanged and requires no initialized project, geometry HDF, or HEC-RAS installation. Start, middle, end, and text-position records must be present; their display position values are ignored. Returned vertices come only from the arc payload.

Python
from ras_commander import GeomBcLines

bc_lines = GeomBcLines.get_bc_lines("child.g01")
outlets = bc_lines.loc[bc_lines["storage_area"] == "Perimeter 1"]

Use HdfBndry.get_bc_lines() to read compiled geometry HDF lines instead. The text reader does not establish mesh attachment or boundary forcing.

replace_bc_lines(geom_file, unsteady_files, *, area_2d, lines, ras_object=None) replaces the complete named-area line set and its forcing in one staged transaction. Pass explicit paths in a disposable cloned project. Each line specification contains name, coordinates, and bc_type: Normal Depth requires friction_slope; Flow Hydrograph requires hydrograph_df and friction_slope; Stage Hydrograph requires hydrograph_df. Hydrographs use hour and value columns. The supplied forcing applies to every supplied flow file. An empty lines list clears the target area's named perimeter boundaries.

Other areas, 1D boundaries, and area-wide rainfall remain intact. Supply every associated unsteady file; an initialized clone ras_object verifies this set through project DataFrames and rejects flows shared with other geometries. Without that context, completeness is the caller's responsibility. The result is a DataFrame with geom_file, unsteady_file, area_2d, bc_line, and bc_type, plus removed names and backup paths in attrs.

Python
from ras_commander.geom import GeomBcLines

written = GeomBcLines.replace_bc_lines(
    "child.g01", ["child.u01"], area_2d="Perimeter 1",
    lines=[dict(name="OUTLET", coordinates=[(100, 200), (300, 200)],
                bc_type="Normal Depth", friction_slope=0.001)],
)

All inputs are validated and staged before replacement, with backups and byte-exact rollback on write exceptions. This is exception atomicity across the supplied files; individual file swaps are atomic. It does not provide crash-atomic visibility across multiple files. Exclude concurrent readers and writers. The method does not create the clone or update compiled HDF files. Run native preprocessing, then inspect HdfMesh.get_mesh_perimeter_faces() before relying on native face attachment. A complete disposable example is provided in scripts/validate_perimeter_bc.py; the companion fleet shell script targets fim-hecras-wine:6.6-clb-v8.

Methods

  • get_bc_lines(geom_file) - Read BC line identities and vertices from geometry text
  • add_bc_lines(geom_file, lines, replace_existing=False) - Add or upsert named geometry lines
  • delete_bc_line(geom_file, name) - Delete a named geometry line
  • rename_bc_line(geom_file, old_name, new_name) - Rename a geometry line
  • replace_bc_lines(...) - Replace all target-area lines and supplied unsteady references
  • set_bc_line_types(geom_file, line_types, *, hecras_dir=None, expected_geometry_sha256=None) - Persist explicit Internal/External classifications in a current compiled geometry through native RAS Mapper APIs. Supply exact BC names and types from the authored placement; lines not named keep their current type. The method requires matching text/HDF BC identities and coordinates, retains a sibling HDF backup, and returns before/after hashes and lines, one type decision per compiled line (unnamed lines included, unchanged). It uses an isolated process with HEC-RAS's bundled HDF5; it does not edit BC coordinates or forcing. Re-run geometry preprocessing after a type changes to rebuild connectivity.

Matching types return with changed=false, identical hashes and no backup or native write. For a real change, native export can omit the compiled Length field and compact identity string storage. The API validates the native row identities and every other retained value, then preserves the original attribute schema, metadata and quantities while copying only verified Type decisions. It never invents a missing length. The native receipt must list every compiled line exactly once with its expected type. Unknown field loss, input changes, an invalid or incomplete decision receipt, a type change on an unnamed line or type truncation fail and restore the whole HDF backup. The additive attribute_schema_preserved flag and, after native work, native_attribute_fields list describe this preservation in the existing ras-bc-line-types/v1 record. Recompile geometry after an actual type change; these fields do not establish native product completion or hydraulic acceptance.

GeomLateral

Complete SA/2D connection records

Use GeomLateral.get_connection_data(geom_file) to read one row per connection. The existing get_connections() metadata interface is unchanged. The complete reader adds LineCoordinates, CrestProfile, TerrainProfile, Culverts and Gates as nested DataFrames; WeirWidth and WeirCoefficient as model-unit scalars; Breach, UnknownRecords, ParseIssues and DefaultsUsed as lists; and exact RawBlock text. Reference-line and IC-point headers terminate a connection block; replacing external BC lines preserves those independent features and the connection inventory. Profiles use Station/Elevation, coordinates use X/Y. Unknown/version-specific records are preserved in raw form, not claimed to be decoded hydraulic parameters. An absent terrain profile is empty; no terrain is silently sampled. CRS, elevation units and vertical datum inherit the source model and are not converted or inferred.

write_connection_data(geom_file, connections_df, create_backup=True) replaces the connection inventory with the supplied complete rows, preserving unrelated geometry text. Omitted rows are removed deliberately. RawBlock is authoritative: decoded columns are checked against it; use focused setters to edit a physical field and reread before a lossless write. Duplicate names and inconsistent rows fail before mutation. Both APIs accept strings or Path objects; they operate on explicit geometry files, with no global project state.

Python
from pathlib import Path
import shutil
from ras_commander import GeomLateral, RasExamples

project = RasExamples.extract_project("BaldEagleCrkMulti2D", output_path="working/sa2d")
source = project / "BaldEagleDamBrk.g13"
child = Path("working/sa2d/roundtrip.g13")
shutil.copy2(source, child)
records = GeomLateral.get_connection_data(source)
GeomLateral.write_connection_data(child, records)
assert records.RawBlock.tolist() == GeomLateral.get_connection_data(child).RawBlock.tolist()

A runnable example is scripts/sa2d_connection_roundtrip.py.

Explicit physical authoring and clipping

GeomStorage.replace_breaklines() preserves the supplied native protection flag in geometry text: -1 and 1 enable one-cell protection; 0 disables it. Other integer values and fractional flags are rejected before mutation. Native HEC-RAS HDF/readback uses Boolean True/1 for the delivered text value -1.

set_connection(..., weir_width=..., weir_coef=..., crest_profile=...) requires explicit physical inputs. crest_profile is a DataFrame with Station and Elevation. Supply both exact existing area names and finite line coordinates. The historical width 100, coefficient 3 and zero crest are only available with allow_defaults=True; DefaultsUsed records which fields used that choice. These numbers are compatibility defaults, not qualified physical geometry. Callers supplying the former implicit defaults must opt in or provide measured parameters. Use culvert, gate, bridge and profile setters for specialized edits.

classify_connections(geom_file, child_boundary, retained_area_names=None, tolerance=0, allow_extended_support=False) returns a GeoDataFrame with Name, From, To, action, reason and support geometry. The default preserves the existing acceptance policy: gates and undecoded records block classification. The child geometry must use the source horizontal CRS and model units. Width-expanded line support and explicit culvert barrel coordinates are considered.

Pass allow_extended_support=True to include verified gate GIS support and accept cell-size metadata and the additional verified empty native bridge template. This adds gate_group_count before geometry in the return frame. The choice applies only to that read-only call; GeomStorage.clip_2d_flow_area() continues to use the default acceptance policy. Gate support requires explicit opening GIS lines, positive finite opening widths/heights and consistent opening counts/stations. The support includes each GIS line buffered by half its delivered gate width. gate_group_count counts verified native gate groups; unknown gate/bridge/breach support still blocks the edit. Empty native bridge templates do not establish physical bridge support. The expanded weir line is a conservative spatial screen; the delivered weir width is a schematic field, not a surveyed embankment footprint. Actions are keep, drop, block. Every decision has a stable reason code. Positive tolerance guards external separation; it does not excuse a physical footprint crossing the child perimeter. Named endpoints must remain present.

get_connection_gate_lines(geom_file, connection_name) reads only explicitly stored opening GIS lines and returns opening_index, opening_name, geometry in source model coordinates without an inferred CRS. Missing, incomplete, duplicated or nonconsecutive indexes and invalid coordinates raise ValueError; no gate GIS records return an empty frame. Station-derived substitute lines are not inferred. The HEC-RAS 6.6 User's Manual, Storage Area and 2D Flow Area Connections describes individual hydraulic-outlet GIS lines, including gates, and the schematic use of weir width. This parser's supported format is tested separately.

remap_connection_areas(geom_file, area_name_map) returns source-ordered Name and authoritative RawBlock pairs without changing the source. Only recognized endpoint area-name records change; physical and control records remain exact. Filter the returned frame and pass it to write_connection_data on a clone. Ambiguous endpoint records or invalid mapping names raise ValueError. Mapping names does not establish native attachment or hydraulic equivalence.

GeomStorage.clip_2d_flow_area(geom_file, flow_area_name, geometry, containment_tolerance=0, create_backup=True) stages all changes, retains internal records exactly and explicitly reports fully external removals. Partial or unknown affected support raises a reason-bearing error before changing the original. Unrelated areas and connections are retained. Its return value uses the six default decision columns; attrs['backup_path'] identifies the backup and attrs['attachment_status'] remains CONNECTION_ATTACHMENT_UNVERIFIED. It accepts a contained Polygon; hole-aware/multipart perimeter authoring remains outside this API. Existing set_2d_flow_area_perimeter() stays compatible and does not provide this connection-classification workflow.

Text retention does not establish attachment or hydraulic equivalence. After fresh native preprocessing, inspect HdfStruc.get_connection_attachments(). Missing native evidence remains unverified; an offset line inside only one area cannot establish the other attachment. Forward flow, tailwater reversal, wet/dry transitions and engineer-selected WSE/volume/peak gates still need hydraulic qualification against an unsplit control.

Lateral structure parsing and modification.

Methods

  • get_lateral_structures(geom_file) - List lateral structures
  • get_lateral_weir_profile(geom_file, name) - Get weir profile data

GeomStorage

Storage area and 2D flow area geometry parsing and writing.

Methods

  • get_storage_areas(geom_file) - List storage areas with elevation-volume data
  • get_2d_flow_areas(geom_file) - List 2D flow areas with settings
  • get_2d_flow_area_settings(geom_file) - Read 2D flow area computation settings
  • set_2d_flow_area_settings(geom_file, area_name, **settings) - Write 2D flow area settings (subgrid sampling, composite classification)
  • write_2d_flow_area_perimeter(geom_file, area_name, coordinates, ...) - Write 2D flow area perimeter
  • plan_2d_flow_area_perimeter(coordinates=..., geometry=...) - Plan native serialization without mutation. Removes only adjacent serialized XY pairs within the existing GeomMesh.PERIMETER_NEAR_DUPLICATE_TOL of 1e-6 source horizontal units, including closure. Uses the last retained point to bound chained removal; preserves distinct 0.003-unit edges. Returns original removed indexes, source/authored WKB hashes, tolerance, validity, boundary displacement and signed area change in source units (square units for area). The authored polygon must be valid, and removal-only displacement must stay within the near-duplicate tolerance. set_2d_flow_area_perimeter() uses this plan; callers retain their own final geometry/feature acceptance checks and canonical input artifacts.
  • replace_breaklines(geom_file, flow_area_name, breaklines, expected_existing_names=..., ...) - Atomically replace the geometry-global breakline collection while preserving supplied near/far spacing, near-repeat, and protection-radius values.

GeomMesh.clip_refinement_regions() accepts a valid, positive-area Polygon or MultiPolygon mask without holes. An inward buffer can split a narrow-necked child polygon into disconnected pieces; clipping retains every positive-area intersection fragment by default and preserves all native refinement controls. The read-only clip report retains its existing schema. This internal mask does not change the requirement to author one computational-domain polygon.

MeshRegenerationWorkflow

Exact RAS Mapper geometry import and legacy mesh-regeneration GUI workflows.

Methods

  • refresh_geometry_hdf_from_text(geom_number=..., geometry_name=..., flow_area_name=..., ras_object=..., ...) - Transactionally displace one exact geometry HDF, let the explicitly initialized HEC-RAS version rebuild it from task-local .g## text, validate the exact 2D perimeter and sibling-HDF isolation, and roll back on failure. This imports geometry features but does not create computation cells.
  • regenerate_mesh(geom_number=..., geometry_name=..., flow_area_name=..., ras_object=..., ...) - Open/save and validate an already-current exact geometry and compiled mesh.
  • regenerate_mesh_iterative(...) - Legacy retry workflow; exact geometry selectors are supported and no first-registration fallback is used.

Cross-section levees

GeomLevee is not a public class. Use GeomCrossSection.get_levees() and GeomCrossSection.set_levees(); their full contracts appear below.

Levee station-elevation parsing and modification.

Methods

  • GeomCrossSection.get_levees(...) - Read left/right levee points; unset points are NaN
  • GeomCrossSection.set_levees(...) - Write explicitly selected left/right station and elevation values

RasBreach

Breach discovery and parameter modification in plan files. Detailed computed results are read separately through HdfResultsBreach.

Methods

  • list_breach_structures_plan(plan_input, *, ras_object=None) - Return one dictionary per stored definition with structure, river, reach, station, and local stored is_active
  • read_breach_block(plan_input, structure_name, *, ras_object=None) - Return the named definition's location, raw values, and parsed table_rows
  • update_breach_block(plan_input, structure_name, *, is_active=None, method=None, geom_values=None, start_values=None, progression_mode=None, progression_pairs=None, downcutting_pairs=None, widening_pairs=None, calculator_data=None, dlb_methods=None, dlb_soil_type=None, dlb_soil_properties=None, dlb_core_soil_type=None, dlb_cover_option=None, dlb_cover_soil_properties=None, dlb_breach_direction=None, user_growth_flag=None, user_growth_ratio=None, mass_wasting_option=None, create_backup=True, ras_object=None) - Update complete stored fields and tables
  • set_breach_geom(plan_input, structure_name, *, centerline=None, final_bottom_width=None, final_bottom_elev=None, left_slope=None, right_slope=None, failure_mode=None, piping_coefficient=None, initial_piping_elevation=None, formation_time=None, weir_coefficient=None, initial_width=None, weir_coef=None, active=None, top_elev=None, formation_method=None, ras_object=None) - Update selected fields in the Breach Geom record; initial_width/weir_coef are deprecated safe aliases, while the three other legacy keywords fail closed with migration guidance
  • create_breach_block(plan_input, structure_name, *, river="", reach="", station="", is_active=True, create_backup=True, ras_object=None) - Create a new minimal stored breach block

The list output is the structure-level discovery API. Project-level plan_df contains only breach_definition_count and breach_active_count; it does not duplicate the full definition records.

Usage Examples

Cross Section Modification

Python
from ras_commander import RasGeometry, init_ras_project

init_ras_project("/path/to/project", "6.5")

# Get station-elevation
sta_elev = RasGeometry.get_station_elevation("01", "River", "Reach", "1000")

# Modify and save
sta_elev['elevation'] = sta_elev['elevation'] - 2.0
RasGeometry.set_station_elevation("01", "River", "Reach", "1000", sta_elev)

Breach Parameter Update

Python
from ras_commander import RasBreach

# Update named fields in Breach Geom
RasBreach.set_breach_geom(
    "01",
    "Dam1",
    formation_time=2.0,
    final_bottom_width=100.0,
    weir_coefficient=2.6,
)

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.

GeomParser source reference

Utility functions for parsing HEC-RAS geometry files.

All methods are static and designed to be used without instantiation.

create_backup staticmethod

Python
create_backup(file_path: Path) -> Path

Create .bak backup of file before modification.

Creates a backup copy with .bak extension. If .bak already exists, creates .bak1, .bak2, etc.

Parameters:

Name Type Description Default
file_path Path

Path to file to backup

required

Returns:

Type Description
Path

Path to backup file

Raises:

Type Description
FileNotFoundError

If original file doesn't exist

IOError

If backup creation fails

Example

from pathlib import Path geom_file = Path("MyProject.g01") backup = GeomParser.create_backup(geom_file) print(f"Backup created: {backup}") Backup created: MyProject.g01.bak

Notes
  • Based on RasGeo.set_mannings_baseoverrides() pattern
  • Always creates backup before file modification
  • Finds next available .bakN filename if .bak exists

extract_comma_list staticmethod

Python
extract_comma_list(line: str, keyword: str) -> List[str]

Extract comma-separated list following keyword.

Handles embedded commas in quoted strings properly.

Parameters:

Name Type Description Default
line str

Line containing keyword and comma-separated values

required
keyword str

Keyword before the list

required

Returns:

Type Description
List[str]

List of values (stripped of whitespace)

Example

line = "River Reach=White Lick,Reach 1" values = GeomParser.extract_comma_list(line, "River Reach") print(values) ['White Lick', 'Reach 1']

line = "Storage Area=Res Pool 1" values = GeomParser.extract_comma_list(line, "Storage Area") print(values) ['Res Pool 1']

Notes
  • Handles cases with or without commas
  • Handles quoted strings with embedded commas

extract_keyword_value staticmethod

Python
extract_keyword_value(line: str, keyword: str) -> str

Extract value following keyword marker.

Finds keyword followed by "=" and returns everything after the "=".

Parameters:

Name Type Description Default
line str

Line containing keyword

required
keyword str

Keyword to search for

required

Returns:

Type Description
str

Value after "=" (stripped of leading/trailing whitespace)

Example

line = "Geom Title=White Lick Creek Geometry" title = GeomParser.extract_keyword_value(line, "Geom Title") print(title) 'White Lick Creek Geometry'

line = "Program Version=6.30" version = GeomParser.extract_keyword_value(line, "Program Version") print(version) '6.30'

Notes
  • Keyword matching is case-insensitive
  • Returns empty string if keyword not found or no value after "="

extract_river_reach staticmethod

Python
extract_river_reach(line: str) -> Optional[Tuple[str, str]]

Parse modern and legacy 1D reach headers.

HEC-RAS 5+ writes River Reach=<river>,<reach>. Older projects can instead contain the single-name Reach=<name> form; when HEC-RAS upgrades those projects it materializes that name as both River and Reach. Mirror that vendor conversion so legacy projects classify as 1D before they are opened or mutated by HEC-RAS.

Returns:

Type Description
Optional[Tuple[str, str]]

(river, reach) for a recognized non-empty header, otherwise

Optional[Tuple[str, str]]

None.

format_fixed_width staticmethod

Python
format_fixed_width(values: List[float], column_width: int = 8, values_per_line: int = 10, precision: int = 2) -> List[str]

Format values into fixed-width lines for writing to geometry files.

Creates properly formatted lines with right-aligned values, left-padded with spaces to fill the column width. Follows HEC-RAS conventions: - 8-char columns: Typically 10 values per line (80 chars total) - 16-char columns: Typically 4 values per line (64 chars total)

Parameters:

Name Type Description Default
values List[float]

List of numeric values to format

required
column_width int

Width of each column in characters. Defaults to 8.

8
values_per_line int

Number of values per line. Defaults to 10.

10
precision int

Decimal places for formatting. Defaults to 2.

2

Returns:

Type Description
List[str]

Lines with fixed-width formatted values (with newlines)

Raises:

Type Description
ValueError

A value is non-finite or cannot fit the column.

Example

values = [0.0, 963.04, 27.2, 963.04] lines = GeomParser.format_fixed_width(values, 8, 10, 2) print(lines[0]) ' 0.00 963.04 27.20 963.04\n'

16-char columns for coordinates

coords = [648224.43125, 4551425.84375] lines = GeomParser.format_fixed_width(coords, 16, 4, 5) print(lines[0]) ' 648224.43125 4551425.84375\n'

Notes
  • Based on RasUnsteady.write_table_to_file() pattern
  • Requested decimals are retained where they fit, then reduced one at a time; values that cannot fit raise ValueError
  • Right-aligned within column, left-padded with spaces
  • Last line may have fewer than values_per_line values

get_1d_footprint staticmethod

Python
get_1d_footprint(geom_file: Union[str, Path], ras_object=None, *, crs: Optional[Any] = None, dissolve: bool = False)

Build 1D reach footprints from plain-text cross-section cut lines.

Cross sections are grouped by river and reach in geometry-file order. Their first and last coordinates form the two model edges, while the complete first and last cut lines close the reach ends. This assumes the canonical upstream-to-downstream file order used by HEC-RAS. Source-file orientation is preserved because endpoint proximity is not a reliable orientation signal for meandering reaches.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to the plain-text HEC-RAS geometry file (.g##).

required
ras_object RasPrj

Optional RasPrj instance used for CRS context.

None
crs CRS or str

Optional CRS assigned to the returned GeoDataFrame. When omitted, ras_object.project_crs is used if available.

None
dissolve bool

Return one combined footprint row when True; otherwise return one row per river/reach.

False

Returns:

Type Description
GeoDataFrame

Columns River, Reach, source, and geometry. Reaches with fewer than two usable cross sections are omitted.

get_geom_title staticmethod

Python
get_geom_title(geom_file: Union[str, Path]) -> str

Read the Geom Title from a HEC-RAS geometry file.

Scans the .g## text file line-by-line for Geom Title= and returns the value. Returns an empty string if the keyword is not present.

Parameters

geom_file : Union[str, Path] Path to the .g## geometry text file.

Returns

str The geometry title, or "" if not found.

Raises

FileNotFoundError If geom_file does not exist.

Examples

title = GeomParser.get_geom_title("MyProject.g01") print(f"Geometry title: {title}") Geometry title: White Lick Creek Geometry

get_river_centerlines staticmethod

Python
get_river_centerlines(geom_file: Union[str, Path], ras_object=None)

Extract river/reach centerline coordinates from geometry file.

Parses "Reach XY=" sections from .g## files and returns a GeoDataFrame with LineString geometries for each river reach.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
ras_object RasPrj

Optional RasPrj instance (unused, for API consistency)

None

Returns:

Type Description
GeoDataFrame

DataFrame with columns: river, reach, geometry (LineString). CRS is not set.

Raises:

Type Description
FileNotFoundError

If geometry file does not exist

ImportError

If geopandas or shapely are not installed

Example

from ras_commander import GeomParser rivers = GeomParser.get_river_centerlines("model.g01") for _, row in rivers.iterrows(): ... print(f"{row['river']}/{row['reach']}: {len(row['geometry'].coords)} pts")

get_xs_cut_lines staticmethod

Python
get_xs_cut_lines(geom_file: Union[str, Path], ras_object=None)

Extract cross-section GIS cut line coordinates from geometry file.

Parses "XS GIS Cut Line=" sections from .g## files and returns a GeoDataFrame with LineString geometries for each cross-section.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
ras_object RasPrj

Optional RasPrj instance (unused, for API consistency)

None

Returns:

Type Description
GeoDataFrame

DataFrame with columns: river, reach, station, geometry (LineString). CRS is not set (caller should set based on project CRS).

Raises:

Type Description
FileNotFoundError

If geometry file does not exist

ImportError

If geopandas or shapely are not installed

Example

from ras_commander import GeomParser xs_gdf = GeomParser.get_xs_cut_lines("model.g01") print(f"Found {len(xs_gdf)} cross-sections") xs_gdf = xs_gdf.set_crs(epsg=2278) # Set project CRS

identify_section staticmethod

Python
identify_section(lines: List[str], keyword: str, start_index: int = 0) -> Optional[Tuple[int, int]]

Find section boundaries based on keyword marker.

Searches for a line starting with the specified keyword and determines where the section ends (either at the next keyword or end of file).

Parameters:

Name Type Description Default
lines List[str]

All lines from geometry file

required
keyword str

Section marker keyword to search for

required
start_index int

Line index to start searching from. Defaults to 0.

0

Returns:

Type Description
Optional[Tuple[int, int]]

(start_line, end_line) or None if not found start_line: Index of line with keyword end_line: Index of last line in section (exclusive)

Example

with open("geometry.g01") as f: ... lines = f.readlines() section = GeomParser.identify_section(lines, "River Reach=") if section: ... start, end = section ... print(f"River Reach section: lines {start} to {end}")

Notes
  • Keyword matching is case-insensitive
  • Returns None if keyword not found
  • Section ends at next keyword starting with capital letter or "=" sign

interpret_count staticmethod

Python
interpret_count(keyword: str, count_value: int, additional_values: Optional[List[int]] = None) -> int

Interpret count declarations based on keyword context.

CRITICAL: Different keywords use counts differently. This is a common source of parsing bugs if not handled correctly.

Count Interpretation Rules: - "#Sta/Elev= 40" -> 40 PAIRS -> 80 total values (station + elevation) - "#Mann= 3 , 0 , 0" -> 3 SEGMENTS -> 9 total values (3 left + 3 channel + 3 right) - "Reach XY= 591" -> 591 PAIRS -> 1182 total values (591 X + 591 Y) - "Storage Area Elev Volume= 53" -> 53 PAIRS -> 106 total values - "Levee= 12 , 0" -> 12 + 0 = 12 values (left side only)

Parameters:

Name Type Description Default
keyword str

Section keyword (e.g., "#Sta/Elev", "#Mann", "Reach XY")

required
count_value int

First count value after keyword

required
additional_values Optional[List[int]]

Additional count values if comma-separated

None

Returns:

Type Description
int

Total number of values to read from the file

Example

Station/elevation: 40 pairs = 80 values

GeomParser.interpret_count("#Sta/Elev", 40) 80

Manning's n: 3 segments x 3 positions = 9 values

GeomParser.interpret_count("#Mann", 3, [0, 0]) 9

Reach coordinates: 591 pairs = 1182 values

GeomParser.interpret_count("Reach XY", 591) 1182

Levees: 12 left + 0 right = 12 values

GeomParser.interpret_count("Levee", 12, [0]) 12

Notes
  • See _PARSING_PATTERNS_REFERENCE.md for complete count interpretation guide
  • This is based on extensive validation against HDF files

parse_fixed_width staticmethod

Python
parse_fixed_width(line: str, column_width: int = 8) -> List[float]

Parse fixed-width numeric data from a line.

HEC-RAS uses FORTRAN-era fixed-width columns for numeric data: - 8-character columns: Station/elevation, Manning's n, elevation-volume - 16-character columns: 2D coordinates (X, Y pairs)

Values are right-aligned and left-padded with spaces within each column. This function MUST parse by column position, NOT by whitespace splitting.

Parameters:

Name Type Description Default
line str

Line containing fixed-width values

required
column_width int

Width of each column in characters. Defaults to 8. Use 16 for 2D coordinate data.

8

Returns:

Type Description
List[float]

Parsed numeric values

Raises:

Type Description
ValueError

If a column contains non-numeric data that can't be parsed

Example

8-character columns (station/elevation)

line = " 0 963.04 27.2 963.04 32.64 963.02" values = GeomParser.parse_fixed_width(line, 8) print(values) [0.0, 963.04, 27.2, 963.04, 32.64, 963.02]

16-character columns (2D coordinates)

line = " 648224.43125 4551425.84375 648229.43125 4551425.84375" coords = GeomParser.parse_fixed_width(line, 16) print(coords) [648224.43125, 4551425.84375, 648229.43125, 4551425.84375]

Notes
  • Based on successful RasUnsteady.parse_fixed_width_table() pattern
  • Handles merged values (adjacent numbers without spaces) using regex
  • Skips empty columns
  • Strips line before parsing to remove trailing newlines

rollback_geometry staticmethod

Python
rollback_geometry(geom_file: Path, backup_path: Path) -> None

Restore geometry file from backup.

Used for recovery after a failed write or modification.

Parameters:

Name Type Description Default
geom_file Path

Path to geometry file to restore

required
backup_path Path

Path to backup file to restore from

required

Raises:

Type Description
FileNotFoundError

If backup file doesn't exist

IOError

If restore fails

Example

from pathlib import Path geom_file = Path("model.g01") backup_path = Path("model.g01.bak") GeomParser.rollback_geometry(geom_file, backup_path)

Notes
  • Overwrites current geometry file with backup contents
  • Does not delete backup file (preserved for additional recovery)

safe_write_geometry staticmethod

Python
safe_write_geometry(geom_file: Union[str, Path], modified_lines: List[str], create_backup: bool = True) -> Optional[Path]

Atomically write geometry file with backup.

This method provides safe file writing with backup creation and atomic write via temp file. If the write fails, the original file remains intact.

Process
  1. Create backup: geom_file.bak (if create_backup=True)
  2. Write to temp file: geom_file.tmp
  3. Validate temp file (basic syntax check)
  4. Rename temp -> original (atomic on most filesystems)
  5. Return backup path for potential rollback

Parameters:

Name Type Description Default
geom_file str | Path

Path to geometry file to write

required
modified_lines List[str]

Lines to write to file

required
create_backup bool

Create .bak file before modifying (default True)

True

Returns:

Type Description
Optional[Path]

Backup file path (for rollback if needed), or None if create_backup=False

Raises:

Type Description
FileNotFoundError

If original file doesn't exist

IOError

If write fails

Example

from pathlib import Path geom_file = Path("model.g01") with open(geom_file, 'r', encoding='utf-8', errors='replace') as f: ... lines = f.readlines()

Modify lines...

backup = GeomParser.safe_write_geometry(geom_file, lines) print(f"Backup at: {backup}")

Notes
  • Uses atomic rename where supported by filesystem
  • Backup can be used with rollback_geometry() for recovery
  • Validates temp file has content before rename

set_geom_title staticmethod

Python
set_geom_title(geom_file: Union[str, Path], title: str, create_backup: bool = True) -> Optional[Path]

Write the Geom Title to a HEC-RAS geometry file.

Replaces the existing Geom Title= line in place. If the keyword is absent it is inserted at index 0, matching the RasPlan.set_plan_title pattern.

Parameters

geom_file : Union[str, Path] Path to the .g## geometry text file. title : str New geometry title to write. create_backup : bool, optional Create a .bak backup before modifying the file (default True).

Returns

Optional[Path] Path to the backup file (from :meth:safe_write_geometry), or None if create_backup is False.

Raises

FileNotFoundError If geom_file does not exist. IOError If the file cannot be written.

Examples

backup = GeomParser.set_geom_title("MyProject.g01", "Updated Geometry") print(f"Backup created: {backup}") Backup created: MyProject.g01.bak

update_timestamp staticmethod

Python
update_timestamp(lines: List[str], keyword: str) -> List[str]

Update timestamp for a modified section.

Finds lines with timestamp keywords and updates them to current time.

Parameters:

Name Type Description Default
lines List[str]

File lines to modify

required
keyword str

Timestamp keyword to search for

required

Returns:

Type Description
List[str]

Modified lines with updated timestamp

Example

lines = ["LCMann Time=01Jan2023 14:30:45\n"] updated = GeomParser.update_timestamp(lines, "LCMann Time") print(updated[0]) 'LCMann Time=11Nov2025 10:45:30\n'

Notes
  • Timestamp format: DDMmmYYYY HH:MM:SS
  • Only updates lines matching the specified keyword
  • Preserves all other lines unchanged

validate_river_reach_rs staticmethod

Python
validate_river_reach_rs(geom_file: Path, river: str, reach: str, rs: str) -> bool

Validate that river/reach/RS combination exists in geometry file.

Parameters:

Name Type Description Default
geom_file Path

Path to geometry file

required
river str

River name

required
reach str

Reach name

required
rs str

River station

required

Returns:

Type Description
bool

True if combination exists

Raises:

Type Description
ValueError

If river/reach/RS not found in geometry file

Example

from pathlib import Path geom_file = Path("BaldEagle.g01") valid = GeomParser.validate_river_reach_rs( ... geom_file, "Bald Eagle Creek", "Reach 1", "138154.4" ... ) print(valid) True

Notes
  • Used before modification operations to ensure valid target
  • Searches for "Type RM Length L Ch R =" line with matching RS

GeomPreprocessor source reference

Run GeomPreprocessor.run_geometry_preprocessor(plan_number, ras_object=project) on a writable project copy. Close any h5py handles to that geometry HDF first. The method temporarily changes plan flags and restores them by default; native geometry and preprocessing artifacts remain in the copy. It preserves the project's CRS and units.

Completion requires normal engine and preprocessing-child exit within max_wait (seconds), unchanged authored inputs, and complete native products. The selected geometry text defines area perimeters and computation points, breaklines, BC/reference lines and structure records. It must remain byte-identical. Compiled area/feature mirrors are checked against that text; an incoming HDF can still describe a parent and does not define child features. Existing valid native BC types are retained when their compiled names and coordinates match the authored lines. A subsequent type change fails input preservation. Unrelated parent BC mirrors do not establish a child type; explicit type intent can be authored with GeomBcLines.set_bc_line_types before recomputation. HDF-only refinement regions, Projection, terrain/classification associations and Manning calibration are preserved semantically. Projection definitions are compared with axis-aware pyproj.CRS.equals: equivalent WKT serialization, including native standard-parallel ordering and numeric formatting, is allowed; a different CRS or axis order fails. Other retained values are unchanged, allowing native fixed-string widths to differ.

For authored 2D areas, the method retains a unique sibling HDF backup and removes recognized native product tables before launch, including .c## caches even when clear_geompre=False. This invalidation is restricted to HEC-RAS 5/6 geometry HDFs and geometry-only results copies named .g##.hdf; results/time-series hierarchies are rejected. Failed native work leaves the backup and diagnostics, and does not restore obsolete products. Completion requires a freshly written Geometry/GeomPreprocess, cell/face property pairs with valid packed ranges, tables sized for the current topology, BC/reference attachments and associated infiltration tables. Infiltration uses interior-cell counts; volume tables also include ghost cells, whose zero-length entries are permitted. Topology validation checks integer index domains, contiguous packed ranges, reciprocal cell/face and point/face incidence with signed orientation, reciprocal cell/point membership, and trailing -1 cell-point padding. Face coordinates must be finite, nondegenerate and consistent with native normals and lengths at float32 storage precision. Fresh child regeneration can replace stale parent topology; no parent indexes are restored. The leading interior center rows must exactly equal the current regenerated 2D Flow Areas/Cell Points mirror in the qualified float64 native schema. That mirror must match the current authored text within one float64 ULP per coordinate, the native decimal-parsing precision; it must be finite and have the exact shape. No incoming parent seed mirror is used for this binding. Remaining rows are two-vertex ghost cells and are not compared to authored seeds. Every native face polyline (endpoint, indexed Faces Perimeter Values intermediate vertices, endpoint) must lie on or inside the current authored perimeter, including interior and ghost-adjacent boundary faces. Both vertices and segments are checked with vectorized, prepared geometry predicates in bounded batches. Concavities and keyhole-encoded holes are honored; a bent boundary face is never replaced by its endpoint chord. The boundary tolerance is eight float64 ULPs at the perimeter's coordinate magnitude, in the geometry CRS units. The predicate subtracts the first perimeter vertex uniformly from perimeter, face endpoints and intermediate vertices before geometric operations, retaining the tolerance computed in original coordinates. This avoids numerical false exclusions at large projected offsets without editing arrays, scaling, snapping or expanding the permitted boundary allowance. Interior-center binding remains an exact comparison in original coordinates. Coherent translations of either coordinate array fail completion. Reference-line terrain profiles are checked when authored. Manning polygon names and coordinates are checked against the geometry text; attachment families are required for regions intersecting a current 2D perimeter. A valid disjoint polygon remains an authored input, with outside_current_mesh evidence, and does not require absent cell/face mappings. Present mappings still require valid region IDs and current mesh indexes. A calibration table name alone does not establish a polygon interaction. Invalid or multipart polygon interaction schemas fail before mutation. The dimensioned product contract covers structure-free HEC-RAS 5/6 geometry with authored 2D areas; it does not qualify pure 1D completion. require_complete_products=False is the public default. Structure-bearing 2D or mixed geometry runs with normal engine/writer lifecycle, native-error and plan-restoration checks, without the unqualified product invalidation/checks. Its completion_contract.status is not_qualified_for_structures, with reason GEOMETRY_COMPLETION_NOT_QUALIFIED_FOR_STRUCTURES, message "completion contract not qualified for structures", inputs_preserved=None, and products_complete=False. Process success therefore does not claim qualified structure products. Set require_complete_products=True for fail-closed workflows: these geometries fail before cache invalidation with GEOMETRY_PRODUCTS_SCHEMA_UNSUPPORTED. RasBreakout2D.prepare_cloned_geometry, GeomMesh.generate, generate_all, and audit_domain_containment expose the same option, defaulting to False. They forward it to all native recompilation and numeric/perimeter-repair calls. In this compatibility path, captured stdout remains diagnostic; blocking errors are parsed from native compute-message files, as on the prior default path. Structure-free geometries always receive the complete contract checks, including blocking-error parsing of captured stdout. The structure-property schema has not been qualified. A nonempty native group does not prove complete structure products. Native infiltration region definitions and overrides are preserved as authored HDF-only inputs. A quiet file or flow-start message does not end the wait. native_worker_threads=1 requests a managed preprocessing worker-pool limit of one by default. This is separate from hydraulic solver core settings and does not guarantee deterministic native products. Positive integers select another limit; None retains inherited managed-pool settings. The override is local to the launched process environment and applies only to geometry_only=True. completion_contract records the requested limit; it does not claim that every native thread was measured. The separate isolated native property/calibration/BC worker also uses a one-worker managed pool; the preprocessor's None option does not change that isolated-worker policy. Recognized Wine desktop, console and plot-display invocations may outlive the geometry writers and are excluded from writer completion; unknown children still require a confirmed exit. A transient Wine invalid-handle error while querying a child's role leaves it supervised. The role query is retried while that same process identity remains active, including after the launcher exits. The geometry reference is read from the selected on-disk plan; a stale project DataFrame cannot redirect inventory validation or .c## cleanup to another geometry. Missing or malformed geometry references fail before engine launch. geometry_only=False also waits for all enabled plan work, so its runtime can include hydraulic computation.

GeometryPreprocessResult remains bool-compatible. return_code records the actual launcher exit; a nonzero exit always fails. timed_out=True fails even if geometry topology exists. missing_geometry_inventory now lists changed or missing authored inputs, rather than every incoming cache object; GEOMETRY_INPUT_CHANGED identifies this failure. missing_geometry_products lists missing or malformed required products; the corresponding reason is GEOMETRY_PRODUCTS_INCOMPLETE. Both lists default to empty. completion_contract records the contract version, text hash, area counts, preservation/completeness decisions, invalidated tables and backup path. It also records lifecycle_verified and plan_restored, both false until normal launcher/writer completion and exact original-plan restoration are positively established. Disabling restoration leaves plan_restored=false. The explicit clear_geompre=True path completes the unique geometry backup and input preflight before deleting caches, messages, or native products. A target open in the caller's h5py runtime returns GEOMETRY_HDF_OPEN; its handle is left with the caller. Captured stdout and stderr participate in blocking native-error parsing even with complete products and launcher exit 0; the merged stream is retained as stdout. Nonspatial preprocessing does not require Shapely; spatial imports occur only when authored Manning polygons require intersection checks. A timeout returns GEOMETRY_PREPROCESS_TIMEOUT; uncertain process inspection or an unconfirmed child exit returns GEOMETRY_PROCESS_COMPLETION_UNVERIFIED. Unexpected monitoring or process-query errors also attempt bounded cancellation of retained owned writers before restoring the plan, even if the launcher has already exited. Launcher ownership is captured immediately after launch, before optional monitoring hooks. Cleanup preserves PID/create-time identities, continues after individual OS errors, and bounds each cleanup phase to a shared ten-second wait budget. Cleanup errors remain in the failed result; uncertain completion never triggers a postrun HDF read. These completion checks do not constitute hydraulic acceptance.

A class for managing HEC-RAS geometry preprocessor files.

All methods are static and designed to be used without instantiation.

clear_geompre_files staticmethod

Python
clear_geompre_files(plan_files: Union[str, Path, List[Union[str, Path]]] = None, ras_object=None) -> None

Clear HEC-RAS geometry preprocessor files for specified plan files.

Geometry preprocessor files (.c* extension) contain computed hydraulic properties derived from the geometry. These should be cleared when the geometry changes to ensure that HEC-RAS recomputes all hydraulic tables with updated geometry information.

This deletes the .c## geometry-preprocessor file only. It deliberately does not mutate the .g##.hdf; use a native HEC-RAS geometry or plan computation to refresh solver-owned HDF datasets.

Limitations/Future Work: - It does not clear the IB (internal boundary) tables.

Parameters:

Name Type Description Default
plan_files Union[str, Path, List[Union[str, Path]]]

Full path(s) to the HEC-RAS plan file(s) (.p*). If None, clears all plan files in the project directory.

None
ras_object RasPrj

An optional RAS object instance.

None

Returns:

Type Description
None

The function deletes files and updates the ras object's geometry dataframe

Example

Clone a plan and geometry

new_plan_number = RasPlan.clone_plan("01") new_geom_number = RasPlan.clone_geom("01")

Set the new geometry for the cloned plan

RasPlan.set_geom(new_plan_number, new_geom_number) plan_path = RasPlan.get_plan_path(new_plan_number)

Clear geometry preprocessor files to ensure clean results

GeomPreprocessor.clear_geompre_files(plan_path) print(f"Cleared geometry preprocessor files for plan {new_plan_number}")

clear_geompre_hdf staticmethod

Python
clear_geompre_hdf(geom_hdf_path: Union[str, Path], *, expected_file_version: Optional[str] = None, acknowledge_legacy_recovery: bool = False, backup_path: Optional[Union[str, Path]] = None) -> List[str]

Deprecated compatibility wrapper for guarded legacy recovery.

Prefer native RasMap.recompute_property_tables() or plan recomputation. To intentionally retain the historical selective invalidation behavior, callers must provide the exact file version and set acknowledge_legacy_recovery=True.

invalidate_legacy_geometry_hdf_preprocessor_cache staticmethod

Python
invalidate_legacy_geometry_hdf_preprocessor_cache(geom_hdf_path: Union[str, Path], *, expected_file_version: str, acknowledge_legacy_recovery: bool = False, backup_path: Optional[Union[str, Path]] = None) -> List[str]

Selectively invalidate a known HEC-RAS 5/6 geometry-HDF cache.

This is an opt-in recovery utility for legacy projects where native property-table recomputation is unavailable or has already failed. It is not the normal preprocessing path. Prefer RasMap.recompute_property_tables() or a completed native plan recompute.

The method accepts only *.g##.hdf files whose root attributes are exactly File Type='HEC-RAS Geometry' and the caller-supplied expected_file_version. HEC-RAS 7.x and unfamiliar schemas fail closed. A non-overwriting full-file backup is created before any dataset is removed.

force_geompre does not call this recovery utility. It preserves the geometry HDF, bypasses the smart results skip, clears .c## files, and requests native complete-geometry processing instead.

Parameters:

Name Type Description Default
geom_hdf_path Union[str, Path]

Existing HEC-RAS geometry HDF.

required
expected_file_version str

Exact root File Version attribute, including the release month/year text.

required
acknowledge_legacy_recovery bool

Must be explicitly True.

False
backup_path Optional[Union[str, Path]]

Optional backup destination. By default, writes <stem>.legacy-recovery.bak.hdf beside the source and refuses to overwrite an existing backup.

None

Returns:

Type Description
List[str]

HDF paths removed from the source file. An already-invalidated,

List[str]

otherwise valid file returns an empty list without creating a

List[str]

backup.

run_geometry_preprocessor staticmethod

Python
run_geometry_preprocessor(plan_number: Union[str, int, float, Path], ras_object=None, max_wait: int = 600, force: bool = True, clear_messages: bool = True, clear_geompre: bool = False, geometry_only: bool = True, restore_plan_settings: bool = True, flow_start_signals: Optional[List[str]] = None, dialog_watchdog: bool = True, native_worker_threads: int | None = 1, require_complete_products: bool = False) -> GeometryPreprocessResult

Run HEC-RAS geometry preprocessing and review detailed compute messages.

Launches the selected engine on the caller's writable project copy and waits for normal launcher and preprocessing-child exit. Compute messages are diagnostic signals, never permission to terminate a successful run. A timeout terminates owned work and returns failure. HDF inspection occurs only before launch and after process completion; all handles opened by this method are closed before engine execution.

Before touching geometry, wait up to 30 seconds within max_wait for the same plan's previous native tree and temporary-HDF handles to close. An unverified handoff returns failure with GEOMETRY_PREPROCESS_HANDOFF_TIMEOUT and never starts another engine. It does not terminate a previous caller's processes.

Authored geometry inputs must survive unchanged. Native products must be freshly generated and complete for the current mesh; obsolete incoming parent products may be replaced. Geometry text, HDF-only associations, Projection and Manning calibration define the retained inputs. Known native product tables are invalidated before launch. Completion checking does not establish hydraulic acceptance. This method emits a result and captured stdout, modifies native artifacts in the project copy, and restores temporary plan flags when requested. It changes no CRS or units.

Parameters:

Name Type Description Default
plan_number Union[str, int, float, Path]

Plan number or path to a plan file.

required
ras_object RasPrj

Optional RasPrj instance. If None, uses the global ras.

None
max_wait int

Positive time budget in seconds, including setup and all observed native children. Expiry returns a failed result.

600
force bool

If True, set Run HTab=-1 and UNET Use Existing IB Tables=-1 before running.

True
clear_messages bool

Delete stale compute-message files before running.

True
clear_geompre bool

Delete stale .c## files before running.

False
geometry_only bool

If True, temporarily disables unsteady flow, post-processing, RAS Mapper, sediment, and water-quality run flags where those plan settings exist. This keeps validation focused on geometry preprocessing.

True
restore_plan_settings bool

Restore original Run HTab and related run flag values after the run.

True
flow_start_signals Optional[List[str]]

Optional diagnostic message strings. Detection does not shorten the normal-exit wait.

None
dialog_watchdog bool

Monitor and dismiss recognized native dialogs.

True
native_worker_threads int | None

Managed preprocessing worker-pool limit. Defaults to a requested limit of one for geometry-only work; it does not guarantee deterministic native products. Positive integers are allowed; None retains the inherited pool settings. Hydraulic solver core settings are unchanged. The override applies only when geometry_only=True.

1
require_complete_products bool

If True, refuse unqualified structure-bearing 2D geometry before cache invalidation. Defaults to False for compatibility: structures run with the normal lifecycle checks, but report completion contract not qualified for structures. Structure-free geometry always receives the complete product checks.

False

Returns:

Type Description
GeometryPreprocessResult

Bool-compatible validation result.

GeomLandCover source reference

A class for 2D Manning's n land cover operations in HEC-RAS geometry files.

All methods are static and designed to be used without instantiation.

get_base_mannings_n staticmethod

Python
get_base_mannings_n(geom_file_path: Union[str, Path]) -> pd.DataFrame

Reads the base Manning's n table from a HEC-RAS geometry file.

Parameters:

Name Type Description Default
geom_file_path Union[str, Path]

Path to the geometry file (.g##)

required

Returns:

Type Description
DataFrame

DataFrame with columns: - Table Number (str): Manning's n table identifier - Land Cover Name (str): Name of the land cover type - Base Mannings n Value (float): Manning's n roughness coefficient

Example

geom_path = RasPlan.get_geom_path("01") mannings_df = GeomLandCover.get_base_mannings_n(geom_path) print(mannings_df)

get_region_mannings_n staticmethod

Python
get_region_mannings_n(geom_file_path: Union[str, Path]) -> pd.DataFrame

Reads the Manning's n region overrides from a HEC-RAS geometry file.

Parameters:

Name Type Description Default
geom_file_path Union[str, Path]

Path to the geometry file (.g##)

required

Returns:

Type Description
DataFrame

DataFrame with columns: - Table Number (str): Region table identifier - Land Cover Name (str): Name of the land cover type - MainChannel (float): Manning's n value for main channel - Region Name (str): Name of the region

Example

geom_path = RasPlan.get_geom_path("01") region_overrides_df = GeomLandCover.get_region_mannings_n(geom_path) print(region_overrides_df)

override_2d_mannings_n staticmethod

Python
override_2d_mannings_n(geom_hdf_path: Union[str, Path], mannings_n: float, area_name: str = None) -> bool

Reject direct writes to solver-owned Manning datasets.

Use set_base_mannings_n or set_region_mannings_n followed by a native HEC-RAS geometry/plan computation. Generated HDF arrays are outputs, not a supported input contract.

replace_base_mannings_n staticmethod

Python
replace_base_mannings_n(geom_file_path: Union[str, Path], mannings_data: Any, table_number: Optional[Union[str, int]] = None, backup: bool = True) -> bool

Replace or create the plain-text LCMann Table= base Manning's n table.

Unlike :meth:set_base_mannings_n, this authoring method allows the land-cover class names themselves to change. It is intended for new land-cover layer workflows where the sidecar HDF class list is being established and the geometry text file must receive the matching authoritative base n-values.

Parameters:

Name Type Description Default
geom_file_path Union[str, Path]

Path to the HEC-RAS geometry text file (.g##).

required
mannings_data Any

DataFrame-like table with land-cover names and n-values. Accepted name columns include Land Cover Name and class_name; accepted n-value columns include Base Mannings n Value, mannings_n, and n_value.

required
table_number Optional[Union[str, int]]

Deprecated compatibility argument interpreted as the expected number of writable rows. When provided, it must match the normalized input row count. LCMann Table= is always authored from the actual emitted row count.

None
backup bool

If True, write .bak beside the geometry file first.

True

Returns:

Type Description
bool

True if the geometry text file was updated.

set_base_mannings_n staticmethod

Python
set_base_mannings_n(geom_file_path: Union[str, Path], mannings_data: DataFrame) -> bool

Writes base Manning's n values to a HEC-RAS geometry file.

Parameters:

Name Type Description Default
geom_file_path Union[str, Path]

Path to the geometry file (.g##)

required
mannings_data DataFrame

DataFrame with columns: - Table Number (str): Manning's n table identifier - Land Cover Name (str): Name of the land cover type - Base Mannings n Value (float): Manning's n roughness coefficient

required

Returns:

Type Description
bool

True if successful

Raises:

Type Description
ValueError

If land cover names don't match between file and DataFrame

set_mannings_region_polygons staticmethod

Python
set_mannings_region_polygons(geom_file: Union[str, Path], regions_gdf: Any, create_backup: bool = True) -> bool

Write Manning's n calibration region polygon blocks to a geometry file.

The plain-text .g## file is the durable source for Manning's n calibration regions. HEC-RAS regenerates the geometry HDF polygon datasets from these LCMann Region Polygon=N blocks during geometry preprocessing.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to the HEC-RAS geometry text file (.g##).

required
regions_gdf Any

GeoDataFrame-like object with Name and geometry columns. Geometry values must be Shapely Polygon or MultiPolygon objects in the project coordinate system. MultiPolygon exteriors are written as consecutive closed rings because the plain-text block has no explicit part-count table. Optional Table Number values are used when creating new region blocks.

required
create_backup bool

If True, write .bak beside the geometry file.

True

Returns:

Type Description
bool

True if the geometry text file was updated.

Raises:

Type Description
FileNotFoundError

If geom_file does not exist.

ValueError

If required columns are missing, region names are duplicated, or polygon coordinates cannot be represented in HEC-RAS fixed-width format.

set_region_mannings_n staticmethod

Python
set_region_mannings_n(geom_file_path: Union[str, Path], mannings_data: DataFrame) -> bool

Writes regional Manning's n overrides to a HEC-RAS geometry file.

Parameters:

Name Type Description Default
geom_file_path Union[str, Path]

Path to the geometry file (.g##)

required
mannings_data DataFrame

DataFrame with columns: - Table Number (str): Region table identifier - Land Cover Name (str): Name of the land cover type - MainChannel (float): Manning's n value - Region Name (str): Name of the region

required

Returns:

Type Description
bool

True if successful

Raises:

Type Description
ValueError

If region or land cover names don't match

ManningsFromLandCover source reference

Assign 1D cross-section Manning's n values from NLCD land-cover rasters.

All methods are static and designed to be used without instantiation.

assign staticmethod

Python
assign(geometry_path: Union[str, Path], land_cover_raster: Union[str, Path], mannings_table: Optional[Any] = None, calibration_regions: Optional[Any] = None, max_blocks: int = DEFAULT_MAX_BLOCKS) -> dict

Assign Manning's n values to all matching 1D cross sections.

Parameters:

Name Type Description Default
geometry_path Union[str, Path]

HEC-RAS text geometry file path (.g##).

required
land_cover_raster Union[str, Path]

NLCD GeoTIFF path. A land-cover sidecar HDF may also be supplied; the matching TIF is resolved automatically.

required
mannings_table Optional[Any]

Optional mapping/DataFrame overriding the built-in NLCD code to Manning's n table.

None
calibration_regions Optional[Any]

Optional polygon overrides. Accepts a GeoDataFrame/DataFrame, list of dicts, or a dict with land_cover and geometry entries.

None
max_blocks int

Maximum Manning's n blocks per cross section. HEC-RAS 6.6 rejects 21 or more, so the default is 20.

DEFAULT_MAX_BLOCKS

Returns:

Type Description
dict

dict with summary counts and the preview DataFrame that was written.

default_landcover_classification_table staticmethod

Python
default_landcover_classification_table(percent_impervious: Optional[Mapping[int, float]] = None, sanitize_names: bool = True) -> pd.DataFrame

Return the built-in NLCD table in RasMap.add_landcover_layer() shape.

The returned DataFrame maps source NLCD raster values to the HEC-RAS land-cover sidecar class ID, class name, and starter Manning's n value. percent_impervious may override the optional sidecar percent impervious field by NLCD code. By default class names are sanitized for RASMapper sidecar authoring because RAS rejects / and \ in land-cover classifications.

default_mannings_table staticmethod

Python
default_mannings_table() -> pd.DataFrame

Return the built-in NLCD to Manning's n lookup table.

preview staticmethod

Python
preview(geometry_path: Union[str, Path], land_cover_raster: Union[str, Path], xs_id: Optional[Any] = None, mannings_table: Optional[Any] = None, calibration_regions: Optional[Any] = None, max_blocks: int = DEFAULT_MAX_BLOCKS) -> pd.DataFrame

Preview Manning's n blocks generated from land-cover sampling.

Parameters:

Name Type Description Default
geometry_path Union[str, Path]

HEC-RAS text geometry file path (.g##).

required
land_cover_raster Union[str, Path]

NLCD GeoTIFF path or land-cover sidecar HDF.

required
xs_id Optional[Any]

Optional cross-section identifier. Accepts unique RS, river|reach|rs, (river, reach, rs), or a mapping.

None
mannings_table Optional[Any]

Optional base table override.

None
calibration_regions Optional[Any]

Optional polygon override definitions.

None
max_blocks int

Maximum block count to enforce in the preview.

DEFAULT_MAX_BLOCKS

Returns:

Type Description
DataFrame

DataFrame with one row per final Manning's n breakpoint.

GeomCrossSection source reference

Operations for parsing and modifying HEC-RAS 1D cross sections.

All methods are static and designed to be used without instantiation.

build_cross_section staticmethod

Python
build_cross_section(input_spec: Optional[CrossSectionBuildInput] = None, **kwargs) -> CrossSectionBuildResult

Build a complete, valid HEC-RAS Type 1 cross-section entry.

The builder accepts either a :class:CrossSectionBuildInput dataclass or flexible keyword arguments. It resolves station/elevation data, bank stations/elevations, Manning's n values, and reach lengths, then returns formatted geometry-file lines. Fallbacks always produce complete geometry and are logged at ERROR level with the river/reach/RS identifier.

Station/elevation resolution: 1. station_elevation DataFrame when supplied. 2. Terrain profile from terrain_profile or RasTerrainMod.get_terrain_profile(rasmap_path, geom_hdf_path). 3. Interpolation from adjacent cross sections using supplied upstream/downstream profiles or geom_file + source RS values.

Bank station resolution
  1. Caller-specified station and elevation values.
  2. Caller-specified stations with elevations from terrain.
  3. River-centerline/cut-line intersection with default 20-unit main-channel width.
  4. Bank elevations interpolated from the station/elevation profile when terrain is unavailable.

Manning's n resolution follows mannings_strategy: - auto/landcover: land cover, neighbor interpolation, user, defaults. - neighbor/adjacent: neighbor interpolation, user, land cover, defaults. - user: user, land cover, neighbor, defaults. - default: logged defaults only.

Parameters:

Name Type Description Default
input_spec Optional[CrossSectionBuildInput]

Optional dataclass or mapping of builder inputs.

None
**kwargs Any

Builder fields; see :class:CrossSectionBuildInput.

{}

Returns:

Type Description
CrossSectionBuildResult

CrossSectionBuildResult with resolved DataFrames and formatted lines.

Raises:

Type Description
ValueError

If required geometry cannot be resolved or inputs are invalid.

format_blocked_obstructions staticmethod

Python
format_blocked_obstructions(obstructions: Any) -> List[str]

Format blocked obstructions for a HEC-RAS geometry text file.

Values are written as 8-character fixed-width fields with 9 values per line, matching three start_sta, end_sta, elevation triplets per line. Lines include trailing newlines and are ready for writelines.

get_bank_stations staticmethod

Python
get_bank_stations(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> Optional[Tuple[float, float]]

Extract left and right bank station locations for a cross section.

Bank stations define the boundary between overbank areas and the main channel, used for subsection conveyance calculations.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
river str

River name

required
reach str

Reach name

required
rs str

River station

required

Returns:

Type Description
Optional[Tuple[float, float]]

(left_bank, right_bank) or None if no banks defined

Example

banks = GeomCrossSection.get_bank_stations("BaldEagle.g01", "Bald Eagle", "Loc Hav", "138154.4") if banks: ... left, right = banks ... print(f"Bank stations: Left={left}, Right={right}") ... print(f"Main channel width: {right - left} ft")

get_blocked_obstructions staticmethod

Python
get_blocked_obstructions(geom_number: Union[str, Number, Path], xs_id: Optional[Any] = None, ras_object=None) -> pd.DataFrame

Read blocked obstruction triplets from one or all cross sections.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number ("01" or 1) or direct path to a .g## text geometry file.

required
xs_id Optional[Any]

Optional cross-section identifier. Accepts the xs_id returned by this method, a unique RS string, (river, reach, rs), or a mapping with River/Reach/RS fields.

None
ras_object RasPrj

Optional RasPrj instance for geometry-number resolution.

None

Returns:

Type Description
DataFrame

DataFrame with at least xs_id, start_sta, end_sta, and

DataFrame

elevation columns. River, Reach, RS, and obstruction_index are

DataFrame

included for review and unambiguous round trips.

get_cross_sections staticmethod

Python
get_cross_sections(geom_file: Union[str, Path], river: Optional[str] = None, reach: Optional[str] = None) -> pd.DataFrame

Extract cross section metadata from geometry file.

Parses all cross sections and returns their metadata including river, reach, river station, type, and reach lengths.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
river Optional[str]

Filter by specific river name. If None, returns all rivers.

None
reach Optional[str]

Filter by specific reach name. If None, returns all reaches. Note: If reach is specified, river must also be specified.

None

Returns:

Type Description
DataFrame

DataFrame with columns: - River (str): River name - Reach (str): Reach name - RS (str): River station - Type (int): Cross section type (1=natural, etc.) - Length_Left (float): Left overbank length to next XS - Length_Channel (float): Channel length to next XS - Length_Right (float): Right overbank length to next XS - NodeName (str): Node name (if specified)

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If reach specified without river

Example

Get all cross sections

xs_df = GeomCrossSection.get_cross_sections("BaldEagle.g01") print(f"Total XS: {len(xs_df)}")

Filter by river

xs_df = GeomCrossSection.get_cross_sections("BaldEagle.g01", river="Bald Eagle Creek")

Filter by river and reach

xs_df = GeomCrossSection.get_cross_sections("BaldEagle.g01", ... river="Bald Eagle Creek", ... reach="Reach 1")

get_expansion_contraction staticmethod

Python
get_expansion_contraction(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> Tuple[float, float]

Extract expansion and contraction coefficients for a cross section.

These coefficients account for energy losses due to flow expansion (downstream) and contraction (upstream) at cross sections.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
river str

River name

required
reach str

Reach name

required
rs str

River station

required

Returns:

Type Description
Tuple[float, float]

(expansion, contraction) coefficients

Example

exp, cntr = GeomCrossSection.get_expansion_contraction( ... "BaldEagle.g01", "Bald Eagle", "Loc Hav", "138154.4" ... ) print(f"Expansion: {exp}, Contraction: {cntr}")

Typical values: expansion=0.3, contraction=0.1

get_ineffective_flow staticmethod

Python
get_ineffective_flow(geom_file: str | Path, river: str, reach: str, rs: str) -> tuple[pd.DataFrame | None, int | None, list[bool] | None]

Read normal left/right or multiple-block ineffective flow areas.

The returned tuple is (DataFrame, format_flag, permanent_flags). Columns remain left_station, right_station and elevation. Multiple blocks (flag -1) contain explicit interval endpoints. Native normal format (flag 0) retains two rows in left/right order: the left activation station is right_station in row 0, and the right activation station is left_station in row 1. The unbounded outer endpoint is NaN or a native zero placeholder. An undefined side has NaN activation station and elevation, retaining its outer placeholder. Blanks and zero placeholders must be retained when writing; no cross-section extents are inferred.

Parameters:

Name Type Description Default
geom_file str | Path

Path to HEC-RAS geometry file.

required
river str

Exact river name.

required
reach str

Exact reach name.

required
rs str

Exact river station.

required

Returns:

Type Description
DataFrame | None

DataFrame, native format flag (0 or -1), and one permanent bool per

int | None

row. Returns (None, None, None) when there is no ineff record.

list[bool] | None

Passing all three results to set_ineffective_flow without edits

tuple[DataFrame | None, int | None, list[bool] | None]

preserves the geometry file byte for byte.

Raises:

Type Description
FileNotFoundError

Geometry file does not exist.

ValueError

Cross section missing or malformed ineffective data.

get_levees staticmethod

Python
get_levees(geom_number: Union[str, Path], river: Optional[str] = None, reach: Optional[str] = None, rs: Optional[str] = None, xs_id: Optional[str] = None, ras_object=None) -> pd.DataFrame

Read left and right levee station-elevation points from cross sections.

Cross-section levees are stored in plain-text geometry files as a single Levee= line with left and right triplets: flag, station, elevation. Active sides use flag -1; inactive sides use flag 0 and blank station/elevation fields.

Parameters:

Name Type Description Default
geom_number Union[str, Path]

Geometry number or direct path to a .g## text file

required
river Optional[str]

Optional river filter

None
reach Optional[str]

Optional reach filter. If supplied, river is required.

None
rs Optional[str]

Optional river-station filter. If supplied, river and reach are required.

None
xs_id Optional[str]

Optional exact ID from the returned xs_id column.

None
ras_object RasPrj

Optional RasPrj instance for API consistency (unused)

None

Returns:

Type Description
DataFrame

Columns xs_id, left_station,

DataFrame

left_elevation, right_station, right_elevation.

DataFrame

Matching cross sections without levees are included with NaN values.

get_mannings_n staticmethod

Python
get_mannings_n(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> pd.DataFrame

Extract Manning's n roughness values for a cross section.

Manning's n values define channel roughness and are organized by subsections (Left Overbank, Main Channel, Right Overbank) based on bank station locations.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
river str

River name

required
reach str

Reach name

required
rs str

River station

required

Returns:

Type Description
DataFrame

DataFrame with columns: - Station (float): Station where this Manning's n value starts - n_value (float): Manning's roughness coefficient - Subsection (str): 'LOB' (Left Overbank), 'Channel', or 'ROB' (Right Overbank)

Example
Python
>>> mann = GeomCrossSection.get_mannings_n("BaldEagle.g01", "Bald Eagle", "Loc Hav", "138154.4")
>>> print(mann)
   Station  n_value Subsection
0      0.0     0.06        LOB
1    190.0     0.04    Channel
2    375.0     0.10        ROB
>>>
>>> # Calculate average channel Manning's n
>>> channel_n = mann[mann['Subsection'] == 'Channel']['n_value'].mean()

get_station_elevation staticmethod

Python
get_station_elevation(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> pd.DataFrame

Extract station/elevation pairs for a cross section.

Reads the cross section geometry data from the plain text geometry file. Uses fixed-width parsing (8-character columns) following FORTRAN conventions.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string, e.g., "138154.4")

required

Returns:

Type Description
DataFrame

DataFrame with columns: - Station (float): Station along cross section (ft or m) - Elevation (float): Ground elevation at station (ft or m)

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If cross section not found

Example

sta_elev = GeomCrossSection.get_station_elevation( ... "BaldEagle.g01", "Bald Eagle Creek", "Reach 1", "138154.4" ... ) print(f"XS has {len(sta_elev)} points") print(f"Station range: {sta_elev['Station'].min():.1f} to {sta_elev['Station'].max():.1f}")

get_xs_coords staticmethod

Python
get_xs_coords(geom_file: Union[str, Path], river: Optional[str] = None, reach: Optional[str] = None, rs: Optional[str] = None, ras_object=None) -> pd.DataFrame

Extract XYZ coordinates for cross sections from plain text geometry file.

Combines GIS cut line geometry with station-elevation data to produce 3D point coordinates along each cross section. This is the plain text equivalent of HdfXsec.get_cross_sections() for extracting XYZ points without requiring geometry HDF files.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river Optional[str]

Filter by specific river name. If None, returns all rivers.

None
reach Optional[str]

Filter by specific reach name. If None, returns all reaches.

None
rs Optional[str]

Filter by specific river station. If None, returns all stations.

None
ras_object RasPrj

Optional RasPrj instance for multi-project workflows (unused, for API consistency)

None

Returns:

Type Description
DataFrame

DataFrame with columns: - river (str): River name - reach (str): Reach name - RS (str): River station - station (float): Station along cross section (from left bank) - x (float): X coordinate - y (float): Y coordinate - z (float): Elevation

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ImportError

If geopandas or shapely are not installed

ValueError

If no cross sections found matching filters

Example

Extract XYZ for all cross sections

xyz = GeomCrossSection.get_xs_coords("model.g01") print(f"Extracted {len(xyz)} total points")

Filter by river/reach

xyz_reach = GeomCrossSection.get_xs_coords("model.g01", river="Main River", reach="Upper")

Export to shapefile (LineStrings)

import geopandas as gpd from shapely.geometry import LineString xs_lines = [] for (r, rc, rs), group in xyz.groupby(['river', 'reach', 'RS']): ... coords = list(zip(group['x'], group['y'], group['z'])) ... xs_lines.append({'river': r, 'reach': rc, 'RS': rs, 'geometry': LineString(coords)}) gdf = gpd.GeoDataFrame(xs_lines, crs="EPSG:26915") gdf.to_file("cross_sections.shp")

get_xs_htab_params staticmethod

Python
get_xs_htab_params(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> dict

Read cross section HTAB (hydraulic table) parameters from geometry file.

HTAB parameters control how HEC-RAS pre-computes hydraulic properties (area, conveyance, storage) as a function of elevation. These tables are used during unsteady flow simulations for fast lookup via interpolation.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string, e.g., "5280")

required

Returns:

Type Description
dict with keys
  • 'starting_el' (float or None): Starting elevation for HTAB
  • 'increment' (float or None): Elevation increment between points
  • 'num_points' (int or None): Number of points in HTAB
  • 'invert' (float): Lowest elevation in cross section
  • 'top' (float): Highest elevation in cross section
  • 'has_htab_lines' (bool): True if explicit HTAB lines found in file
Notes
  • Handles two geometry file formats:
    1. Combined format: "XS HTab Starting El and Incr=val1,val2, val3"
    2. Separate format: "HTAB Starting El and Incr=" and "HTAB Number of Points="
  • If HTAB lines are not present, starting_el/increment/num_points will be None (HEC-RAS uses defaults: starting=invert+0.5-1.0, increment=1.0, points~20)
  • invert/top are always computed from station-elevation data
Example

params = GeomCrossSection.get_xs_htab_params( ... "Muncie.g01", "White", "Muncie", "15696.24" ... ) print(f"Starting El: {params['starting_el']}") print(f"Increment: {params['increment']}") print(f"Num Points: {params['num_points']}") print(f"Invert: {params['invert']}, Top: {params['top']}") if not params['has_htab_lines']: ... print("No HTAB lines - using HEC-RAS defaults")

interpolate_cross_section staticmethod

Python
interpolate_cross_section(geom_file: Union[str, Path], river: str, reach: str, upstream_rs: str, downstream_rs: str, ratio: float = 0.5, bank_left: Optional[float] = None, bank_right: Optional[float] = None, max_points: int = MAX_XS_POINTS, interpolated_rs: Optional[str] = None) -> pd.DataFrame

Read two cross sections from a geometry file and interpolate a reviewable profile.

If bank stations are not supplied, this helper linearly interpolates them from the source cross sections when both source sections define bank stations.

interpolate_station_elevation staticmethod

Python
interpolate_station_elevation(upstream_df: DataFrame, downstream_df: DataFrame, ratio: float = 0.5, bank_left: Optional[float] = None, bank_right: Optional[float] = None, max_points: int = MAX_XS_POINTS) -> pd.DataFrame

Interpolate a reviewable station/elevation profile between two cross sections.

The interpolation uses normalized lateral position so source cross sections can have different station ranges and point spacing. The returned DataFrame includes source station/elevation columns for review and enforces the HEC-RAS cross-section point limit.

Parameters:

Name Type Description Default
upstream_df DataFrame

Upstream station/elevation DataFrame

required
downstream_df DataFrame

Downstream station/elevation DataFrame

required
ratio float

Fraction from upstream to downstream (0=upstream, 1=downstream)

0.5
bank_left Optional[float]

Optional left bank station to insert exactly

None
bank_right Optional[float]

Optional right bank station to insert exactly

None
max_points int

Maximum output points, default HEC-RAS limit of 500

MAX_XS_POINTS

Returns:

Type Description
DataFrame

Reviewable interpolated profile with columns: Station, Elevation, UpstreamStation, UpstreamElevation, DownstreamStation, DownstreamElevation, InterpolationRatio, SourceFraction, Source, IsBankPoint

optimize_xs_htab_from_results staticmethod

Python
optimize_xs_htab_from_results(geom_file: Union[str, Path], hdf_results_path: Union[str, Path], safety_factor: float = 1.3, increment: float = 0.1, num_points: int = 500, create_backup: bool = True) -> dict

Optimize cross section HTAB parameters based on existing HEC-RAS results.

This method reads maximum water surface elevations from HDF results, computes optimal HTAB parameters for each cross section using appropriate safety factors, and writes the optimized parameters to the geometry file.

Algorithm
  1. Get all cross sections from geometry file
  2. Extract maximum WSE for each cross section from HDF results
  3. For each cross section: a. Get invert elevation from geometry b. Look up max WSE from HDF results c. Use GeomHtabUtils.calculate_optimal_xs_htab() to compute parameters d. Collect modification for batch write
  4. Write all modifications to geometry file (single write operation)
  5. Return summary statistics

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
hdf_results_path Union[str, Path]

Path to plan HDF file with results

required
safety_factor float

Multiplier on max depth to provide buffer (default 1.3 = 30%) Recommended: 1.2-1.5 for typical floods, 2.0 for dam break

1.3
increment float

Maximum elevation increment in feet (default 0.1) Smaller increments give more accurate interpolation

0.1
num_points int

Maximum number of points (default 500, HEC-RAS limit)

500
create_backup bool

Whether to create a .bak backup before modification (default True). Set to False when called from an orchestrator that manages its own backup.

True

Returns:

Type Description
dict

Summary statistics with keys: - 'modified_count' (int): Number of cross sections modified - 'total_xs_count' (int): Total number of cross sections in geometry - 'skipped_count' (int): Number of XS skipped (no results or errors) - 'backup_path' (Path): Path to geometry backup file - 'min_increment' (float): Minimum increment used - 'max_increment' (float): Maximum increment used - 'avg_increment' (float): Average increment used - 'modifications' (List[dict]): Details of each modification

Raises:

Type Description
FileNotFoundError

If geometry file or HDF file doesn't exist

ValueError

If safety_factor < 1.0 or other invalid parameters

IOError

If file read/write fails

Example

from ras_commander import RasExamples, init_ras_project, RasCmdr from ras_commander.geom import GeomCrossSection

Extract and run example project

path = RasExamples.extract_project("Muncie", suffix="htab_opt") init_ras_project(path, "7.0") RasCmdr.compute_plan("01") # Run to get results

Optimize HTAB from results

summary = GeomCrossSection.optimize_xs_htab_from_results( ... path / "Muncie.g01", ... path / "Muncie.p01.hdf", ... safety_factor=1.3, ... increment=0.1, ... num_points=500 ... ) print(f"Modified {summary['modified_count']} of {summary['total_xs_count']} XS") print(f"Increment range: {summary['min_increment']:.2f} - {summary['max_increment']:.2f}")

Notes
  • Creates a single backup before any modifications
  • Cross sections without matching HDF results are skipped
  • Modifications are batched to minimize file I/O
  • Safety factor is applied to depth range (max_wse - invert), not absolute elevation
See Also
  • GeomHtabUtils.calculate_optimal_xs_htab(): Core calculation algorithm
  • set_xs_htab_params(): Write HTAB parameters for single XS
  • get_xs_htab_params(): Read current HTAB parameters

parse_blocked_obstructions staticmethod

Python
parse_blocked_obstructions(data_lines: List[str], expected_count: int) -> List[Any]

Parse blocked obstruction fixed-width data into obstruction objects.

#Block Obstruct= data is stored in 8-character columns as start_sta, end_sta, elevation triplets, with up to three obstructions per line.

Parameters:

Name Type Description Default
data_lines List[str]

Fixed-width data lines following #Block Obstruct=.

required
expected_count int

Obstruction count declared in the header.

required

Returns:

Type Description
List[Any]

List of BlockedObstruction objects.

set_all_xs_htab_params staticmethod

Python
set_all_xs_htab_params(geom_file: Union[str, Path], starting_el: Union[float, str] = 'invert', increment: float = 0.1, num_points: int = 500, create_backup: bool = True) -> dict

Set HTAB parameters for ALL cross sections in geometry file.

This method efficiently updates HTAB parameters for every cross section in a single file read/write cycle. It's optimized for batch operations on geometry files with many cross sections.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
starting_el Union[float, str]

Starting elevation for all XS: - float: Use this elevation for all cross sections - 'invert': Copy each XS's invert (minimum elevation) - RECOMMENDED

'invert'
increment float

Elevation increment for all XS (default 0.1) Typical values: 0.1-0.2 ft for fine resolution

0.1
num_points int

Number of points for all XS (default 500) HEC-RAS maximum is 500

500
create_backup bool

Create .bak file before modifying (default True)

True

Returns:

Type Description
dict

Summary of modifications with keys: - 'modified' (int): Number of cross sections successfully modified - 'skipped' (int): Number of cross sections skipped (no valid data) - 'backup' (Path or None): Path to backup file, or None if no backup - 'xs_details' (List[dict]): Per-XS details with river/reach/rs/starting_el

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If invalid parameters (increment <= 0, num_points out of range)

IOError

If file write fails

Notes
  • Processes all cross sections in a SINGLE file read/write cycle
  • Much more efficient than calling set_xs_htab_params() in a loop
  • When starting_el='invert', each XS gets its own invert elevation
  • Uses safe_write_geometry() for atomic write with backup
  • Handles both HTAB formats: separate lines and combined "XS HTab" format
Performance
  • Target: <5 seconds for 100 cross sections
  • Single file read, single file write
Example

result = GeomCrossSection.set_all_xs_htab_params( ... "model.g01", ... starting_el='invert', # Copy each XS's invert ... increment=0.1, ... num_points=500 ... ) print(f"Modified {result['modified']} cross sections") print(f"Backup at: {result['backup']}")

Set fixed starting elevation for all XS

result = GeomCrossSection.set_all_xs_htab_params( ... "model.g01", ... starting_el=580.0, # Same starting el for all ... increment=0.2, ... num_points=250 ... )

See Also
  • set_xs_htab_params(): Set HTAB for single XS
  • get_xs_htab_params(): Read current HTAB parameters
  • get_cross_sections(): List all XS in geometry file

set_bank_stations staticmethod

Python
set_bank_stations(geom_file: Union[str, Path], river: str, reach: str, rs: str, bank_left: float, bank_right: float, create_backup: bool = True) -> Optional[Path]

Set left and right bank stations for a cross section.

Updates or inserts the Bank Sta= line and rewrites the #Sta/Elev block so both bank stations are exact station/elevation points, as required by HEC-RAS. Missing bank points are linearly interpolated from the existing station/elevation profile.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to HEC-RAS geometry file

required
river str

River name

required
reach str

Reach name

required
rs str

River station

required
bank_left float

Left bank station

required
bank_right float

Right bank station

required
create_backup bool

Whether to create a .bak backup before modification (default True)

True

Returns:

Type Description
Optional[Path]

Backup path if create_backup=True, otherwise None.

Raises:

Type Description
FileNotFoundError

If geometry file does not exist

ValueError

If cross section not found, bank stations are invalid, or bank interpolation would exceed the point limit

IOError

If file write fails

set_blocked_obstructions staticmethod

Python
set_blocked_obstructions(geom_number: Union[str, Number, Path], xs_id: Any, obstructions: Any, create_backup: bool = True, ras_object=None) -> Optional[Path]

Write blocked obstruction triplets to a cross section.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number ("01" or 1) or direct path to a .g## text geometry file.

required
xs_id Any

Cross-section identifier from get_blocked_obstructions(), a unique RS string, (river, reach, rs), or a mapping with River/Reach/RS fields.

required
obstructions Any

DataFrame/list containing start_sta, end_sta, and elevation values, or BlockedObstruction objects.

required
create_backup bool

Whether to create a .bak backup before writing.

True
ras_object RasPrj

Optional RasPrj instance for geometry-number resolution.

None

Returns:

Type Description
Optional[Path]

Optional backup path if create_backup=True and the file changed.

set_expansion_contraction staticmethod

Python
set_expansion_contraction(geom_file: Union[str, Path], river: str, reach: str, rs: str, expansion: float, contraction: float, create_backup: bool = True) -> Optional[Path]

Set expansion and contraction coefficients for a cross section.

Updates an existing Exp/Cntr= line or inserts one into the target cross-section block. Creates a .bak backup before modifying by default.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to HEC-RAS geometry file

required
river str

River name

required
reach str

Reach name

required
rs str

River station

required
expansion float

Expansion coefficient

required
contraction float

Contraction coefficient

required
create_backup bool

Whether to create a .bak backup before modification (default True)

True

Returns:

Type Description
Optional[Path]

Backup path if create_backup=True, otherwise None.

Raises:

Type Description
FileNotFoundError

If geometry file does not exist

ValueError

If cross section not found or coefficients are invalid

IOError

If file write fails

set_ineffective_flow staticmethod

Python
set_ineffective_flow(geom_file: str | Path, river: str, reach: str, rs: str, ineff_df: DataFrame, fmt_flag: int | None = 0, permanent_flags: list[bool] | None = None) -> None

Write normal L/R or multiple-block ineffective flow areas.

Parameters:

Name Type Description Default
geom_file str | Path

Path to HEC-RAS geometry file.

required
river str

Exact river name.

required
reach str

Exact reach name.

required
rs str

Exact river station.

required
ineff_df DataFrame

Columns left_station, right_station, elevation. Native normal rows retain NaN outer endpoints and undefined sides as documented by get_ineffective_flow.

required
fmt_flag int | None

Native flag (0 or -1), or None to preserve the original.

0
permanent_flags list[bool] | None

One bool per row; omitted means all False.

None

Passing the unchanged reader results performs no write, preserving all bytes, whitespace, numeric precision and line endings. Actual edits create a .bak backup and use native CRLF serialization. A permanent-only edit retains the numeric record verbatim. Changing the block count replaces only its records, preserving subsequent cross-section data.

Raises:

Type Description
FileNotFoundError

Geometry file does not exist.

ValueError

Missing cross section/record, invalid fields or flags. Validation completes before backup creation or mutation.

set_levees staticmethod

Python
set_levees(geom_number: Union[str, Path], xs_id: Optional[str] = None, left_station: Optional[float] = None, left_elevation: Optional[float] = None, right_station: Optional[float] = None, right_elevation: Optional[float] = None, *, river: Optional[str] = None, reach: Optional[str] = None, rs: Optional[str] = None, create_backup: bool = True, ras_object=None) -> Optional[Path]

Write left and right levee station-elevation points for a cross section.

Updates an existing Levee= line or inserts one immediately after the target cross section's #Mann= data block. Pass station/elevation together for each side; omit both values for a side to write it as inactive.

Parameters:

Name Type Description Default
geom_number Union[str, Path]

Geometry number or direct path to a .g## text file

required
xs_id Optional[str]

Cross-section ID emitted by get_levees(). Optional if river, reach, and rs are provided.

None
left_station Optional[float]

Optional left levee station

None
left_elevation Optional[float]

Optional left levee elevation

None
right_station Optional[float]

Optional right levee station

None
right_elevation Optional[float]

Optional right levee elevation

None
river Optional[str]

Optional target river, used with reach and rs

None
reach Optional[str]

Optional target reach

None
rs Optional[str]

Optional target river station

None
create_backup bool

Whether to create a .bak backup before modification

True
ras_object RasPrj

Optional RasPrj instance for API consistency (unused)

None

Returns:

Type Description
Optional[Path]

Backup path if create_backup=True, otherwise None.

set_mannings_n staticmethod

Python
set_mannings_n(geom_file: Union[str, Path], river: str, reach: str, rs: str, mann_df: DataFrame, format_flag: int = 0, change_flag: int = 0) -> None

Write Manning's n data to a cross section.

Replaces the #Mann= data block in the geometry file with new breakpoint data. Creates a .bak backup before modifying.

HEC-RAS enforces a hard limit of 20 Manning's n blocks per cross section. Block counts of 21 or more are rejected at compute time with a data_errors limit violation (verified empirically on HEC-RAS 6.6 across multiple example models).

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to HEC-RAS geometry file

required
river str

River name

required
reach str

Reach name

required
rs str

River station

required
mann_df DataFrame

DataFrame with 'Station' and 'n_value' columns. Rows define LOB/MC/ROB breakpoints in ascending station order. Maximum 20 rows (see MAX_MANNINGS_N_BLOCKS).

required
format_flag int

Format flag for #Mann= header (0 or -1)

0
change_flag int

Change flag for #Mann= header

0

Raises:

Type Description
FileNotFoundError

If geometry file not found

ValueError

If cross section or #Mann= block not found, or if mann_df exceeds 20 rows

Example

import pandas as pd mann = pd.DataFrame({ ... 'Station': [18340.0, 19992.13, 20110.0], ... 'n_value': [0.08, 0.05, 0.08] ... }) GeomCrossSection.set_mannings_n( ... "model.g01", "Hunting Bayou", "Mainstem", "65919", mann ... )

set_station_elevation staticmethod

Python
set_station_elevation(geom_file: Union[str, Path], river: str, reach: str, rs: str, sta_elev_df: DataFrame, bank_left: Optional[float] = None, bank_right: Optional[float] = None, create_backup: bool = True) -> Optional[Path]

Write station/elevation pairs to a cross section with automatic bank interpolation.

Modifies the geometry file in-place, replacing the station/elevation data and optionally updating bank stations. Creates a .bak backup automatically.

CRITICAL REQUIREMENTS (HEC-RAS compatibility): - Bank stations MUST appear as exact points in station/elevation data - This method automatically interpolates elevations at bank locations - Existing points within 0.005 units of a bank station are snapped to the exact bank value rather than inserting a near-duplicate point - Maximum 500 points per cross section (HEC-RAS hard limit)

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
river str

River name

required
reach str

Reach name

required
rs str

River station

required
sta_elev_df DataFrame

DataFrame with 'Station' and 'Elevation' columns

required
bank_left Optional[float]

Left bank station. If provided, updates bank in file. If None, reads existing banks and interpolates them.

None
bank_right Optional[float]

Right bank station. If provided, updates bank in file.

None
create_backup bool

Whether to create a .bak backup before modification (default True).

True

Returns:

Type Description
Optional[Path]

Backup path if create_backup=True, otherwise None.

Raises:

Type Description
FileNotFoundError

If geometry file does not exist

ValueError

If cross section not found, DataFrame invalid, or >500 points

IOError

If file write fails

Example

Simple elevation modification (banks auto-interpolated)

sta_elev = GeomCrossSection.get_station_elevation(geom_file, river, reach, rs) sta_elev['Elevation'] += 1.0 GeomCrossSection.set_station_elevation(geom_file, river, reach, rs, sta_elev)

Modify geometry AND change bank stations

GeomCrossSection.set_station_elevation(geom_file, river, reach, rs, sta_elev, ... bank_left=200.0, bank_right=400.0)

set_xs_htab_params staticmethod

Python
set_xs_htab_params(geom_file: Union[str, Path], river: str, reach: str, rs: str, starting_el: Optional[Union[float, str]] = None, increment: Optional[float] = None, num_points: Optional[int] = None) -> None

Set cross section HTAB (hydraulic table) parameters in geometry file.

This method modifies the HTAB parameters for a specific cross section, either replacing existing values or inserting new HTAB lines if they don't exist.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string, e.g., "5280")

required
starting_el Optional[Union[float, str]]

Starting elevation: - float: Use this elevation value - 'invert': Copy the cross section's minimum elevation - None: No change (keep existing or HEC-RAS default)

None
increment Optional[float]

Elevation increment (0.1-2.0 typical) - None: No change (keep existing or HEC-RAS default)

None
num_points Optional[int]

Number of points (20-500) - None: No change (keep existing or HEC-RAS default)

None

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If cross section not found, or parameters invalid

IOError

If file write fails

Notes
  • Only specified parameters are modified
  • If HTAB lines don't exist in the file, they are inserted
  • Geometry file is modified in-place with backup (.bak) created
  • HTAB lines are inserted after "Type RM Length" line, before "XS GIS Cut Line" or "#Sta/Elev"
File Format

HTAB Starting El and Incr= 580.0, 0.1 HTAB Number of Points= 500

Example

Set optimal HTAB for single XS

GeomCrossSection.set_xs_htab_params( ... "model.g01", "River", "Reach", "5280", ... starting_el=580.0, increment=0.1, num_points=500 ... )

Copy invert as starting elevation

GeomCrossSection.set_xs_htab_params( ... "model.g01", "River", "Reach", "5280", ... starting_el='invert', increment=0.1, num_points=500 ... )

Only update increment (keep other values)

GeomCrossSection.set_xs_htab_params( ... "model.g01", "River", "Reach", "5280", ... increment=0.2 ... )

See Also
  • get_xs_htab_params(): Read current HTAB parameters
  • GeomHtabUtils.validate_xs_htab_params(): Validate parameters
  • GeomHtabUtils.calculate_optimal_xs_htab(): Calculate optimal values

validate_blocked_obstructions_hdf staticmethod

Python
validate_blocked_obstructions_hdf(geom_number: Union[str, Number, Path], hdf_path: Optional[Union[str, Path]] = None, ras_object=None) -> pd.DataFrame

Cross-check text #Block Obstruct= data against HDF block-mode flags.

The geometry HDF exposes Obstr Block Mode as a cross-section attribute. That flag does not contain the obstruction triplets, so this validation compares per-cross-section text obstruction presence/count with whether the HDF flag indicates blocked-obstruction mode.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number or direct .g## text path.

required
hdf_path Optional[Union[str, Path]]

Optional explicit geometry HDF path. If omitted, <geom_file>.hdf is used.

None
ras_object RasPrj

Optional RasPrj instance for geometry-number resolution.

None

Returns:

Type Description
DataFrame

DataFrame with one row per text geometry cross section and a

DataFrame

matches_hdf boolean.

CrossSectionBankStations source reference

Resolved cross-section bank stations and their profile elevations.

CrossSectionBuildInput source reference

Optional dataclass accepted by :meth:GeomCrossSection.build_cross_section.

Any field can also be supplied directly as a keyword argument to the builder. Keyword arguments override values from this dataclass.

CrossSectionBuildResult source reference

Resolved complete 1D cross-section geometry entry.

text property

Python
text: str

Return the formatted HEC-RAS geometry entry text.

CrossSectionManningsN source reference

Resolved LOB, main-channel, and ROB Manning's n values.

CrossSectionReachLengths source reference

Left overbank, channel, and right overbank reach lengths.

GeomStorage source reference

Operations for parsing HEC-RAS storage areas in geometry files.

All methods are static and designed to be used without instantiation.

clip_2d_flow_area staticmethod

Python
clip_2d_flow_area(geom_file: Union[str, Path], flow_area_name: str, geometry: BaseGeometry, *, containment_tolerance: float = 0.0, create_backup: bool = True) -> GeoDataFrame

Clip a named area while preserving complete internal connection records.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Geometry text in a disposable working project (str or Path).

required
flow_area_name str

Exact existing 2D area name; other areas stay unchanged.

required
geometry BaseGeometry

Child Polygon in the source geometry's horizontal CRS/units.

required
containment_tolerance float

Nonnegative external-separation guard in model units. Does not excuse a footprint crossing the child perimeter.

0.0
create_backup bool

Back up the original before the final atomic write.

True

Returns:

Type Description
GeoDataFrame

Affected connections, with Name, From, To, action,

GeoDataFrame

reason and physical support geometry. Fully contained records are

GeoDataFrame

kept, disjoint records dropped. The frame's attrs contain backup_path.

GeoDataFrame

Native attachment remains unverified until fresh preprocessing.

Raises:

Type Description
FileNotFoundError

If the source geometry is absent.

ValueError

If the child is invalid/not contained, an area is missing, or a connection crosses the cut or has unknown physical support.

get_2d_flow_area_settings staticmethod

Python
get_2d_flow_area_settings(geom_file: Union[str, Path]) -> pd.DataFrame

Read 2D flow area settings from storage-area-backed .g## blocks.

get_elevation_volume staticmethod

Python
get_elevation_volume(geom_file: Union[str, Path], storage_name: str) -> pd.DataFrame

Extract elevation-volume curve for a storage area.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
storage_name str

Storage area name (case-sensitive)

required

Returns:

Type Description
DataFrame

DataFrame with columns: - Elevation (float): Storage elevation (ft or m) - Volume (float): Storage volume at elevation (acre-ft or m³)

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If storage area not found

Example

elev_vol = GeomStorage.get_elevation_volume("model.g01", "Reservoir Pool 1") print(f"Storage curve has {len(elev_vol)} points") print(f"Elevation range: {elev_vol['Elevation'].min():.1f} to {elev_vol['Elevation'].max():.1f}") print(f"Max volume: {elev_vol['Volume'].max():,.0f} acre-ft")

get_storage_area_polygons staticmethod

Python
get_storage_area_polygons(geom_file: Union[str, Path], exclude_2d: bool = True) -> GeoDataFrame

Extract storage area polygon perimeter geometry from plain text geometry file.

Parses the Storage Area Surface Line= N block to build a Shapely Polygon from the N 16-char fixed-width XY pairs that follow it.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to .g## geometry file

required
exclude_2d bool

If True, exclude 2D flow areas identified by Storage Area Is2D= -1 (default True)

True

Returns:

Type Description
GeoDataFrame with columns
  • Name (str): Storage area name
  • geometry (Polygon): Perimeter polygon in project CRS
  • centroid_x (float): SA centroid X coordinate
  • centroid_y (float): SA centroid Y coordinate
  • is_2d (bool): Whether this is a 2D flow area

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

Example

sa_polygons = GeomStorage.get_storage_area_polygons("model.g01") print(f"Found {len(sa_polygons)} storage area polygons") for _, row in sa_polygons.iterrows(): ... coords = list(row.geometry.exterior.coords) ... print(f" {row['Name']}: {len(coords)-1} vertices")

get_storage_areas staticmethod

Python
get_storage_areas(geom_file: Union[str, Path], exclude_2d: bool = True) -> pd.DataFrame

Extract storage area metadata from geometry file.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
exclude_2d bool

If True, exclude 2D flow areas (default True). 2D flow areas are identified by having "Storage Area Is2D=" set to -1.

True

Returns:

Type Description
DataFrame

DataFrame with columns: - Name (str): Storage area name - NumPoints (int): Number of elevation-volume points - MinElev (float): Minimum elevation in storage curve (if available) - MaxElev (float): Maximum elevation in storage curve (if available) - Is2D (bool): Whether this is a 2D flow area

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

Example

Get only traditional storage areas (exclude 2D)

storage_df = GeomStorage.get_storage_areas("model.g01", exclude_2d=True) print(f"Found {len(storage_df)} storage areas")

Get all storage areas including 2D flow areas

all_storage = GeomStorage.get_storage_areas("model.g01", exclude_2d=False)

repair_viewing_rectangle_from_2d_areas staticmethod

Python
repair_viewing_rectangle_from_2d_areas(geom_file: Union[str, Path], buffer_percent: float = 1.0, backup: bool = True, update_hdf: bool = True) -> tuple[float, float, float, float]

Repair global geometry extents from the union of 2D-area perimeters.

This is an explicit opt-in repair for 2D-only projects whose Viewing Rectangle= and top-level geometry-HDF Extents are pathological. It must not be used blindly for mixed 1D/2D projects, because 1D reaches or structures may extend beyond the 2D perimeters.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Plain-text HEC-RAS geometry file (.g##).

required
buffer_percent float

Symmetric padding as a percentage of each union span. Defaults to 1 percent.

1.0
backup bool

Write <geometry>.bak before changing the text file.

True
update_hdf bool

Also update the existing sibling .g##.hdf top-level /Geometry Extents attribute.

True

Returns:

Type Description
tuple[float, float, float, float]

(xmin, xmax, ymin, ymax) written to the geometry artifacts.

replace_breaklines staticmethod

Python
replace_breaklines(geom_file: Union[str, Path], flow_area_name: str, breaklines: Sequence[dict], *, expected_existing_names: Optional[Sequence[str]] = None, create_backup: bool = True) -> Optional[Path]

Atomically replace every breakline block in a geometry text file.

HEC-RAS stores BreakLine blocks as a geometry-wide collection; the text format does not carry a 2D-area identifier on each block. flow_area_name therefore selects the insertion anchor, while this method intentionally replaces the complete collection. Callers working with multiple 2D areas must supply the complete retained collection.

expected_existing_names is an optimistic-concurrency guard. When supplied, the existing names and order must match before any write. Passing an empty breaklines sequence removes the collection. protection_radius accepts the native Boolean text encodings -1 (enabled), 0 (disabled), and 1 (enabled), preserving the supplied value.

set_2d_flow_area_perimeter staticmethod

Python
set_2d_flow_area_perimeter(geom_file: Union[str, Path], flow_area_name: str, coordinates: Optional[Sequence[Sequence[float]]] = None, geometry=None, point_generation_data: Optional[Union[str, Sequence[Optional[float]]]] = None, recompute_centroid: bool = False, create_backup: bool = True) -> Path

Create or update a storage-area-backed 2D flow area perimeter in .g## text.

Existing blocks retain unrelated records and settings in their source order. Unchanged perimeters retain their original coordinate records; changed perimeters use one XY pair per row with source trailing padding. A perimeter change clears stored mesh points and refreshes its timestamp.

Parameters:

Name Type Description Default
recompute_centroid bool

When updating an existing block, recompute the header centroid from the polygon. Default False preserves the original header coordinates.

False

set_2d_flow_area_settings staticmethod

Python
set_2d_flow_area_settings(geom_file: Union[str, Path], flow_area_name: str, spatially_varied_mann_on_faces: Optional[bool] = None, composite_classification: Optional[bool] = None, mannings_n: Optional[float] = None, cell_vol_tol: Optional[float] = None, cell_min_area_fraction: Optional[float] = None, face_profile_tol: Optional[float] = None, face_area_tol: Optional[float] = None, face_conv_ratio: Optional[float] = None, laminar_depth: Optional[float] = None, min_face_length_ratio: Optional[float] = None, point_generation_data: Optional[Union[str, Sequence[Optional[float]]]] = None, create_backup: bool = True) -> Path

Update 2D flow area text settings without making HDF the edit target.

set_breaklines staticmethod

Python
set_breaklines(geom_file: Union[str, Path], flow_area_name: str, breaklines: List[dict], create_backup: bool = True) -> Path

Write breakline blocks into a .g## for a 2D flow area.

Each dict in breaklines must have: name (str): breakline display name (unpadded). coords (list[tuple[float,float]]): polyline vertices. cell_size_near (float|None): BreakLine CellSize Min value. cell_size_far (float|None): BreakLine CellSize Max value.

Breaklines are inserted after the storage-area block for flow_area_name and before BC Line / Connection / LCMann blocks. Any existing breakline blocks are preserved (new ones are appended).

Returns the backup path if create_backup is True, else geom_file.

set_elevation_volume staticmethod

Python
set_elevation_volume(geom_file: Union[str, Path], storage_name: str, elevations: List[float], volumes: List[float], create_backup: bool = True) -> Path

Write elevation-volume curve for a storage area to geometry file.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
storage_name str

Storage area name (case-sensitive, must exist)

required
elevations List[float]

List of elevation values (must be ascending)

required
volumes List[float]

List of volume values (same length as elevations)

required
create_backup bool

If True, create .bak backup before modification (default True)

True

Returns:

Type Description
Path

Path to backup file if created, or geometry file path if no backup

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If storage area not found, or if elevations/volumes invalid

Example

Modify an existing storage curve

backup = GeomStorage.set_elevation_volume( ... "model.g01", "Reservoir Pool 1", ... elevations=[1200.0, 1210.0, 1220.0, 1230.0], ... volumes=[0.0, 500.0, 1500.0, 3500.0] ... ) print(f"Backup created: {backup}")

GeomStorage.set_elevation_volume( ... "model.g01", "Reservoir Pool 1", ... elevations=[1200.0, 1220.0], ... volumes=[0.0, 1000.0], ... create_backup=False ... )

Notes
  • Elevations must be in ascending order
  • Lengths of elevations and volumes must match
  • Creates .bak backup by default (strongly recommended)
  • Supports both "Storage Area Elev Volume=" and "Storage Area Vol Elev=" keywords

GeomProjection source reference

Reproject HEC-RAS model geometry coordinates.

All methods are static and designed to be used without instantiation.

reproject_geometry staticmethod

Python
reproject_geometry(geom_file: PathLike, source_crs: Any, destination_crs: Any, output_geom: Optional[PathLike] = None, *, allow_datum_shift: bool = False, overwrite: bool = False, create_backup: bool = False) -> Dict[str, Any]

Transform coordinates in one HEC-RAS plain-text geometry file.

The default writes a copied geometry next to the source file using a _reprojected suffix. Passing output_geom=geom_file updates that file in place, which is intended for already-copied project folders.

Parameters:

Name Type Description Default
geom_file PathLike

Source .g## geometry text file.

required
source_crs Any

Source CRS as a pyproj.CRS input, ESRI .prj path, or WKT text.

required
destination_crs Any

Destination CRS as a pyproj.CRS input, ESRI .prj path, or WKT text.

required
output_geom Optional[PathLike]

Optional output .g## path. Defaults to a copied sibling named *_reprojected.g##.

None
allow_datum_shift bool

HEC-RAS cannot reproduce datum transformations. By default, transformations between different geodetic datums raise ValueError. Set True only when the caller has made a project-specific engineering decision to allow the pyproj datum operation.

False
overwrite bool

Allow replacing an existing output_geom.

False
create_backup bool

Create .bak before an in-place write.

False

Returns:

Type Description
Dict[str, Any]

Dictionary with source/output paths, CRS metadata, transformation

Dict[str, Any]

counts, and post-conversion QA findings.

reproject_model_geometry staticmethod

Python
reproject_model_geometry(project_path: PathLike, source_crs: Any, destination_crs: Any, dest_folder: Optional[PathLike] = None, *, geometry_files: Optional[Sequence[PathLike]] = None, projection_filename: Optional[str] = None, allow_datum_shift: bool = False, overwrite: bool = False) -> Dict[str, Any]

Copy a HEC-RAS project and reproject its plain-text geometries.

This method preserves the source project by default. It copies the project folder, transforms .g## text geometry coordinates in the copied folder, writes a destination ESRI projection file, updates copied .rasmap projection references, and reports terrain/compiled-geometry rebuild requirements.

Parameters:

Name Type Description Default
project_path PathLike

Project folder, .prj file, or .rasmap file.

required
source_crs Any

Source CRS as a pyproj.CRS input, ESRI .prj path, or WKT text.

required
destination_crs Any

Destination CRS as a pyproj.CRS input, ESRI .prj path, or WKT text.

required
dest_folder Optional[PathLike]

Destination project folder. Defaults to a sibling folder named <project>_reprojected.

None
geometry_files Optional[Sequence[PathLike]]

Optional geometry filenames/paths to transform. Relative names are resolved in the copied project folder. Defaults to Geom File= entries in the copied project file, with a *.g## fallback.

None
projection_filename Optional[str]

Optional destination .prj filename under the copied project's Projection folder.

None
allow_datum_shift bool

See :meth:reproject_geometry.

False
overwrite bool

Allow replacing an existing dest_folder.

False

Returns:

Type Description
Dict[str, Any]

Dictionary with copied project path, projection update details,

Dict[str, Any]

per-geometry transformation results, terrain requirements, and

Dict[str, Any]

compiled geometry rebuild notes.

GeomLateral source reference

Operations for lateral structures and SA/2D connections in geometry files.

All methods are static and designed to be used without instantiation.

classify_connections staticmethod

Python
classify_connections(geom_file: Union[str, Path], child_boundary: BaseGeometry, *, retained_area_names: Optional[Sequence[str]] = None, tolerance: float = 0, allow_extended_support: bool = False) -> GeoDataFrame

Classify full physical support as keep/drop/block, without mutation.

geometry is the union of the width-buffered crest and width-buffered explicit culvert barrels. Gates, undecoded records, bridges and breaches have unverified support and fail closed. Positive tolerance supplies an external separation guard: disjoint support near the child blocks with CONNECTION_NEAR_CHILD_BOUNDARY. Containment remains exact; tolerance never permits physical crossings. Coordinates and widths use model units.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Plain-text geometry path as str or Path.

required
child_boundary BaseGeometry

Valid Polygon or MultiPolygon in model coordinates.

required
retained_area_names Optional[Sequence[str]]

Names preserved in the child, or None for all source areas. Both named endpoints must remain.

None
tolerance float

Finite nonnegative external separation guard in model units; never expands the child's containment boundary.

0
allow_extended_support bool

Explicitly accept complete gate opening GIS support, cell-size metadata and the additional verified empty bridge template. Defaults to False, preserving existing decisions and the six-column return shape. Other unknown support blocks.

False

Returns:

Type Description
GeoDataFrame

GeoDataFrame with Name, From, To, action, reason and geometry.

GeoDataFrame

Unverified extent produces block; verified disjoint support drop;

GeoDataFrame

complete containment with retained endpoints keep.

GeoDataFrame

With allow_extended_support=True, gate_group_count is added before

GeoDataFrame

geometry and counts verified gate groups. Gate GIS lines are buffered

GeoDataFrame

by half their positive finite opening widths; dimensions and opening

GeoDataFrame

counts/stations must be complete. No native attachment is established.

Raises:

Type Description
FileNotFoundError

Geometry file does not exist.

ValueError

Boundary or tolerance is invalid.

get_connection_gate_lines staticmethod

Python
get_connection_gate_lines(geom_file: str | Path, connection_name: str) -> GeoDataFrame

Read complete explicit gate opening GIS polylines without mutation.

Coordinates retain model horizontal units and have no inferred CRS. Returns opening_index (one-based), opening_name and geometry. Missing GIS lines return an empty frame; duplicate indexes, incomplete declared coordinate counts, nonfinite coordinates or zero-length lines raise ValueError. Stationing alone is never substituted for explicit gate GIS evidence.

remap_connection_areas staticmethod

Python
remap_connection_areas(geom_file: str | Path, area_name_map: dict[str, str]) -> pd.DataFrame

Return connection records with explicit endpoint-name replacements.

Reads the source without mutation. Only recognized From/To area records are changed; native physical/control records and coordinates remain exact. The returned Name/RawBlock DataFrame can be filtered and passed to write_connection_data on an attempt-owned clone. No units or CRS change. This name mapping does not establish native attachment or hydraulic equivalence; those require fresh preprocessing and separate checks.

Parameters:

Name Type Description Default
geom_file str | Path

Plain-text geometry path, as str or Path.

required
area_name_map dict[str, str]

Explicit old-to-new storage/2D area names. Names must be nonempty strings without newlines, commas or equals signs.

required

Returns:

Type Description
DataFrame

Name and authoritative RawBlock columns, source order.

Raises:

Type Description
FileNotFoundError

Source geometry is missing.

ValueError

Mapping names or source endpoint records are ambiguous.

delete_connection staticmethod

Python
delete_connection(geom_file: Union[str, Path], connection_name: str, create_backup: bool = True) -> Optional[Path]

Remove a connection block entirely from a geometry file.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name to delete

required
create_backup bool

Create .bak backup before writing (default True)

True

Returns:

Type Description
Optional[Path]

Backup path when create_backup=True, else None

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If connection not found

get_bridge_approach_xs staticmethod

Python
get_bridge_approach_xs(geom_file: Union[str, Path], connection_name: str, side: int = 1) -> pd.DataFrame

Extract approach cross-section for a bridge connection.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required
side int

1 for upstream, 2 for downstream

1

Returns:

Type Description
pd.DataFrame with columns

Station, Elevation

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If connection or approach XS not found

get_bridge_data staticmethod

Python
get_bridge_data(geom_file: Union[str, Path], connection_name: str) -> Dict[str, Any]

Extract all bridge sub-record data for a connection.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required

Returns:

Type Description
dict with keys

bridge_params, deck, bridge_xs, piers, coefficients, approach_xs

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If connection not found or has no bridge sub-records

get_bridge_deck staticmethod

Python
get_bridge_deck(geom_file: Union[str, Path], connection_name: str) -> pd.DataFrame

Extract deck geometry for a bridge connection.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required

Returns:

Type Description
pd.DataFrame with columns

Location, Station, Elevation, LowChord

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If connection or deck not found

get_bridge_piers staticmethod

Python
get_bridge_piers(geom_file: Union[str, Path], connection_name: str) -> pd.DataFrame

Extract pier definitions for a bridge connection.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required

Returns:

Type Description
pd.DataFrame with columns

PierIndex, Skew, UpstreamStation,

DataFrame

NumUpstreamPoints, DownstreamStation, NumDownstreamPoints,

DataFrame

UpstreamWidths, UpstreamElevations, DownstreamWidths, DownstreamElevations

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If connection not found or has no piers

get_bridge_xs staticmethod

Python
get_bridge_xs(geom_file: Union[str, Path], connection_name: str, side: int = 1) -> pd.DataFrame

Extract bridge cross-section for a connection.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required
side int

1 for upstream, 2 for downstream

1

Returns:

Type Description
pd.DataFrame with columns

Station, Elevation

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If connection or cross-section not found

get_connection_culverts staticmethod

Python
get_connection_culverts(geom_file: Union[str, Path], connection_name: str) -> pd.DataFrame

Read the culvert(s) on a SA/2D connection, one row per barrel.

A 2D connection culvert stores explicit per-barrel GIS endpoint coordinates (unlike a 1D inline culvert, whose barrel line is derived).

Returns:

Type Description
pd.DataFrame with columns

CulvertName, GroupIndex, Shape, ShapeName,

DataFrame

Span, Rise, Length, ManningsN, EntranceLoss, ExitLoss, Chart, Scale,

DataFrame

UpstreamInvert, DownstreamInvert, NumBarrels, BottomN, BarrelIndex,

DataFrame

BarrelName, us_station, ds_station, us_x, us_y, ds_x, ds_y.

DataFrame

Empty DataFrame if the connection has no culverts.

get_connection_data staticmethod

Python
get_connection_data(geom_file: Union[str, Path]) -> pd.DataFrame

Read complete connection records with an authoritative lossless block.

Physical tables are nested DataFrames, not flattened scalar columns. Breach and UnknownRecords contain undecoded native record strings; these records are preserved, not represented as fully decoded physics. DefaultsUsed lists the fields explicitly defaulted by set_connection. Missing optional profiles are empty Station/Elevation DataFrames. EmptyRecords preserves recognized zero-count profile records and the metadata of a completely empty native bridge skeleton as raw strings. RawBlock preserves original line endings and undecodable source bytes using UTF-8 surrogateescape and is authoritative for writing.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Plain-text geometry path as str or Path.

required

Returns:

Type Description
DataFrame

DataFrame with CONNECTION_DATA_COLUMNS, including nested physical

DataFrame

tables and ParseIssues for records that cannot be fully decoded.

Raises:

Type Description
FileNotFoundError

The geometry file does not exist.

OSError

The geometry file cannot be read.

get_connection_gates staticmethod

Python
get_connection_gates(geom_file: Union[str, Path], connection_name: str) -> pd.DataFrame

Extract gate definitions for a SA/2D connection.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required

Returns:

Type Description
DataFrame

DataFrame with gate parameters including: - GateName, Width, Height, InvertElevation, etc.

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If connection not found or has no gates

Example

gates = GeomLateral.get_connection_gates("model.g01", "Dam Outlet") print(f"Found {len(gates)} gates")

get_connection_line_coords staticmethod

Python
get_connection_line_coords(geom_file: Union[str, Path], connection_name: str) -> pd.DataFrame

Extract the polyline XY coordinates of a SA/2D connection line.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required

Returns:

Type Description
DataFrame

DataFrame with columns X, Y

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If connection not found or has no line coordinates

get_connection_profile staticmethod

Python
get_connection_profile(geom_file: Union[str, Path], connection_name: str) -> pd.DataFrame

Extract dam/weir crest profile for a SA/2D connection.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required

Returns:

Type Description
DataFrame

DataFrame with columns: - Station (float): Station along weir - Elevation (float): Weir crest elevation

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If connection not found

Example

profile = GeomLateral.get_connection_profile("model.g01", "Dam Embankment") print(f"Weir crest has {len(profile)} points")

get_connections staticmethod

Python
get_connections(geom_file: Union[str, Path]) -> pd.DataFrame

Extract SA/2D area connection metadata from geometry file.

Connections include storage area to storage area connections, storage area to 2D flow area connections, and 2D to 2D flow area connections.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required

Returns:

Type Description
DataFrame

DataFrame with columns: - Name (str): Connection name - Type (str): Connection type (SA to SA, SA to 2D, etc.) - From (str): Upstream area name - To (str): Downstream area name - NumPoints (int): Number of station/elevation points in weir profile - Conn Routing Type (int): Routing method from the geometry file. 1 = standard connection (weir/weir-with-gates). 32 = bridge connection with full hydraulic sub-records (deck, bridge opening cross-sections, piers, approach cross-sections, and hydraulic coefficients in Conn BR: blocks). - HasGate (bool): Whether the connection has gate definitions - HasCulvert (bool): Whether the connection has culvert definitions

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

Example

connections = GeomLateral.get_connections("model.g01") bridges = connections[connections["Conn Routing Type"] == 32] print(f"Found {len(bridges)} bridge connections")

get_lateral_structures staticmethod

Python
get_lateral_structures(geom_file: Union[str, Path], river: Optional[str] = None) -> pd.DataFrame

Extract lateral weir structure metadata from geometry file.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
river Optional[str]

Filter by specific river name

None

Returns:

Type Description
DataFrame

DataFrame with columns: - River (str): River name - Reach (str): Reach name - Name (str): Lateral weir name - StartRS (str): Starting river station - EndRS (str): Ending river station - NumPoints (int): Number of station/elevation points

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

Example

laterals = GeomLateral.get_lateral_structures("model.g01") for _, row in laterals.iterrows(): ... print(f"Lateral: {row['Name']} from RS {row['StartRS']} to {row['EndRS']}")

get_weir_profile staticmethod

Python
get_weir_profile(geom_file: Union[str, Path], lateral_name: str) -> pd.DataFrame

Extract station/elevation profile for a lateral weir.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
lateral_name str

Lateral weir name

required

Returns:

Type Description
DataFrame

DataFrame with columns: - Station (float): Station along weir - Elevation (float): Weir crest elevation

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If lateral weir not found

Example

profile = GeomLateral.get_weir_profile("model.g01", "Spillway") print(f"Weir profile has {len(profile)} points") print(f"Crest elevation range: {profile['Elevation'].min():.1f} to {profile['Elevation'].max():.1f}")

set_bridge_approach_xs staticmethod

Python
set_bridge_approach_xs(geom_file: Union[str, Path], connection_name: str, sta_elev_df: DataFrame, side: int = 1, *, bank_stations: Optional[Tuple[float, float]] = None, mannings_n: Optional[List[Tuple[float, float]]] = None, create_backup: bool = True) -> Optional[Path]

Write approach cross-section for a bridge connection.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required
sta_elev_df DataFrame

DataFrame with Station and Elevation columns

required
side int

1 for upstream, 2 for downstream

1
bank_stations Optional[Tuple[float, float]]

(left, right) bank station tuple

None
mannings_n Optional[List[Tuple[float, float]]]

List of (station, n_value) tuples

None
create_backup bool

Create .bak backup before writing (default True)

True

Returns:

Type Description
Optional[Path]

Backup path when create_backup=True, else None

set_bridge_coefficients staticmethod

Python
set_bridge_coefficients(geom_file: Union[str, Path], connection_name: str, coefficients: List[str], *, create_backup: bool = True) -> Optional[Path]

Write bridge hydraulic coefficients for a connection.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required
coefficients List[str]

List of coefficient strings matching Conn BR: BR Coef= format

required
create_backup bool

Create .bak backup before writing (default True)

True

Returns:

Type Description
Optional[Path]

Backup path when create_backup=True, else None

set_bridge_deck staticmethod

Python
set_bridge_deck(geom_file: Union[str, Path], connection_name: str, deck_df: DataFrame, *, deck_distance: float = 50.0, weir_coef: float = 2.6, create_backup: bool = True) -> Optional[Path]

Write deck geometry for a bridge connection.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required
deck_df DataFrame

DataFrame with columns Location, Station, Elevation, LowChord

required
deck_distance float

Distance between upstream and downstream faces

50.0
weir_coef float

Weir discharge coefficient for deck overflow

2.6
create_backup bool

Create .bak backup before writing (default True)

True

Returns:

Type Description
Optional[Path]

Backup path when create_backup=True, else None

set_bridge_piers staticmethod

Python
set_bridge_piers(geom_file: Union[str, Path], connection_name: str, piers, *, create_backup: bool = True) -> Optional[Path]

Write pier definitions for a bridge connection.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required
piers DataFrame or list[dict]

DataFrame or list of dicts with pier data

required
create_backup bool

Create .bak backup before writing (default True)

True

Returns:

Type Description
Optional[Path]

Backup path when create_backup=True, else None

set_bridge_xs staticmethod

Python
set_bridge_xs(geom_file: Union[str, Path], connection_name: str, sta_elev_df: DataFrame, side: int = 1, *, bank_stations: Optional[Tuple[float, float]] = None, mannings_n: Optional[List[Tuple[float, float]]] = None, create_backup: bool = True) -> Optional[Path]

Write bridge cross-section for a connection.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required
sta_elev_df DataFrame

DataFrame with Station and Elevation columns

required
side int

1 for upstream, 2 for downstream

1
bank_stations Optional[Tuple[float, float]]

(left, right) bank station tuple

None
mannings_n Optional[List[Tuple[float, float]]]

List of (station, n_value) tuples

None
create_backup bool

Create .bak backup before writing (default True)

True

Returns:

Type Description
Optional[Path]

Backup path when create_backup=True, else None

set_connection staticmethod

Python
set_connection(geom_file: Union[str, Path], connection_name: str, coordinates: List[Tuple[float, float]], upstream_area: str, downstream_area: str, *, routing_type: int = 1, weir_width: Optional[float] = None, weir_coef: Optional[float] = None, crest_profile: Optional[DataFrame] = None, allow_defaults: bool = False, overflow_method_2d: bool = True, create_backup: bool = True) -> Optional[Path]

Create or replace a SA/2D connection block in a geometry file.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required
coordinates List[Tuple[float, float]]

List of (x, y) tuples defining the connection line

required
upstream_area str

Upstream storage/2D area name

required
downstream_area str

Downstream storage/2D area name

required
routing_type int

Routing type (1 = 2D structure, default)

1
weir_width Optional[float]

Explicit positive weir width in model units.

None
weir_coef Optional[float]

Explicit positive weir discharge coefficient.

None
crest_profile Optional[DataFrame]

Explicit Station/Elevation DataFrame.

None
allow_defaults bool

Opt into width=100, coefficient=3 and a flat zero crest for missing physical inputs. Defaults are recorded in Connection Desc and exposed by get_connection_data.

False
overflow_method_2d bool

Use 2D overflow method (default True)

True
create_backup bool

Create .bak backup before writing (default True)

True

Returns:

Type Description
Optional[Path]

Backup path when create_backup=True, else None

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If coordinates are empty

set_connection_culverts staticmethod

Python
set_connection_culverts(geom_file: Union[str, Path], connection_name: str, culverts: List[Dict[str, Any]]) -> Dict[str, Any]

Author (replace) the culvert group(s) on a SA/2D connection, writing the Connection Culv= records with explicit per-barrel GIS endpoint coordinates. Verified to compute in HEC-RAS.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##). A .bak backup is created.

required
connection_name str

Connection (must already exist with a Connection Line=).

required
culverts List[Dict[str, Any]]

list of culvert-group dicts, each with::

{ "Shape": 2, "Span": 8.0, "Rise": 6.0, "Length": 60.0, "ManningsN": 0.024, "EntranceLoss": 0.5, "ExitLoss": 1.0, "Chart": 8, "Scale": 1, "Name": "Retrofit Culv", "UpstreamInvert": 539.56, "DownstreamInvert": 539.06, "BottomN": 0.024, # optional (-> ManningsN) "barrels": [ {"name": "Barrel #1", "us_xy": (x, y), "ds_xy": (x, y), "us_station": 7113.55, "ds_station": 7113.55}, # stations optional ], }

If a barrel omits us_station/ds_station they default to the arc-length projection of the barrel midpoint onto the connection line.

required

Returns:

Type Description
dict

{culverts_written, barrels_written, backup_path, length_warnings}

set_connection_gates staticmethod

Python
set_connection_gates(geom_file: Union[str, Path], connection_name: str, gates, create_backup: bool = True) -> Optional[Path]

Write gate definitions into an existing connection block.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name (must already exist)

required
gates DataFrame or list[dict]

DataFrame or list of dicts with gate parameters: GateName, Width, Height, InvertElevation, GateCoefficient, NumOpenings, OpeningStations

required
create_backup bool

Create .bak backup before writing (default True)

True

Returns:

Type Description
Optional[Path]

Backup path when create_backup=True, else None

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If connection not found or gates are empty

set_connection_profile staticmethod

Python
set_connection_profile(geom_file: Union[str, Path], connection_name: str, sta_elev_df: DataFrame, create_backup: bool = True) -> Optional[Path]

Write the dam/weir crest station-elevation profile for a connection.

Supports both modern Connection= blocks with Conn Weir SE= records and legacy SA/2D Area Conn= blocks with #Conn Weir Sta/Elev= records.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required
sta_elev_df DataFrame

DataFrame with Station and Elevation columns

required
create_backup bool

Create a .bak backup before writing (default True)

True

Returns:

Type Description
Optional[Path]

Backup path when create_backup=True, else None

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If the connection/profile or required columns are missing

set_connection_profile_from_terrain staticmethod

Python
set_connection_profile_from_terrain(geom_file: Union[str, Path], connection_name: str, rasmap_path: Union[str, Path], geom_hdf_path: Union[str, Path], *, create_backup: bool = True) -> pd.DataFrame

Sample terrain along the connection line and write as weir crest profile.

Chains get_connection_line_coords() -> RasTerrainMod.get_terrain_profile() -> set_connection_profile().

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file

required
connection_name str

Connection name

required
rasmap_path Union[str, Path]

Path to .rasmap file (for terrain layer discovery)

required
geom_hdf_path Union[str, Path]

Path to geometry HDF file

required
create_backup bool

Create .bak backup before writing (default True)

True

Returns:

Type Description
DataFrame

The sampled terrain profile (Station, Elevation)

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If connection not found or has no line data

write_connection_data staticmethod

Python
write_connection_data(geom_file: Union[str, Path], connections_df: DataFrame, *, create_backup: bool = True) -> Optional[Path]

Replace the connection inventory losslessly, preserving unrelated text.

Omitted rows remove their connection. RawBlock is authoritative; every supplied decoded column must agree with it (except positional StartLine and EndLine). To edit physical inputs use focused authoring methods and read again, rather than editing only a nested table. Validation precedes backup creation. Return the existing geometry backup convention.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Target plain-text geometry path as str or Path.

required
connections_df DataFrame

Complete replacement inventory. Name and RawBlock are required; other decoded columns, when supplied, are checked.

required
create_backup bool

Create a geometry backup before atomic replacement.

True

Returns:

Type Description
Optional[Path]

Backup path, or None when create_backup=False.

Raises:

Type Description
FileNotFoundError

Target geometry does not exist.

TypeError

connections_df is not a DataFrame.

ValueError

Names, blocks or decoded columns disagree or duplicate.

OSError

The backup or atomic write fails.

GeomInlineWeir source reference

Operations for parsing HEC-RAS inline weirs in geometry files.

All methods are static and designed to be used without instantiation.

get_gates staticmethod

Python
get_gates(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> pd.DataFrame

Extract gate parameters and opening definitions for an inline weir.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string)

required

Returns:

Type Description
pd.DataFrame with columns
-GateName

Gate identifier (e.g., "Gate #1")

(-Width, Height, InvertElevation)

Gate dimensions

-GateCoefficient

Flow coefficient

(-ExpansionTop, ExpansionOrifice, ExpansionHydraulic)

Expansion coefficients

-GateType

Gate type code

(-WeirCoefficient, IsOgee)

Weir parameters

(-SpillwayHeight, DesignHead)

Design parameters

-NumOpenings

Number of gate openings

-OpeningStations

List of station values for each opening

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If inline weir not found or has no gates

Example

gates = GeomInlineWeir.get_gates( ... "BaldEagle.g01", "Bald Eagle Creek", "Reach 1", "81084.18" ... ) print(f"Found {len(gates)} gates")

get_profile staticmethod

Python
get_profile(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> pd.DataFrame

Extract weir crest station/elevation profile for an inline weir.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string)

required

Returns:

Type Description
pd.DataFrame with columns
-Station

Station values along weir crest

-Elevation

Elevation values at each station

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If inline weir not found

Example

profile = GeomInlineWeir.get_profile( ... "BaldEagle.g01", "Bald Eagle Creek", "Reach 1", "81084.18" ... ) print(f"Profile has {len(profile)} points")

get_weirs staticmethod

Python
get_weirs(geom_file: Union[str, Path], river: Optional[str] = None, reach: Optional[str] = None) -> pd.DataFrame

List all inline weirs in geometry file with metadata.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river Optional[str]

Optional filter by river name (case-sensitive)

None
reach Optional[str]

Optional filter by reach name (case-sensitive)

None

Returns:

Type Description
pd.DataFrame with columns
(-River, Reach, RS)

Location identifiers

-NodeName

Descriptive name (if available)

-PilotFlow

Pilot flow flag (0/1)

(-Distance, Width, Coefficient, Skew)

Weir parameters

(-MaxSubmergence, MinElevation, IsOgee)

Additional parameters

(-SpillwayHeight, DesignHead)

Design parameters

-HasGate

Boolean indicating if gates are present

-NumOpenings

Number of gate openings (if gates present)

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

Example

weirs = GeomInlineWeir.get_weirs("BaldEagle.g01") print(f"Found {len(weirs)} inline weirs") print(weirs[['River', 'Reach', 'RS', 'Coefficient']])

GeomBridge source reference

Operations for parsing HEC-RAS bridges in geometry files.

All methods are static and designed to be used without instantiation.

get_abutment staticmethod

Python
get_abutment(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> pd.DataFrame

Extract abutment geometry for a bridge (if present).

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string)

required

Returns:

Type Description
pd.DataFrame with columns
-Location

'upstream' or 'downstream'

-Station

Abutment station values

-Parameter

Abutment parameter values

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If bridge not found or has no abutment

Example

abutment = GeomBridge.get_abutment("model.g08", "River", "Reach", "25548") print(f"Abutment has {len(abutment)} points")

get_approach_sections staticmethod

Python
get_approach_sections(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> pd.DataFrame

Extract BR U (upstream) and BR D (downstream) approach section geometry.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string)

required

Returns:

Type Description
pd.DataFrame with columns
-Location

'upstream' or 'downstream'

-DataType

'station_elevation', 'mannings_n', or 'banks'

(-Station, Elevation, N_Value, LeftBank, RightBank)

Data values

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If bridge not found

Example

approach = GeomBridge.get_approach_sections("model.g08", "River", "Reach", "25548") upstream_xs = approach[(approach['Location'] == 'upstream') & (approach['DataType'] == 'station_elevation')] print(f"Upstream XS has {len(upstream_xs)} points")

get_bridge_opening_xs staticmethod

Python
get_bridge_opening_xs(geom_file: Union[str, Path], river: str, reach: str, rs: str, section: str = 'upstream') -> pd.DataFrame

Extract the ground profile inside the bridge opening for a 1D bridge.

In HEC-RAS 1D bridge modeling, sections 2 and 3 represent the ground profile at the downstream and upstream faces of the bridge opening. These are stored as BR D / BR U #Sta/Elev records in the bridge block. When no explicit inside-bridge XS data exists, the method falls back to the nearest regular cross-section in the appropriate direction.

Inside-bridge sections are typically initialized as copies of the approach cross-sections when a bridge is first created in HEC-RAS, but users may edit them independently.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string)

required
section str

'upstream' for section 3 (upstream face) or 'downstream' for section 2 (downstream face)

'upstream'

Returns:

Type Description
pd.DataFrame with columns
-Station

Cross-section station (float)

-Elevation

Ground elevation (float)

-Source

'bridge_block' if from BR U/BR D data, 'approach_xs' if from adjacent regular cross-section

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If bridge not found, invalid section, or no XS data available

Example

xs = GeomBridge.get_bridge_opening_xs("model.g01", "River", "Reach", "5.4") print(f"Section 3 has {len(xs)} points, source: {xs['Source'].iloc[0]}") downstream = GeomBridge.get_bridge_opening_xs( ... "model.g01", "River", "Reach", "5.4", section='downstream' ... )

get_bridges staticmethod

Python
get_bridges(geom_file: Union[str, Path], river: Optional[str] = None, reach: Optional[str] = None) -> pd.DataFrame

List all bridges/culverts in geometry file with metadata.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river Optional[str]

Optional filter by river name (case-sensitive)

None
reach Optional[str]

Optional filter by reach name (case-sensitive)

None

Returns:

Type Description
pd.DataFrame with columns
(-River, Reach, RS)

Location identifiers

-NodeName

Bridge name/description

-NumDecks

Number of deck spans

-DeckWidth

Bridge deck width

-WeirCoefficient

Weir flow coefficient

-Skew

Bridge skew angle

-NumPiers

Count of pier definitions

-HasAbutment

Boolean indicating abutment presence

-HTabHWMax

Maximum headwater elevation

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

Example

bridges = GeomBridge.get_bridges("model.g08") print(f"Found {len(bridges)} bridges")

get_coefficients staticmethod

Python
get_coefficients(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> pd.DataFrame

Extract bridge hydraulic coefficients and parameters.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string)

required

Returns:

Type Description
pd.DataFrame with columns
-ParameterType

'br_coef', 'wspro', or 'bc_design'

-Index

Parameter index

-Value

Parameter value

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If bridge not found

Example

coef = GeomBridge.get_coefficients("model.g08", "River", "Reach", "25548") br_coefs = coef[coef['ParameterType'] == 'br_coef'] print(br_coefs)

get_deck staticmethod

Python
get_deck(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> pd.DataFrame

Extract complete deck geometry for a bridge.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string)

required

Returns:

Type Description
pd.DataFrame with columns
-Location

'upstream' or 'downstream'

-Station

Station values

-Elevation

Deck elevation values

-LowChord

Low chord elevation values

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If bridge not found

Example

deck = GeomBridge.get_deck("model.g08", "River", "Reach", "25548") upstream = deck[deck['Location'] == 'upstream'] print(f"Upstream deck has {len(upstream)} points")

get_htab staticmethod

Python
get_htab(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> pd.DataFrame

Extract structure hydraulic table (HTab) parameters.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string)

required

Returns:

Type Description
pd.DataFrame with columns
-Parameter

Parameter name (HWMax, TWMax, MaxFlow, etc.)

-Value

Parameter value

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If structure not found

Example
Python
>>> htab = GeomBridge.get_htab("model.g08", "River", "Reach", "25548")
>>> hw_max = htab[htab['Parameter'] == 'HWMax']['Value'].values[0]
>>> print(f"HW Max: {hw_max}")

get_htab_dict staticmethod

Python
get_htab_dict(geom_file: Union[str, Path], river: str, reach: str, rs: str, include_invert: bool = True) -> Dict[str, Any]

Extract structure hydraulic table (HTab) parameters as a dictionary.

This method provides a more convenient dictionary interface compared to get_htab() which returns a DataFrame. It also optionally includes the structure invert elevation extracted from bridge deck geometry.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string)

required
include_invert bool

If True, extract invert from deck geometry (default: True)

True

Returns:

Type Description
dict with keys
-hw_max

Maximum headwater elevation (float or None)

-tw_max

Maximum tailwater elevation (float or None)

-max_flow

Maximum flow through structure (float or None)

-use_user_curves

Flag for user curves (-1 = enabled, 0 = defaults, None if missing)

-free_flow_points

Number of points on free flow curve (int or None)

-submerged_curves

Number of submerged rating curves (int or None)

-points_per_curve

Points per submerged curve (int or None)

-invert

Minimum low chord elevation from deck (float or None, only if include_invert=True)

-has_htab_lines

True if any BC HTab lines were found

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If structure not found

Example

htab = GeomBridge.get_htab_dict("model.g08", "River", "Reach", "25548") print(f"HW Max: {htab['hw_max']}, Max Flow: {htab['max_flow']}") if htab['invert']: ... print(f"Invert: {htab['invert']}")

Notes
  • Returns None for missing parameters (doesn't raise errors)
  • The 'invert' key contains the minimum LowChord value from deck geometry
  • This can be used to calculate optimal HWMax with safety factors: optimal_hw_max = invert + (max_observed_depth * safety_factor)

get_hydraulic_methods staticmethod

Python
get_hydraulic_methods(geom_file: Union[str, Path], river: str, reach: str, rs: str, opening_index: int = 0) -> Dict[str, Any]

Read bridge hydraulic method selections from geometry text records.

This parser reads the bridge Bridge Culvert- marker, deck/weir coefficient record, and the selected opening's BR Coef= and WSPro= records. The BR Coef= record stores the selected low-flow method code and high-flow method flag used by the Bridge Modeling Approach editor.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string)

required
opening_index int

Zero-based bridge opening/coefficient record index when a bridge has multiple BR Coef= records (default 0)

0

Returns:

Type Description
dict with keys
-low_flow_method

one of energy, momentum, yarnell, wspro or None if no method code is present

-high_flow_method

energy or pressure_weir when available

-enabled_low_flow_methods

per-method compute flags from BR Coef

-coefficients

Momentum, Yarnell, pressure-flow, deck/weir, and audit values

-deck

parsed values from the Deck Dist Width WeirC record

-wspro

named WSPRO fields, or None if no WSPro record exists

-raw

original method records and comma fields for audit

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If bridge or opening is not found

IOError

If file read fails

Example

methods = GeomBridge.get_hydraulic_methods( ... "model.g01", "Beaver Creek", "Kentwood", "5.4" ... ) methods["low_flow_method"] 'momentum'

get_piers staticmethod

Python
get_piers(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> pd.DataFrame

Extract all pier definitions for a bridge.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string)

required

Returns:

Type Description
pd.DataFrame with columns
-PierIndex

Pier number (1, 2, 3...)

(-UpstreamStation, DownstreamStation)

Pier locations

(-NumUpstreamPoints, NumDownstreamPoints)

Point counts

(-UpstreamWidths, UpstreamElevations)

Lists

(-DownstreamWidths, DownstreamElevations)

Lists

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If bridge not found or has no piers

Example

piers = GeomBridge.get_piers("model.g08", "River", "Reach", "25548") print(f"Found {len(piers)} piers")

optimize_all_structures_from_results staticmethod

Python
optimize_all_structures_from_results(geom_file: Union[str, Path], hdf_results_path: Union[str, Path], hw_safety_factor: float = 2.0, flow_safety_factor: float = 2.0, tw_safety_factor: float = 2.0, free_flow_points: int = 100, submerged_curves: int = 60, points_per_curve: int = 50, create_backup: bool = True, ras_object=None) -> Dict[str, Any]

Optimize HTAB parameters for ALL structures in geometry file based on results.

This method finds all structures (bridges, culverts, inline weirs) in the geometry file, extracts their maximum values from HDF results, and writes optimal HTAB parameters for each.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
hdf_results_path Union[str, Path]

Path to plan HDF file with results

required
hw_safety_factor float

Multiplier for headwater range (default 2.0 = 100% safety)

2.0
flow_safety_factor float

Multiplier for flow (default 2.0 = 100% safety)

2.0
tw_safety_factor float

Multiplier for tailwater range (default 2.0 = 100% safety)

2.0
free_flow_points int

Points on free flow curve (optimal 100)

100
submerged_curves int

Number of submerged curves (optimal 60)

60
points_per_curve int

Points per submerged curve (optimal 50)

50
create_backup bool

Whether to create a .bak backup before modification (default True). Set to False when called from an orchestrator that manages its own backup.

True
ras_object RasPrj

RasPrj object for multi-project workflows

None

Returns:

Type Description
dict

Summary with keys: - 'optimized': Number of structures successfully optimized - 'failed': Number of structures that couldn't be optimized - 'total': Total structures found - 'details': List of per-structure results - 'errors': List of error messages for failed structures - 'backup_path': Path to geometry backup (or None if create_backup=False)

Raises:

Type Description
FileNotFoundError

If geometry or HDF file doesn't exist

IOError

If file write fails

Example

Optimize all structures after running simulation

result = GeomBridge.optimize_all_structures_from_results( ... "model.g01", "model.p01.hdf", ... hw_safety_factor=2.0, flow_safety_factor=2.0 ... ) print(f"Optimized {result['optimized']} of {result['total']} structures") if result['failed'] > 0: ... print(f"Failed: {result['errors']}")

Notes
  • Processes all structures found in geometry file
  • Creates single backup before any modifications
  • Continues processing if individual structures fail
  • Reports detailed results for each structure
See Also
  • optimize_htab_from_results(): Optimize single structure
  • get_bridges(): List all bridges in file

optimize_htab_from_results staticmethod

Python
optimize_htab_from_results(geom_file: Union[str, Path], river: str, reach: str, rs: str, hdf_results_path: Union[str, Path], hw_safety_factor: float = 2.0, flow_safety_factor: float = 2.0, tw_safety_factor: float = 2.0, free_flow_points: int = 100, submerged_curves: int = 60, points_per_curve: int = 50, validate: bool = True, ras_object=None) -> Dict[str, Any]

Optimize structure HTAB parameters based on existing HDF results.

This method extracts maximum headwater, tailwater, and flow values from a completed HEC-RAS simulation, applies safety factors, and writes optimal HTAB parameters to the geometry file.

Algorithm
  1. Extract max headwater from HDF results at structure location
  2. Extract max tailwater from HDF results at structure location
  3. Extract max flow from HDF results at structure location
  4. Get structure invert from deck geometry
  5. Calculate optimal values using GeomHtabUtils.calculate_optimal_structure_htab():
  6. hw_max = invert + (max_hw - invert) * hw_safety_factor
  7. tw_max = invert + (max_tw - invert) * tw_safety_factor
  8. max_flow = max_flow * flow_safety_factor
  9. Set all curve point counts to optimal for best resolution
  10. Write parameters to geometry file

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station of structure (as string)

required
hdf_results_path Union[str, Path]

Path to plan HDF file with results

required
hw_safety_factor float

Multiplier for headwater range above invert (default 2.0 = 100%) Safety is applied to range, not absolute value.

2.0
flow_safety_factor float

Multiplier for maximum flow (default 2.0 = 100%)

2.0
tw_safety_factor float

Multiplier for tailwater range above invert (default 2.0 = 100%)

2.0
free_flow_points int

Points on free flow curve (default 100, optimal 100)

100
submerged_curves int

Number of submerged curves (default 60, optimal 60)

60
points_per_curve int

Points per submerged curve (default 50, optimal 50)

50
validate bool

If True, validate parameters before writing (default: True)

True
ras_object RasPrj

RasPrj object for multi-project workflows

None

Returns:

Type Description
dict

Parameters applied with keys: - 'hw_max': Calculated max headwater - 'tw_max': Calculated max tailwater - 'max_flow': Calculated max flow - 'struct_invert': Structure invert elevation - 'max_hw_from_results': Max HW observed in results - 'max_tw_from_results': Max TW observed in results - 'max_flow_from_results': Max flow observed in results - 'free_flow_points', 'submerged_curves', 'points_per_curve': Curve settings - 'hw_source', 'tw_source', 'flow_source': Source locations for data - 'backup_path': Path to backup file

Raises:

Type Description
FileNotFoundError

If geometry or HDF file doesn't exist

ValueError

If structure not found or no results available

IOError

If file write fails

Example

Run simulation first, then optimize HTAB based on results

params = GeomBridge.optimize_htab_from_results( ... "model.g01", "White River", "Muncie", "5600", ... "model.p01.hdf", ... hw_safety_factor=2.0, ... flow_safety_factor=2.0 ... ) print(f"Optimized HWMax: {params['hw_max']:.2f}") print(f"Based on max HW: {params['max_hw_from_results']:.2f}")

Notes
  • Requires a completed simulation with results in HDF file
  • Safety factors are applied to the RANGE above invert, not absolute values
  • For bridges: BR U section provides headwater, BR D provides tailwater
  • If tailwater not found separately, uses headwater value as conservative estimate
  • Creates .bak backup before modification
See Also
  • set_htab(): Direct HTAB parameter setting
  • GeomHtabUtils.calculate_optimal_structure_htab(): Parameter calculation
  • HdfStruc1D.get_structure_max_values(): HDF result extraction

set_abutments staticmethod

Python
set_abutments(geom_file: Union[str, Path], river: str, reach: str, rs: str, abutments: Union[DataFrame, List[Dict[str, Any]], None], create_backup: bool = True) -> Optional[Path]

Create, replace, or remove bridge abutment blocks.

set_all_structures_htab staticmethod

Python
set_all_structures_htab(geom_file: Union[str, Path], hw_max_multiplier: Optional[float] = None, max_flow_multiplier: Optional[float] = None, free_flow_points: int = 100, submerged_curves: int = 60, points_per_curve: int = 50, create_backup: bool = True) -> Dict[str, Any]

Set HTAB parameters for ALL structures (bridges, culverts, inline weirs) in geometry file.

This method processes all hydraulic structures in a single file read/write cycle for efficiency. It can apply multipliers to existing HWMax/MaxFlow values and always sets curve point counts to the specified values for optimal resolution.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
hw_max_multiplier Optional[float]

Optional multiplier for existing HWMax values. If provided, new_hw_max = existing_hw_max * multiplier. If None, HWMax is not modified (existing value kept).

None
max_flow_multiplier Optional[float]

Optional multiplier for existing MaxFlow values. If provided, new_max_flow = existing_max_flow * multiplier. If None, MaxFlow is not modified (existing value kept).

None
free_flow_points int

Number of points on free flow curve (default 100, optimal 100). Applied to all structures.

100
submerged_curves int

Number of submerged rating curves (default 60, optimal 60). Applied to all structures.

60
points_per_curve int

Points per submerged curve (default 50, optimal 50). Applied to all structures.

50
create_backup bool

If True (default), create .bak backup before modification.

True

Returns:

Type Description
dict

Summary of modifications with keys: - 'bridges': Number of bridge/culvert structures modified - 'inline_weirs': Number of inline weirs modified - 'total': Total structures modified - 'structures_detail': List of dicts with per-structure details - 'backup': Path to backup file (or None if create_backup=False)

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

IOError

If file write fails

Notes
  • If multipliers are provided, existing HTAB values are scaled
  • If multipliers are None, only curve point counts are updated
  • Structures without existing HTAB lines get new lines inserted
  • Structures with existing HTAB lines have values replaced
  • Uses single file read/write cycle for efficiency (faster than calling set_htab() for each structure individually)
Example

Double existing HWMax/MaxFlow values and set optimal curve points

result = GeomBridge.set_all_structures_htab( ... "model.g01", ... hw_max_multiplier=2.0, ... max_flow_multiplier=2.0, ... free_flow_points=100, ... submerged_curves=60, ... points_per_curve=50 ... ) print(f"Modified {result['total']} structures") print(f"Bridges: {result['bridges']}, Inline weirs: {result['inline_weirs']}")

Update curve points only (don't change HWMax/MaxFlow)

result = GeomBridge.set_all_structures_htab( ... "model.g01", ... free_flow_points=100, ... submerged_curves=60, ... points_per_curve=50 ... )

See Also
  • set_htab(): Set HTAB for single structure
  • get_bridges(): List all bridges in file
  • GeomInlineWeir.get_weirs(): List all inline weirs in file

set_approach_sections staticmethod

Python
set_approach_sections(geom_file: Union[str, Path], river: str, reach: str, rs: str, approach_df: Optional[DataFrame] = None, upstream_banks: Optional[List[float]] = None, downstream_banks: Optional[List[float]] = None, create_backup: bool = True) -> Optional[Path]

Create, replace, or remove embedded BR U/BR D approach section blocks.

set_coefficients staticmethod

Python
set_coefficients(geom_file: Union[str, Path], river: str, reach: str, rs: str, br_coef: Any = None, wspro: Any = None, bc_design: Any = None, create_backup: bool = True) -> Optional[Path]

Create or replace bridge coefficient lines.

br_coef, wspro, and bc_design accept full lists or sparse {index: value} dictionaries. Sparse updates are merged into the existing line before writing.

set_deck staticmethod

Python
set_deck(geom_file: Union[str, Path], river: str, reach: str, rs: str, deck_df: DataFrame, distance: Optional[float] = None, width: Optional[float] = None, weir_coefficient: Optional[float] = None, skew: Optional[float] = None, min_low_chord: Optional[float] = None, max_high_chord: Optional[float] = None, max_submergence: Optional[float] = None, is_ogee: Optional[int] = None, bridge_flags: Optional[List[Any]] = None, extra_parameters: Optional[List[Any]] = None, create_backup: bool = True) -> Optional[Path]

Create or replace bridge deck/roadway high chord and low chord geometry.

If the bridge marker is missing but the river/reach/station exists, this method creates the Bridge Culvert- block at that station before writing the deck block.

set_htab staticmethod

Python
set_htab(geom_file: Union[str, Path], river: str, reach: str, rs: str, hw_max: Optional[float] = None, tw_max: Optional[float] = None, max_flow: Optional[float] = None, use_user_curves: int = -1, free_flow_points: Optional[int] = None, submerged_curves: Optional[int] = None, points_per_curve: Optional[int] = None, validate: bool = True) -> Dict[str, Any]

Set structure HTAB parameters in geometry file.

Modifies the geometry file in-place, inserting or replacing HTAB parameter lines for a bridge, culvert, or inline weir structure. Creates a .bak backup automatically before modification.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station of structure (as string)

required
hw_max Optional[float]

Maximum headwater elevation

None
tw_max Optional[float]

Maximum tailwater elevation (optional)

None
max_flow Optional[float]

Maximum flow through structure

None
use_user_curves int

-1 to enable custom settings, 0 for defaults

-1
free_flow_points Optional[int]

Number of points on free flow curve (optimal 100)

None
submerged_curves Optional[int]

Number of submerged rating curves (optimal 60)

None
points_per_curve Optional[int]

Points per submerged curve (optimal 50)

None
validate bool

If True, validate parameters before writing (default: True)

True

Returns:

Type Description
dict

Parameters that were written, with keys: - 'hw_max', 'tw_max', 'max_flow': Elevation/flow values (or None) - 'use_user_curves', 'free_flow_points', etc.: Curve settings - 'lines_replaced': Number of existing HTAB lines replaced - 'lines_inserted': Number of new HTAB lines inserted - 'backup_path': Path to backup file

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If structure not found or validation fails

IOError

If file write fails

Notes
  • Only specified (non-None) parameters are written
  • If HTAB lines don't exist, they are inserted after structure geometry
  • If HTAB lines exist, they are replaced entirely
  • Works for bridges, culverts, inline weirs (all use same HTAB format)
  • Automatically creates .bak backup before modification
  • If write fails, attempts to restore from backup
Example

GeomBridge.set_htab( ... "model.g01", "River", "Reach", "5280", ... hw_max=620.0, max_flow=75000.0, ... free_flow_points=100, submerged_curves=60, ... points_per_curve=50 ... )

See Also
  • get_htab(): Read structure HTAB parameters as DataFrame
  • get_htab_dict(): Read structure HTAB parameters as dict
  • GeomHtabUtils.calculate_optimal_structure_htab(): Calculate optimal values
  • GeomHtabUtils.validate_structure_htab_params(): Validate parameters

set_hydraulic_methods staticmethod

Python
set_hydraulic_methods(geom_file: Union[str, Path], river: str, reach: str, rs: str, low_flow_method: Optional[str] = None, high_flow_method: Optional[str] = None, use_energy: Optional[bool] = None, use_momentum: Optional[bool] = None, use_yarnell: Optional[bool] = None, use_wspro: Optional[bool] = None, momentum_cd: Optional[float] = None, yarnell_k: Optional[float] = None, pressure_flow_submerged_inlet_cd: Optional[float] = None, pressure_flow_submerged_inlet_outlet_cd: Optional[float] = None, weir_coefficient: Optional[float] = None, opening_index: int = 0, create_backup: bool = True, validate: bool = True) -> Dict[str, Any]

Set bridge low-flow/high-flow hydraulic method selections.

Accepted low_flow_method values are energy, momentum, yarnell, and wspro. Accepted high_flow_method values are energy and pressure_weir. Momentum and Yarnell selections require an existing or supplied coefficient. Existing comma-field spacing is preserved for updated BR Coef= and deck/weir fields, and a .bak backup is created by default before writing.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string)

required
low_flow_method Optional[str]

Optional low-flow method selection

None
high_flow_method Optional[str]

Optional high-flow method selection

None
use_energy Optional[bool]

Optional compute flag for the energy method

None
use_momentum Optional[bool]

Optional compute flag for the momentum method

None
use_yarnell Optional[bool]

Optional compute flag for the Yarnell method

None
use_wspro Optional[bool]

Optional compute flag for the WSPRO method

None
momentum_cd Optional[float]

Optional momentum drag coefficient

None
yarnell_k Optional[float]

Optional Yarnell pier coefficient

None
pressure_flow_submerged_inlet_cd Optional[float]

Optional pressure-flow Cd

None
pressure_flow_submerged_inlet_outlet_cd Optional[float]

Optional pressure-flow Cd

None
weir_coefficient Optional[float]

Optional bridge deck/weir coefficient from the Deck Dist Width WeirC record

None
opening_index int

Zero-based bridge opening/coefficient record index

0
create_backup bool

Create .bak backup before writing (default True)

True
validate bool

Validate method names and unsupported combinations

True

Returns:

Type Description
Dict[str, Any]

dict with before/after method dictionaries, changed line text, and

Dict[str, Any]

backup path.

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If bridge, method value, or combination is invalid

IOError

If file write fails

Example

GeomBridge.set_hydraulic_methods( ... "model.g01", "Beaver Creek", "Kentwood", "5.4", ... low_flow_method="yarnell", ... high_flow_method="energy", ... yarnell_k=1.05 ... )

set_piers staticmethod

Python
set_piers(geom_file: Union[str, Path], river: str, reach: str, rs: str, piers: Union[DataFrame, List[Dict[str, Any]], None], create_backup: bool = True) -> Optional[Path]

Create, replace, or remove bridge pier blocks.

GeomCulvert source reference

Operations for parsing and authoring HEC-RAS culverts in geometry files.

All methods are static and designed to be used without instantiation.

get_adjacent_cross_sections staticmethod

Python
get_adjacent_cross_sections(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> Dict[str, Optional[Dict[str, Any]]]

Return the nearest upstream and downstream cross sections around a structure.

The helper scans the same river/reach block and returns the immediate Type 1 cross sections before and after the bridge/culvert structure.

get_all staticmethod

Python
get_all(geom_file: Union[str, Path], river: Optional[str] = None, reach: Optional[str] = None) -> pd.DataFrame

List all culverts in geometry file across all bridge/culvert structures.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river Optional[str]

Optional filter by river name (case-sensitive)

None
reach Optional[str]

Optional filter by reach name (case-sensitive)

None

Returns:

Type Description
DataFrame

pd.DataFrame with all culvert data plus River, Reach, RS columns

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

Example

all_culverts = GeomCulvert.get_all("model.g08") print(f"Found {len(all_culverts)} total culverts")

Group by shape

print(all_culverts.groupby('ShapeName').size())

get_culverts staticmethod

Python
get_culverts(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> pd.DataFrame

List all culverts at a bridge/culvert structure.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station (as string)

required

Returns:

Type Description
pd.DataFrame with columns
-CulvertName

Culvert identifier (e.g., "Culvert #1")

-Shape

Shape code (1=Circular, 2=Box, etc.)

-ShapeName

Human-readable shape name

-Span

Width/diameter (feet or meters)

-Rise

Height (feet or meters)

-Length

Culvert length

-ManningsN

Manning's roughness coefficient

-EntranceLoss

Entrance loss coefficient (Ke)

-ExitLoss

Exit loss coefficient

-InletType

Inlet control type code

-OutletType

Outlet control type code

-UpstreamInvert

Upstream invert elevation

-UpstreamStation

Upstream station location

-DownstreamInvert

Downstream invert elevation

-DownstreamStation

Downstream station location

-ChartNumber

Inlet control chart number (legacy alias of the trailing record field; kept as an int for backward compatibility)

-UsDistance

Structure US Distance (float) -- the offset of the culvert's upstream face downstream of the upstream bounding cross section. This is the trailing field of the plain-text record; set_culverts preserves it. Do not treat it as the chart number.

-BottomN

Bottom Manning's n (if different)

-NumBarrels

Number of barrels

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If bridge/culvert structure not found

Example

culverts = GeomCulvert.get_culverts( ... "model.g08", "River", "Reach", "23367" ... ) print(f"Found {len(culverts)} culverts") print(culverts[['CulvertName', 'ShapeName', 'Span', 'Rise', 'Length']])

set_adjacent_ineffective_flow staticmethod

Python
set_adjacent_ineffective_flow(geom_file: Union[str, Path], river: str, reach: str, rs: str, upstream_ineffective: Optional[Union[DataFrame, Sequence[Dict[str, Any]]]] = None, downstream_ineffective: Optional[Union[DataFrame, Sequence[Dict[str, Any]]]] = None, upstream_permanent_flags: Optional[List[bool]] = None, downstream_permanent_flags: Optional[List[bool]] = None, fmt_flag: int = 0) -> Dict[str, Any]

Write ineffective-flow areas at the cross sections adjacent to a culvert.

upstream_ineffective and downstream_ineffective use the GeomCrossSection.set_ineffective_flow columns: left_station, right_station, and elevation.

set_culvert staticmethod

Python
set_culvert(geom_file: Union[str, Path], river: str, reach: str, rs: str, culvert: Optional[Dict[str, Any]] = None, culvert_index: Optional[int] = None, culvert_name: Optional[str] = None, **kwargs) -> Dict[str, Any]

Update one culvert record or append a new one at a bridge/culvert structure.

If culvert_index or culvert_name matches an existing record, that record is replaced. If neither selector is supplied, the record is appended. Keyword arguments are merged into culvert for ergonomic single-record authoring.

set_culverts staticmethod

Python
set_culverts(geom_file: Union[str, Path], river: str, reach: str, rs: str, culverts: Union[DataFrame, Sequence[Dict[str, Any]], Dict[str, Any]]) -> Dict[str, Any]

Replace all culvert records at an existing bridge/culvert structure.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River name (case-sensitive)

required
reach str

Reach name (case-sensitive)

required
rs str

River station for the bridge/culvert structure

required
culverts Union[DataFrame, Sequence[Dict[str, Any]], Dict[str, Any]]

DataFrame, list of dicts, or single dict with culvert fields. Supported shape inputs are numeric Shape codes or ShapeName values from culvert_taxonomy.json. Legacy InletType and OutletType fields map to HEC-RAS Chart # and Scale#; ChartID and ScaleID aliases are also accepted. Multi-barrel culverts require NumBarrels and BarrelStations.

required

Returns:

Type Description
Dict[str, Any]

dict with replacement counts and backup path

Note

The hydraulic culvert data (shape, dimensions, inverts, stations, losses, US Distance, bottom n/depth) round-trips faithfully. The optional per-barrel BC Culvert Barrel=<index>,<name>,<flag> boundary-condition reference lines are NOT preserved on rewrite -- HEC-RAS regenerates them when the geometry is opened/recomputed. If a workflow depends on specific BC barrel names/flags, re-author them.

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist

ValueError

If structure is missing, shape is unsupported, or required fields are missing

IOError

If write fails

GeomCulvertGIS source reference

Reconstruct and validate 1D inline culvert GIS placement (plain text).

mesh_cell_min_from_terrain staticmethod

Python
mesh_cell_min_from_terrain(geom_hdf: Union[str, Path], points_xy: Sequence[Tuple[float, float]], terrain_path: Optional[Union[str, Path]] = None, max_dist_to_cell: Optional[float] = None, all_touched: bool = False) -> pd.DataFrame

Terrain-derived minimum ground elevation of the 2D mesh cell nearest each (x, y) point -- computed directly from the terrain raster, so it does not require the HEC-RAS 2D hydraulic-table preprocessor (it does require a generated mesh in the geometry HDF) and reflects terrain modifications baked into the raster.

Each point is matched to the NEAREST mesh cell (connection/structure cut lines sit on the mesh boundary, so strict point-in-cell containment is not reliable). A point farther than max_dist_to_cell from any cell (i.e. off the mesh) yields cell_terrain_min = None.

Parameters:

Name Type Description Default
geom_hdf Union[str, Path]

2D geometry HDF (*.g##.hdf) with a generated mesh.

required
points_xy Sequence[Tuple[float, float]]

iterable of (x, y) in the mesh CRS.

required
terrain_path Optional[Union[str, Path]]

optional explicit terrain raster (.vrt/.tif); auto-resolved from the geometry HDF when omitted.

None
max_dist_to_cell Optional[float]

max distance (mesh units) a point may sit from its nearest cell before it is treated as off-mesh (None = no limit).

None
all_touched bool

rasterize policy. Default False (pixel-center): for a minimum statistic, including edge-touched pixels pulls in neighbour-cell lows and understates the cell minimum. Set True only as a diagnostic.

False

Returns:

Type Description
pd.DataFrame with columns

point, x, y, cell_id, dist_to_cell,

DataFrame

cell_terrain_min, on_mesh.

reconstruct_barrels staticmethod

Python
reconstruct_barrels(geom_file: Union[str, Path], river: str, reach: str, rs: str, ras_object=None) -> pd.DataFrame

Reconstruct the planimetric (GIS) centerline of every culvert barrel at a structure from the plain-text geometry.

Each barrel runs from the structure's upstream face to its downstream face. Face positions are located US Distance and US Distance + Length downstream of the upstream bounding cross section, interpolated between the bounding XS cut lines using per-zone (LOB/Channel/ROB) reach lengths; barrel endpoints are placed at the barrel's US/DS stations.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
river str

River identifier.

required
reach str

Reach identifier.

required
rs str

River-station identifier.

required
ras_object RasPrj

optional RasPrj for multi-project workflows

None

Returns:

Type Description
pd.DataFrame with one row per barrel
  • CulvertName, Barrel (1-based index within the group)
  • us_x, us_y, ds_x, ds_y (endpoint coordinates)
  • planimetric_length, length_3d, entered_length
  • length_error_pct (|planimetric - entered| / entered * 100)

validate_2d_inverts staticmethod

Python
validate_2d_inverts(geom_hdf: Union[str, Path], points_xy: Sequence[Tuple[float, float]], inverts: Sequence[float], terrain_path: Optional[Union[str, Path]] = None, invert_tol: Optional[float] = None, max_dist_to_cell: Optional[float] = None) -> pd.DataFrame

Validate proposed culvert/structure inverts at 2D locations: each invert must not sit below the terrain minimum of its associated mesh cell (within invert_tol). Terrain-based; needs a generated mesh but not the 2D hydraulic-table preprocessor.

Parameters:

Name Type Description Default
geom_hdf Union[str, Path]

2D geometry HDF with a generated mesh.

required
points_xy Sequence[Tuple[float, float]]

(x, y) locations of the culvert/structure ends in mesh CRS.

required
inverts Sequence[float]

proposed invert elevation at each point (same length/order).

required
terrain_path Optional[Union[str, Path]]

optional explicit terrain raster.

None
invert_tol Optional[float]

ft below the cell minimum tolerated (default INVERT_TOLERANCE).

None
max_dist_to_cell Optional[float]

points farther than this from any cell are reported OFF_MESH rather than validated against a distant cell.

None

Returns:

Type Description
DataFrame

point, x, y, cell_id, dist_to_cell, cell_terrain_min,

DataFrame

invert, status (PASS/FAIL/OFF_MESH/N/A), detail.

validate_placement staticmethod

Python
validate_placement(geom_file: Union[str, Path], river: str, reach: str, rs: str, length_tol_pct: float = 1.0, invert_tol: Optional[float] = None, ras_object=None) -> pd.DataFrame

Run hydraulic-validity checks on every culvert at a structure.

Checks per culvert group
  • length : reconstructed GIS length vs entered Length, reported as an informational REVIEW flag beyond length_tol_pct (reconstruction is approximate; see module docstring).
  • us_invert : US invert >= local bed under the opening on the upstream bounding XS (within +/- invert_tol). The global XS minimum is reported in detail for reference.
  • ds_invert : DS invert >= local bed under the opening on the downstream bounding XS.
  • entrance_loss : entered Ke within tolerance of the HDS-5 value for the selected inlet (advisory).
  • exit_loss : exit loss near the typical 1.0 (advisory).

Returns:

Type Description
pd.DataFrame with columns

CulvertName, check, status (PASS/FAIL/WARN),

DataFrame

value, reference, detail.

GeomHtabUtils source reference

Utility functions for HTAB parameter calculations.

All methods are static and designed to be used without instantiation.

These functions calculate optimal HTAB parameters based on observed maximum water surface elevations and flows, applying appropriate safety factors to prevent extrapolation during simulation.

calculate_optimal_structure_htab staticmethod

Python
calculate_optimal_structure_htab(struct_invert: float, max_hw: float, max_tw: float, max_flow: float, hw_safety: float = 2.0, flow_safety: float = 2.0, tw_safety: float = 2.0, free_flow_points: int = 100, submerged_curves: int = 60, points_per_curve: int = 50) -> Dict[str, Union[float, int]]

Calculate optimal structure HTAB parameters.

This function computes optimal HTAB parameters for hydraulic structures (bridges, culverts, inline weirs) based on observed maximum headwater, tailwater, and flow values with appropriate safety factors.

The safety factors are applied to the RANGE above the structure invert, not to the absolute values. This provides a more reasonable result than simply multiplying the headwater elevation by 2.0.

Algorithm
  1. Calculate HW range above invert: hw_range = max_hw - struct_invert
  2. Apply safety factor to range: safe_hw_range = hw_range * hw_safety
  3. Calculate HW max: hw_max = struct_invert + safe_hw_range
  4. Repeat for tailwater
  5. For flow, apply safety factor directly: flow_max = max_flow * flow_safety
  6. Set maximum curve point counts for best resolution

Parameters:

Name Type Description Default
struct_invert float

Structure invert elevation (lowest opening elevation)

required
max_hw float

Maximum headwater elevation from simulation results

required
max_tw float

Maximum tailwater elevation from simulation results

required
max_flow float

Maximum flow through structure from simulation results

required
hw_safety float

Safety factor on headwater range (default 2.0 = 100%)

2.0
flow_safety float

Safety factor on flow (default 2.0 = 100%)

2.0
tw_safety float

Safety factor on tailwater range (default 2.0 = 100%)

2.0
free_flow_points int

Points on free flow rating curve (default 100, optimal 100)

100
submerged_curves int

Number of submerged flow curves (default 60, optimal 60)

60
points_per_curve int

Points per submerged curve (default 50, optimal 50)

50

Returns:

Type Description
dict

Optimal structure HTAB parameters with keys: - 'hw_max' (float): Maximum headwater elevation - 'tw_max' (float): Maximum tailwater elevation - 'max_flow' (float): Maximum flow - 'use_user_curves' (int): Flag to use user-specified curves (-1) - 'free_flow_points' (int): Points on free flow curve - 'submerged_curves' (int): Number of submerged curves - 'points_per_curve' (int): Points per submerged curve - 'hw_range_applied' (float): Headwater range with safety applied - 'tw_range_applied' (float): Tailwater range with safety applied

Raises:

Type Description
ValueError

If max_hw < struct_invert

ValueError

If safety factors < 1.0

ValueError

If curve point counts out of range

Examples:

Python Console Session
>>> # Standard structure optimization
>>> params = GeomHtabUtils.calculate_optimal_structure_htab(
...     struct_invert=590.0, max_hw=605.0, max_tw=600.0, max_flow=25000.0
... )
>>> print(f"HW Max: {params['hw_max']}")  # 590 + (605-590)*2 = 620
HW Max: 620.0
>>> print(f"Max Flow: {params['max_flow']}")  # 25000 * 2 = 50000
Max Flow: 50000.0
Python Console Session
>>> # Dam break scenario with extreme flows
>>> params = GeomHtabUtils.calculate_optimal_structure_htab(
...     struct_invert=500.0, max_hw=550.0, max_tw=530.0, max_flow=100000.0,
...     hw_safety=3.0, flow_safety=3.0  # Higher safety for extreme events
... )
Notes
  • Safety is applied to RANGE above invert (e.g., if HW=605, invert=590, range=15, with 2.0 safety: 590 + 15*2 = 620) rather than multiplying the absolute elevation (605 * 2 = 1210, which is unreasonable)
  • Flow safety is applied directly as a multiplier since flow has no inherent reference elevation
  • Setting curve points to maximum values provides best interpolation resolution for rating curves
See Also
  • validate_structure_htab_params(): Validate parameters before use
  • feature_dev_notes/HTAB_Parameter_Modification/optimal_values_algorithm.md

calculate_optimal_xs_htab staticmethod

Python
calculate_optimal_xs_htab(invert: float, max_wse: float, safety_factor: float = 1.3, target_increment: float = 0.1, max_points: int = 500) -> Dict[str, Union[float, int]]

Calculate optimal cross section HTAB parameters from invert and max WSE.

This function computes the optimal starting elevation, increment, and number of points for a cross section's hydraulic table based on the observed maximum water surface elevation and a safety factor.

Algorithm
  1. Calculate max depth: max_wse - invert
  2. Apply safety factor: target_depth = max_depth * safety_factor
  3. Calculate target max elevation: invert + target_depth
  4. Set starting_el = invert (copy invert, don't use default offset)
  5. Check if target increment fits within max_points
  6. If not, increase increment to fit range in max_points
  7. Round increment to clean value (2 decimal places)

Parameters:

Name Type Description Default
invert float

Cross section invert elevation (minimum elevation in XS)

required
max_wse float

Maximum water surface elevation from simulation results

required
safety_factor float

Multiplier on max depth to provide buffer (default 1.3 = 30%) Recommended: 1.2-1.5 for typical floods, 2.0 for dam break

1.3
target_increment float

Desired elevation increment in feet (default 0.1) Smaller increments give more accurate interpolation

0.1
max_points int

Maximum number of points (HEC-RAS limit is 500)

500

Returns:

Type Description
dict

Optimal HTAB parameters with keys: - 'starting_el' (float): Starting elevation (equals invert) - 'increment' (float): Elevation increment - 'num_points' (int): Number of points - 'actual_max_el' (float): Actual maximum elevation covered - 'target_max_el' (float): Target maximum elevation with safety - 'target_depth' (float): Target depth with safety factor applied - 'coverage_adequate' (bool): True if actual_max >= target_max

Raises:

Type Description
ValueError

If invert >= max_wse (invalid inputs)

ValueError

If safety_factor < 1.0

ValueError

If max_points < MIN_XS_POINTS or > MAX_XS_POINTS

Examples:

Python Console Session
>>> # Standard flood scenario
>>> params = GeomHtabUtils.calculate_optimal_xs_htab(
...     invert=580.0, max_wse=605.0, safety_factor=1.3
... )
>>> print(params)
{'starting_el': 580.0, 'increment': 0.1, 'num_points': 500,
 'actual_max_el': 629.9, 'target_max_el': 612.5, 'target_depth': 32.5,
 'coverage_adequate': True}
Python Console Session
>>> # Very deep cross section (needs larger increment)
>>> params = GeomHtabUtils.calculate_optimal_xs_htab(
...     invert=400.0, max_wse=500.0, safety_factor=1.3
... )
>>> print(f"Increment adjusted to: {params['increment']}")
Increment adjusted to: 0.27
Python Console Session
>>> # Dam break scenario with higher safety factor
>>> params = GeomHtabUtils.calculate_optimal_xs_htab(
...     invert=580.0, max_wse=620.0, safety_factor=2.0
... )
Notes
  • Starting elevation is always set to invert (HEC-RAS default +0.5-1ft often misses low flow calculations)
  • For very deep cross sections (>49.9 ft with 0.1 increment), the increment is automatically increased to fit within 500 points
  • The increment is rounded to 2 decimal places for clean values
See Also
  • validate_xs_htab_params(): Validate parameters before use
  • feature_dev_notes/HTAB_Parameter_Modification/optimal_values_algorithm.md

get_structure_htab_defaults staticmethod

Python
get_structure_htab_defaults() -> Dict[str, Union[float, int]]

Get default structure HTAB parameter recommendations.

Returns:

Type Description
dict

Recommended default values with keys: - 'hw_safety': Default headwater safety factor (2.0) - 'tw_safety': Default tailwater safety factor (2.0) - 'flow_safety': Default flow safety factor (2.0) - 'free_flow_points': Default free flow points (100) - 'submerged_curves': Default submerged curves (60) - 'points_per_curve': Default points per curve (50)

get_xs_htab_defaults staticmethod

Python
get_xs_htab_defaults() -> Dict[str, Union[float, int]]

Get default XS HTAB parameter recommendations.

Returns:

Type Description
dict

Recommended default values with keys: - 'increment': Default elevation increment (0.1 ft) - 'num_points': Default number of points (500) - 'safety_factor': Default safety factor (1.3) - 'min_points': Minimum points (20) - 'max_points': Maximum points (500)

validate_structure_htab_params staticmethod

Python
validate_structure_htab_params(params: Dict[str, Union[float, int]], struct_invert: float, max_expected_hw: float, max_expected_flow: float) -> Tuple[List[str], List[str]]

Validate structure HTAB parameters.

This function validates structure (bridge, culvert, inline weir) HTAB parameters against expected values and best practices.

Parameters:

Name Type Description Default
params Dict[str, Union[float, int]]

HTAB parameters dict with keys: - 'hw_max': Maximum headwater elevation - 'max_flow': Maximum flow - 'free_flow_points': Optional - points on free flow curve - 'submerged_curves': Optional - number of submerged curves - 'points_per_curve': Optional - points per submerged curve

required
struct_invert float

Structure invert (lowest opening) elevation

required
max_expected_hw float

Maximum expected headwater from results

required
max_expected_flow float

Maximum expected flow from results

required

Returns:

Type Description
tuple

(errors, warnings) where: - errors (List[str]): Critical issues that will cause problems - warnings (List[str]): Non-critical issues to review

Examples:

Python Console Session
>>> params = {'hw_max': 620.0, 'max_flow': 50000.0, 'free_flow_points': 20}
>>> errors, warnings = GeomHtabUtils.validate_structure_htab_params(
...     params, struct_invert=590.0, max_expected_hw=605.0,
...     max_expected_flow=25000.0
... )
>>> print(f"Valid: {len(errors) == 0}")
Valid: True
Validation Checks

ERRORS (will cause HEC-RAS problems): - hw_max < max_expected_hw (will extrapolate) - max_flow < max_expected_flow (will extrapolate) - hw_max < struct_invert (physically impossible)

WARNINGS (may cause issues): - free_flow_points < 10 (coarse rating curve) - submerged_curves < 10 (coarse submerged flow) - hw_max only slightly above max_expected (low safety margin)

validate_xs_htab_params staticmethod

Python
validate_xs_htab_params(params: Dict[str, Union[float, int]], xs_invert: float, xs_top: float) -> Tuple[List[str], List[str]]

Validate XS HTAB parameters.

This function validates cross section HTAB parameters against HEC-RAS limits and best practices, returning lists of errors and warnings.

Parameters:

Name Type Description Default
params Dict[str, Union[float, int]]

HTAB parameters dict with keys: - 'starting_el': Starting elevation - 'increment': Elevation increment - 'num_points': Number of points

required
xs_invert float

Cross section invert (minimum) elevation

required
xs_top float

Cross section top (maximum) elevation

required

Returns:

Type Description
tuple

(errors, warnings) where: - errors (List[str]): Critical issues that will cause problems - warnings (List[str]): Non-critical issues to review

Examples:

Python Console Session
>>> params = {'starting_el': 580.0, 'increment': 0.1, 'num_points': 500}
>>> errors, warnings = GeomHtabUtils.validate_xs_htab_params(
...     params, xs_invert=580.0, xs_top=595.0
... )
>>> if errors:
...     print(f"ERRORS: {errors}")
>>> if warnings:
...     print(f"WARNINGS: {warnings}")
Validation Checks

ERRORS (will cause HEC-RAS problems): - num_points < 20 or > 500 (HEC-RAS limits) - increment <= 0 - starting_el significantly above invert (>1 ft)

WARNINGS (may cause issues): - starting_el > invert + 0.5 (missing low flow range) - increment > 1.0 (coarse resolution) - actual_max < xs_top (doesn't cover full XS)

Notes
  • An empty errors list indicates parameters are valid for HEC-RAS
  • Warnings should be reviewed but don't prevent use

GeomHtab source reference

Unified HTAB parameter management for HEC-RAS geometry files.

This class provides a single entry point for optimizing all HTAB parameters (cross sections and structures) in a geometry file based on existing HDF results.

All methods are static and designed to be used without instantiation.

Key Features
  • One-call optimization of ALL HTAB parameters
  • Automatic safety factor application
  • Single backup creation for all modifications
  • Comprehensive summary of changes made
Example

from ras_commander.geom import GeomHtab

Optimize all HTAB from results

result = GeomHtab.optimize_all_htab_from_results( ... "model.g01", "model.p01.hdf" ... ) print(f"Backup: {result['backup']}") print(f"XS modified: {result['xs_modified']}") print(f"Structures modified: {result['structures_modified']}")

get_optimization_report staticmethod

Python
get_optimization_report(geom_file: Union[str, Path], hdf_results_path: Union[str, Path], xs_safety_factor: float = 1.3, structure_hw_safety: float = 2.0) -> str

Generate markdown report showing current vs recommended HTAB parameters.

This method analyzes the geometry file and HDF results to produce a report showing what HTAB optimizations would be made, without actually modifying the file.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
hdf_results_path Union[str, Path]

Path to plan HDF file with results

required
xs_safety_factor float

Safety factor for XS depth analysis

1.3
structure_hw_safety float

Safety factor for structure HW analysis

2.0

Returns:

Type Description
str

Markdown-formatted report

Example

report = GeomHtab.get_optimization_report( ... "model.g01", "model.p01.hdf" ... ) print(report)

Or write to file:

Path("htab_report.md").write_text(report)

optimize_all_htab_from_results staticmethod

Python
optimize_all_htab_from_results(geom_file: Union[str, Path], hdf_results_path: Union[str, Path], xs_safety_factor: float = 1.3, structure_hw_safety: float = 2.0, structure_flow_safety: float = 2.0, xs_target_increment: float = 0.1, xs_max_points: int = 500, structure_free_flow_points: int = 100, structure_submerged_curves: int = 60, structure_points_per_curve: int = 50, create_backup: bool = True) -> Dict[str, Any]

One-call optimization of ALL HTAB parameters in geometry file.

This method optimizes HTAB parameters for both cross sections and hydraulic structures (bridges, culverts, inline weirs) based on observed maximum water surface elevations and flows from HDF results.

The optimization process
  1. Creates a single backup of the geometry file
  2. Extracts maximum WSE values for all cross sections from HDF
  3. Calculates and applies optimal XS HTAB parameters
  4. Extracts maximum HW/flow values for structures from HDF
  5. Calculates and applies optimal structure HTAB parameters
  6. Returns comprehensive summary of all changes

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
hdf_results_path Union[str, Path]

Path to plan HDF file with results (.p##.hdf)

required
xs_safety_factor float

Safety factor for XS max depth (default 1.3 = 30%) Higher values provide more buffer against extrapolation. Recommended: 1.2-1.5 for typical floods, 2.0 for dam break.

1.3
structure_hw_safety float

Safety factor for structure headwater (default 2.0 = 100%)

2.0
structure_flow_safety float

Safety factor for structure flow (default 2.0 = 100%)

2.0
xs_target_increment float

Target elevation increment for XS HTAB (default 0.1 ft)

0.1
xs_max_points int

Maximum points in XS HTAB (HEC-RAS limit is 500)

500
structure_free_flow_points int

Points on free flow rating curve (optimal 100)

100
structure_submerged_curves int

Number of submerged rating curves (optimal 60)

60
structure_points_per_curve int

Points per submerged curve (optimal 50)

50
create_backup bool

Whether to create .bak backup file (default True)

True

Returns:

Type Description
dict

Summary of optimization with keys: - 'xs_modified' (int): Number of cross sections modified - 'structures_modified' (int): Number of structures modified - 'backup' (Path or None): Path to backup file - 'xs_summary' (dict): Cross section optimization summary - 'structure_summary' (dict): Structure optimization summary - 'total_changes' (int): Total HTAB modifications made - 'success' (bool): Whether optimization completed without errors - 'errors' (list): List of any errors encountered - 'warnings' (list): List of any warnings generated

Raises:

Type Description
FileNotFoundError

If geometry file or HDF file doesn't exist

ValueError

If HDF file doesn't contain required results data

IOError

If file write fails

Example

Standard optimization with defaults

result = GeomHtab.optimize_all_htab_from_results( ... "model.g01", "model.p01.hdf" ... ) print(f"Optimized {result['xs_modified']} XS, " ... f"{result['structures_modified']} structures")

Dam break scenario with higher safety factors

result = GeomHtab.optimize_all_htab_from_results( ... "model.g01", "model.p01.hdf", ... xs_safety_factor=2.0, ... structure_hw_safety=3.0, ... structure_flow_safety=3.0 ... )

Notes
  • A single backup is created before any modifications
  • If structures optimization fails, XS changes are retained
  • Re-run geometric preprocessor (clear_geompre=True) after optimization
  • Verify HEC-RAS can open modified file before discarding backup
See Also
  • optimize_xs_htab_from_results(): XS-only optimization
  • optimize_structures_htab_from_results(): Structures-only optimization
  • GeomHtabUtils: Utility functions for HTAB calculations

optimize_structures_htab_from_results staticmethod

Python
optimize_structures_htab_from_results(geom_file: Union[str, Path], hdf_results_path: Union[str, Path], hw_safety_factor: float = 2.0, flow_safety_factor: float = 2.0, tw_safety_factor: float = 2.0, free_flow_points: int = 100, submerged_curves: int = 60, points_per_curve: int = 50, create_backup: bool = True) -> Dict[str, Any]

Optimize HTAB parameters for ALL structures from HDF results.

Delegates to GeomBridge.optimize_all_structures_from_results() which uses HdfStruc1D for robust HDF extraction and processes all structure types.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
hdf_results_path Union[str, Path]

Path to plan HDF file with results

required
hw_safety_factor float

Safety factor for headwater (default 2.0 = 100%)

2.0
flow_safety_factor float

Safety factor for flow (default 2.0 = 100%)

2.0
tw_safety_factor float

Safety factor for tailwater (default 2.0 = 100%)

2.0
free_flow_points int

Points on free flow curve (default 100, optimal 100)

100
submerged_curves int

Number of submerged curves (default 60, optimal 60)

60
points_per_curve int

Points per submerged curve (default 50, optimal 50)

50
create_backup bool

Whether to create .bak backup (default True)

True

Returns:

Type Description
dict

Summary with keys: - 'modified' (int): Number of structures modified - 'skipped' (int): Number of structures skipped (no results) - 'errors' (list): List of structures that failed - 'structures_processed' (list): List of structure identifiers - 'backup' (Path or None): Path to backup file

Notes
  • Processes bridges, culverts, and inline weirs
  • Structures without results data are skipped with warning
  • Safety is applied to range above invert, not absolute elevation
See Also
  • GeomBridge.optimize_all_structures_from_results(): Full implementation

optimize_xs_htab_from_results staticmethod

Python
optimize_xs_htab_from_results(geom_file: Union[str, Path], hdf_results_path: Union[str, Path], safety_factor: float = 1.3, target_increment: float = 0.1, max_points: int = 500, create_backup: bool = True) -> Dict[str, Any]

Optimize HTAB parameters for ALL cross sections from HDF results.

Delegates to GeomCrossSection.optimize_xs_htab_from_results() which uses batch I/O (single read/write cycle) for optimal performance.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
hdf_results_path Union[str, Path]

Path to plan HDF file with results

required
safety_factor float

Multiplier for max depth (default 1.3 = 30% safety)

1.3
target_increment float

Desired elevation increment (default 0.1 ft)

0.1
max_points int

Maximum number of points (default 500, HEC-RAS max)

500
create_backup bool

Whether to create .bak backup (default True)

True

Returns:

Type Description
dict

Summary with keys: - 'modified' (int): Number of XS modified - 'skipped' (int): Number of XS skipped (no results) - 'errors' (list): List of XS that failed - 'params_summary' (dict): Statistics of parameters applied - 'backup' (Path or None): Path to backup file

Notes
  • For 1D cross sections, extracts max WSE from HDF 1D results
  • For 2D-connected XS, attempts to use mesh max WSE
  • XS without results data are skipped with warning
See Also
  • GeomCrossSection.optimize_xs_htab_from_results(): Batch implementation

GeomMetadata source reference

Extract geometry metadata counts efficiently from HDF or plain text files.

All methods are static and designed to be used without instantiation.

get_geometry_counts staticmethod

Python
get_geometry_counts(geom_path: Union[str, Path], hdf_path: Optional[Union[str, Path]] = None) -> Dict[str, Any]

Extract all geometry element counts from geometry file.

Prefers HDF-based extraction (fast) when hdf_path is provided and exists. Falls back to plain text parsing when HDF is not available.

Parameters:

Name Type Description Default
geom_path Union[str, Path]

Path to plain text geometry file (.g##)

required
hdf_path Optional[Union[str, Path]]

Optional path to geometry HDF file (.g##.hdf)

None

Returns:

Type Description
dict with keys
  • has_1d_xs (bool): True if num_cross_sections > 0
  • has_2d_mesh (bool): True when text declares a 2D flow area or HDF metadata identifies a mesh area
  • num_cross_sections (int): Count of 1D cross sections
  • num_inline_structures (int): Total bridges + culverts + weirs
  • num_bridges (int): Bridge count
  • num_culverts (int): Culvert count
  • num_weirs (int): Inline weir count
  • num_gates (int): Gate count
  • num_lateral_structures (int): Lateral structure count
  • num_sa_2d_connections (int): SA to 2D connections count
  • mesh_cell_count (int | None): Total HDF mesh cells; None when only text geometry is available
  • mesh_area_names (list[str]): Names of 2D flow areas
  • geometry_metadata_source (str): hdf, text, or unavailable
  • geometry_metadata_valid (bool): Whether a geometry source was successfully inspected
  • geometry_metadata_error (str | None): Failed source reads encountered before success, or the terminal failure
Note

Always returns a complete dict and never raises, except that required-native mode (RAS_COMMANDER_FAST_HDF=native) propagates a native :class:~ras_commander.fast_hdf.FastHdfError. The two has_* values remain None when no source can be inspected, so dispatch cannot mistake unreadable geometry for valid 1D.

Example

counts = GeomMetadata.get_geometry_counts("model.g01", "model.g01.hdf") if counts['has_2d_mesh']: ... print(f"2D areas: {counts['mesh_area_names']}")

GeomReferenceFeatures source reference

Insert reference lines and reference points into .g## geometry files.

add_reference_lines staticmethod

Python
add_reference_lines(geom_file: Union[str, Path], lines: List[dict], storage_area: str) -> int

Insert reference lines into a plain text geometry file.

Reference lines are inserted after BC Lines and before IC Points or LCMann sections. They persist through HEC-RAS recomputation because HEC-RAS reads them from the plain text file during geometry preprocessing.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##)

required
lines List[dict]

List of dicts with: - 'name': str -- unique reference line name - 'coordinates': list of (x,y) tuples or array (N,2)

required
storage_area str

Name of the 2D flow area (e.g., 'BaldEagleCr')

required

Returns:

Type Description
int

Number of reference lines inserted

Example

GeomReferenceFeatures.add_reference_lines( ... "model.g01", ... lines=[ ... {"name": "Gauge_01", "coordinates": [(1000, 2000), (1100, 2000)]}, ... ], ... storage_area="MyMesh", ... )

add_reference_lines_from_longitudinal_line staticmethod

Python
add_reference_lines_from_longitudinal_line(geom_file: Union[str, Path], longitudinal_lines: Any, storage_area: str, spacing: float, line_length: float, **kwargs: Any) -> int

Generate and insert transverse reference lines into a geometry file.

This is a convenience wrapper around :meth:generate_reference_lines_from_longitudinal_line and :meth:add_reference_lines. Use the generator directly when manual review of the proposed coordinates is needed before writing.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to geometry file (.g##).

required
longitudinal_lines Any

Source line input accepted by generate_reference_lines_from_longitudinal_line.

required
storage_area str

Name of the 2D flow area receiving the reference lines.

required
spacing float

Station interval along each source line.

required
line_length float

Generated transverse reference-line length.

required
**kwargs Any

Additional generator options such as longitudinal_line_name, orientation_plan_hdf, and name_template.

{}

Returns:

Type Description
int

Number of reference lines inserted.

add_reference_points staticmethod

Python
add_reference_points(geom_file: Union[str, Path], points: List[dict]) -> int

Append native Reference Point Name/Position records to geometry.

points contains unique name (at most 40 UTF-8 bytes), finite x and y in project coordinates. Names are preserved without a prefix. Native records are placed before LCMann, after existing reference features. An existing .bak is preserved; validation completes before writing. Returns the number inserted. Duplicate names, invalid fields or coordinates raise ValueError.

Before this fix the method wrote IC Point records. Existing IC Points are preserved and are not converted or returned as native reference points. To migrate, explicitly supply desired names/coordinates to this method. Mesh membership and solver-recorded output require preprocessing and a new computation; a text round trip alone does not establish output validity.

generate_reference_lines_from_longitudinal_line staticmethod

Python
generate_reference_lines_from_longitudinal_line(longitudinal_lines: Any, spacing: float, line_length: float, *, longitudinal_line_name: Optional[str] = None, name_column: str = 'Name', name_template: str = '{source_name}_Ref_{index:03d}', start_station: float = 0.0, end_station: Optional[float] = None, include_end: bool = False, tangent_sample_distance: Optional[float] = None, extend_by: float = 0.0, orientation: str = 'normal', orientation_plan_hdf: Optional[Union[str, Path]] = None, orientation_time_index: Union[int, str] = -1, orientation_query_method: str = 'nearest', orientation_angle_callback: Optional[Callable[[dict], Optional[float]]] = None, orientation_fallback: str = 'normal', velocity_min: float = 1e-06, depth_min: float = 0.0, ras_object: Optional[Any] = None, storage_area: Optional[str] = None) -> List[dict]

Generate transverse reference lines along longitudinal/profile lines.

This creates the same {"name", "coordinates"} dictionaries accepted by :meth:add_reference_lines, so callers can review the generated transects before writing them to a HEC-RAS plain text geometry file.

Parameters:

Name Type Description Default
longitudinal_lines Any

A Shapely LineString, GeoDataFrame, coordinate array, dict with geometry/coordinates, or list of those dicts. GeoDataFrame rows can be selected by name.

required
spacing float

Station interval along each longitudinal line, in model units.

required
line_length float

Generated transverse reference-line length, in model units.

required
longitudinal_line_name Optional[str]

Optional name of the source line to select from GeoDataFrame/list inputs.

None
name_column str

Preferred source-name column for GeoDataFrame inputs.

'Name'
name_template str

Format string for generated line names. Available fields are source_name, index, global_index, station, and station_int.

'{source_name}_Ref_{index:03d}'
start_station float

First station along the source line.

0.0
end_station Optional[float]

Last station along the source line. Defaults to the source line length.

None
include_end bool

Include end_station even when it is not on the regular spacing interval.

False
tangent_sample_distance Optional[float]

Half-window used to compute the local tangent direction. Defaults to half the spacing.

None
extend_by float

Extra length added to each side of the generated line.

0.0
orientation str

"normal" for perpendicular to source line, "velocity" for perpendicular to sampled velocity vector, or "depth_velocity" for velocity orientation only where sampled depth exceeds depth_min.

'normal'
orientation_plan_hdf Optional[Union[str, Path]]

Plan/result HDF used when orientation is "velocity" or "depth_velocity".

None
orientation_time_index Union[int, str]

Time index passed to HdfResultsQuery.

-1
orientation_query_method str

Query method passed to HdfResultsQuery.

'nearest'
orientation_angle_callback Optional[Callable[[dict], Optional[float]]]

Optional callable receiving a context dict and returning a reference-line angle in degrees. Returning None keeps the normal or velocity-derived angle.

None
orientation_fallback str

"normal" or "raise" when sampled velocity/depth data are unavailable at a station.

'normal'
velocity_min float

Minimum sampled velocity magnitude for velocity-based orientation.

1e-06
depth_min float

Minimum sampled depth for "depth_velocity".

0.0
ras_object Optional[Any]

Optional RasPrj object for HDF result queries.

None
storage_area Optional[str]

Optional 2D flow area name included in returned metadata for review.

None

Returns:

Type Description
List[dict]

List of reference-line dictionaries. Each dictionary includes

List[dict]

name and coordinates for writing, plus station/orientation

List[dict]

metadata for review.

Example

ref_lines = GeomReferenceFeatures.generate_reference_lines_from_longitudinal_line( ... centerlines_gdf, ... longitudinal_line_name="Main River", ... spacing=500, ... line_length=1500, ... ) GeomReferenceFeatures.add_reference_lines("model.g01", ref_lines, "Perimeter 1")

get_reference_lines staticmethod

Python
get_reference_lines(geom_file: Union[str, Path]) -> List[dict]

Read named area-associated lines; reject malformed coordinate blocks.

get_reference_points staticmethod

Python
get_reference_points(geom_file: Union[str, Path]) -> List[dict]

Read native Reference Point records as name/x/y dictionaries.

IC Point records are separate initial-condition features and are ignored, even when their names start with 'Reference Point'. No inferred conversion occurs. Malformed native records or duplicate names raise ValueError.

replace_reference_lines staticmethod

Python
replace_reference_lines(geom_file: Union[str, Path], storage_area: str, reference_lines: Sequence[Mapping[str, Any]], *, expected_existing_names: Optional[Sequence[str]] = None, create_backup: bool = True) -> Optional[Path]

Atomically replace one 2D area's complete reference-line collection.

This is the safe mutation for reduced 2D domains: callers can remove parent reference lines that no longer intersect the retained mesh and optionally clip the survivors before replacing them. Reference lines belonging to other 2D areas are preserved byte-for-byte.

Names may contain commas, parentheses and spaces. Unchanged named lines retain their original records, including padding, positions and coordinate precision. Changed collections are written with CRLF. An unchanged ordered collection is not rewritten, preserving all bytes and its placement in the file.

expected_existing_names is an optional ordered optimistic- concurrency guard. An empty reference_lines sequence removes all reference lines associated with storage_area. Returns the backup path when create_backup is true, otherwise None.

GeomBcLines source reference

Read and author BC line geometry in .g## text files; do not instantiate.

add_bc_lines staticmethod

Python
add_bc_lines(geom_file: Union[str, Path], lines: List[Dict[str, Any]], replace_existing: bool = False) -> Dict[str, Any]

Insert one or more 2D BC line blocks into a geometry text file.

Parameters

geom_file : str or Path Path to the HEC-RAS plain text geometry file (.g##). lines : list of dict Each dict describes one BC line and must contain:

Text Only
- ``name`` (str): the BC line name. Used by the
  `BC Line Name=` keyword and by `RasUnsteady` boundary
  setters to attach BC types. Must be unique within the
  file unless ``replace_existing=True``.
- ``storage_area`` (str): the 2D Flow Area name this BC
  line attaches to. Must match an existing
  `Storage Area=<name>` block in the file.
- ``coordinates`` (sequence of (x, y) or ``(N, 2)`` array):
  endpoint and intermediate vertices of the BC line in the
  project's native CRS. At least two points required.
bool, default False

When False (the default), inserting a BC line whose name already exists in the file raises ValueError. When True, the existing block is removed before the new one is inserted (upsert semantics).

Returns

Dict[str, Any] Reviewable metadata with keys:

Text Only
- ``geom_file`` (str): absolute path written
- ``inserted`` (List[str]): names that were newly added
- ``replaced`` (List[str]): names whose blocks were
  overwritten (only populated when ``replace_existing=True``)
- ``insert_index`` (int): line index (0-based) where the new
  blocks were placed
- ``backup_path`` (str): absolute path of the `.bak` backup
Raises

FileNotFoundError If geom_file does not exist. ValueError If lines is empty; if a line dict is missing required keys; if coordinates is malformed; if a referenced storage_area does not exist as a Storage Area= block in the file; or if a name already exists in the file and replace_existing is False.

Examples

Add a downstream Normal Depth BC line to the Perimeter 1 2D Flow Area in a Chippewa-style geometry, then attach Normal Depth in the unsteady file via set_normal_depth_boundary:

Python
>>> from ras_commander import GeomBcLines, RasUnsteady
>>> result = GeomBcLines.add_bc_lines(
...     "project.g01",
...     lines=[{
...         "name": "DSNormalDepth",
...         "storage_area": "Perimeter 1",
...         "coordinates": [(1027205.96, 7858200.24),
...                          (1025994.94, 7858316.68)],
...     }],
... )
>>> result["inserted"]
['DSNormalDepth']
>>> # ... after running HEC-RAS geometry preprocessing ...
>>> RasUnsteady.set_normal_depth_boundary(
...     "project.u01",
...     friction_slope=0.0003,
...     area_2d="Perimeter 1",
...     bc_line="DSNormalDepth",
... )
See Also

delete_bc_line, rename_bc_line : Companion writers for the update, delete, and rename verbs in CLB-309's API surface. ras_commander.geom.GeomReferenceFeatures.add_reference_lines : Sibling writer with identical text-format conventions.

delete_bc_line staticmethod

Python
delete_bc_line(geom_file: Union[str, Path], name: str) -> Dict[str, Any]

Remove a BC line block by name.

Parameters

geom_file : str or Path Path to the .g## geometry file. name : str BC Line name to remove. Whitespace-padding on the matching line is tolerated.

Returns

Dict[str, Any] Keys: geom_file, deleted (bool), name, backup_path, lines_removed (int).

Raises

FileNotFoundError If geom_file does not exist. ValueError If no BC line with the given name is present.

rename_bc_line staticmethod

Python
rename_bc_line(geom_file: Union[str, Path], old_name: str, new_name: str) -> Dict[str, Any]

Rename a BC line in place, preserving its geometry, storage_area association, and position in the file.

Parameters

geom_file : str or Path Path to the .g## geometry file. old_name, new_name : str Current and desired BC Line name.

Returns

Dict[str, Any] Keys: geom_file, old_name, new_name, backup_path.

Raises

FileNotFoundError If geom_file does not exist. ValueError If old_name does not exist; if new_name already exists; if either name is empty.

replace_bc_lines staticmethod

Python
replace_bc_lines(geom_file: str | Path, unsteady_files: list[str | Path], *, area_2d: str, lines: list[dict[str, Any]], ras_object: Any | None = None) -> pd.DataFrame

Completely replace one area's perimeter BC lines and forcing.

Parameters

geom_file : str or Path Explicit geometry text path in the caller's disposable clone. unsteady_files : list of str or Path Complete set of cloned unsteady files referencing this geometry. At least one is required. Paths must share the geometry directory. With ras_object, completeness is checked against plan_df; otherwise the caller is responsible for supplying the complete set. area_2d : str Exact 2D Flow Area name (maximum 16 characters). lines : list of dict Complete replacement set; an empty list clears perimeter lines. Each entry has name (maximum 32 characters), coordinates (finite N-by-2 vertices), and bc_type. Supported types are Normal Depth (friction_slope required), Flow Hydrograph (hydrograph_df and friction_slope required), and Stage Hydrograph (hydrograph_df required). Hydrograph frames have hour and value columns accepted by RasUnsteady. The supplied forcing is applied to every supplied unsteady file. ras_object : optional Initialized clone project used to verify geometry/flow association and refresh boundaries_df after successful writes.

Returns

pandas.DataFrame One row per new line and unsteady file, with geom_file, unsteady_file, area_2d, bc_line, and bc_type columns. Empty replacements return the same empty schema. attrs includes removed_bc_lines, backup_paths and boundaries_df_refreshed.

Raises

FileNotFoundError If an explicit input file is missing. ValueError If inputs, native blocks, names, forcing or project associations are invalid, ambiguous, or incomplete. OSError If staging, backup creation, or replacement fails.

Notes

This method modifies only explicitly supplied paths; it does not clone projects. Other areas, 1D boundaries and area-wide rainfall are retained. All content is staged and validated before writes, with same-directory atomic replacement per file and byte-exact rollback on write exceptions. This is an exception-atomic transaction, not a crash-atomic multi-file transaction; concurrent readers/writers must be excluded by the caller. Existing backups are retained. Compiled HDF files are not updated: run native preprocessing before inspecting native face attachments. A post-commit metadata refresh failure is logged and returned through boundaries_df_refreshed=False; it does not undo committed files. standardize_input is HDF-specific; these text paths are normalized explicitly and never resolved through the global project.

set_bc_line_types staticmethod

Python
set_bc_line_types(geom_file: str | Path, line_types: dict[str, str], *, hecras_dir: str | Path | None = None, expected_geometry_sha256: str | None = None) -> dict[str, Any]

Set authored Internal/External BC types through native RAS Mapper APIs.

Works on a writable geometry HDF in a disposable project copy. The compiled BC identities and coordinates must match the selected geometry text. line_types maps exact existing names to Internal or External; callers supply the classification from their authored boundary placement. SetConnectionType and SaveFeatureTable persist it in an isolated process with HEC-RAS's bundled HDF5 runtime. No line geometry, CRS, units or forcing is changed. A sibling backup is retained. line_types may name a subset of lines; unnamed lines keep their type. Returns before/after file hashes, backup path and lines: one native type decision per compiled line, unnamed lines included. The native receipt must match every decision. Matching types return without native writes or a backup. When the native exporter omits compiled Length or compacts fixed-width identity strings, preserve the original attribute schema and values and copy only verified Type decisions. Unknown field loss, input changes or truncation raise and restore the entire HDF backup. Re-run geometry preprocessing to rebuild connectivity after a change.

GeomPipeNetwork source reference

Static helpers for pipe-network and pump-station scenario edits.

set_conduit_dimensions staticmethod

Python
set_conduit_dimensions(geom_file: Union[str, Path], dimensions: Mapping[str, Sequence[float]], *, create_backup: bool = True) -> pd.DataFrame

Set absolute rise/span values for named pipe conduits.

The write uses the dataset's native HDF datatype. This is required for HEC-RAS compound datasets because ordinary high-level assignment can corrupt fixed-width string members on some h5py/HDF5 combinations.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Plain-text geometry path (.g##) or its .hdf.

required
dimensions Mapping[str, Sequence[float]]

Mapping of conduit name to (rise, span).

required
create_backup bool

Create an HDF backup before a material change.

True

Returns:

Type Description
DataFrame

DataFrame containing the prior and requested dimensions and a

DataFrame

changed flag for each requested conduit.

set_pump_group_hq_curve staticmethod

Python
set_pump_group_hq_curve(geom_file: Union[str, Path], group_name: str, curve: Sequence[Sequence[float]], *, create_backup: bool = True) -> pd.DataFrame

Set an absolute pump-group HQ curve in text and geometry HDF.

This is an idempotent setter. To represent identical pumps in parallel, keep the head ordinates and multiply the flow ordinates by the number of pumps before calling this method.

RasGeometry source reference

Operations for parsing and modifying HEC-RAS geometry files.

DEPRECATED: This class is deprecated and will be removed before v1.0. Please migrate to the new geometry subpackage classes: - GeomCrossSection for cross section operations - GeomStorage for storage area operations - GeomLateral for lateral structure and connection operations

All methods are static and designed to be used without instantiation.

get_bank_stations staticmethod

Python
get_bank_stations(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> Optional[Tuple[float, float]]

Extract left and right bank station locations for a cross section.

DEPRECATED: Use GeomCrossSection.get_bank_stations() instead.

get_connection_gates staticmethod

Python
get_connection_gates(geom_file: Union[str, Path], connection_name: str) -> pd.DataFrame

Extract gate definitions for a connection.

DEPRECATED: Use GeomLateral.get_connection_gates() instead.

get_connection_weir_profile staticmethod

Python
get_connection_weir_profile(geom_file: Union[str, Path], connection_name: str) -> pd.DataFrame

Extract weir/dam crest station-elevation profile for a connection.

DEPRECATED: Use GeomLateral.get_connection_profile() instead.

get_connections staticmethod

Python
get_connections(geom_file: Union[str, Path]) -> pd.DataFrame

Extract all SA/2D area connection definitions.

DEPRECATED: Use GeomLateral.get_connections() instead.

get_cross_sections staticmethod

Python
get_cross_sections(geom_file: Union[str, Path], river: Optional[str] = None, reach: Optional[str] = None) -> pd.DataFrame

Extract cross section metadata from geometry file.

DEPRECATED: Use GeomCrossSection.get_cross_sections() instead.

get_expansion_contraction staticmethod

Python
get_expansion_contraction(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> Tuple[float, float]

Extract expansion and contraction coefficients for a cross section.

DEPRECATED: Use GeomCrossSection.get_expansion_contraction() instead.

get_lateral_structures staticmethod

Python
get_lateral_structures(geom_file: Union[str, Path], river: Optional[str] = None, reach: Optional[str] = None) -> pd.DataFrame

Extract lateral structure definitions from geometry file.

DEPRECATED: Use GeomLateral.get_lateral_structures() instead.

get_lateral_weir_profile staticmethod

Python
get_lateral_weir_profile(geom_file: Union[str, Path], river: str, reach: str, rs: str, position: int = 0) -> pd.DataFrame

Extract lateral weir station-elevation profile.

DEPRECATED: Use GeomLateral.get_weir_profile() instead.

get_mannings_n staticmethod

Python
get_mannings_n(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> pd.DataFrame

Extract Manning's n roughness values for a cross section.

DEPRECATED: Use GeomCrossSection.get_mannings_n() instead.

get_station_elevation staticmethod

Python
get_station_elevation(geom_file: Union[str, Path], river: str, reach: str, rs: str) -> pd.DataFrame

Extract station/elevation pairs for a cross section.

DEPRECATED: Use GeomCrossSection.get_station_elevation() instead.

get_storage_areas staticmethod

Python
get_storage_areas(geom_file: Union[str, Path], exclude_2d: bool = True) -> List[str]

Extract list of storage area names from geometry file.

DEPRECATED: Use GeomStorage.get_storage_areas() instead. Note: The new method returns a DataFrame with more information. This wrapper converts it to List[str] for backward compatibility.

get_storage_elevation_volume staticmethod

Python
get_storage_elevation_volume(geom_file: Union[str, Path], area_name: str) -> pd.DataFrame

Extract storage area elevation-volume curve.

DEPRECATED: Use GeomStorage.get_elevation_volume() instead.

interpolate_cross_section staticmethod

Python
interpolate_cross_section(geom_file: Union[str, Path], river: str, reach: str, upstream_rs: str, downstream_rs: str, ratio: float = 0.5, bank_left: Optional[float] = None, bank_right: Optional[float] = None, max_points: int = 500, interpolated_rs: Optional[str] = None) -> pd.DataFrame

Read two cross sections and interpolate a reviewable profile.

DEPRECATED: Use GeomCrossSection.interpolate_cross_section() instead.

interpolate_station_elevation staticmethod

Python
interpolate_station_elevation(upstream_df: DataFrame, downstream_df: DataFrame, ratio: float = 0.5, bank_left: Optional[float] = None, bank_right: Optional[float] = None, max_points: int = 500) -> pd.DataFrame

Interpolate a station/elevation profile between two cross sections.

DEPRECATED: Use GeomCrossSection.interpolate_station_elevation() instead.

set_bank_stations staticmethod

Python
set_bank_stations(geom_file: Union[str, Path], river: str, reach: str, rs: str, bank_left: float, bank_right: float, create_backup: bool = True)

Set left and right bank station locations for a cross section.

DEPRECATED: Use GeomCrossSection.set_bank_stations() instead.

set_connection_weir_profile staticmethod

Python
set_connection_weir_profile(geom_file: Union[str, Path], connection_name: str, sta_elev_df: DataFrame, create_backup: bool = True)

Write weir/dam crest station-elevation profile for a connection.

DEPRECATED: Use GeomLateral.set_connection_profile() instead.

set_expansion_contraction staticmethod

Python
set_expansion_contraction(geom_file: Union[str, Path], river: str, reach: str, rs: str, expansion: float, contraction: float, create_backup: bool = True)

Set expansion and contraction coefficients for a cross section.

DEPRECATED: Use GeomCrossSection.set_expansion_contraction() instead.

set_station_elevation staticmethod

Python
set_station_elevation(geom_file: Union[str, Path], river: str, reach: str, rs: str, sta_elev_df: DataFrame, bank_left: Optional[float] = None, bank_right: Optional[float] = None, create_backup: bool = True)

Write station/elevation pairs to a cross section with automatic bank interpolation.

DEPRECATED: Use GeomCrossSection.set_station_elevation() instead.

RasGeometryUtils source reference

Utility functions for parsing HEC-RAS geometry files.

DEPRECATED: This class is deprecated and will be removed before v1.0. Please migrate to GeomParser from the geometry subpackage:

from ras_commander import GeomParser

All methods are static and designed to be used without instantiation.

create_backup staticmethod

Python
create_backup(file_path: Path) -> Path

Create .bak backup of file before modification.

DEPRECATED: Use GeomParser.create_backup() instead.

extract_comma_list staticmethod

Python
extract_comma_list(line: str, keyword: str) -> List[str]

Extract comma-separated list following keyword.

DEPRECATED: Use GeomParser.extract_comma_list() instead.

extract_keyword_value staticmethod

Python
extract_keyword_value(line: str, keyword: str) -> str

Extract value following keyword marker.

DEPRECATED: Use GeomParser.extract_keyword_value() instead.

format_fixed_width staticmethod

Python
format_fixed_width(values: List[float], column_width: int = 8, values_per_line: int = 10, precision: int = 2) -> List[str]

Format values into fixed-width lines for writing to geometry files.

DEPRECATED: Use GeomParser.format_fixed_width() instead.

identify_section staticmethod

Python
identify_section(lines: List[str], keyword: str, start_index: int = 0) -> Optional[Tuple[int, int]]

Find section boundaries based on keyword marker.

DEPRECATED: Use GeomParser.identify_section() instead.

interpret_count staticmethod

Python
interpret_count(keyword: str, count_value: int, additional_values: Optional[List[int]] = None) -> int

Interpret count declarations based on keyword context.

DEPRECATED: Use GeomParser.interpret_count() instead.

parse_fixed_width staticmethod

Python
parse_fixed_width(line: str, column_width: int = 8) -> List[float]

Parse fixed-width numeric data from a line.

DEPRECATED: Use GeomParser.parse_fixed_width() instead.

update_timestamp staticmethod

Python
update_timestamp(lines: List[str], keyword: str) -> List[str]

Update timestamp for a modified section.

DEPRECATED: Use GeomParser.update_timestamp() instead.

validate_river_reach_rs staticmethod

Python
validate_river_reach_rs(geom_file: Path, river: str, reach: str, rs: str) -> bool

Validate that river/reach/RS combination exists in geometry file.

DEPRECATED: Use GeomParser.validate_river_reach_rs() instead.

RasBreach source reference

Handles dam breach parameter reading and modification in plan files.

This class provides methods for manipulating breach parameters in plain text plan files (.p##). For extracting breach RESULTS from HDF files, use HdfResultsBreach.

Key Functionality: - List breach structures defined in plan files - Read breach parameters (method, geometry, timing, etc.) - Create new breach blocks for structures - Modify breach parameters (activation, progression, geometry) - Support DLBreach (Method 9) physics-based erosion modeling - Support advanced parameters (user growth ratio, mass wasting) - Create backups before modification - Validate CRLF line endings for HEC-RAS compatibility

All methods accept plan numbers, integers, or file paths.

Examples:

Python Console Session
>>> from ras_commander import RasBreach, HdfResultsBreach
>>>
>>> # List breach structures in plan file
>>> structures = RasBreach.list_breach_structures_plan("02")
>>>
>>> # Read breach parameters
>>> params = RasBreach.read_breach_block("02", "Dam")
>>> print(f"Active: {params['is_active']}")
>>>
>>> # Create new breach block
>>> RasBreach.create_breach_block("02", "New_Dam", river="Big River", reach="Upper")
>>>
>>> # Modify parameters (traditional methods)
>>> RasBreach.update_breach_block("02", "Dam", method=1)
>>>
>>> # Configure DLBreach (Method 9) with soil properties
>>> RasBreach.update_breach_block("02", "Dam",
...                               method=9,
...                               dlb_methods=[9, 0, 0, 0, 0, 0, 0],
...                               dlb_soil_type=3,  # Clay
...                               dlb_soil_properties=[0.3, 0, 0, 0, 0, 0, 0])
>>>
>>> # Set advanced parameters
>>> RasBreach.update_breach_block("02", "Dam",
...                               user_growth_flag=-1,
...                               user_growth_ratio=1.0,
...                               mass_wasting_option=0)
>>>
>>> # For HDF results extraction, use HdfResultsBreach:
>>> timeseries = HdfResultsBreach.get_breach_timeseries("02", "Dam")
>>> summary = HdfResultsBreach.get_breach_summary("02")

create_breach_block staticmethod

Python
create_breach_block(plan_input: Union[str, int, Path], structure_name: str, *, river: str = '', reach: str = '', station: str = '', is_active: bool = True, create_backup: bool = True, ras_object=None) -> Dict

Create a new breach block for a structure in the plan file.

Creates a minimal breach block with default parameters that can be customized using update_breach_block() after creation.

CRITICAL: Creates backup before modification. Uses CRLF line endings for HEC-RAS compatibility.

Parameters

plan_input : Union[str, int, Path] Plan number (e.g., "02", 2) or path to HEC-RAS plan file structure_name : str Name of breach structure (must match structure name in geometry file) river : str, optional River name (default: empty string) reach : str, optional Reach name (default: empty string) station : str, optional River station (default: empty string) is_active : bool, default True Initial breach activation status create_backup : bool, default True Create backup file before modification ras_object : RasPrj, optional RAS object for multi-project workflows

Returns

Dict Created breach block as dictionary with default parameters

Examples

Create new breach block

RasBreach.create_breach_block("02", "New_Dam")

Create with location info

RasBreach.create_breach_block("02", "Dam", ... river="Big River", ... reach="Upper", ... station="5000")

Create and then configure

RasBreach.create_breach_block("02", "Dam") RasBreach.update_breach_block("02", "Dam", ... method=9, ... dlb_methods=[9, 0, 0, 0, 0, 0, 0], ... dlb_soil_type=3)

Raises

ValueError If structure already has a breach block in the plan file RuntimeError If CRLF line endings not preserved (HEC-RAS incompatibility)

Warnings
  • Modifies plan file in-place
  • Backup created in same directory with timestamp
  • HEC-RAS must be closed before modification
  • Validates CRLF line endings after write
Notes

Creates a minimal breach block with: - Method 0 (user-specified breach geometry) - Overtopping failure mode with a one-hour formation time and 2.6 breach weir coefficient; geometry dimensions remain zero until configured - Empty start conditions - Empty breach progression

The block is inserted after the last existing breach block in the file, or at the end if no breach blocks exist.

list_breach_structures_plan staticmethod

Python
list_breach_structures_plan(plan_input: Union[str, int, Path], *, ras_object=None) -> List[Dict]

List all breach structures defined in plan file.

Parameters

plan_input : Union[str, int, Path] Plan number (e.g., "02", 2) or path to HEC-RAS plan file ras_object : RasPrj, optional RAS object for multi-project workflows

Returns

List[Dict] List of dictionaries containing breach location information: - structure: Structure name - river: River name - reach: Reach name - station: River station - is_active: Boolean, True if breach is active

Examples

Using plan number

structures = RasBreach.list_breach_structures_plan("02") for struct in structures: ... print(f"{struct['structure']}: Active={struct['is_active']}")

Using plan file path

plan_path = Path("MyProject.p02") structures = RasBreach.list_breach_structures_plan(plan_path)

Notes
  • Returns breach structures regardless of activation status
  • Use is_active field to filter for active breaches only
  • Accepts plan number (string/int) or full plan file path

read_breach_block staticmethod

Python
read_breach_block(plan_input: Union[str, int, Path], structure_name: str, *, ras_object=None) -> Dict

Read breach parameters for specified structure from plan file.

Parameters

plan_input : Union[str, int, Path] Plan number (e.g., "02", 2) or path to HEC-RAS plan file structure_name : str Name of breach structure to read ras_object : RasPrj, optional RAS object for multi-project workflows

Returns

Dict Dictionary containing all breach parameters: - structure_name: Structure name - is_active: Boolean, breach activation status - river, reach, station: Location information - values: Dict of all breach parameter values - table_rows: Dict of numeric tables (progression, downcutting, etc.)

Examples

Using plan number

breach_data = RasBreach.read_breach_block("02", "Laxton_Dam") print(f"Active: {breach_data['is_active']}")

Using plan file path

plan_path = Path("MyProject.p02") breach_data = RasBreach.read_breach_block(plan_path, "Laxton_Dam")

Raises

ValueError If specified structure not found in plan file

Notes
  • Accepts plan number (string/int) or full plan file path
  • Uses RasUtils.normalize_ras_number() for plan number handling
  • All values returned as strings; parse as needed

set_breach_geom staticmethod

Python
set_breach_geom(plan_input: Union[str, int, Path], structure_name: str, *, centerline: Optional[float] = None, final_bottom_width: Optional[float] = None, final_bottom_elev: Optional[float] = None, left_slope: Optional[float] = None, right_slope: Optional[float] = None, failure_mode: Optional[Literal['overtopping', 'piping']] = None, piping_coefficient: Optional[float] = None, initial_piping_elevation: Optional[float] = None, formation_time: Optional[float] = None, weir_coefficient: Optional[float] = None, initial_width: Optional[float] = None, active: Optional[bool] = None, weir_coef: Optional[float] = None, top_elev: Optional[float] = None, formation_method: Optional[int] = None, ras_object=None) -> Dict

Update individual breach geometry parameters.

Convenience function for modifying specific breach geometry fields without reconstructing the entire Breach Geom CSV. Reads current values and updates only the specified parameters.

Parameters

plan_input : Union[str, int, Path] Plan number (e.g., "02", 2) or path to HEC-RAS plan file structure_name : str Name of breach structure to update centerline : float, optional Centerline/station location (ft or m) final_bottom_width : float, optional Final breach bottom width (ft or m) final_bottom_elev : float, optional Final breach bottom elevation (ft or m) - Common modification left_slope : float, optional Left side slope (H:V ratio, e.g., 0.5 = 0.5H:1V) right_slope : float, optional Right side slope (H:V ratio) failure_mode : {"overtopping", "piping"}, optional Failure mode stored in Breach Geom field 5 piping_coefficient : float, optional Piping/orifice coefficient stored in field 6 initial_piping_elevation : float, optional Initial piping elevation stored in field 7 (ft or m) formation_time : float, optional Breach/full formation time in hours weir_coefficient : float, optional Breach weir coefficient. Adds the optional tenth field to a nine-field legacy record when supplied. initial_width : float, optional Deprecated alias for final_bottom_width active : bool, optional Unsupported legacy argument. Use update_breach_block(..., is_active=...) instead. weir_coef : float, optional Deprecated alias for weir_coefficient top_elev : float, optional Unsupported legacy argument; no Breach Geom field stores a top elevation. formation_method : int, optional Unsupported legacy argument; the breach method and starting condition are stored outside Breach Geom. ras_object : RasPrj, optional RAS object for multi-project workflows

Returns

Dict Updated breach block dictionary

Examples

Update just Final Bottom Elevation

RasBreach.set_breach_geom("19", "Dam", final_bottom_elev=605)

Update multiple parameters

RasBreach.set_breach_geom("19", "Dam", ... final_bottom_width=250, ... final_bottom_elev=600, ... formation_time=3.0)

Configure a piping failure

RasBreach.set_breach_geom("template_plan", "Dam", ... failure_mode="piping", ... piping_coefficient=0.5, ... formation_time=2.5)

Notes
  • Only specified parameters are modified; others retain current values
  • Automatically reads current Breach Geom and updates selectively
  • Creates backup before modification
  • Validates CRLF line endings
  • Fields 1 and 2 are interpreted as final bottom width/elevation for user-entered breaches, but as maximum possible bottom width and minimum possible bottom elevation for applicable physical methods. This setter updates the same stored slots without asserting that all methods use those values identically.
Breach Geom Field Reference

[0] centerline - Breach centerline/station location [1] final_bottom_width - Final breach bottom width [2] final_bottom_elev - Final breach bottom elevation [3] left_slope - Left side slope (H:V) [4] right_slope - Right side slope (H:V) [5] failure_mode - False=Overtopping, True=Piping [6] piping_coefficient - Piping/orifice coefficient [7] initial_piping_elevation - Initial piping elevation [8] formation_time - Breach/full formation time (hours) [9] weir_coefficient - Breach weir coefficient (optional in legacy nine-field records)

update_breach_block staticmethod

Python
update_breach_block(plan_input: Union[str, int, Path], structure_name: str, *, is_active: bool = None, method: int = None, geom_values: List = None, start_values: List = None, progression_mode: int = None, progression_pairs: List[Tuple[float, float]] = None, downcutting_pairs: List[Tuple[float, float]] = None, widening_pairs: List[Tuple[float, float]] = None, calculator_data: List = None, dlb_methods: Optional[List] = None, dlb_soil_type: Optional[Union[str, int]] = None, dlb_soil_properties: Optional[List] = None, dlb_core_soil_type: Optional[Union[str, int]] = None, dlb_cover_option: Optional[Union[str, int]] = None, dlb_cover_soil_properties: Optional[List] = None, dlb_breach_direction: Optional[Union[str, int]] = None, user_growth_flag: Optional[int] = None, user_growth_ratio: Optional[float] = None, mass_wasting_option: Optional[int] = None, create_backup: bool = True, ras_object=None) -> Dict

Update breach parameters for specified structure in plan file.

CRITICAL: Creates backup before modification. Uses CRLF line endings for HEC-RAS compatibility.

Parameters

plan_input : Union[str, int, Path] Plan number (e.g., "02", 2) or path to HEC-RAS plan file structure_name : str Name of breach structure to update is_active : bool, optional Set breach activation status (True/False) method : int, optional Breach calculation method (0-9, where 9 is DLBreach) geom_values : List, optional Raw Breach Geom values in HEC-RAS field order: center station, final bottom width, final bottom elevation, left slope, right slope, failure mode (False=overtopping, True=piping), piping coefficient, initial piping elevation, formation time, and optional breach weir coefficient. Legacy records may contain only the first nine fields. start_values : List, optional Breach starting conditions progression_mode : int, optional Progression mode (0=Linear, 1=Non-linear) progression_pairs : List[Tuple[float, float]], optional Time/breach fraction pairs for non-linear progression downcutting_pairs : List[Tuple[float, float]], optional Time/elevation pairs for physical breach downcutting widening_pairs : List[Tuple[float, float]], optional Time/width pairs for physical breach widening calculator_data : List, optional Breach calculator heuristic inputs dlb_methods : List, optional DLBreach Methods (7 values, first is primary method 0-9) dlb_soil_type : Union[str, int], optional DLBreach SoilType (0-7) dlb_soil_properties : List, optional DLBreach Soil Properties (7 erosion parameter values) dlb_core_soil_type : Union[str, int], optional DLBreach Core SoilType dlb_cover_option : Union[str, int], optional DLBreach Cover Option dlb_cover_soil_properties : List, optional DLBreach Cover Soil Properties (7 values) dlb_breach_direction : Union[str, int], optional DLBreach Breach Direction user_growth_flag : int, optional User-defined growth flag (-1 or 1) user_growth_ratio : float, optional User-defined growth ratio (dimensionless) mass_wasting_option : int, optional Mass wasting model option (0-2) create_backup : bool, default True Create backup file before modification ras_object : RasPrj, optional RAS object for multi-project workflows

Returns

Dict Updated breach block as dictionary

Examples

Activate breach

RasBreach.update_breach_block("02", "Laxton_Dam", is_active=True)

Set breach geometry

geom = [150, 100, 1400, 1, 1, False, "", "", 0.5, 2.6] RasBreach.update_breach_block("02", "Laxton_Dam", geom_values=geom)

Set non-linear progression

progression = [(0, 0), (0.5, 0.3), (1.0, 1.0)] # time, fraction pairs RasBreach.update_breach_block("02", "Laxton_Dam", ... progression_mode=1, ... progression_pairs=progression)

Configure DLBreach (Method 9) with soil properties

RasBreach.update_breach_block("02", "Dam", ... method=9, ... dlb_methods=[9, 0, 0, 0, 0, 0, 0], ... dlb_soil_type=3, # Clay ... dlb_soil_properties=[0.3, 0, 0, 0, 0, 0, 0])

Set advanced parameters

RasBreach.update_breach_block("02", "Dam", ... user_growth_flag=-1, ... user_growth_ratio=1.0, ... mass_wasting_option=0)

Raises

ValueError If structure not found in plan file, or if dlb_methods doesn't have 7 values RuntimeError If CRLF line endings not preserved (HEC-RAS incompatibility)

Warnings
  • Modifies plan file in-place
  • Backup created in same directory with timestamp
  • HEC-RAS must be closed before modification
  • Validates CRLF line endings after write
Notes

Based on TNTech Dam Breach Dashboard breach_io.py implementation. Adapted to ras-commander conventions with plan-number support. DLBreach (Method 9) provides physics-based erosion modeling using soil properties.

RasCrossSections source reference

Common, static API for point-level HEC-RAS cross-section exports.

get_points staticmethod

Python
get_points(project: Any, geometry: str | int | Path, *, source: str = 'auto', river: str | None = None, reach: str | None = None, river_station: str | None = None, horizontal_crs: Any = None, vertical_units: str | None = None, vertical_datum: str | None = None, vertical_transform: VerticalTransform | None = None) -> pd.DataFrame

Return a unified, provenance-rich cross-section point table.

project accepts a :class:RasPrj, project folder, or project .prj path. geometry accepts a geometry number, title, text path, or geometry-HDF path. In source='auto' mode an explicit path keeps its source type; a project geometry selector prefers an available HDF and otherwise uses the text geometry.

Native elevations are preserved by default. A vertical transformation occurs only when vertical_transform is supplied, and its complete per-point operation provenance is repeated in the export-safe vertical_transform_provenance column and stored in DataFrame.attrs.

VerticalTransform source reference

Explicit, auditable three-dimensional coordinate transformation.

Supply an exact PROJ pipeline or both source_crs and target_crs. CRS-to-CRS mode requires full 3D or compound CRS definitions when a vertical datum change is intended. Every point is transformed with its own X, Y, and Z coordinate; no representative model centroid is used.

The source/target vertical datum and unit labels are required independently of the CRS definitions so exported provenance remains understandable without interpreting WKT.

apply

Python
apply(frame: DataFrame) -> tuple[pd.DataFrame, dict[str, Any]]

Apply the configured operation to every row and return provenance.

Numeric breakline containment retry

RasBreakout2D.prepare_cloned_geometry permits one automatic retry only when native containment violations exclusively identify breaklines outside the one-cell inward buffer. The planner clips each identified line against the exact compiled collection perimeter eroded by cell spacing plus max(1e-6, cell_spacing * 1e-8) source horizontal units, intersected with the strict buffer. A repair must preserve one valid positive LineString, its name, child FID and all native spacing/repeat/protection controls, with Hausdorff movement at most 0.01 source horizontal units. No source file is changed.

A cloned geometry sidecar <geometry>.breakline_containment_repair.json (ras-numeric-breakline-containment-repair/v1) is written before mutation. It records reason_code=NUMERIC_BREAKLINE_CONTAINMENT_CLIP or NUMERIC_BREAKLINE_CONTAINMENT_VERTEX_REPAIR, with each line's method set to endpoint_clip or bounded_vertex_projection, horizontal units, maximum movement, one-cell spacing, additional margin, compiled perimeter WKB SHA256, perimeter/control preservation flags, and per-line before/after WKB hashes, lengths, removed length and movement. The plan binds the current text and HDF SHA256. Status advances from planned to applied (with preprocessing success) to validated or failed (with native mesh success and final hashes). Exceptions preserve the last sidecar. The result's default-empty breakline_containment_repairs list returns completed retry records. Native compilation and the original strict containment audit still must pass.

Fresh geometry preprocessor evidence

GeomPreprocessor.run_geometry_preprocessor(..., geometry_only=True) waits for normal launcher and owned-child exits before inspecting the geometry HDF. Messages and fresh sidecars cannot shorten that wait. The post-completion contract checks fresh products, authored inputs, topology, native face binding, process errors and exact plan restoration. Run against a disposable project copy and inspect the returned completion evidence. FIM callers require require_complete_products=True, including repair and mesh-generation paths. The upstream default remains False for explicitly unqualified structure schemas; it does not waive qualified structure-free checks. These checks establish software geometry completion, not hydraulic acceptance.

Recorded refinement and generated-point repairs

Supplied parent-seed repair

Use GeomMesh.plan_computation_point_repair when a child should start with its parent's computation points, allowing recorded native repairs at the cut edge. The default write_computation_points path still writes supplied points without repair. Coordinates and spacing use the geometry's horizontal CRS and units.

Python
from ras_commander.geom import GeomMesh

plan = GeomMesh.plan_computation_point_repair(
    child_geometry, parent_points, mesh_name="ChildArea", ras_object=child_project,
)
evidence = plan.to_dict()  # inspect seed additions, exclusions and removed vertices
result = GeomMesh.apply_computation_point_repair(plan)
readback = GeomMesh.validate_computation_point_repair(plan)

Planning performs native previews without changing the target text or compiled HDF. It follows the supplied-seed recipe retained in the Salt Draw subdomain assembly research: up to seven MaxFaces repairs at face-length ratios 0.0025, 0.05 and 0.1, and up to six perimeter-connection repairs. MaxFaces is checked again after each perimeter change, sharing the same seven-repair budget. New midpoints are rounded to three decimal places before being moved inside, then deduplicated by exact equality. It removes perimeter vertices nearest native error locations and records seeds excluded by the repaired perimeter. Final previews must complete at all three ratios, both before and after native text serialization. Breakline and connection-line constraints participate in the native previews. Kept breaklines and complete connection footprints must remain contained, and boundary-condition line ends must still touch the repaired perimeter (within 1e-6 model unit for text serialization). Breakout also audits compiled feature containment and connection/BC geometry after native preprocessing.

The default loss limits are 0.001 of supplied parent seeds and 0.001 of the original perimeter area. Set max_parent_seed_loss_fraction and max_area_loss_fraction explicitly when planning if the reviewed workflow needs different limits. Loss uses the original polygon's excluded area, not net area change. Exceeding either limit raises with a repair_evidence dictionary; no successful plan or target mutation occurs. Failure or exhausted repair budgets also leave the target unchanged.

Application requires unchanged input bytes, preserves a numbered backup and atomically replaces only the geometry text. The explicitly supplied project's runtime must agree with the actual loaded RasMapperLib assembly; use a fresh worker to switch runtimes. Without ras_object, supply explicit geometry and installation paths; the global project is never selected. A project's unresolved Ras.exe fallback accepts an explicit installation instead of resolving against the working folder. Successful readback establishes that the text matches the plan. It does not establish identical parent face topology or hydraulic equivalence. Run native Geometry and Event Conditions preprocessing and review the resulting compiled mesh and hydraulics separately.

For breakout authoring, opt in with RasBreakout2D.prepare_cloned_geometry(computation_points=parent_points, repair_computation_points=True, refresh_method="rasexe", remesh=False, ...). The returned computation_points_result.seed_repair retains the plan and application readback. Omitting the repair flag preserves existing behavior.

The recipe was adapted from FIM Commander's retained pipelines/rog/subdomain_assembly/author_piece.py at commit 2384719e. It uses GeomMesh's existing native repair helpers; no optimesh dependency is required.

Synchronize cloned area association caches

After relocating a clone's terrain or classification sidecars, compiled 2D areas may retain filenames from the parent even when /Geometry has current links. Inspect and synchronize those caches through RasMap:

Python
plan = RasMap.plan_geometry_area_association_sync(child_hdf, ["ChildArea"])
# Review plan["changes"] before application.
receipt = RasMap.apply_geometry_area_association_sync(plan)

Planning requires existing current geometry-wide sidecars and records every selected area's filename/layer change. Application rejects changed input or a modified plan, verifies staged readback, preserves a numbered backup and replaces the HDF atomically. Area-only associations are preserved when no geometry-wide filename is declared. A stale area layer name is removed when the current geometry filename has no corresponding layer name.

Absent optional area layer names remain absent; current filename links are still synchronized. In a HEC-RAS 6.6 geometry-refresh readback, the native save retained the child terrain filename but omitted the area Terrain Layername even though the canonical geometry association named the layer. The API preserves that cache representation instead of introducing a label that native save removes. An existing area layer name is still updated or removed to match the canonical association.

Only the selected cached association attributes change. Calibration overrides, mesh datasets, other area attributes and canonical geometry links remain intact. An already synchronized plan preserves the file bytes and creates no backup. These APIs do not execute HEC-RAS or establish native/hydraulic acceptance; preprocess and review the child afterwards.

GeomMesh.clip_refinement_regions(..., invalid_regions="repair") reads delivered geometry without changing the source HDF. GEOS make_valid supplies valid polygon coverage; every positive-area component survives before clipping. Holes are partitioned into hole-free pieces without filling them. Zero-area remnants are recorded explicitly. The returned DataFrame keeps its existing columns and stores source repair records in report.attrs["repairs"], including validity, source/repaired WKB hashes and areas, nonpolygon remnants and the positive-area preservation check. Default invalid_regions="raise" is unchanged. Breakout preflight normalizes invalid source refinements before intersection, and marks the corresponding feature-action reason.

GeomMeshRepair.plan_refinement_support plans a bounded grid for a retained region whose final cells fail local-resolution QA. Coordinates and dx/dy share the source projected CRS and project length units. Plans preserve source region coverage and spacing controls, retain existing points, record each added XY coordinate, and fail before mutation if the candidate budget is exceeded. When the bounding box exceeds the remaining budget, the planner intersects grid columns with the support polygon. It bounds each fallback region's column count and the total examined grid sites by max_points, preserving the original lattice, ordering and strict containment checks. candidate_count still records the bounding-box count. Such plans also record candidate_generation and examined_candidate_count; ordinary plans keep their existing evidence shape. GeomMeshRepair.apply_refinement_support requires a hash-guarded child geometry, an exact serialized-seed match and strictly interior additions. It changes only the selected child's point block. Use attempt-owned copies and then refresh native mesh metadata, recompile and recheck all engineering gates.

GeomMeshRepair.plan_native_seed_removal reads specific native topology errors. It requires native error indexes or fewer-than-three-face cells, and proves each cell point matches the corresponding generated seed within 1e-6 project units. It never changes perimeter vertices. DuplicatePoints repairs use native BadIndexes referring to input seeds, because this state may have no physical cell collection. Every index must be integral and within the supplied finite XY seed array. The plan records the index basis, native index count, seed count, selected coordinates and removal budget (max_removals, default 8192). Missing indexes, indexes outside the input array, removing every seed, or exceeding the budget hold before mutation. Remaining seed order and all perimeter and feature controls are preserved. Successful native recompilation and all final spacing checks remain required. Optional generate_computation_points(..., repair_generated_points=True) applies at most five such bootstrap repairs and emits each plan to evidence_callback before writing geometry text. Observer errors abort generation and appear in the returned MeshResult error. Supply the persisted dimensionless minimum face length ratio for the preview. The option defaults to False.

These repair plans support native meshing; they do not establish hydraulic acceptance. Successful native recompilation and the caller's spatial and hydraulic review remain required.

Numeric breakline containment repairs keep their maximum geometry displacement of 0.01 in project horizontal units and the exact one-cell inward containment gate. The usual endpoint clip is unchanged. At an acute intersection, clipping can remove a long endpoint despite a microscopic normal deficit; a bounded fallback projects exterior vertices into the guarded polygon. It must retain one valid line, satisfy the original displacement cap and exact containment, and preserve controls and the perimeter. Material deficits and disconnected fragments still fail closed. Each record identifies endpoint_clip or bounded_vertex_projection in repairs[].method; projection uses reason NUMERIC_BREAKLINE_CONTAINMENT_VERTEX_REPAIR, while endpoint clipping keeps NUMERIC_BREAKLINE_CONTAINMENT_CLIP. Coordinates remain in the same CRS.

removed_length is the signed original length minus repaired length in project units; bounded vertex projection can make this diagnostic negative.

GeomMeshRepair.plan_compiled_polygon_seed_removal accepts serialized XY seeds, native-index-ordered physical centers and public HDF polygon diagnostics in one projected CRS/project unit system. Both complete center arrays must have the same count and agree by index within 1e-6 units. Only consistent no_polygon and multiple_polygons records for physical cells authorize a plan; ghost IDs and unrelated diagnostics do not. Duplicate/inconsistent diagnostics fail. The caller may lower the removal budget from its hard maximum of 32; removing every seed is prohibited. The method returns ras-compiled-polygon-seed-repair/v1 with diagnostic and coordinate evidence, and changes nothing. Hash-guarded application to disposable geometry, native rebuilding, exhaustive physical polygon reconstruction and all feature/hydraulic gates remain caller duties.