Skip to content

Results Queries

For repeatable batch plots, start with the 2D profile and reference workflow guide. The classes below separate cell sampling, native Mapper rendering, geometry reference-feature authoring, and reading recorded solver output. These methods do not themselves run a hydraulic simulation.

Runtime and output contracts

Surface Input Return Requirements
Offline point/straight-profile sampling Completed plan HDF, model-coordinate points/endpoints, variable and stored time selector Dictionary or DataFrame of values and nearest-cell provenance Python/HDF; reconstructed quantities are not a Mapper renderer
Native polyline profile Plan HDF, LineString/coordinates, time index, spacing, optional terrain HDF DataFrame: station, x, y, mesh_name, face_id, variable fields; WSE/velocity/flow profiles also include depth, terrain_elev pythonnet and compatible installed HEC-RAS libraries
Native polyline time series Same inputs, optional time_range Long DataFrame, or wide=True station-by-time_index pivot of the selected variable Same native runtime; saved result times only
Stored reference output Completed plan HDF, optional variable names xarray Dataset; lines use time, refln_id and coordinate refln_name; points use refpt_id and refpt_name; both include mesh_name Reference locations present during computation; offline reader
Reference-feature generation/writing Longitudinal coordinates, spacing/length, geometry file, target 2D area Reviewable dictionaries or write count Writes geometry, not computed results

Native terrain_raster arguments currently resolve a RAS terrain HDF. Coordinates must already match the model; the query does not reproject them. sample_spacing=None requests 50 model coordinate units. Returned stations need not be uniformly spaced at that request and may repeat. Native minimum-spacing and sample-count limits also apply. wide=True uses a first-value aggregation for repeated station/time-index pairs; keep long output to inspect all samples. Native polyline methods require a concrete output index and reject "max"; time-series ranges are start-inclusive/stop-exclusive. The current shared input path rejects 2D bridge groups. There is no public render-mode selector in these methods.

face_id in native sampled profiles is nearest-face metadata, not a guarantee that a renderer used only that face. Preserve DataFrame attrs alongside CSV exports for source/version/unit information. See the guide for terrain, maximum-envelope and timestamp comparisons.

Offline spatial sampling

Spatial query utilities for 2D HEC-RAS results.

query_point staticmethod

Python
query_point(hdf_path: Path, x: float, y: float, variable: str = 'wse', time_index: Union[int, str] = -1, method: str = 'nearest', ras_object: Optional[Any] = None) -> Dict[str, Any]

Query one arbitrary point against the nearest mesh cell or IDW.

At integer time indexes, unsteady velocity queries prefer stored Cell Velocity - Velocity X/Y components with validated cell/time axes, Location and velocity units. Speed is their magnitude. Legacy components and face reconstruction remain fallbacks when the stored pair is incomplete. Vector queries select a complete pair from one source per mesh; direct single-component queries may use a qualified stored axis alone. Invalid present schemas raise ValueError rather than silently falling back.

Returns:

Type Description
dict with keys

value, cell_id, mesh_name, distance, x, y

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_point(
    hdf_path: Path,
    x: float,
    y: float,
    variable: str = "wse",
    time_index: Union[int, str] = -1,
    method: str = "nearest",
    ras_object: Optional[Any] = None,
) -> Dict[str, Any]:
    """
    Query one arbitrary point against the nearest mesh cell or IDW.

    At integer time indexes, unsteady velocity queries prefer stored
    ``Cell Velocity - Velocity X/Y``
    components with validated cell/time axes, Location and velocity units.
    Speed is their magnitude. Legacy components and face reconstruction
    remain fallbacks when the stored pair is incomplete. Vector queries select
    a complete pair from one source per mesh; direct single-component
    queries may use a qualified stored axis alone. Invalid present schemas
    raise ValueError rather than silently falling back.

    Returns:
        dict with keys: value, cell_id, mesh_name, distance, x, y
    """
    points_df = pd.DataFrame({"x": [float(x)], "y": [float(y)]})
    result_df = _query_points_core(
        hdf_path,
        points_df,
        variable,
        time_index,
        method,
        ras_object=ras_object,
    )
    row = result_df.iloc[0]
    return {
        "value": float(row["value"]),
        "cell_id": int(row["cell_id"]),
        "mesh_name": str(row["mesh_name"]),
        "distance": float(row["distance"]),
        "x": float(row["x"]),
        "y": float(row["y"]),
    }

query_points staticmethod

Python
query_points(hdf_path: Path, points: Any, variable: str = 'wse', time_index: Union[int, str] = -1, method: str = 'nearest', ras_object: Optional[Any] = None) -> pd.DataFrame

Query many points against the nearest mesh cells in one call.

At integer time indexes, unsteady velocities use the stored-component precedence and validation documented by :meth:query_point, independently for each mesh.

Accepted point formats: - list of (x, y) tuples - numpy array with shape (N, 2) - GeoDataFrame with Point geometries

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_points(
    hdf_path: Path,
    points: Any,
    variable: str = "wse",
    time_index: Union[int, str] = -1,
    method: str = "nearest",
    ras_object: Optional[Any] = None,
) -> pd.DataFrame:
    """
    Query many points against the nearest mesh cells in one call.

    At integer time indexes, unsteady velocities use the stored-component precedence and validation
    documented by :meth:`query_point`, independently for each mesh.

    Accepted point formats:
    - list of (x, y) tuples
    - numpy array with shape (N, 2)
    - GeoDataFrame with Point geometries
    """
    points_df = _coerce_points_dataframe(points)
    result_df = _query_points_core(
        hdf_path,
        points_df,
        variable,
        time_index,
        method,
        ras_object=ras_object,
    )
    return result_df[
        ["x", "y", "value", "cell_id", "mesh_name", "distance"]
    ]

query_profile staticmethod

Python
query_profile(hdf_path: Path, x1: float, y1: float, x2: float, y2: float, variable: str = 'wse', n_points: int = 100, time_index: Union[int, str] = -1, ras_object: Optional[Any] = None) -> pd.DataFrame

Sample evenly spaced points along a transect.

Returns:

Type Description
DataFrame

DataFrame with station, x, y, value, cell_id, mesh_name, distance

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_profile(
    hdf_path: Path,
    x1: float,
    y1: float,
    x2: float,
    y2: float,
    variable: str = "wse",
    n_points: int = 100,
    time_index: Union[int, str] = -1,
    ras_object: Optional[Any] = None,
) -> pd.DataFrame:
    """
    Sample evenly spaced points along a transect.

    Returns:
        DataFrame with station, x, y, value, cell_id, mesh_name, distance
    """
    n_points = int(n_points)
    if n_points <= 0:
        raise ValueError("n_points must be a positive integer")

    fractions = np.linspace(0.0, 1.0, n_points)
    xs = x1 + (x2 - x1) * fractions
    ys = y1 + (y2 - y1) * fractions
    stations = np.linspace(
        0.0,
        float(np.hypot(x2 - x1, y2 - y1)),
        n_points,
    )

    profile_points = pd.DataFrame({"x": xs, "y": ys})
    points_df = _query_points_core(
        hdf_path,
        profile_points,
        variable,
        time_index,
        "nearest",
        ras_object=ras_object,
        point_label="profile sample point",
    )
    points_df.insert(0, "station", stations)
    return points_df[
        [
            "station",
            "x",
            "y",
            "value",
            "cell_id",
            "mesh_name",
            "distance",
        ]
    ]

query_transverse_profile staticmethod

Python
query_transverse_profile(hdf_path: Path, x: float, y: float, time_index: Union[int, str] = -1, max_steps: int = 25, min_velocity: float = 0.05, mesh_name: Optional[str] = None, ras_object: Optional[Any] = None) -> pd.DataFrame

March cell-by-cell across local flow to build an approximate velocity transect.

.. warning::

This method reconstructs cell-centered velocities from stored HDF face-normal components via least-squares. It does not have access to the internal solver state that HEC-RAS uses when computing Reference Line output. Treat this as an approximate cell-based transect. query_polyline_velocity_profile provides native RASMapper station-wise postprocessing; it is not a reader for solver-recorded Reference Line hydrographs. For those hydrographs, define Reference Lines before computing the plan, then use HdfResultsXsec.get_ref_lines_timeseries to read the recorded variables. A station profile and a line-integrated or line-averaged time series answer different questions; neither is a substitute for checking the model and the quantity required by the study.

The seed point is snapped to the nearest 2D cell. The seed cell's velocity vector defines the transverse axis, and the marcher advances across adjacent mesh faces in both directions until it reaches a mesh boundary, an already visited cell, max_steps, or a cell below min_velocity.

Returns:

Type Description
DataFrame

DataFrame with station, x, y, cell_id, mesh_name, velocity,

DataFrame

velocity_x, velocity_y, side, step, entry_face_id, and

DataFrame

distance_from_seed.

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_transverse_profile(
    hdf_path: Path,
    x: float,
    y: float,
    time_index: Union[int, str] = -1,
    max_steps: int = 25,
    min_velocity: float = 0.05,
    mesh_name: Optional[str] = None,
    ras_object: Optional[Any] = None,
) -> pd.DataFrame:
    """
    March cell-by-cell across local flow to build an approximate velocity
    transect.

    .. warning::

       This method reconstructs cell-centered velocities from stored HDF
       face-normal components via least-squares. It does **not** have access
       to the internal solver state that HEC-RAS uses when computing
       Reference Line output. Treat this as an approximate cell-based
       transect. ``query_polyline_velocity_profile`` provides native
       RASMapper station-wise postprocessing; it is not a reader for
       solver-recorded Reference Line hydrographs. For those hydrographs,
       define Reference Lines before computing the plan, then use
       ``HdfResultsXsec.get_ref_lines_timeseries`` to read the recorded
       variables. A station profile and a line-integrated or line-averaged
       time series answer different questions; neither is a substitute
       for checking the model and the quantity required by the study.

    The seed point is snapped to the nearest 2D cell. The seed cell's
    velocity vector defines the transverse axis, and the marcher advances
    across adjacent mesh faces in both directions until it reaches a mesh
    boundary, an already visited cell, ``max_steps``, or a cell below
    ``min_velocity``.

    Returns:
        DataFrame with station, x, y, cell_id, mesh_name, velocity,
        velocity_x, velocity_y, side, step, entry_face_id, and
        distance_from_seed.
    """
    if time_index == "max":
        raise ValueError(
            "query_transverse_profile requires a signed time_index; "
            "'max' envelope velocities do not preserve flow direction."
        )

    max_steps = int(max_steps)
    if max_steps < 0:
        raise ValueError("max_steps must be non-negative")
    min_velocity = float(min_velocity)
    if min_velocity < 0.0:
        raise ValueError("min_velocity must be non-negative")

    geom_hdf_path = _resolve_geometry_hdf(hdf_path, ras_object=ras_object)
    cache = _get_kdtree(geom_hdf_path, ras_object=ras_object)
    steady_plan = HdfResultsPlan.is_steady_plan(hdf_path)

    velocity_x, velocity_y = _get_cell_velocity_components(
        hdf_path,
        geom_hdf_path,
        cache,
        int(time_index),
        steady_plan,
    )
    _validate_value_length(velocity_x, cache, "Velocity X")
    _validate_value_length(velocity_y, cache, "Velocity Y")

    seed_point = np.array([float(x), float(y)], dtype=float)
    seed_global_index, seed_distance = _nearest_cell_global_index(
        cache,
        seed_point,
        mesh_name=mesh_name,
    )
    _warn_on_large_distances(
        np.array([seed_distance], dtype=float),
        point_label="transverse seed point",
    )

    seed_mesh_name = str(cache["mesh_names"][seed_global_index])
    seed_cell_id = int(cache["cell_ids"][seed_global_index])
    topology = _get_mesh_topology(geom_hdf_path, seed_mesh_name)
    cell_to_global = _mesh_cell_global_lookup(cache, seed_mesh_name)

    seed_vx = float(velocity_x[seed_global_index])
    seed_vy = float(velocity_y[seed_global_index])
    seed_speed = float(np.hypot(seed_vx, seed_vy))
    if not np.isfinite(seed_speed) or seed_speed < min_velocity:
        raise ValueError(
            f"Seed cell velocity {seed_speed:.6g} is below "
            f"min_velocity {min_velocity:.6g}; transverse direction "
            "cannot be determined."
        )

    transverse_direction = np.array(
        [-seed_vy / seed_speed, seed_vx / seed_speed],
        dtype=float,
    )
    visited = {seed_cell_id}
    seed_row = _transverse_profile_row(
        0.0,
        seed_mesh_name,
        seed_cell_id,
        np.asarray(topology["cell_centers"][seed_cell_id], dtype=float),
        seed_vx,
        seed_vy,
        "seed",
        0,
        None,
    )

    left_rows = _march_transverse_side(
        topology,
        seed_mesh_name,
        seed_cell_id,
        -transverse_direction,
        -1,
        velocity_x,
        velocity_y,
        cell_to_global,
        min_velocity,
        max_steps,
        visited,
    )
    right_rows = _march_transverse_side(
        topology,
        seed_mesh_name,
        seed_cell_id,
        transverse_direction,
        1,
        velocity_x,
        velocity_y,
        cell_to_global,
        min_velocity,
        max_steps,
        visited,
    )

    profile = pd.DataFrame(left_rows + [seed_row] + right_rows)
    profile = profile.sort_values("station").reset_index(drop=True)
    profile["distance_from_seed"] = profile["station"].abs()
    return profile[
        [
            "station",
            "distance_from_seed",
            "x",
            "y",
            "cell_id",
            "mesh_name",
            "velocity",
            "velocity_x",
            "velocity_y",
            "side",
            "step",
            "entry_face_id",
        ]
    ]

Native mapped profiles and time series

The flow sample column is not automatically whole-line Q. Use recorded reference-line flow for that quantity when available; do not sum station samples.

Spatial query utilities for 2D HEC-RAS results.

query_polyline_wse_profile staticmethod

Python
query_polyline_wse_profile(hdf_path: Path, polyline: Any, time_index: int, sample_spacing: Optional[float] = None, terrain_raster: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None) -> pd.DataFrame

Extract RAS Mapper WSE/depth/terrain samples along a profile line.

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_polyline_wse_profile(
    hdf_path: Path,
    polyline: Any,
    time_index: int,
    sample_spacing: Optional[float] = None,
    terrain_raster: Optional[Union[str, Path]] = None,
    ras_object: Optional[Any] = None,
) -> pd.DataFrame:
    """Extract RAS Mapper WSE/depth/terrain samples along a profile line."""
    polyline_xy, geom_hdf_path, spacing, terrain_hdf_path = _polyline_profile_inputs(
        hdf_path,
        polyline,
        sample_spacing,
        terrain_raster,
        ras_object,
    )
    from ..dotnet._profile_interop import query_polyline_wse

    profile_data = query_polyline_wse(
        hdf_path,
        polyline_xy,
        time_index,
        sample_spacing=spacing,
        geometry_hdf_path=geom_hdf_path,
        terrain_hdf_path=terrain_hdf_path,
    )
    columns = [
        "station",
        "x",
        "y",
        "mesh_name",
        "face_id",
        "wse",
        "depth",
        "terrain_elev",
    ]
    return _profile_dataframe(
        profile_data,
        columns,
        hdf_path,
        geom_hdf_path,
        spacing,
        "wse_source",
        "RasMapperLib.Render.WaterSurfaceRenderer",
    )

query_polyline_velocity_profile staticmethod

Python
query_polyline_velocity_profile(hdf_path: Path, polyline: Any, time_index: int, sample_spacing: Optional[float] = None, terrain_raster: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None) -> pd.DataFrame

Extract RAS Mapper velocity/depth/terrain samples along a profile line.

This method delegates velocity computation to RasMapperLib.Render.VelocityRenderer.Compute through pythonnet.

Returns:

Type Description
DataFrame

DataFrame with station, x, y, mesh_name, face_id, velocity_x,

DataFrame

velocity_y, velocity_mag, depth, and terrain_elev columns.

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_polyline_velocity_profile(
    hdf_path: Path,
    polyline: Any,
    time_index: int,
    sample_spacing: Optional[float] = None,
    terrain_raster: Optional[Union[str, Path]] = None,
    ras_object: Optional[Any] = None,
) -> pd.DataFrame:
    """
    Extract RAS Mapper velocity/depth/terrain samples along a profile line.

    This method delegates velocity computation to
    ``RasMapperLib.Render.VelocityRenderer.Compute`` through pythonnet.

    Returns:
        DataFrame with station, x, y, mesh_name, face_id, velocity_x,
        velocity_y, velocity_mag, depth, and terrain_elev columns.
    """
    if isinstance(time_index, str) and time_index.strip().lower() == "max":
        raise ValueError(
            "time_index='max' is not supported for RAS Mapper velocity "
            "profile extraction; pass a concrete profile index or name."
        )

    polyline_xy, geom_hdf_path, spacing, terrain_hdf_path = _polyline_profile_inputs(
        hdf_path,
        polyline,
        sample_spacing,
        terrain_raster,
        ras_object,
    )

    from ..dotnet._profile_interop import query_polyline_velocity

    profile_data = query_polyline_velocity(
        hdf_path,
        polyline_xy,
        time_index,
        sample_spacing=spacing,
        geometry_hdf_path=geom_hdf_path,
        terrain_hdf_path=terrain_hdf_path,
    )

    columns = [
        "station",
        "x",
        "y",
        "mesh_name",
        "face_id",
        "velocity_x",
        "velocity_y",
        "velocity_mag",
        "depth",
        "terrain_elev",
    ]
    return _profile_dataframe(
        profile_data,
        columns,
        hdf_path,
        geom_hdf_path,
        spacing,
        "velocity_source",
        "RasMapperLib.Render.VelocityRenderer",
    )

query_polyline_flow_profile staticmethod

Python
query_polyline_flow_profile(hdf_path: Path, polyline: Any, time_index: int, sample_spacing: Optional[float] = None, terrain_raster: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None) -> pd.DataFrame

Extract RAS Mapper flow/depth/terrain samples along a profile line.

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_polyline_flow_profile(
    hdf_path: Path,
    polyline: Any,
    time_index: int,
    sample_spacing: Optional[float] = None,
    terrain_raster: Optional[Union[str, Path]] = None,
    ras_object: Optional[Any] = None,
) -> pd.DataFrame:
    """Extract RAS Mapper flow/depth/terrain samples along a profile line."""
    polyline_xy, geom_hdf_path, spacing, terrain_hdf_path = _polyline_profile_inputs(
        hdf_path,
        polyline,
        sample_spacing,
        terrain_raster,
        ras_object,
    )
    from ..dotnet._profile_interop import query_polyline_flow

    profile_data = query_polyline_flow(
        hdf_path,
        polyline_xy,
        time_index,
        sample_spacing=spacing,
        geometry_hdf_path=geom_hdf_path,
        terrain_hdf_path=terrain_hdf_path,
    )
    columns = [
        "station",
        "x",
        "y",
        "mesh_name",
        "face_id",
        "flow",
        "depth",
        "terrain_elev",
    ]
    return _profile_dataframe(
        profile_data,
        columns,
        hdf_path,
        geom_hdf_path,
        spacing,
        "flow_source",
        "RasMapperLib.Render.FlowRenderer",
    )

query_polyline_wse_timeseries staticmethod

Python
query_polyline_wse_timeseries(hdf_path: Path, polyline: Any, time_range: Optional[tuple[int, int]] = None, sample_spacing: Optional[float] = None, terrain_raster: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None, wide: bool = False) -> pd.DataFrame

Extract RAS Mapper WSE time series along a profile line.

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_polyline_wse_timeseries(
    hdf_path: Path,
    polyline: Any,
    time_range: Optional[tuple[int, int]] = None,
    sample_spacing: Optional[float] = None,
    terrain_raster: Optional[Union[str, Path]] = None,
    ras_object: Optional[Any] = None,
    wide: bool = False,
) -> pd.DataFrame:
    """Extract RAS Mapper WSE time series along a profile line."""
    polyline_xy, geom_hdf_path, spacing, terrain_hdf_path = _polyline_profile_inputs(
        hdf_path,
        polyline,
        sample_spacing,
        terrain_raster,
        ras_object,
    )
    from ..dotnet._profile_interop import query_polyline_wse_timeseries

    profile_data = query_polyline_wse_timeseries(
        hdf_path,
        polyline_xy,
        time_range=time_range,
        sample_spacing=spacing,
        geometry_hdf_path=geom_hdf_path,
        terrain_hdf_path=terrain_hdf_path,
    )
    columns = [
        "time_index",
        "time",
        "station",
        "x",
        "y",
        "mesh_name",
        "face_id",
        "wse",
        "depth",
        "terrain_elev",
    ]
    return _timeseries_dataframe(
        profile_data,
        columns,
        hdf_path,
        geom_hdf_path,
        spacing,
        "wse_source",
        "RasMapperLib.Render.WaterSurfaceTimeSeries",
        "wse",
        wide,
    )

query_polyline_velocity_timeseries staticmethod

Python
query_polyline_velocity_timeseries(hdf_path: Path, polyline: Any, time_range: Optional[tuple[int, int]] = None, sample_spacing: Optional[float] = None, terrain_raster: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None, wide: bool = False) -> pd.DataFrame

Extract RAS Mapper velocity time series along a profile line.

time_range uses Python slicing semantics: (start, stop) includes start and excludes stop. None returns all profiles.

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_polyline_velocity_timeseries(
    hdf_path: Path,
    polyline: Any,
    time_range: Optional[tuple[int, int]] = None,
    sample_spacing: Optional[float] = None,
    terrain_raster: Optional[Union[str, Path]] = None,
    ras_object: Optional[Any] = None,
    wide: bool = False,
) -> pd.DataFrame:
    """
    Extract RAS Mapper velocity time series along a profile line.

    ``time_range`` uses Python slicing semantics: ``(start, stop)`` includes
    ``start`` and excludes ``stop``. ``None`` returns all profiles.
    """
    polyline_xy, geom_hdf_path, spacing, terrain_hdf_path = _polyline_profile_inputs(
        hdf_path,
        polyline,
        sample_spacing,
        terrain_raster,
        ras_object,
    )
    from ..dotnet._profile_interop import query_polyline_velocity_timeseries

    profile_data = query_polyline_velocity_timeseries(
        hdf_path,
        polyline_xy,
        time_range=time_range,
        sample_spacing=spacing,
        geometry_hdf_path=geom_hdf_path,
        terrain_hdf_path=terrain_hdf_path,
    )
    columns = [
        "time_index",
        "time",
        "station",
        "x",
        "y",
        "mesh_name",
        "face_id",
        "velocity_x",
        "velocity_y",
        "velocity_mag",
        "depth",
        "terrain_elev",
    ]
    return _timeseries_dataframe(
        profile_data,
        columns,
        hdf_path,
        geom_hdf_path,
        spacing,
        "velocity_source",
        "RasMapperLib.Render.VelocityTimeSeries",
        "velocity_mag",
        wide,
    )

query_polyline_flow_timeseries staticmethod

Python
query_polyline_flow_timeseries(hdf_path: Path, polyline: Any, time_range: Optional[tuple[int, int]] = None, sample_spacing: Optional[float] = None, terrain_raster: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None, wide: bool = False) -> pd.DataFrame

Extract RAS Mapper flow time series along a profile line.

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_polyline_flow_timeseries(
    hdf_path: Path,
    polyline: Any,
    time_range: Optional[tuple[int, int]] = None,
    sample_spacing: Optional[float] = None,
    terrain_raster: Optional[Union[str, Path]] = None,
    ras_object: Optional[Any] = None,
    wide: bool = False,
) -> pd.DataFrame:
    """Extract RAS Mapper flow time series along a profile line."""
    polyline_xy, geom_hdf_path, spacing, terrain_hdf_path = _polyline_profile_inputs(
        hdf_path,
        polyline,
        sample_spacing,
        terrain_raster,
        ras_object,
    )
    from ..dotnet._profile_interop import query_polyline_flow_timeseries

    profile_data = query_polyline_flow_timeseries(
        hdf_path,
        polyline_xy,
        time_range=time_range,
        sample_spacing=spacing,
        geometry_hdf_path=geom_hdf_path,
        terrain_hdf_path=terrain_hdf_path,
    )
    columns = [
        "time_index",
        "time",
        "station",
        "x",
        "y",
        "mesh_name",
        "face_id",
        "flow",
        "depth",
        "terrain_elev",
    ]
    return _timeseries_dataframe(
        profile_data,
        columns,
        hdf_path,
        geom_hdf_path,
        spacing,
        "flow_source",
        "RasMapperLib.Render.FlowRenderer",
        "flow",
        wide,
    )

query_polyline_wse_difference staticmethod

Python
query_polyline_wse_difference(base_hdf_path: Path, compare_hdf_path: Path, polyline: Any, time_index: int, sample_spacing: Optional[float] = None, terrain_raster: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None) -> pd.DataFrame

Compare RAS Mapper water-surface profiles between two plan HDFs.

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_polyline_wse_difference(
    base_hdf_path: Path,
    compare_hdf_path: Path,
    polyline: Any,
    time_index: int,
    sample_spacing: Optional[float] = None,
    terrain_raster: Optional[Union[str, Path]] = None,
    ras_object: Optional[Any] = None,
) -> pd.DataFrame:
    """Compare RAS Mapper water-surface profiles between two plan HDFs."""
    base_hdf_path = _resolve_plan_hdf_input(
        base_hdf_path,
        ras_object=ras_object,
    )
    compare_hdf_path = _resolve_plan_hdf_input(
        compare_hdf_path,
        ras_object=ras_object,
    )
    polyline_xy, geom_hdf_path, spacing, terrain_hdf_path = _polyline_profile_inputs(
        base_hdf_path,
        polyline,
        sample_spacing,
        terrain_raster,
        ras_object,
    )
    from ..dotnet._profile_interop import query_polyline_wse_difference

    profile_data = query_polyline_wse_difference(
        base_hdf_path,
        compare_hdf_path,
        polyline_xy,
        time_index,
        sample_spacing=spacing,
        geometry_hdf_path=geom_hdf_path,
        terrain_hdf_path=terrain_hdf_path,
    )
    columns = [
        "station",
        "x",
        "y",
        "mesh_name",
        "face_id",
        "wse_base",
        "wse_compare",
        "wse_delta",
    ]
    return _profile_dataframe(
        profile_data,
        columns,
        base_hdf_path,
        geom_hdf_path,
        spacing,
        "wse_difference_source",
        "RasMapperLib.Render.WaterSurfaceDifferenceRenderer",
    )

query_polyline_velocity_difference staticmethod

Python
query_polyline_velocity_difference(base_hdf_path: Path, compare_hdf_path: Path, polyline: Any, time_index: int, sample_spacing: Optional[float] = None, terrain_raster: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None) -> pd.DataFrame

Compare RAS Mapper velocity profiles between two plan HDFs.

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_polyline_velocity_difference(
    base_hdf_path: Path,
    compare_hdf_path: Path,
    polyline: Any,
    time_index: int,
    sample_spacing: Optional[float] = None,
    terrain_raster: Optional[Union[str, Path]] = None,
    ras_object: Optional[Any] = None,
) -> pd.DataFrame:
    """Compare RAS Mapper velocity profiles between two plan HDFs."""
    base_hdf_path = _resolve_plan_hdf_input(
        base_hdf_path,
        ras_object=ras_object,
    )
    compare_hdf_path = _resolve_plan_hdf_input(
        compare_hdf_path,
        ras_object=ras_object,
    )
    polyline_xy, geom_hdf_path, spacing, terrain_hdf_path = _polyline_profile_inputs(
        base_hdf_path,
        polyline,
        sample_spacing,
        terrain_raster,
        ras_object,
    )
    from ..dotnet._profile_interop import query_polyline_velocity_difference

    profile_data = query_polyline_velocity_difference(
        base_hdf_path,
        compare_hdf_path,
        polyline_xy,
        time_index,
        sample_spacing=spacing,
        geometry_hdf_path=geom_hdf_path,
        terrain_hdf_path=terrain_hdf_path,
    )
    columns = [
        "station",
        "x",
        "y",
        "mesh_name",
        "face_id",
        "velocity_x_base",
        "velocity_y_base",
        "velocity_mag_base",
        "velocity_x_compare",
        "velocity_y_compare",
        "velocity_mag_compare",
        "velocity_x_delta",
        "velocity_y_delta",
        "velocity_mag_delta",
    ]
    return _profile_dataframe(
        profile_data,
        columns,
        base_hdf_path,
        geom_hdf_path,
        spacing,
        "velocity_difference_source",
        "RasMapperLib.Render.VelocityDifferenceRenderer",
    )

query_polyline_pipe_velocity_profile staticmethod

Python
query_polyline_pipe_velocity_profile(hdf_path: Path, polyline: Any, time_index: int, sample_spacing: Optional[float] = None, terrain_raster: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None) -> pd.DataFrame

Extract RAS Mapper pipe velocity samples along a profile line.

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_polyline_pipe_velocity_profile(
    hdf_path: Path,
    polyline: Any,
    time_index: int,
    sample_spacing: Optional[float] = None,
    terrain_raster: Optional[Union[str, Path]] = None,
    ras_object: Optional[Any] = None,
) -> pd.DataFrame:
    """Extract RAS Mapper pipe velocity samples along a profile line."""
    polyline_xy, geom_hdf_path, spacing, terrain_hdf_path = _polyline_profile_inputs(
        hdf_path,
        polyline,
        sample_spacing,
        terrain_raster,
        ras_object,
    )
    from ..dotnet._profile_interop import query_polyline_pipe_velocity

    profile_data = query_polyline_pipe_velocity(
        hdf_path,
        polyline_xy,
        time_index,
        sample_spacing=spacing,
        geometry_hdf_path=geom_hdf_path,
        terrain_hdf_path=terrain_hdf_path,
    )
    columns = [
        "station",
        "x",
        "y",
        "mesh_name",
        "face_id",
        "velocity_mag",
        "depth",
        "terrain_elev",
    ]
    return _profile_dataframe(
        profile_data,
        columns,
        hdf_path,
        geom_hdf_path,
        spacing,
        "velocity_source",
        "RasMapperLib.Render.VelocityRendererPipe",
    )

query_polyline_pipe_flow_profile staticmethod

Python
query_polyline_pipe_flow_profile(hdf_path: Path, polyline: Any, time_index: int, sample_spacing: Optional[float] = None, terrain_raster: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None) -> pd.DataFrame

Extract RAS Mapper pipe flow samples along a profile line.

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_polyline_pipe_flow_profile(
    hdf_path: Path,
    polyline: Any,
    time_index: int,
    sample_spacing: Optional[float] = None,
    terrain_raster: Optional[Union[str, Path]] = None,
    ras_object: Optional[Any] = None,
) -> pd.DataFrame:
    """Extract RAS Mapper pipe flow samples along a profile line."""
    polyline_xy, geom_hdf_path, spacing, terrain_hdf_path = _polyline_profile_inputs(
        hdf_path,
        polyline,
        sample_spacing,
        terrain_raster,
        ras_object,
    )
    from ..dotnet._profile_interop import query_polyline_pipe_flow

    profile_data = query_polyline_pipe_flow(
        hdf_path,
        polyline_xy,
        time_index,
        sample_spacing=spacing,
        geometry_hdf_path=geom_hdf_path,
        terrain_hdf_path=terrain_hdf_path,
    )
    columns = [
        "station",
        "x",
        "y",
        "mesh_name",
        "face_id",
        "flow",
        "depth",
        "terrain_elev",
    ]
    return _profile_dataframe(
        profile_data,
        columns,
        hdf_path,
        geom_hdf_path,
        spacing,
        "flow_source",
        "RasMapperLib.Render.FlowRendererPipe",
    )

query_polyline_pipe_velocity_timeseries staticmethod

Python
query_polyline_pipe_velocity_timeseries(hdf_path: Path, polyline: Any, time_range: Optional[tuple[int, int]] = None, sample_spacing: Optional[float] = None, terrain_raster: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None, wide: bool = False) -> pd.DataFrame

Extract RAS Mapper pipe velocity time series along a profile line.

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_polyline_pipe_velocity_timeseries(
    hdf_path: Path,
    polyline: Any,
    time_range: Optional[tuple[int, int]] = None,
    sample_spacing: Optional[float] = None,
    terrain_raster: Optional[Union[str, Path]] = None,
    ras_object: Optional[Any] = None,
    wide: bool = False,
) -> pd.DataFrame:
    """Extract RAS Mapper pipe velocity time series along a profile line."""
    polyline_xy, geom_hdf_path, spacing, terrain_hdf_path = _polyline_profile_inputs(
        hdf_path,
        polyline,
        sample_spacing,
        terrain_raster,
        ras_object,
    )
    from ..dotnet._profile_interop import query_polyline_pipe_velocity_timeseries

    profile_data = query_polyline_pipe_velocity_timeseries(
        hdf_path,
        polyline_xy,
        time_range=time_range,
        sample_spacing=spacing,
        geometry_hdf_path=geom_hdf_path,
        terrain_hdf_path=terrain_hdf_path,
    )
    columns = [
        "time_index",
        "time",
        "station",
        "x",
        "y",
        "mesh_name",
        "face_id",
        "velocity_mag",
        "depth",
        "terrain_elev",
    ]
    return _timeseries_dataframe(
        profile_data,
        columns,
        hdf_path,
        geom_hdf_path,
        spacing,
        "velocity_source",
        "RasMapperLib.Render.VelocityPipeTimeSeries",
        "velocity_mag",
        wide,
    )

query_polyline_pipe_flow_timeseries staticmethod

Python
query_polyline_pipe_flow_timeseries(hdf_path: Path, polyline: Any, time_range: Optional[tuple[int, int]] = None, sample_spacing: Optional[float] = None, terrain_raster: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None, wide: bool = False) -> pd.DataFrame

Extract RAS Mapper pipe flow time series along a profile line.

Source code in ras_commander/hdf/HdfResultsQuery.py
Python
@staticmethod
@log_call
@standardize_input(file_type="plan_hdf")
def query_polyline_pipe_flow_timeseries(
    hdf_path: Path,
    polyline: Any,
    time_range: Optional[tuple[int, int]] = None,
    sample_spacing: Optional[float] = None,
    terrain_raster: Optional[Union[str, Path]] = None,
    ras_object: Optional[Any] = None,
    wide: bool = False,
) -> pd.DataFrame:
    """Extract RAS Mapper pipe flow time series along a profile line."""
    polyline_xy, geom_hdf_path, spacing, terrain_hdf_path = _polyline_profile_inputs(
        hdf_path,
        polyline,
        sample_spacing,
        terrain_raster,
        ras_object,
    )
    from ..dotnet._profile_interop import query_polyline_pipe_flow_timeseries

    profile_data = query_polyline_pipe_flow_timeseries(
        hdf_path,
        polyline_xy,
        time_range=time_range,
        sample_spacing=spacing,
        geometry_hdf_path=geom_hdf_path,
        terrain_hdf_path=terrain_hdf_path,
    )
    columns = [
        "time_index",
        "time",
        "station",
        "x",
        "y",
        "mesh_name",
        "face_id",
        "flow",
        "depth",
        "terrain_elev",
    ]
    return _timeseries_dataframe(
        profile_data,
        columns,
        hdf_path,
        geom_hdf_path,
        spacing,
        "flow_source",
        "RasMapperLib.Render.FlowPipeTimeSeries",
        "flow",
        wide,
    )

Recorded reference hydrographs

These methods read HDF datasets recorded during computation, including 2D reference results despite the class name. An absent group or no matching numeric variables produces an empty Dataset; a present group missing required Name or timestamps raises KeyError. Missing or malformed output is not zero flow. Use list(result.data_vars) to discover available variables and retain their unit/source attributes. Feature names are coordinates, not necessarily xarray indexes; use isel(refln_id=...) or explicit coordinate filtering instead of assuming .sel(refln_name=...) works.

A static class for extracting and processing 1D results data from HEC-RAS HDF files.

This class provides methods to extract and process unsteady flow simulation results for cross-sections, reference lines, and reference points. All methods are static and designed to be used without class instantiation.

The class handles: - Cross-section timeseries (water surface, velocity, flow) - Reference line timeseries - Reference point timeseries

Dependencies
  • HdfBase: Core HDF file operations
  • HdfUtils: Utility functions for HDF processing

get_ref_lines_timeseries staticmethod

Python
get_ref_lines_timeseries(hdf_path: Path, variables: Optional[Union[str, Sequence[str]]] = None) -> xr.Dataset

Extract timeseries output data for reference lines from HEC-RAS HDF file.

Parameters:

hdf_path : Path Path to the HEC-RAS results HDF file variables : str or sequence of str, optional HDF dataset names to include. If omitted, all numeric datasets with shape (time, reference_line) are returned.

Returns:

xr.Dataset Dataset containing numeric native HDF time-series data for reference lines. Returns empty dataset if reference line data not found.

Raises:

FileNotFoundError If the specified HDF file is not found KeyError If required datasets are missing from the HDF file

Source code in ras_commander/hdf/HdfResultsXsec.py
Python
@staticmethod
@log_call
@standardize_input(file_type='plan_hdf')
def get_ref_lines_timeseries(
    hdf_path: Path,
    variables: Optional[Union[str, Sequence[str]]] = None
) -> xr.Dataset:
    """
    Extract timeseries output data for reference lines from HEC-RAS HDF file.

    Parameters:
    -----------
    hdf_path : Path
        Path to the HEC-RAS results HDF file
    variables : str or sequence of str, optional
        HDF dataset names to include. If omitted, all numeric datasets with
        shape (time, reference_line) are returned.

    Returns:
    --------
    xr.Dataset
        Dataset containing numeric native HDF time-series data for reference lines.
        Returns empty dataset if reference line data not found.

    Raises:
    -------
    FileNotFoundError
        If the specified HDF file is not found
    KeyError
        If required datasets are missing from the HDF file
    """
    return HdfResultsXsec._reference_timeseries_output(
        hdf_path,
        reftype="lines",
        variables=variables,
    )

get_ref_points_timeseries staticmethod

Python
get_ref_points_timeseries(hdf_path: Path, variables: Optional[Union[str, Sequence[str]]] = None) -> xr.Dataset

Extract timeseries output data for reference points from HEC-RAS HDF file.

This method extracts flow, velocity, and water surface elevation data for all reference points defined in the model. Reference points are user-defined locations where detailed output is desired.

Parameters:

hdf_path : Path Path to the HEC-RAS results HDF file variables : str or sequence of str, optional HDF dataset names to include. If omitted, all numeric datasets with shape (time, reference_point) are returned.

Returns:

xr.Dataset Dataset containing numeric native HDF time-series variables for each reference point.

Text Only
The dataset includes coordinates:
- time: Simulation timesteps
- refpt_id: Unique identifier for each reference point
- refpt_name: Name of each reference point
- mesh_name: Associated 2D mesh area name

Returns empty dataset if reference point data not found.
Raises:

FileNotFoundError If the specified HDF file is not found KeyError If required datasets are missing from the HDF file

Examples:

ds = HdfResultsXsec.get_ref_points_timeseries("path/to/plan.hdf")

Get water surface timeseries for first reference point

ws = ds['Water Surface'].isel(refpt_id=0)

Get all data for a specific reference point by name

point_data = ds.where(ds['refpt_name'] == 'Point1', drop=True)

Source code in ras_commander/hdf/HdfResultsXsec.py
Python
@staticmethod
@log_call
@standardize_input(file_type='plan_hdf')
def get_ref_points_timeseries(
    hdf_path: Path,
    variables: Optional[Union[str, Sequence[str]]] = None
) -> xr.Dataset:
    """
    Extract timeseries output data for reference points from HEC-RAS HDF file.

    This method extracts flow, velocity, and water surface elevation data for all
    reference points defined in the model. Reference points are user-defined locations
    where detailed output is desired.

    Parameters:
    -----------
    hdf_path : Path
        Path to the HEC-RAS results HDF file
    variables : str or sequence of str, optional
        HDF dataset names to include. If omitted, all numeric datasets with
        shape (time, reference_point) are returned.

    Returns:
    --------
    xr.Dataset
        Dataset containing numeric native HDF time-series variables for each
        reference point.

        The dataset includes coordinates:
        - time: Simulation timesteps
        - refpt_id: Unique identifier for each reference point
        - refpt_name: Name of each reference point
        - mesh_name: Associated 2D mesh area name

        Returns empty dataset if reference point data not found.

    Raises:
    -------
    FileNotFoundError
        If the specified HDF file is not found
    KeyError
        If required datasets are missing from the HDF file

    Examples:
    --------
    >>> ds = HdfResultsXsec.get_ref_points_timeseries("path/to/plan.hdf")
    >>> # Get water surface timeseries for first reference point
    >>> ws = ds['Water Surface'].isel(refpt_id=0)
    >>> # Get all data for a specific reference point by name
    >>> point_data = ds.where(ds['refpt_name'] == 'Point1', drop=True)
    """
    return HdfResultsXsec._reference_timeseries_output(
        hdf_path,
        reftype="points",
        variables=variables,
    )

For a tidy DataFrame instead of xarray, use HdfResultsPlan.get_reference_timeseries(hdf_path, reftype="lines") (or "points"). It delegates to the reference readers and returns one row per stored time/feature pair. An empty DataFrame can mean missing output or a caught read error; inspect logged diagnostics rather than interpreting absence as zero flow or stage.

Handles extraction of results data from HEC-RAS plan HDF files.

This class provides static methods for accessing and analyzing
  • Unsteady flow results
  • Volume accounting data
  • Runtime statistics
  • Reference line/point time series outputs
All methods use
  • @standardize_input decorator for consistent file path handling
  • @log_call decorator for operation logging
  • HdfUtils class for common HDF operations
Note

No instantiation required - all methods are static.

get_reference_timeseries staticmethod

Python
get_reference_timeseries(hdf_path: Path, reftype: str) -> pd.DataFrame

Get reference-line or reference-point time series as a tidy DataFrame.

Modern HEC-RAS HDF files store a Name vector plus shared (time, feature) matrices such as Flow, Velocity, and Water Surface. This compatibility method delegates schema handling to :class:HdfResultsXsec and converts its native xarray Dataset to one row per time/feature pair. It therefore supports all numeric variables present in the HDF instead of assuming one dataset per feature.

Parameters:

Name Type Description Default
hdf_path Path

Path to HEC-RAS plan HDF file

required
reftype str

Type of reference data ('lines' or 'points')

required

Returns:

Type Description
DataFrame

Tidy frame containing time, reference ID/name, mesh name, and every numeric native result variable. Returns an empty frame when the requested reference output is absent or an error is caught, including an invalid reftype. Inspect log diagnostics; an empty result is not a zero-valued hydrograph.

Source code in ras_commander/hdf/HdfResultsPlan.py
Python
@staticmethod
@log_call
@standardize_input(file_type='plan_hdf')
def get_reference_timeseries(hdf_path: Path, reftype: str) -> pd.DataFrame:
    """
    Get reference-line or reference-point time series as a tidy DataFrame.

    Modern HEC-RAS HDF files store a ``Name`` vector plus shared
    ``(time, feature)`` matrices such as Flow, Velocity, and Water Surface.
    This compatibility method delegates schema handling to
    :class:`HdfResultsXsec` and converts its native xarray Dataset to one
    row per time/feature pair. It therefore supports all numeric variables
    present in the HDF instead of assuming one dataset per feature.

    Args:
        hdf_path (Path): Path to HEC-RAS plan HDF file
        reftype (str): Type of reference data ('lines' or 'points')

    Returns:
        pd.DataFrame: Tidy frame containing time, reference ID/name, mesh
            name, and every numeric native result variable. Returns an
            empty frame when the requested reference output is absent or
            an error is caught, including an invalid reftype. Inspect log
            diagnostics; an empty result is not a zero-valued hydrograph.
    """
    try:
        from .HdfResultsXsec import HdfResultsXsec

        normalized = str(reftype).strip().lower()
        if normalized == "lines":
            dataset = HdfResultsXsec.get_ref_lines_timeseries(hdf_path)
        elif normalized == "points":
            dataset = HdfResultsXsec.get_ref_points_timeseries(hdf_path)
        else:
            raise ValueError("reftype must be 'lines' or 'points'")

        if not dataset.data_vars:
            logger.debug(
                "Reference %s data not found in %s",
                normalized,
                Path(hdf_path).name,
            )
            return pd.DataFrame()
        return dataset.to_dataframe().reset_index()

    except Exception as e:
        reraise_required(e)
        logger.error(f"Error reading reference {reftype} timeseries: {str(e)}")
        return pd.DataFrame()

Named-line Q and extraction provenance

The canonical method needs RasMapperLib. It first attempts a native-associated precomputed hydrograph via ObservedDataLayer.TryReadRefLineFlow, then falls back to face aggregation. This native-associated hydrograph's provenance has not been independently qualified as solver output and may be observed data. Use HdfResultsXsec.get_ref_lines_timeseries for explicit solver-recorded HDF Reference Lines datasets. Inspect selection_source in the returned DataFrame: try_read_ref_line_flow is distinct from reference_line_internal_faces and rasmapper_perimeter_faces.

For native-associated hydrographs, direction="absolute" takes abs(Q); for aggregated faces it sums abs(Q_face). The latter is not a net flux. The signed face fallback sums native face signs without a common line-normal correction or solver projected-length weighting. _legacy is the explicit offline path, not an automatic fallback when the native runtime is unavailable. The workflow guide provides the interpretation table. The native-associated lookup is by name only, so duplicate names across meshes are ambiguous. Its face_count=0 and empty face_ids identify the lookup path, not a physical face count; an omitted mesh_name is reported as an empty string.

Handles mesh-related results from HEC-RAS HDF files.

Provides methods to extract and analyze: - Mesh summary outputs - Timeseries data - Water surface elevations - Velocities - Error metrics

Works with HEC-RAS 6.0+ plan HDF files.

get_profile_line_flow_timeseries staticmethod

Python
get_profile_line_flow_timeseries(hdf_path: Path, line_name: str, mesh_name: Optional[str] = None, profile_lines_path: Optional[Union[str, Path]] = None, direction: str = 'absolute', truncate: bool = False, ras_object: Optional[Any] = None) -> pd.DataFrame

Return a flow time series across a RAS Mapper profile/reference line.

Recorded computed reference-line Flow is read first through HdfResultsXsec.get_ref_lines_timeseries(), without pythonnet or face-output requirements. Observed Event Conditions data is not used. Otherwise native reference-line faces and ad-hoc profile lines are read through RASResults.ReadUnsteadyTimeSeries() after selecting ad-hoc faces with MeshFV2D.PerimeterFacesAlongPolyline().

Parameters:

Name Type Description Default
hdf_path Path

Completed plan HDF, with the matching geometry available.

required
line_name str

Exact reference-line or profile-layer feature name.

required
mesh_name Optional[str]

Optional 2D flow area selector.

None
profile_lines_path Optional[Union[str, Path]]

Optional external profile-line layer. Coordinates must match the model CRS; project metadata can resolve this path.

None
direction str

"absolute" takes the absolute value of a recorded reference hydrograph, but sums absolute face flows in a fallback branch. "signed" preserves the recorded hydrograph sign, or sums native face-normal signs without line-orientation correction in a fallback. These are not interchangeable fluxes.

'absolute'
truncate bool

Trim leading and trailing zero-flow samples when true.

False
ras_object RasPrj

Optional initialized project context.

None

Returns:

Type Description
DataFrame

DataFrame with time, flow, line_name, mesh_name,

DataFrame

direction, face_count and selection_source. Attributes

include units, variable and face IDs. Preserve this provenance
DataFrame

reference_line_recorded_flow identifies the computed HDF

DataFrame

reference matrix, with its dataset path and reference ID in attrs;

DataFrame

face-selection routes identify

DataFrame

aggregation of stored face output, not a new solver calculation.

DataFrame

Missing units are not inferred.

Notes

Face fallbacks require pythonnet and compatible RasMapperLib. For an offline approximation use get_profile_line_flow_timeseries_legacy. To read recorded reference matrices directly without native mapping, use HdfResultsXsec.get_ref_lines_timeseries. Reading an HDF cannot create reference output that was not recorded by the model run.

Source code in ras_commander/hdf/HdfResultsMesh.py
Python
@staticmethod
@log_call
@standardize_input(file_type='plan_hdf')
def get_profile_line_flow_timeseries(
    hdf_path: Path,
    line_name: str,
    mesh_name: Optional[str] = None,
    profile_lines_path: Optional[Union[str, Path]] = None,
    direction: str = "absolute",
    truncate: bool = False,
    ras_object: Optional[Any] = None,
) -> pd.DataFrame:
    """
    Return a flow time series across a RAS Mapper profile/reference line.

    Recorded computed reference-line Flow is read first through
    ``HdfResultsXsec.get_ref_lines_timeseries()``, without pythonnet or
    face-output requirements. Observed Event Conditions data is not used.
    Otherwise native reference-line faces and ad-hoc profile lines are read through
    ``RASResults.ReadUnsteadyTimeSeries()`` after selecting ad-hoc faces
    with ``MeshFV2D.PerimeterFacesAlongPolyline()``.

    Args:
        hdf_path: Completed plan HDF, with the matching geometry available.
        line_name: Exact reference-line or profile-layer feature name.
        mesh_name: Optional 2D flow area selector.
        profile_lines_path: Optional external profile-line layer. Coordinates
            must match the model CRS; project metadata can resolve this path.
        direction: ``"absolute"`` takes the absolute value of a recorded
            reference hydrograph, but sums absolute face flows in a fallback
            branch. ``"signed"`` preserves the recorded hydrograph sign,
            or sums native face-normal signs without line-orientation
            correction in a fallback. These are not interchangeable fluxes.
        truncate: Trim leading and trailing zero-flow samples when true.
        ras_object (RasPrj, optional): Optional initialized project context.

    Returns:
        DataFrame with ``time``, ``flow``, ``line_name``, ``mesh_name``,
        ``direction``, ``face_count`` and ``selection_source``. Attributes
        include units, variable and face IDs. Preserve this provenance:
        ``reference_line_recorded_flow`` identifies the computed HDF
        reference matrix, with its dataset path and reference ID in attrs;
        face-selection routes identify
        aggregation of stored face output, not a new solver calculation.
        Missing units are not inferred.

    Notes:
        Face fallbacks require pythonnet and compatible RasMapperLib. For an
        offline approximation use ``get_profile_line_flow_timeseries_legacy``.
        To read recorded reference matrices directly without native mapping,
        use ``HdfResultsXsec.get_ref_lines_timeseries``. Reading an HDF cannot
        create reference output that was not recorded by the model run.
    """
    direction = HdfResultsMesh._normalize_profile_line_direction(direction)
    refline_flow = HdfResultsMesh._try_read_ref_line_flow_rasmapper(
        hdf_path=hdf_path,
        line_name=line_name,
        mesh_name=mesh_name,
        direction=direction,
    )
    if refline_flow is not None:
        return HdfResultsMesh._truncate_profile_line_flow_dataframe(
            refline_flow,
            truncate,
        )

    native_faces = HdfResultsMesh._get_native_profile_line_faces(
        hdf_path=hdf_path,
        line_name=line_name,
        mesh_name=mesh_name,
        ras_object=ras_object,
    )
    if not native_faces.empty:
        resolved_mesh_name = HdfResultsMesh._resolve_single_mesh_name(
            native_faces,
            mesh_name,
            line_name,
        )
        selected_faces = native_faces[native_faces["mesh_name"] == resolved_mesh_name]
        flow_df = HdfResultsMesh._read_rasmapper_face_flow_timeseries(
            hdf_path=hdf_path,
            line_name=line_name,
            mesh_name=resolved_mesh_name,
            face_ids=HdfResultsMesh._unique_int_values(selected_faces["face_id"]),
            direction=direction,
            selection_source="reference_line_internal_faces",
        )
        return HdfResultsMesh._truncate_profile_line_flow_dataframe(
            flow_df,
            truncate,
        )

    resolved_profile_lines_path = HdfResultsMesh._resolve_profile_lines_path(
        profile_lines_path=profile_lines_path,
        ras_object=ras_object,
    )
    if resolved_profile_lines_path is None:
        raise ValueError(
            f"Profile/reference line '{line_name}' was not found in native HDF "
            "reference lines, and no RAS Mapper profile-lines feature path could "
            "be resolved. Pass profile_lines_path or initialize a ras_object with "
            "rasmap_df."
        )

    reference_hdf_path = HdfResultsMesh._resolve_reference_line_hdf_path(
        hdf_path,
        ras_object=ras_object,
    )
    profile_line = HdfResultsMesh._read_profile_line_geometry(
        profile_lines_path=resolved_profile_lines_path,
        line_name=line_name,
    )
    selected_faces = HdfResultsMesh._get_rasmapper_perimeter_faces(
        geometry_hdf_path=reference_hdf_path,
        profile_line=profile_line,
        mesh_name=mesh_name,
        line_name=line_name,
    )
    resolved_mesh_name = HdfResultsMesh._resolve_single_mesh_name(
        selected_faces,
        mesh_name,
        line_name,
    )
    selected_faces = selected_faces[selected_faces["mesh_name"] == resolved_mesh_name]
    flow_df = HdfResultsMesh._read_rasmapper_face_flow_timeseries(
        hdf_path=hdf_path,
        line_name=line_name,
        mesh_name=resolved_mesh_name,
        face_ids=HdfResultsMesh._unique_int_values(selected_faces["face_id"]),
        direction=direction,
        selection_source="rasmapper_perimeter_faces",
    )
    return HdfResultsMesh._truncate_profile_line_flow_dataframe(
        flow_df,
        truncate,
    )

get_profile_line_flow_timeseries_legacy staticmethod

Python
get_profile_line_flow_timeseries_legacy(hdf_path: Path, line_name: str, mesh_name: Optional[str] = None, profile_lines_path: Optional[Union[str, Path]] = None, direction: str = 'absolute', truncate: bool = False, ras_object: Optional[Any] = None) -> pd.DataFrame

Return a legacy pure-Python profile/reference-line flow time series.

This method predates the pythonnet/RasMapperLib profile API. It selects native reference-line internal faces when available, otherwise reads a RAS Mapper Profile Lines feature file and uses HdfMesh.get_faces_along_profile_line() plus direct HDF Face Flow time series. Keep using it for offline analysis without a HEC-RAS install or to reproduce pre-CLB-852 results; it is retained for backward compatibility.

Parameters

hdf_path : Path Plan HDF path, plan number, or other input accepted by @standardize_input(file_type='plan_hdf'). line_name : str Profile/reference line name to extract. mesh_name : Optional[str], optional 2D flow area name. Required when the line resolves to more than one mesh area. profile_lines_path : Optional[Union[str, Path]], optional Explicit RAS Mapper Profile Lines feature path. If omitted, the method attempts to use ras_object.rasmap_df.profile_lines_path. direction : str, default "absolute" "absolute" sums absolute face flows to avoid face-normal sign cancellation. "signed" preserves native HEC-RAS face-flow signs; orientation is controlled by the underlying face normals. truncate : bool, default False Passed to get_mesh_timeseries(). ras_object : Optional[Any], optional RAS project object used for plan-number and rasmap path resolution.

Returns

pd.DataFrame Columns: time, flow, line_name, mesh_name, direction, face_count, and selection_source.

Source code in ras_commander/hdf/HdfResultsMesh.py
Python
@staticmethod
@log_call
@standardize_input(file_type='plan_hdf')
def get_profile_line_flow_timeseries_legacy(
    hdf_path: Path,
    line_name: str,
    mesh_name: Optional[str] = None,
    profile_lines_path: Optional[Union[str, Path]] = None,
    direction: str = "absolute",
    truncate: bool = False,
    ras_object: Optional[Any] = None,
) -> pd.DataFrame:
    """
    Return a legacy pure-Python profile/reference-line flow time series.

    This method predates the pythonnet/RasMapperLib profile API. It selects
    native reference-line internal faces when available, otherwise reads a
    RAS Mapper Profile Lines feature file and uses
    ``HdfMesh.get_faces_along_profile_line()`` plus direct HDF ``Face Flow``
    time series. Keep using it for offline analysis without a HEC-RAS
    install or to reproduce pre-CLB-852 results; it is retained for
    backward compatibility.

    Parameters
    ----------
    hdf_path : Path
        Plan HDF path, plan number, or other input accepted by
        ``@standardize_input(file_type='plan_hdf')``.
    line_name : str
        Profile/reference line name to extract.
    mesh_name : Optional[str], optional
        2D flow area name. Required when the line resolves to more than one
        mesh area.
    profile_lines_path : Optional[Union[str, Path]], optional
        Explicit RAS Mapper Profile Lines feature path. If omitted, the
        method attempts to use ``ras_object.rasmap_df.profile_lines_path``.
    direction : str, default "absolute"
        ``"absolute"`` sums absolute face flows to avoid face-normal sign
        cancellation. ``"signed"`` preserves native HEC-RAS face-flow signs;
        orientation is controlled by the underlying face normals.
    truncate : bool, default False
        Passed to ``get_mesh_timeseries()``.
    ras_object : Optional[Any], optional
        RAS project object used for plan-number and rasmap path resolution.

    Returns
    -------
    pd.DataFrame
        Columns: ``time``, ``flow``, ``line_name``, ``mesh_name``,
        ``direction``, ``face_count``, and ``selection_source``.
    """
    direction = HdfResultsMesh._normalize_profile_line_direction(direction)
    selected_faces, resolved_mesh_name, selection_source = (
        HdfResultsMesh._resolve_profile_line_faces(
            hdf_path=hdf_path,
            line_name=line_name,
            mesh_name=mesh_name,
            profile_lines_path=profile_lines_path,
            ras_object=ras_object,
        )
    )

    face_ids = HdfResultsMesh._unique_int_values(selected_faces['face_id'])
    if not face_ids:
        raise ValueError(f"No valid face IDs resolved for profile line '{line_name}'.")

    face_flow = HdfResultsMesh.get_mesh_timeseries(
        hdf_path,
        resolved_mesh_name,
        "Face Flow",
        truncate=truncate,
    )
    if "face_id" not in face_flow.coords:
        raise ValueError(
            f"Face Flow output for mesh '{resolved_mesh_name}' does not include face_id coordinates."
        )

    available_face_ids = {
        int(face_id) for face_id in face_flow.coords["face_id"].values.tolist()
    }
    missing_face_ids = [
        face_id for face_id in face_ids if face_id not in available_face_ids
    ]
    if missing_face_ids:
        preview = missing_face_ids[:10]
        more = "" if len(missing_face_ids) <= len(preview) else (
            f" and {len(missing_face_ids) - len(preview)} more"
        )
        raise ValueError(
            f"Face Flow output for mesh '{resolved_mesh_name}' is missing selected "
            f"face IDs: {preview}{more}"
        )

    selected_flow = face_flow.sel(face_id=face_ids)
    values = np.asarray(selected_flow.values, dtype=float)
    if values.ndim == 1:
        values = values.reshape((-1, 1))

    if direction == "absolute":
        flow = np.abs(values).sum(axis=1)
    else:
        flow = values.sum(axis=1)

    result = pd.DataFrame({
        "time": pd.to_datetime(face_flow.coords["time"].values),
        "flow": flow,
        "line_name": str(line_name),
        "mesh_name": resolved_mesh_name,
        "direction": direction,
        "face_count": len(face_ids),
        "selection_source": selection_source,
    })
    result.attrs["face_ids"] = face_ids
    result.attrs["units"] = face_flow.attrs.get("units", "")
    result.attrs["variable"] = "Face Flow"
    return result

get_profile_line_peak_flow staticmethod

Python
get_profile_line_peak_flow(hdf_path: Path, line_name: str, mesh_name: Optional[str] = None, profile_lines_path: Optional[Union[str, Path]] = None, direction: str = 'absolute', ras_object: Optional[Any] = None) -> pd.DataFrame

Return peak flow across a RAS Mapper profile/reference line.

For direction="absolute", the peak is the maximum of the selected extraction route's absolute-flow series: absolute recorded reference hydrograph flow or a sum of absolute face flows. Preserve selection_source to distinguish these quantities. For direction="signed", the peak timestep is selected by maximum signed-flow magnitude and the returned peak_flow preserves the native sign at that timestep. A peak from saved output times need not equal a peak over every computational timestep.

Source code in ras_commander/hdf/HdfResultsMesh.py
Python
@staticmethod
@log_call
@standardize_input(file_type='plan_hdf')
def get_profile_line_peak_flow(
    hdf_path: Path,
    line_name: str,
    mesh_name: Optional[str] = None,
    profile_lines_path: Optional[Union[str, Path]] = None,
    direction: str = "absolute",
    ras_object: Optional[Any] = None,
) -> pd.DataFrame:
    """
    Return peak flow across a RAS Mapper profile/reference line.

    For ``direction="absolute"``, the peak is the maximum of the selected
    extraction route's absolute-flow series: absolute recorded reference
    hydrograph flow or a sum of absolute face flows. Preserve ``selection_source`` to
    distinguish these quantities. For ``direction="signed"``, the peak timestep is selected by
    maximum signed-flow magnitude and the returned ``peak_flow`` preserves
    the native sign at that timestep. A peak from saved output times need
    not equal a peak over every computational timestep.
    """
    flow_df = HdfResultsMesh.get_profile_line_flow_timeseries(
        hdf_path=hdf_path,
        line_name=line_name,
        mesh_name=mesh_name,
        profile_lines_path=profile_lines_path,
        direction=direction,
        truncate=False,
        ras_object=ras_object,
    )
    if flow_df.empty:
        return pd.DataFrame(
            columns=[
                "line_name",
                "mesh_name",
                "peak_time",
                "peak_flow",
                "direction",
                "face_count",
                "selection_source",
            ]
        )

    peak_index = flow_df["flow"].abs().idxmax()
    peak_row = flow_df.loc[peak_index]
    return pd.DataFrame([{
        "line_name": peak_row["line_name"],
        "mesh_name": peak_row["mesh_name"],
        "peak_time": peak_row["time"],
        "peak_flow": peak_row["flow"],
        "direction": peak_row["direction"],
        "face_count": peak_row["face_count"],
        "selection_source": peak_row["selection_source"],
    }])

Reference-feature authoring

Generate proposed lines first, inspect them, then write to a working geometry. Recompute and inspect the resulting reference output groups. In particular, add_reference_points writes native Reference Point Name/Position records with literal names. Notebook 207 demonstrates a fresh 6.6 compute and native HDF reads. Example 314's retained historical IC-authored run is separate evidence. Authored point records plus a successful run do not guarantee recorded point results. A profile line used only for postprocessing does not retroactively become a recorded reference location. Reference areas are not covered by these point/line writers.

Insert reference lines and reference points into .g## geometry files.

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")

Source code in ras_commander/geom/GeomReferenceFeatures.py
Python
@staticmethod
@log_call
def 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 = 1.0e-6,
    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.

    Args:
        longitudinal_lines: A Shapely LineString, GeoDataFrame, coordinate
            array, dict with ``geometry``/``coordinates``, or list of those
            dicts. GeoDataFrame rows can be selected by name.
        spacing: Station interval along each longitudinal line, in model
            units.
        line_length: Generated transverse reference-line length, in model
            units.
        longitudinal_line_name: Optional name of the source line to select
            from GeoDataFrame/list inputs.
        name_column: Preferred source-name column for GeoDataFrame inputs.
        name_template: Format string for generated line names. Available
            fields are ``source_name``, ``index``, ``global_index``,
            ``station``, and ``station_int``.
        start_station: First station along the source line.
        end_station: Last station along the source line. Defaults to the
            source line length.
        include_end: Include ``end_station`` even when it is not on the
            regular spacing interval.
        tangent_sample_distance: Half-window used to compute the local
            tangent direction. Defaults to half the spacing.
        extend_by: Extra length added to each side of the generated line.
        orientation: ``"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``.
        orientation_plan_hdf: Plan/result HDF used when ``orientation`` is
            ``"velocity"`` or ``"depth_velocity"``.
        orientation_time_index: Time index passed to ``HdfResultsQuery``.
        orientation_query_method: Query method passed to ``HdfResultsQuery``.
        orientation_angle_callback: Optional callable receiving a context
            dict and returning a reference-line angle in degrees. Returning
            ``None`` keeps the normal or velocity-derived angle.
        orientation_fallback: ``"normal"`` or ``"raise"`` when sampled
            velocity/depth data are unavailable at a station.
        velocity_min: Minimum sampled velocity magnitude for velocity-based
            orientation.
        depth_min: Minimum sampled depth for ``"depth_velocity"``.
        ras_object: Optional ``RasPrj`` object for HDF result queries.
        storage_area: Optional 2D flow area name included in returned
            metadata for review.

    Returns:
        List of reference-line dictionaries. Each dictionary includes
        ``name`` and ``coordinates`` for writing, plus station/orientation
        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")
    """
    if line_length <= 0:
        raise ValueError(f"line_length must be positive, got {line_length}")
    if extend_by < 0:
        raise ValueError("extend_by must be non-negative")

    normalized_orientation = str(orientation).strip().lower()
    valid_orientations = {"normal", "velocity", "depth_velocity"}
    if normalized_orientation not in valid_orientations:
        raise ValueError(
            f"orientation must be one of {sorted(valid_orientations)}, "
            f"got '{orientation}'"
        )

    normalized_fallback = str(orientation_fallback).strip().lower()
    if normalized_fallback not in {"normal", "raise"}:
        raise ValueError("orientation_fallback must be 'normal' or 'raise'")

    if (
        normalized_orientation in {"velocity", "depth_velocity"}
        and orientation_plan_hdf is None
    ):
        raise ValueError(
            "orientation_plan_hdf is required for velocity-based orientation"
        )

    records = _coerce_longitudinal_line_records(
        longitudinal_lines,
        longitudinal_line_name,
        name_column,
    )

    generated_lines = []
    global_index = 1
    total_length = float(line_length) + 2.0 * float(extend_by)

    for record in records:
        source_name = str(record["name"])
        source_line = record["geometry"]
        source_length = float(source_line.length)
        stations = _station_values(
            source_length,
            float(spacing),
            float(start_station),
            end_station,
            bool(include_end),
        )
        if not stations:
            continue

        sample_distance = (
            float(tangent_sample_distance)
            if tangent_sample_distance is not None
            else max(float(spacing) / 2.0, source_length * 1.0e-6)
        )

        station_points = [
            source_line.interpolate(station) for station in stations
        ]
        velocity_samples = GeomReferenceFeatures._sample_velocity_orientation(
            station_points,
            orientation=normalized_orientation,
            orientation_plan_hdf=orientation_plan_hdf,
            orientation_time_index=orientation_time_index,
            orientation_query_method=orientation_query_method,
            orientation_fallback=normalized_fallback,
            velocity_min=velocity_min,
            depth_min=depth_min,
            ras_object=ras_object,
        )

        for line_index, (station, point) in enumerate(
            zip(stations, station_points),
            start=1,
        ):
            x, y = _point_xy(point)
            tangent_angle = _tangent_angle_degrees(
                source_line,
                station,
                sample_distance,
            )
            normal_angle = tangent_angle + 90.0
            selected_angle = normal_angle
            orientation_method = "normal"

            velocity_sample = velocity_samples[line_index - 1]
            velocity_angle = velocity_sample.get("orientation_angle")
            if velocity_angle is not None and np.isfinite(velocity_angle):
                selected_angle = float(velocity_angle)
                orientation_method = normalized_orientation
            elif normalized_orientation in {"velocity", "depth_velocity"}:
                if normalized_fallback == "raise":
                    raise ValueError(
                        "Velocity-based orientation was unavailable at "
                        f"station {station:g} on '{source_name}'"
                    )
                orientation_method = "normal_fallback"

            context = {
                "source_name": source_name,
                "source_geometry": source_line,
                "index": line_index,
                "global_index": global_index,
                "station": float(station),
                "point": point,
                "x": x,
                "y": y,
                "tangent_angle": float(tangent_angle),
                "normal_angle": float(normal_angle),
                "orientation_angle": float(selected_angle),
                "orientation_method": orientation_method,
                "velocity_sample": velocity_sample,
            }
            if orientation_angle_callback is not None:
                callback_angle = orientation_angle_callback(context)
                if callback_angle is not None:
                    selected_angle = float(callback_angle)
                    orientation_method = "callback"
                    context["orientation_angle"] = selected_angle
                    context["orientation_method"] = orientation_method

            name = name_template.format(
                source_name=source_name,
                index=line_index,
                global_index=global_index,
                station=float(station),
                station_int=int(round(float(station))),
            )
            coords = _line_coordinates_from_angle(
                x,
                y,
                selected_angle,
                total_length,
            )
            generated_lines.append(
                {
                    "name": str(name),
                    "coordinates": coords,
                    "storage_area": storage_area,
                    "source_name": source_name,
                    "station": float(station),
                    "line_length": float(total_length),
                    "orientation": orientation_method,
                    "orientation_angle": float(selected_angle),
                    "tangent_angle": float(tangent_angle),
                    "center": (x, y),
                    "velocity_sample": velocity_sample,
                }
            )
            global_index += 1

    if not generated_lines:
        raise ValueError("No reference lines were generated")

    logger.debug(
        f"Generated {len(generated_lines)} transverse reference line(s) "
        f"from {len(records)} longitudinal line(s)"
    )
    return generated_lines

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.

Source code in ras_commander/geom/GeomReferenceFeatures.py
Python
@staticmethod
@log_call
def 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.

    Args:
        geom_file: Path to geometry file (.g##).
        longitudinal_lines: Source line input accepted by
            ``generate_reference_lines_from_longitudinal_line``.
        storage_area: Name of the 2D flow area receiving the reference
            lines.
        spacing: Station interval along each source line.
        line_length: Generated transverse reference-line length.
        **kwargs: Additional generator options such as
            ``longitudinal_line_name``, ``orientation_plan_hdf``, and
            ``name_template``.

    Returns:
        int: Number of reference lines inserted.
    """
    generated_lines = (
        GeomReferenceFeatures.generate_reference_lines_from_longitudinal_line(
            longitudinal_lines,
            spacing,
            line_length,
            storage_area=storage_area,
            **kwargs,
        )
    )
    return GeomReferenceFeatures.add_reference_lines(
        geom_file,
        generated_lines,
        storage_area,
    )

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", ... )

Source code in ras_commander/geom/GeomReferenceFeatures.py
Python
@staticmethod
@log_call
def 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.

    Args:
        geom_file: Path to geometry file (.g##)
        lines: List of dicts with:
            - 'name': str -- unique reference line name
            - 'coordinates': list of (x,y) tuples or array (N,2)
        storage_area: Name of the 2D flow area (e.g., 'BaldEagleCr')

    Returns:
        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",
        ... )
    """
    geom_file = Path(geom_file)
    if not geom_file.exists():
        raise FileNotFoundError(f"Geometry file not found: {geom_file}")

    if not lines:
        raise ValueError("lines must contain at least one reference line")

    # Read file with CRLF preservation
    with open(geom_file, "r", encoding="utf-8", errors="ignore", newline="") as f:
        file_lines = f.readlines()

    names = {b['name'] for b in _reference_line_blocks(file_lines)}
    # Build reference line blocks
    new_blocks = []
    for item in lines:
        name = _validate_reference_line_field(item["name"], "line name", 40, allow_commas=True)
        storage_area = _validate_reference_line_field(storage_area, "storage_area", 16)
        if name in names:
            raise ValueError(f"Duplicate reference line name {name!r}")
        names.add(name)
        coords = np.asarray(item["coordinates"], dtype=np.float64)
        if coords.ndim != 2 or coords.shape[1] != 2 or len(coords) < 2 or not np.isfinite(coords).all():
            raise ValueError(
                f"Reference line '{name}' needs at least 2 points as (N,2) array"
            )
        block = _build_reference_line_block(name, storage_area, coords)
        new_blocks.extend(block)

    # Find insertion point: after last BC Line block, before IC Points or LCMann
    insert_idx = len(file_lines)  # default: end of file

    last_bc_line_idx = -1
    first_ic_point_idx = -1
    first_lcmann_idx = -1
    first_existing_refline_idx = -1

    for i, line in enumerate(file_lines):
        stripped = line.rstrip("\r\n")
        if stripped.startswith("BC Line Text Position="):
            last_bc_line_idx = i
        if stripped.startswith(("IC Point Name=", "Reference Point Name=")) and first_ic_point_idx == -1:
            first_ic_point_idx = i
        if stripped.startswith("LCMann ") and first_lcmann_idx == -1:
            first_lcmann_idx = i
        if stripped.startswith("Reference Line Name=") and first_existing_refline_idx == -1:
            first_existing_refline_idx = i

    # Priority: insert at existing ref line location, or after BC lines,
    # or before IC points, or before LCMann
    if first_existing_refline_idx >= 0:
        insert_idx = first_existing_refline_idx
    elif last_bc_line_idx >= 0:
        insert_idx = last_bc_line_idx + 1
    elif first_ic_point_idx >= 0:
        insert_idx = first_ic_point_idx
    elif first_lcmann_idx >= 0:
        insert_idx = first_lcmann_idx

    # Detect line ending from file
    line_ending = "\r\n" if file_lines and "\r\n" in file_lines[0] else "\n"

    # Insert
    insert_lines = [block_line + line_ending for block_line in new_blocks]
    file_lines[insert_idx:insert_idx] = insert_lines

    GeomParser.safe_write_geometry(
        geom_file,
        file_lines,
        create_backup=True,
    )

    logger.debug(
        f"Inserted {len(lines)} reference line(s) into {geom_file.name} "
        f"(storage area: {storage_area}) at line {insert_idx + 1}"
    )
    return len(lines)

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.

Source code in ras_commander/geom/GeomReferenceFeatures.py
Python
@staticmethod
@log_call
def 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``.
    """
    geom_path = Path(geom_file)
    if not geom_path.is_file():
        raise FileNotFoundError(f"Geometry file not found: {geom_path}")
    area = _validate_reference_line_field(
        storage_area,
        "storage_area",
        _REFERENCE_LINE_STORAGE_AREA_BYTES,
    )

    prepared: List[tuple[str, List[str]]] = []
    seen: set[str] = set()
    for index, item in enumerate(reference_lines):
        if not isinstance(item, Mapping):
            raise TypeError(f"reference_lines[{index}] must be a mapping")
        name = _validate_reference_line_field(
            item.get("name", ""),
            f"reference_lines[{index}] name",
            _REFERENCE_LINE_NAME_BYTES,
            allow_commas=True,
        )
        name_key = name.casefold()
        if name_key in seen:
            raise ValueError(f"duplicate reference line name: {name!r}")
        seen.add(name_key)
        if "coordinates" not in item:
            raise ValueError(
                f"Reference line {name!r} is missing coordinates"
            )
        coords = np.asarray(item["coordinates"], dtype=np.float64)
        if coords.ndim != 2 or coords.shape[1] != 2 or len(coords) < 2:
            raise ValueError(
                f"Reference line {name!r} needs at least 2 points as "
                "an (N, 2) array"
            )
        if not np.isfinite(coords).all():
            raise ValueError(
                f"Reference line {name!r} coordinates must be finite"
            )
        prepared.append((name, _build_reference_line_block(name, area, coords)))

    with open(
        geom_path,
        "r",
        encoding="utf-8",
        errors="strict",
        newline="",
    ) as handle:
        file_lines = handle.readlines()
    _require_unique_2d_storage_area(file_lines, area)
    blocks = _reference_line_blocks(file_lines)
    original_file_lines = list(file_lines)
    original_blocks = list(blocks)
    target_blocks = [block for block in blocks if block["storage_area"] == area]
    existing_names = [str(block["name"]) for block in target_blocks]
    if expected_existing_names is not None:
        expected_existing = [
            str(name).strip() for name in expected_existing_names
        ]
        if existing_names != expected_existing:
            raise ValueError(
                f"Reference-line population changed for {area!r}: expected "
                f"{expected_existing!r}, observed {existing_names!r}"
            )

    line_ending = "\r\n" if any(
        line.endswith("\r\n") for line in file_lines
    ) else "\n"
    replacement_lines: list[str] = []
    unchanged_names: list[str] = []
    for (name, new_block), item in zip(prepared, reference_lines):
        matches = [block for block in target_blocks if block["name"] == name]
        if len(matches) == 1 and np.array_equal(
            matches[0]["coordinates"], item["coordinates"]
        ):
            block = matches[0]
            replacement_lines.extend(
                original_file_lines[int(block["start"]):int(block["end"])]
            )
            unchanged_names.append(name)
        else:
            replacement_lines.extend(line + line_ending for line in new_block)

    if unchanged_names != existing_names or len(unchanged_names) != len(prepared):
        for block in sorted(target_blocks, key=lambda value: value["start"], reverse=True):
            del file_lines[int(block["start"]):int(block["end"])]
        insert_idx = _reference_line_insert_index(file_lines)
        file_lines[insert_idx:insert_idx] = replacement_lines

    written_blocks = _reference_line_blocks(file_lines)
    written_names = [
        str(block["name"])
        for block in written_blocks
        if block["storage_area"] == area
    ]
    expected_names = [name for name, _ in prepared]
    if written_names != expected_names:
        raise RuntimeError(
            f"Reference-line replacement validation failed: {written_names!r}"
        )

    original_other_blocks = [
        (
            block["name"],
            block["storage_area"],
            "".join(
                original_file_lines[int(block["start"]):int(block["end"])]
            ),
        )
        for block in original_blocks
        if block["storage_area"] != area
    ]
    written_other_blocks = [
        (
            block["name"],
            block["storage_area"],
            "".join(file_lines[int(block["start"]):int(block["end"])]),
        )
        for block in written_blocks
        if block["storage_area"] != area
    ]
    if written_other_blocks != original_other_blocks:
        raise RuntimeError("Reference-line replacement changed another 2D area's data")

    if file_lines == original_file_lines:
        backup_path = GeomParser.create_backup(geom_path) if create_backup else None
    else:
        backup_path = GeomParser.safe_write_geometry(
            geom_path,
            file_lines,
            create_backup=create_backup,
        )
    logger.info(
        "Replaced %d reference line(s) with %d for %s in %s",
        len(existing_names),
        len(expected_names),
        area,
        geom_path.name,
    )
    return backup_path

get_reference_lines staticmethod

Python
get_reference_lines(geom_file: Union[str, Path]) -> List[dict]

Read named area-associated lines; reject malformed coordinate blocks.

Source code in ras_commander/geom/GeomReferenceFeatures.py
Python
@staticmethod
@log_call
def get_reference_lines(geom_file: Union[str, Path]) -> List[dict]:
    """Read named area-associated lines; reject malformed coordinate blocks."""
    geom_file = Path(geom_file)
    with open(geom_file, "r", encoding="utf-8", newline="") as f:
        blocks = _reference_line_blocks(f.readlines())
    return [dict(name=b['name'], storage_area=b['storage_area'], coordinates=b['coordinates']) for b in blocks]

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.

Source code in ras_commander/geom/GeomReferenceFeatures.py
Python
@staticmethod
@log_call
def 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.
    """
    geom_file = Path(geom_file)
    if not geom_file.exists():
        raise FileNotFoundError(f"Geometry file not found: {geom_file}")
    if not points:
        raise ValueError("points must contain at least one reference point")
    with open(geom_file, "r", encoding="utf-8", newline="") as f:
        file_lines = f.readlines()
    names = {p["name"] for p in _reference_point_records(file_lines)}
    blocks = []
    for item in points:
        name = _validate_reference_line_field(item['name'], "point name", 40, allow_commas=True)
        if name in names:
            raise ValueError(f"Duplicate native reference point name {name!r}")
        names.add(name)
        x, y = float(item['x']), float(item['y'])
        if not math.isfinite(x) or not math.isfinite(y):
            raise ValueError(f"Reference point {name!r} needs finite X,Y")
        blocks.extend(_build_reference_point_block(name, x, y))
    insert = next((i for i, line in enumerate(file_lines) if line.startswith("LCMann ")), len(file_lines))
    ending = "\r\n" if file_lines and file_lines[0].endswith("\r\n") else "\n"
    file_lines[insert:insert] = [line + ending for line in blocks]
    GeomParser.safe_write_geometry(geom_file, file_lines, create_backup=True)
    return len(points)

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.

Source code in ras_commander/geom/GeomReferenceFeatures.py
Python
@staticmethod
@log_call
def 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.
    """
    with open(Path(geom_file), "r", encoding="utf-8", newline="") as f:
        return _reference_point_records(f.readlines())

Inspect geometry and output settings

A class for handling boundary-related data from HEC-RAS HDF files.

This class provides methods to extract and process various boundary elements such as boundary condition lines, breaklines, refinement regions, and reference lines/points from HEC-RAS geometry HDF files.

Methods in this class return data primarily as GeoDataFrames, making it easy to work with spatial data in a geospatial context.

Note

This class relies on the HdfBase and HdfUtils classes for some of its functionality. Ensure these classes are available in the same package.

get_reference_lines staticmethod

Python
get_reference_lines(hdf_path: Path, mesh_name: Optional[str] = None) -> gpd.GeoDataFrame

Return the reference lines geometry and attributes.

Parameters

hdf_path : Path Path to the HEC-RAS geometry HDF file. mesh_name : Optional[str], optional Name of the mesh to filter by. Default is None.

Returns

gpd.GeoDataFrame A GeoDataFrame containing the reference lines. If mesh_name is provided, returns only lines for that mesh.

Source code in ras_commander/hdf/HdfBndry.py
Python
@staticmethod
@standardize_input(file_type='plan_hdf')
def get_reference_lines(hdf_path: Path, mesh_name: Optional[str] = None) -> gpd.GeoDataFrame:
    """
    Return the reference lines geometry and attributes.

    Parameters
    ----------
    hdf_path : Path
        Path to the HEC-RAS geometry HDF file.
    mesh_name : Optional[str], optional
        Name of the mesh to filter by. Default is None.

    Returns
    -------
    gpd.GeoDataFrame
        A GeoDataFrame containing the reference lines. If mesh_name is provided,
        returns only lines for that mesh.
    """
    reference_lines_path = "Geometry/Reference Lines"
    attributes_path = f"{reference_lines_path}/Attributes"
    try:
        with h5py.File(hdf_path, 'r') as hdf_file:
            if attributes_path not in hdf_file:
                logger.debug(
                    "Reference lines attributes group '%s' not found in %s.",
                    attributes_path,
                    hdf_path.name,
                )
                return gpd.GeoDataFrame()

            attributes = read_typed(hdf_file[attributes_path])
            refline_ids = range(attributes.shape[0])
            v_conv_str = np.vectorize(HdfUtils.convert_ras_string)
            names = v_conv_str(attributes["Name"])
            mesh_names = v_conv_str(attributes["SA-2D"])

            try:
                types = v_conv_str(attributes["Type"])
            except ValueError:
                logger.debug(
                    "Reference line Type field not found in %s (%s); "
                    "using blank Type values.",
                    hdf_path.name,
                    attributes_path,
                )
                types = np.array([""] * attributes.shape[0])

            geoms = HdfBase.get_polylines_from_parts(hdf_path, reference_lines_path)

            gdf = gpd.GeoDataFrame(
                {
                    "refln_id": refline_ids,
                    "Name": names,
                    "mesh_name": mesh_names,
                    "Type": types,
                    "geometry": geoms,
                },
                geometry="geometry",
                crs=HdfBase.get_projection(hdf_file),
            )

            # Filter by mesh_name if provided
            if mesh_name is not None:
                gdf = gdf[gdf['mesh_name'] == mesh_name]

            return gdf

    except Exception as e:
        reraise_required(e)
        logger.error(
            "Error reading reference lines from %s (%s): %s",
            hdf_path,
            reference_lines_path,
            str(e),
        )
        # An absent group returns an empty frame above; a group that exists
        # but cannot be read is an error, not "no reference lines".
        raise ValueError(
            f"Failed to read reference lines from {hdf_path} ({reference_lines_path}): {e}"
        ) from e

get_reference_points staticmethod

Python
get_reference_points(hdf_path: Path, mesh_name: Optional[str] = None) -> gpd.GeoDataFrame

Return the reference points geometry and attributes.

Parameters

hdf_path : Path Path to the HEC-RAS geometry HDF file. mesh_name : Optional[str], optional Name of the mesh to filter by. Default is None.

Returns

gpd.GeoDataFrame A GeoDataFrame containing the reference points. If mesh_name is provided, returns only points for that mesh.

Source code in ras_commander/hdf/HdfBndry.py
Python
@staticmethod
@standardize_input(file_type='plan_hdf')
def get_reference_points(hdf_path: Path, mesh_name: Optional[str] = None) -> gpd.GeoDataFrame:
    """
    Return the reference points geometry and attributes.

    Parameters
    ----------
    hdf_path : Path
        Path to the HEC-RAS geometry HDF file.
    mesh_name : Optional[str], optional
        Name of the mesh to filter by. Default is None.

    Returns
    -------
    gpd.GeoDataFrame
        A GeoDataFrame containing the reference points. If mesh_name is provided,
        returns only points for that mesh.
    """
    reference_points_path = "Geometry/Reference Points"
    attributes_path = f"{reference_points_path}/Attributes"
    try:
        with h5py.File(hdf_path, 'r') as hdf_file:
            if attributes_path not in hdf_file:
                logger.debug(
                    "Reference points attributes group '%s' not found in %s.",
                    attributes_path,
                    hdf_path.name,
                )
                return gpd.GeoDataFrame()

            ref_points_group = hdf_file[reference_points_path]
            attributes = read_typed(ref_points_group["Attributes"], slice(None))
            v_conv_str = np.vectorize(HdfUtils.convert_ras_string)
            names = v_conv_str(attributes["Name"])
            mesh_names = v_conv_str(attributes["SA/2D"])
            cell_id = attributes["Cell Index"]
            points = read_typed(ref_points_group["Points"])

            gdf = gpd.GeoDataFrame(
                {
                    "refpt_id": range(attributes.shape[0]),
                    "Name": names,
                    "mesh_name": mesh_names,
                    "Cell Index": cell_id,
                    "geometry": list(map(shapely_geometry.Point, points)),
                },
                geometry="geometry",
                crs=HdfBase.get_projection(hdf_file),
            )

            # Filter by mesh_name if provided
            if mesh_name is not None:
                gdf = gdf[gdf['mesh_name'] == mesh_name]

            return gdf

    except Exception as e:
        reraise_required(e)
        logger.error(
            "Error reading reference points from %s (%s): %s",
            hdf_path,
            reference_points_path,
            str(e),
        )
        # An absent group returns an empty frame above; a group that exists
        # but cannot be read is an error, not "no reference points".
        raise ValueError(
            f"Failed to read reference points from {hdf_path} ({reference_points_path}): {e}"
        ) from e

A class for handling mesh-related operations on HEC-RAS HDF files.

This class provides methods to extract and analyze mesh data from HEC-RAS HDF files, including mesh area names, mesh areas, cell polygons, cell points, cell faces, and 2D flow area attributes.

Methods in this class are designed to work with the mesh geometry data stored in HEC-RAS HDF files, providing functionality to retrieve and process various aspects of the 2D flow areas and their associated mesh structures.

Note: This class relies on HdfBase and HdfUtils for some underlying operations.

get_reference_line_internal_faces staticmethod

Python
get_reference_line_internal_faces(hdf_path: Path, mesh_name: Optional[str] = None) -> pd.DataFrame

Return internal mesh faces associated with native HEC-RAS reference lines.

Parameters

hdf_path : Path Path to the HEC-RAS geometry HDF file. mesh_name : Optional[str], optional If provided, return only reference-line faces for this 2D flow area.

Returns

pd.DataFrame Rows keyed by reference line and face with columns such as reference_line_id, profile_name, mesh_name, face_id, fp_start_index, fp_end_index, station_start, station_end, station_length, face_length, and station_fraction where source fields are available. Returns an empty DataFrame when reference lines or internal faces are absent. station_fraction is the raw HDF-derived fraction and may be outside [0, 1] for unusual station data; consumers should validate or clip it before using it as a multiplier.

Source code in ras_commander/hdf/HdfMesh.py
Python
@staticmethod
@log_call
@standardize_input(file_type='geom_hdf')
def get_reference_line_internal_faces(
    hdf_path: Path,
    mesh_name: Optional[str] = None
) -> pd.DataFrame:
    """
    Return internal mesh faces associated with native HEC-RAS reference lines.

    Parameters
    ----------
    hdf_path : Path
        Path to the HEC-RAS geometry HDF file.
    mesh_name : Optional[str], optional
        If provided, return only reference-line faces for this 2D flow area.

    Returns
    -------
    pd.DataFrame
        Rows keyed by reference line and face with columns such as
        ``reference_line_id``, ``profile_name``, ``mesh_name``, ``face_id``,
        ``fp_start_index``, ``fp_end_index``, ``station_start``,
        ``station_end``, ``station_length``, ``face_length``, and
        ``station_fraction`` where source fields are available. Returns an
        empty DataFrame when reference lines or internal faces are absent.
        ``station_fraction`` is the raw HDF-derived fraction and may be
        outside [0, 1] for unusual station data; consumers should validate
        or clip it before using it as a multiplier.
    """
    columns = [
        'reference_line_id',
        'profile_name',
        'mesh_name',
        'face_id',
        'fp_start_index',
        'fp_end_index',
        'station_start',
        'station_end',
        'station_length',
        'face_length',
        'station_fraction',
    ]

    try:
        with h5py.File(hdf_path, 'r') as hdf_file:
            ref_path = "Geometry/Reference Lines"
            attrs_path = f"{ref_path}/Attributes"
            internal_faces_path = f"{ref_path}/Internal Faces"

            if attrs_path not in hdf_file or internal_faces_path not in hdf_file:
                return pd.DataFrame(columns=columns)

            attributes = read_typed(hdf_file[attrs_path])
            internal_faces = read_typed(hdf_file[internal_faces_path])
            if len(attributes) == 0 or len(internal_faces) == 0:
                return pd.DataFrame(columns=columns)

            attr_lookup = HdfMesh._reference_line_attribute_lookup(attributes)
            rows = []
            for face_row in internal_faces:
                reference_line_id = HdfMesh._get_hdf_row_value(
                    face_row, 'Reference Line ID', default=np.nan
                )
                if pd.isna(reference_line_id):
                    continue

                reference_line_id = int(reference_line_id)
                attr = attr_lookup.get(reference_line_id, {})
                row_mesh_name = attr.get('mesh_name') or mesh_name
                if mesh_name is not None and row_mesh_name != mesh_name:
                    continue

                station_start = HdfMesh._get_hdf_row_value(
                    face_row, 'Station Start', default=np.nan
                )
                station_end = HdfMesh._get_hdf_row_value(
                    face_row, 'Station End', default=np.nan
                )
                face_id = HdfMesh._get_hdf_row_value(
                    face_row, 'Face Index', default=np.nan
                )
                face_length = HdfMesh._get_face_length(
                    hdf_file, row_mesh_name, face_id
                )

                station_length = np.nan
                if np.isfinite(station_start) and np.isfinite(station_end):
                    station_length = float(station_end) - float(station_start)

                station_fraction = np.nan
                if np.isfinite(station_length) and np.isfinite(face_length) and face_length > 0:
                    station_fraction = station_length / face_length

                rows.append({
                    'reference_line_id': reference_line_id,
                    'profile_name': attr.get('profile_name'),
                    'mesh_name': row_mesh_name,
                    'face_id': HdfMesh._safe_int(face_id),
                    'fp_start_index': HdfMesh._safe_int(HdfMesh._get_hdf_row_value(
                        face_row, 'FP Start Index', default=np.nan
                    )),
                    'fp_end_index': HdfMesh._safe_int(HdfMesh._get_hdf_row_value(
                        face_row, 'FP End Index', default=np.nan
                    )),
                    'station_start': float(station_start) if np.isfinite(station_start) else np.nan,
                    'station_end': float(station_end) if np.isfinite(station_end) else np.nan,
                    'station_length': station_length,
                    'face_length': face_length,
                    'station_fraction': station_fraction,
                })

            return pd.DataFrame(rows, columns=columns)

    except Exception as e:
        reraise_required(e)
        logger.error(
            f"Error reading reference line internal faces from {hdf_path}: {str(e)}"
        )
        return pd.DataFrame(columns=columns)

Saved output intervals are distinct from the computation timestep. Updating a plan's settings does not change an existing result HDF: recompute to produce the new output, then inspect the timestamps actually written.

A class for operations on HEC-RAS plan files.

update_plan_intervals staticmethod

Python
update_plan_intervals(plan_number_or_path: Union[str, Path], computation_interval: Optional[str] = None, output_interval: Optional[str] = None, instantaneous_interval: Optional[str] = None, mapping_interval: Optional[str] = None, ras_object=None, *, validate: bool = True) -> None

Update the computation, output, detailed and mapping intervals in a plan file.

Parameters: plan_number_or_path (Union[str, Path]): The plan number (1 to 99) or full path to the plan file computation_interval (Optional[str]): New computation interval. Valid entries are RasPlan.VALID_PLAN_INTERVALS ('0.1SEC' ... '1SEC' ... '1MIN' ... '1HOUR' ... '1DAY', '1WEEK', '1MON', '1YEAR'). output_interval (Optional[str]): Hydrograph Output Interval (Output Interval=). instantaneous_interval (Optional[str]): Detailed Output Interval (Instantaneous Interval=). mapping_interval (Optional[str]): Mapping Output Interval (Mapping Interval=). ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance. validate (bool): Keyword-only. Check the relationships described in validate_plan_intervals against the resulting plan (new values merged with those already in the file, including values you did not change, plus the simulation start time). Default True.

Raises: ValueError: If the plan file is not found or if an invalid/inconsistent interval is provided IOError: If there's an error reading or writing the plan file

Notes

Lines that are not intervals are written back untouched (line endings are normalised to CRLF like every other ras-commander writer). A missing interval key is inserted after the last existing interval key. Short output/mapping intervals enlarge the plan HDF; see set_hdf_compression.

Example:

RasPlan.update_plan_intervals("01", computation_interval="30SEC", output_interval="15MIN", instantaneous_interval="1HOUR", mapping_interval="15MIN")

Source code in ras_commander/RasPlan.py
Python
@staticmethod
@log_call
def update_plan_intervals(
    plan_number_or_path: Union[str, Path],
    computation_interval: Optional[str] = None,
    output_interval: Optional[str] = None,
    instantaneous_interval: Optional[str] = None,
    mapping_interval: Optional[str] = None,
    ras_object=None,
    *,
    validate: bool = True
) -> None:
    """
    Update the computation, output, detailed and mapping intervals in a plan file.

    Parameters:
    plan_number_or_path (Union[str, Path]): The plan number (1 to 99) or full path to the plan file
    computation_interval (Optional[str]): New computation interval. Valid entries are
        ``RasPlan.VALID_PLAN_INTERVALS`` ('0.1SEC' ... '1SEC' ... '1MIN' ... '1HOUR' ...
        '1DAY', '1WEEK', '1MON', '1YEAR').
    output_interval (Optional[str]): Hydrograph Output Interval (``Output Interval=``).
    instantaneous_interval (Optional[str]): Detailed Output Interval (``Instantaneous Interval=``).
    mapping_interval (Optional[str]): Mapping Output Interval (``Mapping Interval=``).
    ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.
    validate (bool): Keyword-only. Check the relationships described in
        ``validate_plan_intervals`` against the *resulting* plan (new values merged
        with those already in the file, including values you did not change, plus
        the simulation start time). Default True.

    Raises:
    ValueError: If the plan file is not found or if an invalid/inconsistent interval is provided
    IOError: If there's an error reading or writing the plan file

    Notes:
        Lines that are not intervals are written back untouched (line endings are
        normalised to CRLF like every other ras-commander writer). A missing
        interval key is inserted after the last existing interval key.
        Short output/mapping intervals enlarge the plan HDF; see
        ``set_hdf_compression``.

    Example:
    >>> RasPlan.update_plan_intervals("01", computation_interval="30SEC", output_interval="15MIN", instantaneous_interval="1HOUR", mapping_interval="15MIN")
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    plan_file_path = Path(plan_number_or_path)
    if not plan_file_path.is_file():
        plan_file_path = RasPlan.get_plan_path(plan_number_or_path, ras_object=ras_obj)
        if plan_file_path is None or not Path(plan_file_path).exists():
            raise ValueError(f"Plan file not found: {plan_file_path}")

    requested = {
        'Computation Interval': computation_interval,
        'Output Interval': output_interval,
        'Instantaneous Interval': instantaneous_interval,
        'Mapping Interval': mapping_interval,
    }
    requested = {
        key: str(value).strip().upper() for key, value in requested.items() if value is not None
    }
    if not requested:
        return

    # Value validity is always enforced; relationships only when validate=True.
    for key, value in requested.items():
        if value not in RasPlan.VALID_PLAN_INTERVALS:
            raise ValueError(
                f"Invalid {key}: {value}. Must be one of {list(RasPlan.VALID_PLAN_INTERVALS)}"
            )

    try:
        with open(plan_file_path, 'r', encoding='utf-8', errors='replace') as file:
            lines = file.readlines()
    except IOError as e:
        logger.error(f"Error reading plan file {plan_file_path}: {e}")
        raise

    interval_keys = set(RasPlan.PLAN_INTERVAL_KEYS.values())

    if validate:
        effective: Dict[str, str] = {}
        start_time = None
        for _, key, raw in _iter_plan_key_lines(lines):
            if key in interval_keys:
                effective.setdefault(key, raw.strip().upper())
            elif key == "Simulation Date" and start_time is None:
                parts = [p.strip() for p in raw.split(",")]
                if len(parts) >= 2:
                    start_time = parts[1]
        effective.update(requested)
        # Hand-edited values already in the file that are not valid strings are
        # ignored rather than blamed on this call.
        for key in list(effective):
            if key not in requested and effective[key] not in RasPlan.VALID_PLAN_INTERVALS:
                del effective[key]
        problems = RasPlan.validate_plan_intervals(
            computation_interval=effective.get('Computation Interval'),
            output_interval=effective.get('Output Interval'),
            instantaneous_interval=effective.get('Instantaneous Interval'),
            mapping_interval=effective.get('Mapping Interval'),
            simulation_start_time=start_time,
        )
        if problems:
            raise ValueError("Inconsistent plan intervals: " + "; ".join(problems))

    present_keys = set()
    last_interval_index = None
    for i, key, _raw in _iter_plan_key_lines(lines):
        if key in interval_keys:
            last_interval_index = i
            if key in requested:
                # HEC-RAS updates every occurrence when a hand-edited plan
                # contains duplicate interval records. Keep reads first-wins
                # and restore that single effective value on every write.
                lines[i] = f"{key}={requested[key]}\n"
                present_keys.add(key)

    missing_keys = set(requested) - present_keys
    if missing_keys:
        if last_interval_index is None:
            for i, key, _raw in _iter_plan_key_lines(lines):
                if key in {"Encroach Param", "Geom File", "Flow File"}:
                    last_interval_index = i
            if last_interval_index is None:
                # Append after a complete Description block rather than using
                # a raw-line index that could point inside one.
                last_interval_index = len(lines) - 1
        new_lines = [
            f"{key}={requested[key]}\n"
            for key in RasPlan.PLAN_INTERVAL_KEYS.values() if key in missing_keys
        ]
        if lines and not lines[last_interval_index].endswith("\n"):
            lines[last_interval_index] += "\n"
        lines[last_interval_index + 1:last_interval_index + 1] = new_lines

    _write_ras_text(
        plan_file_path, "".join(lines), encoding="utf-8", errors="replace"
    )
    if hasattr(ras_obj, "get_plan_entries"):
        ras_obj.plan_df = ras_obj.get_plan_entries()

    logger.info("Updated intervals in plan file: %s", Path(plan_file_path).name)
    logger.debug("Updated intervals in plan file path: %s", plan_file_path)

get_hdf_output_options staticmethod

Python
get_hdf_output_options(plan_number_or_path: Union[str, Number, Path], ras_object=None) -> Dict[str, Optional[Any]]

Get HDF output options configured in a HEC-RAS plan file.

Alias for get_hdf_write_parameters() using output-control naming.

Source code in ras_commander/RasPlan.py
Python
@staticmethod
@log_call
def get_hdf_output_options(
    plan_number_or_path: Union[str, Number, Path],
    ras_object=None
) -> Dict[str, Optional[Any]]:
    """
    Get HDF output options configured in a HEC-RAS plan file.

    Alias for ``get_hdf_write_parameters()`` using output-control naming.
    """
    return RasPlan.get_hdf_write_parameters(
        plan_number_or_path,
        ras_object=ras_object
    )

set_hdf_output_options staticmethod

Python
set_hdf_output_options(plan_number_or_path: Union[str, Number, Path], write_warmup: Optional[bool] = None, write_time_slices: Optional[bool] = None, hdf_flush: Optional[bool] = None, compression: Optional[int] = None, chunk_size_mb: Optional[int] = None, spatial_parts: Optional[int] = None, use_max_rows: Optional[bool] = None, fixed_rows: Optional[int] = None, ras_object=None) -> bool

Set HDF output options in a HEC-RAS plan file.

Alias for set_hdf_write_parameters() using output-control naming.

Source code in ras_commander/RasPlan.py
Python
@staticmethod
@log_call
def set_hdf_output_options(
    plan_number_or_path: Union[str, Number, Path],
    write_warmup: Optional[bool] = None,
    write_time_slices: Optional[bool] = None,
    hdf_flush: Optional[bool] = None,
    compression: Optional[int] = None,
    chunk_size_mb: Optional[int] = None,
    spatial_parts: Optional[int] = None,
    use_max_rows: Optional[bool] = None,
    fixed_rows: Optional[int] = None,
    ras_object=None
) -> bool:
    """
    Set HDF output options in a HEC-RAS plan file.

    Alias for ``set_hdf_write_parameters()`` using output-control naming.
    """
    return RasPlan.set_hdf_write_parameters(
        plan_number_or_path,
        write_warmup=write_warmup,
        write_time_slices=write_time_slices,
        hdf_flush=hdf_flush,
        compression=compression,
        chunk_size_mb=chunk_size_mb,
        spatial_parts=spatial_parts,
        use_max_rows=use_max_rows,
        fixed_rows=fixed_rows,
        ras_object=ras_object
    )

apply_hdf_output_profile staticmethod

Python
apply_hdf_output_profile(plan_number_or_path: Union[str, Number, Path], profile: str = 'balanced', additional_variables: Optional[List[str]] = None, ras_object=None, *, target_ras_version: Optional[Union[str, float, Path]] = None) -> bool

Apply a named HDF write-parameter profile and optional output variables.

All requested labels and version gates are checked before any writes; see add_hdf_output_variable for normalization and physics limits.

Parameters:

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

Plan number or path to the plan file.

required
profile str

One of balanced, speed, size, or nas.

'balanced'
additional_variables Optional[List[str]]

Optional additional HDF output variables to enable.

None
ras_object RasPrj

Optional RAS project object. If None, uses global ras.

None
target_ras_version str, float, or Path

HEC-RAS version that will run the plan ("7.0", "7.0.1", "70", or a versioned Ras.exe path). When given, it replaces the plan's declared Program Version for the version-limited labels in HDF_OUTPUT_VARIABLE_MIN_VERSIONS. None (default) keeps the declared-version gate.

None

Returns:

Type Description
bool

True when all requested updates succeeded.

Source code in ras_commander/RasPlan.py
Python
@staticmethod
@log_call
def apply_hdf_output_profile(
    plan_number_or_path: Union[str, Number, Path],
    profile: str = "balanced",
    additional_variables: Optional[List[str]] = None,
    ras_object=None,
    *,
    target_ras_version: Optional[Union[str, float, Path]] = None,
) -> bool:
    """
    Apply a named HDF write-parameter profile and optional output variables.

    All requested labels and version gates are checked before any writes;
    see ``add_hdf_output_variable`` for normalization and physics limits.

    Args:
        plan_number_or_path: Plan number or path to the plan file.
        profile: One of ``balanced``, ``speed``, ``size``, or ``nas``.
        additional_variables: Optional additional HDF output variables to enable.
        ras_object (RasPrj, optional): Optional RAS project object. If None, uses global ``ras``.
        target_ras_version (str, float, or Path, optional): HEC-RAS version
            that will run the plan (``"7.0"``, ``"7.0.1"``, ``"70"``, or a
            versioned ``Ras.exe`` path). When given, it replaces the plan's
            declared Program Version for the version-limited labels in
            ``HDF_OUTPUT_VARIABLE_MIN_VERSIONS``. None (default) keeps the
            declared-version gate.

    Returns:
        bool: True when all requested updates succeeded.
    """
    profile_key = profile.lower()
    if profile_key not in RasPlan.HDF_OUTPUT_SETTING_PROFILES:
        valid = ", ".join(sorted(RasPlan.HDF_OUTPUT_SETTING_PROFILES))
        raise ValueError(f"Unknown HDF output profile '{profile}'. Valid profiles: {valid}")

    settings = RasPlan.HDF_OUTPUT_SETTING_PROFILES[profile_key]
    # Validate the entire request before changing either options or labels.
    additional_variables = [
        RasPlan._normalize_hdf_output_variable(v) for v in additional_variables or []
    ]
    if additional_variables:
        ras_obj = ras_object or ras
        ras_obj.check_initialized()
        plan_path = RasPlan._resolve_plan_file_path(plan_number_or_path, ras_obj)
        if not plan_path or not plan_path.exists():
            return False
        try:
            lines = plan_path.read_text(encoding='utf-8', errors='replace').splitlines(True)
        except IOError as exc:
            logger.error("Error reading HDF output plan %s: %s", plan_path, exc)
            return False
        RasPlan._check_hdf_output_versions(
            additional_variables, lines, target_ras_version=target_ras_version
        )
    success = RasPlan.set_hdf_write_parameters(
        plan_number_or_path,
        ras_object=ras_object,
        **settings
    )

    for variable in additional_variables or []:
        success = (
            RasPlan.set_hdf_output_variable(
                plan_number_or_path,
                variable,
                enabled=True,
                ras_object=ras_object,
                target_ras_version=target_ras_version,
            )
            and success
        )

    return success