Skip to content

RASMapper

Use these dedicated references for related tasks:

Task Reference
Generate, diagnose, or repair a 2D mesh Meshing
Sample results, profiles, or reference hydrographs Results Queries
Export computed results to raster maps Stored Maps
Create, modify, or export terrain Terrain

This page covers the remaining RASMapper operations: screenshots and spatial review, map and geometry layers, display controls, geometry associations, and native geometry completion. Use the static namespaces directly; there is no single RASMapper object to instantiate. File readers and XML editors can run without a visible desktop. Native methods need their documented HEC-RAS runtime; GUI capture additionally needs an interactive Windows desktop. A headless Wine qualification does not establish GUI screenshot support.

Registration in .rasmap and associations in compiled geometry HDF are distinct. Changing visibility does not alter hydraulic results, and geometry completion does not execute a hydraulic plan. Use RasCmdr for execution and review the resulting evidence before exporting maps.

Inspect, configure, and capture

Python
from pathlib import Path
from ras_commander import RasMap

project_path = Path("review-copy/Model.prj")
print(RasMap.list_map_layers(project_path))
print(RasMap.get_current_view(project_path))

# Register an existing vector layer on the copied project.
RasMap.add_reference_map_layer(
    project_path,
    source_path=Path("review-inputs/review-area.geojson"),
    layer_name="Review area",
)

GeoJSON registration validates WGS84 compatibility. Use method-specific CRS rules instead of assuming all layer inputs are in the model CRS. clone_geometry_layer() registers an existing geometry clone; it does not copy the geometry files. Use geometry cloning first, then register the new HDF and verify its compiled associations.

On an interactive Windows review desktop:

Python
from ras_commander import RasMap

snapshot = RasMap.screenshot_model(
    "review-copy/Model.prj",
    output_path="review-output/model.png",
    ras_version="6.6",
)
if snapshot is None:
    raise RuntimeError("No screenshot was captured; inspect the logged diagnostics")
print(snapshot)

create_spatial_review_package() can produce an evidence bundle without a screenshot (capture_snapshot=False, the default). That path can still persist display settings in .rasmap; it is not a read-only inventory. To require a screenshot, select a GUI-capable runtime and use capture_snapshot=True with require_snapshot=True. See the method for preflight and restoration behavior.

RASMapper display and spatial review

Use RasMap to select geometry and result layers, set visibility and view bounds, and capture review evidence. Visibility and rendering changes are persisted in .rasmap; HDF feature readers supply model bounds and feature inventories.

Task Input Output
Layer and feature discovery Project and exact geometry/layer selector Lists or DataFrames
Visibility and terrain display Layer selector and display options Updated XML; Boolean or changed-entry count
View and zoom Explicit bounds or HDF feature selector View/bounds dictionary
Open/capture/close Project and optionally an owned process ID Process handle, optional PNG path, closed-window count
Screenshot gallery / review package Projects and output directory Gallery records or review-bundle dictionary

Screenshots require Windows GUI facilities and a visible RASMapper window. Prefer the process ID returned by open_rasmapper() when capturing or closing that window. screenshot_model() temporarily configures display layers and restores its .rasmap backup after capture. Read each method's return value; an absent screenshot is not successful visual evidence.

Examples with retained outputs: 122 — spatial review, 123 — geometry layer updates, and 124 — bank lines.

Display, features and review methods

Class for parsing and accessing information from HEC-RAS mapper configuration files (.rasmap).

This class provides methods to extract paths to terrain, soil, land cover data, and various project settings from the .rasmap file associated with a HEC-RAS project. It also includes functionality to automate the post-processing of stored maps.

list_geometries staticmethod

Python
list_geometries(ras_object=None) -> List[Dict[str, Any]]

List all geometry layers in the RASMapper configuration file.

Parameters:

Name Type Description Default
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
List[Dict[str, Any]]

List of dicts with geometry info: [{"name": str, "filename": str, "geom_number": str, "checked": bool}, ...]

Examples:

Python Console Session
>>> from ras_commander import init_ras_project, RasMap
>>> init_ras_project("/path/to/project", "7.0")
>>> geoms = RasMap.list_geometries()
>>> for g in geoms:
...     print(f"{g['geom_number']}: {g['name']} - Visible: {g['checked']}")
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_geometries(ras_object=None) -> List[Dict[str, Any]]:
    """
    List all geometry layers in the RASMapper configuration file.

    Args:
        ras_object (RasPrj, optional): Optional RasPrj object instance.

    Returns:
        List[Dict[str, Any]]: List of dicts with geometry info:
            [{"name": str, "filename": str, "geom_number": str, "checked": bool}, ...]

    Examples:
        >>> from ras_commander import init_ras_project, RasMap
        >>> init_ras_project("/path/to/project", "7.0")
        >>> geoms = RasMap.list_geometries()
        >>> for g in geoms:
        ...     print(f"{g['geom_number']}: {g['name']} - Visible: {g['checked']}")
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    if not rasmap_path.exists():
        logger.warning(f"RASMapper file not found: {rasmap_path}")
        return []

    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()
    except ET.ParseError as e:
        logger.error(f"Error parsing .rasmap XML: {e}")
        return []

    geometries_elem = root.find("Geometries")
    if geometries_elem is None:
        logger.debug("No Geometries section found in .rasmap")
        return []

    geometries = []
    for layer in geometries_elem.findall("Layer"):
        filename = layer.get("Filename", "")
        # Extract geometry number from filename (e.g., ".\BaldEagle.g08.hdf" -> "08")
        import re

        match = re.search(r"\.g(\d+)\.hdf", filename)
        geom_num = match.group(1) if match else ""

        geometries.append(
            {
                "name": layer.get("Name", ""),
                "filename": filename,
                "geom_number": geom_num,
                "checked": layer.get("Checked", "").lower() == "true",
            }
        )

    logger.debug("Found %d geometries in .rasmap", len(geometries))
    return geometries

clone_geometry_layer staticmethod

Python
clone_geometry_layer(source_geometry: Union[str, int], target_geometry: Union[str, int], *, name: Optional[str] = None, checked: bool = True, expanded: bool = True, ras_object=None) -> Dict[str, Any]

Register a cloned geometry HDF in the RASMapper tree.

RasGeo.clone_geom() copies the geometry control file and HDF, but HEC-RAS does not add the cloned HDF to <Geometries> in the project .rasmap file. Exact text-to-HDF refresh workflows therefore cannot resolve the clone until it has a RASMapper geometry layer.

The source geometry layer is deep-copied so the target keeps the same child-layer display configuration. Only the top-level display name, visibility, expansion state, and HDF filename are changed. Repeating the call for the same target is idempotent.

Parameters:

Name Type Description Default
source_geometry Union[str, int]

Source geometry number, such as "01".

required
target_geometry Union[str, int]

Cloned geometry number, such as "02".

required
name Optional[str]

Optional target display name. Defaults to the source name.

None
checked bool

Whether the target geometry is visible.

True
expanded bool

Whether the target geometry tree is expanded.

True
ras_object RasPrj

Optional initialized :class:RasPrj instance.

None

Returns:

Type Description
Dict[str, Any]

Registered layer metadata and the .rasmap path.

Raises:

Type Description
FileNotFoundError

If the .rasmap or target geometry HDF is absent.

ValueError

If the source layer is absent or the numbers are equal.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def clone_geometry_layer(
    source_geometry: Union[str, int],
    target_geometry: Union[str, int],
    *,
    name: Optional[str] = None,
    checked: bool = True,
    expanded: bool = True,
    ras_object=None,
) -> Dict[str, Any]:
    """Register a cloned geometry HDF in the RASMapper tree.

    ``RasGeo.clone_geom()`` copies the geometry control file and HDF, but
    HEC-RAS does not add the cloned HDF to ``<Geometries>`` in the project
    ``.rasmap`` file. Exact text-to-HDF refresh workflows therefore cannot
    resolve the clone until it has a RASMapper geometry layer.

    The source geometry layer is deep-copied so the target keeps the same
    child-layer display configuration. Only the top-level display name,
    visibility, expansion state, and HDF filename are changed. Repeating
    the call for the same target is idempotent.

    Args:
        source_geometry: Source geometry number, such as ``"01"``.
        target_geometry: Cloned geometry number, such as ``"02"``.
        name: Optional target display name. Defaults to the source name.
        checked: Whether the target geometry is visible.
        expanded: Whether the target geometry tree is expanded.
        ras_object (RasPrj, optional): Optional initialized :class:`RasPrj` instance.

    Returns:
        Dict[str, Any]: Registered layer metadata and the ``.rasmap`` path.

    Raises:
        FileNotFoundError: If the ``.rasmap`` or target geometry HDF is absent.
        ValueError: If the source layer is absent or the numbers are equal.
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()
    source_number = RasUtils.normalize_ras_number(source_geometry)
    target_number = RasUtils.normalize_ras_number(target_geometry)
    if source_number == target_number:
        raise ValueError("source_geometry and target_geometry must differ")

    project_folder = Path(ras_obj.project_folder)
    project_name = str(ras_obj.project_name)
    rasmap_path = project_folder / f"{project_name}.rasmap"
    target_hdf = project_folder / f"{project_name}.g{target_number}.hdf"
    if not rasmap_path.exists():
        raise FileNotFoundError(f"RASMapper file not found: {rasmap_path}")
    if not target_hdf.exists():
        raise FileNotFoundError(f"Cloned geometry HDF not found: {target_hdf}")

    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()
    except ET.ParseError as e:
        raise ValueError(f"Error parsing .rasmap XML: {e}") from e
    geometries = root.find("Geometries")
    if geometries is None:
        raise ValueError("No Geometries section found in .rasmap")

    source_token = f".g{source_number}.hdf"
    target_token = f".g{target_number}.hdf"
    source_layer = None
    target_layer = None
    for layer in geometries.findall("Layer"):
        filename = _normalize_rasmap_filename(layer.get("Filename"))
        if source_token in filename:
            source_layer = layer
        if target_token in filename:
            target_layer = layer
    if source_layer is None:
        raise ValueError(
            f"Source geometry g{source_number} is not registered in {rasmap_path}"
        )

    if target_layer is None:
        target_layer = copy.deepcopy(source_layer)
        source_index = list(geometries).index(source_layer)
        geometries.insert(source_index + 1, target_layer)

    rel_hdf = _rasmap_relative_path(project_folder, target_hdf)
    layer_name = str(name).strip() if name is not None else ""
    target_layer.set("Name", layer_name or source_layer.get("Name", ""))
    target_layer.set("Type", "RASGeometry")
    target_layer.set("Checked", "True" if checked else "False")
    target_layer.set("Expanded", "True" if expanded else "False")
    target_layer.set("Filename", rel_hdf)
    _write_ras_xml(tree, rasmap_path, encoding="utf-8", xml_declaration=False)

    readback = ET.parse(rasmap_path).getroot().find("Geometries")
    registered = None if readback is None else next(
        (
            layer
            for layer in readback.findall("Layer")
            if target_token
            in _normalize_rasmap_filename(layer.get("Filename"))
        ),
        None,
    )
    if registered is None:
        raise RuntimeError(
            f"RASMapper geometry registration failed readback for g{target_number}"
        )
    record = {
        "name": registered.get("Name", ""),
        "filename": registered.get("Filename", ""),
        "geom_number": target_number,
        "checked": registered.get("Checked", "").lower() == "true",
        "expanded": registered.get("Expanded", "").lower() == "true",
        "rasmap_path": rasmap_path,
    }
    logger.info(
        "Registered cloned geometry g%s as RASMapper layer '%s'",
        target_number,
        record["name"],
    )
    return record

set_geometry_visibility staticmethod

Python
set_geometry_visibility(geom_identifier: str, visible: bool = True, ras_object=None) -> bool

Set visibility of a specific geometry layer in RASMapper.

Parameters:

Name Type Description Default
geom_identifier str

Geometry to modify - can be: - Geometry name (e.g., "1D-2D Dam Break Model Refined Grid") - Geometry number (e.g., "08" or "g08") - Filename pattern (e.g., "g08.hdf")

required
visible bool

True to show geometry, False to hide.

True
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
bool

True if geometry was found and modified.

Examples:

Python Console Session
>>> from ras_commander import init_ras_project, RasMap
>>> init_ras_project("/path/to/project", "7.0")
>>> # Show geometry by number
>>> RasMap.set_geometry_visibility("08", visible=True)
>>> # Hide geometry by name
>>> RasMap.set_geometry_visibility("Old Geometry", visible=False)
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def set_geometry_visibility(
    geom_identifier: str, visible: bool = True, ras_object=None
) -> bool:
    """
    Set visibility of a specific geometry layer in RASMapper.

    Args:
        geom_identifier: Geometry to modify - can be:
            - Geometry name (e.g., "1D-2D Dam Break Model Refined Grid")
            - Geometry number (e.g., "08" or "g08")
            - Filename pattern (e.g., "g08.hdf")
        visible: True to show geometry, False to hide.
        ras_object (RasPrj, optional): Optional RasPrj object instance.

    Returns:
        bool: True if geometry was found and modified.

    Examples:
        >>> from ras_commander import init_ras_project, RasMap
        >>> init_ras_project("/path/to/project", "7.0")
        >>> # Show geometry by number
        >>> RasMap.set_geometry_visibility("08", visible=True)
        >>> # Hide geometry by name
        >>> RasMap.set_geometry_visibility("Old Geometry", visible=False)
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    if not rasmap_path.exists():
        logger.warning(f"RASMapper file not found: {rasmap_path}")
        return False

    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()
    except ET.ParseError as e:
        logger.error(f"Error parsing .rasmap XML: {e}")
        return False

    geometries_elem = root.find("Geometries")
    if geometries_elem is None:
        logger.warning("No Geometries section found in .rasmap")
        return False

    # Normalize identifier for matching
    identifier_lower = geom_identifier.lower().strip()
    # Handle "g08" -> "08" format
    if identifier_lower.startswith("g") and identifier_lower[1:].isdigit():
        identifier_lower = identifier_lower[1:]

    found = False
    for layer in geometries_elem.findall("Layer"):
        name = layer.get("Name", "")
        filename = layer.get("Filename", "")

        # Check if this layer matches the identifier
        matches = (
            name.lower() == identifier_lower
            or identifier_lower in filename.lower()
            or f".g{identifier_lower}." in filename.lower()
            or f".g{identifier_lower.zfill(2)}." in filename.lower()
        )

        if matches:
            layer.set("Checked", "True" if visible else "False")
            logger.info(f"Set geometry '{name}' visibility to {visible}")
            found = True
            break

    if found:
        _write_ras_xml(tree, rasmap_path, encoding="utf-8", xml_declaration=True)
        return True
    else:
        logger.warning(f"Geometry '{geom_identifier}' not found in .rasmap")
        return False

set_all_geometries_visibility staticmethod

Python
set_all_geometries_visibility(visible: bool = False, except_geom: Optional[str] = None, ras_object=None) -> int

Set visibility for all geometry layers, optionally excluding one.

This is useful for hiding all geometries except the one you want to display.

Parameters:

Name Type Description Default
visible bool

True to show all geometries, False to hide all.

False
except_geom Optional[str]

Optional geometry to exclude from visibility change. Can be geometry name, number (e.g., "08"), or filename pattern.

None
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
int

Number of geometries modified.

Examples:

Python Console Session
>>> from ras_commander import init_ras_project, RasMap
>>> init_ras_project("/path/to/project", "7.0")
>>> # Hide all geometries except G08
>>> RasMap.set_all_geometries_visibility(visible=False, except_geom="08")
>>> # Then show only G08
>>> RasMap.set_geometry_visibility("08", visible=True)
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def set_all_geometries_visibility(
    visible: bool = False, except_geom: Optional[str] = None, ras_object=None
) -> int:
    """
    Set visibility for all geometry layers, optionally excluding one.

    This is useful for hiding all geometries except the one you want to display.

    Args:
        visible: True to show all geometries, False to hide all.
        except_geom: Optional geometry to exclude from visibility change.
            Can be geometry name, number (e.g., "08"), or filename pattern.
        ras_object (RasPrj, optional): Optional RasPrj object instance.

    Returns:
        int: Number of geometries modified.

    Examples:
        >>> from ras_commander import init_ras_project, RasMap
        >>> init_ras_project("/path/to/project", "7.0")
        >>> # Hide all geometries except G08
        >>> RasMap.set_all_geometries_visibility(visible=False, except_geom="08")
        >>> # Then show only G08
        >>> RasMap.set_geometry_visibility("08", visible=True)
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    if not rasmap_path.exists():
        logger.warning(f"RASMapper file not found: {rasmap_path}")
        return 0

    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()
    except ET.ParseError as e:
        logger.error(f"Error parsing .rasmap XML: {e}")
        return 0

    geometries_elem = root.find("Geometries")
    if geometries_elem is None:
        logger.warning("No Geometries section found in .rasmap")
        return 0

    # Normalize except identifier for matching
    except_lower = None
    if except_geom:
        except_lower = except_geom.lower().strip()
        if except_lower.startswith("g") and except_lower[1:].isdigit():
            except_lower = except_lower[1:]

    modified_count = 0
    for layer in geometries_elem.findall("Layer"):
        name = layer.get("Name", "")
        filename = layer.get("Filename", "")

        # Check if this is the exception geometry
        if except_lower:
            is_exception = (
                name.lower() == except_lower
                or except_lower in filename.lower()
                or f".g{except_lower}." in filename.lower()
                or f".g{except_lower.zfill(2)}." in filename.lower()
            )
            if is_exception:
                # Set opposite visibility for exception
                layer.set("Checked", "False" if visible else "True")
                logger.debug(f"Exception: Set geometry '{name}' to {not visible}")
                modified_count += 1
                continue

        # Set visibility for all others
        layer.set("Checked", "True" if visible else "False")
        modified_count += 1

    if modified_count > 0:
        _write_ras_xml(tree, rasmap_path, encoding="utf-8", xml_declaration=True)
        logger.info(f"Modified visibility for {modified_count} geometries")

    return modified_count

list_geometry_layers staticmethod

Python
list_geometry_layers(ras_project_path: Optional[Union[str, Path]] = None, *, ras_object=None) -> pd.DataFrame

List top-level geometries and child geometry elements from .rasmap.

This is the discoverable RASMapper tree view for geometry automation. It includes both compiled geometry HDF entries and child elements such as RASXS, RASD2FlowArea, MeshPerimeterLayer, and structure layers. Use this when deciding what to toggle before opening RASMapper or taking documentation screenshots.

Parameters:

Name Type Description Default
ras_project_path Optional[Union[str, Path]]

Project folder, .prj file, or .rasmap file. If omitted, the active RasPrj object is used.

None
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
DataFrame

One row per top-level geometry and child geometry element, including layer id, layer type, visibility state, and resolved geometry HDF path.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_geometry_layers(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    ras_object=None,
) -> pd.DataFrame:
    """
    List top-level geometries and child geometry elements from ``.rasmap``.

    This is the discoverable RASMapper tree view for geometry automation.
    It includes both compiled geometry HDF entries and child elements such as
    ``RASXS``, ``RASD2FlowArea``, ``MeshPerimeterLayer``, and structure
    layers. Use this when deciding what to toggle before opening RASMapper or
    taking documentation screenshots.

    Args:
        ras_project_path: Project folder, ``.prj`` file, or ``.rasmap`` file.
            If omitted, the active ``RasPrj`` object is used.
        ras_object (RasPrj, optional): Optional ``RasPrj`` object instance.

    Returns:
        pd.DataFrame: One row per top-level geometry and child geometry
            element, including layer id, layer type, visibility state, and
            resolved geometry HDF path.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.list_geometry_layers(resolved_project_path)

set_geometry_layer_visibility staticmethod

Python
set_geometry_layer_visibility(ras_project_path: Optional[Union[str, Path]] = None, *, checked: bool = True, layer_id: Optional[str] = None, layer_type: Optional[Union[str, Sequence[str]]] = None, layer_name: Optional[str] = None, geometry_name: Optional[str] = None, geometry_number: Optional[str] = None, exclusive: bool = False, ras_object=None) -> int

Toggle child geometry elements in the RASMapper tree.

This complements set_geometry_visibility(), which toggles a whole compiled geometry. set_geometry_layer_visibility() targets child elements inside that geometry, such as cross sections, 2D flow areas, mesh perimeters, and structures.

Parameters:

Name Type Description Default
ras_project_path Optional[Union[str, Path]]

Project folder, .prj file, or .rasmap file. If omitted, the active RasPrj object is used.

None
checked bool

True to show matching elements, False to hide them.

True
layer_id Optional[str]

Stable id from list_geometry_layers().

None
layer_type Optional[Union[str, Sequence[str]]]

RASMapper child layer type, such as "RASD2FlowArea", or a sequence of layer types for combined QA views.

None
layer_name Optional[str]

Optional child layer display name.

None
geometry_name Optional[str]

Optional parent geometry display name filter.

None
geometry_number Optional[str]

Optional parent geometry number filter, such as "04" or "g04".

None
exclusive bool

If True, hide all geometries and child elements first, then show only the matching parent geometry and selected child element. This is useful for screenshot workflows.

False
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
int

Number of XML visibility attributes modified.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def set_geometry_layer_visibility(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    checked: bool = True,
    layer_id: Optional[str] = None,
    layer_type: Optional[Union[str, Sequence[str]]] = None,
    layer_name: Optional[str] = None,
    geometry_name: Optional[str] = None,
    geometry_number: Optional[str] = None,
    exclusive: bool = False,
    ras_object=None,
) -> int:
    """
    Toggle child geometry elements in the RASMapper tree.

    This complements ``set_geometry_visibility()``, which toggles a whole
    compiled geometry. ``set_geometry_layer_visibility()`` targets child
    elements inside that geometry, such as cross sections, 2D flow areas,
    mesh perimeters, and structures.

    Args:
        ras_project_path: Project folder, ``.prj`` file, or ``.rasmap`` file.
            If omitted, the active ``RasPrj`` object is used.
        checked: ``True`` to show matching elements, ``False`` to hide them.
        layer_id: Stable id from ``list_geometry_layers()``.
        layer_type: RASMapper child layer type, such as ``"RASD2FlowArea"``,
            or a sequence of layer types for combined QA views.
        layer_name: Optional child layer display name.
        geometry_name: Optional parent geometry display name filter.
        geometry_number: Optional parent geometry number filter, such as
            ``"04"`` or ``"g04"``.
        exclusive: If ``True``, hide all geometries and child elements first,
            then show only the matching parent geometry and selected child
            element. This is useful for screenshot workflows.
        ras_object (RasPrj, optional): Optional ``RasPrj`` object instance.

    Returns:
        int: Number of XML visibility attributes modified.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.set_geometry_layer_visibility(
        resolved_project_path,
        checked=checked,
        layer_id=layer_id,
        layer_type=layer_type,
        layer_name=layer_name,
        geometry_name=geometry_name,
        geometry_number=geometry_number,
        exclusive=exclusive,
    )

list_result_layers staticmethod

Python
list_result_layers(ras_project_path: Optional[Union[str, Path]] = None, *, ras_object=None) -> pd.DataFrame

List RASMapper result plans and child result layers.

The returned DataFrame includes the top-level RASResults plan rows and nested result layers such as depth, WSE, velocity, or calculated layers, with their current visibility state.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_result_layers(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    ras_object=None,
) -> pd.DataFrame:
    """
    List RASMapper result plans and child result layers.

    The returned DataFrame includes the top-level ``RASResults`` plan rows
    and nested result layers such as depth, WSE, velocity, or calculated
    layers, with their current visibility state.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.list_result_layers(resolved_project_path)

set_result_layer_visibility staticmethod

Python
set_result_layer_visibility(ras_project_path: Optional[Union[str, Path]] = None, *, checked: bool = True, layer_id: Optional[str] = None, plan_name: Optional[Union[str, Sequence[str]]] = None, layer_name: Optional[Union[str, Sequence[str]]] = None, layer_type: Optional[Union[str, Sequence[str]]] = None, exclusive: bool = False, ras_object=None) -> int

Toggle RASMapper result plans and child result layers.

When no selector is supplied, all result layers are targeted. Use exclusive=True with checked=True to hide every non-matching result layer and show only the selected result plan or map type needed for a figure.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def set_result_layer_visibility(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    checked: bool = True,
    layer_id: Optional[str] = None,
    plan_name: Optional[Union[str, Sequence[str]]] = None,
    layer_name: Optional[Union[str, Sequence[str]]] = None,
    layer_type: Optional[Union[str, Sequence[str]]] = None,
    exclusive: bool = False,
    ras_object=None,
) -> int:
    """
    Toggle RASMapper result plans and child result layers.

    When no selector is supplied, all result layers are targeted. Use
    ``exclusive=True`` with ``checked=True`` to hide every non-matching
    result layer and show only the selected result plan or map type needed
    for a figure.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.set_result_layer_visibility(
        resolved_project_path,
        checked=checked,
        layer_id=layer_id,
        plan_name=plan_name,
        layer_name=layer_name,
        layer_type=layer_type,
        exclusive=exclusive,
    )

list_geometry_features staticmethod

Python
list_geometry_features(geometry_hdf_path: Union[str, Path], *, layer_type: Optional[Union[str, Sequence[str]]] = None) -> pd.DataFrame

List HDF geometry features for supported RASMapper layers.

This is more granular than list_geometry_layers(). It exposes feature names, indexes, and bounds for objects such as 2D flow areas, lateral structures, breaklines, and cross sections.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_geometry_features(
    geometry_hdf_path: Union[str, Path],
    *,
    layer_type: Optional[Union[str, Sequence[str]]] = None,
) -> pd.DataFrame:
    """
    List HDF geometry features for supported RASMapper layers.

    This is more granular than ``list_geometry_layers()``. It exposes
    feature names, indexes, and bounds for objects such as 2D
    flow areas, lateral structures, breaklines, and cross sections.
    """
    from . import _rasmap_control_helper as _rch

    return _rch.list_geometry_features(
        geometry_hdf_path,
        layer_type=layer_type,
    )

get_current_view staticmethod

Python
get_current_view(ras_project_path: Optional[Union[str, Path]] = None, *, ras_object=None) -> Dict[str, Any]

Read the CurrentView bounds from a project .rasmap file.

Bounds are in the project/RASMapper coordinate system. The returned dictionary also includes the resolved projection file path when the .rasmap references one.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def get_current_view(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    ras_object=None,
) -> Dict[str, Any]:
    """
    Read the ``CurrentView`` bounds from a project ``.rasmap`` file.

    Bounds are in the project/RASMapper coordinate system. The returned
    dictionary also includes the resolved projection file path when the
    ``.rasmap`` references one.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.get_current_view(resolved_project_path)

set_current_view staticmethod

Python
set_current_view(ras_project_path: Optional[Union[str, Path]] = None, *, min_x: float, min_y: float, max_x: float, max_y: float, ras_object=None) -> Dict[str, Any]

Write the CurrentView bounds in a project .rasmap file.

Use this before launching standalone RASMapper when you want a deterministic documentation or QA/QC viewport.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def set_current_view(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    min_x: float,
    min_y: float,
    max_x: float,
    max_y: float,
    ras_object=None,
) -> Dict[str, Any]:
    """
    Write the ``CurrentView`` bounds in a project ``.rasmap`` file.

    Use this before launching standalone RASMapper when you want a
    deterministic documentation or QA/QC viewport.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.set_current_view(
        resolved_project_path,
        min_x=min_x,
        min_y=min_y,
        max_x=max_x,
        max_y=max_y,
    )

set_terrain_layer_visibility staticmethod

Python
set_terrain_layer_visibility(ras_project_path: Optional[Union[str, Path]] = None, *, terrain_name: Optional[str] = None, checked: bool = True, exclusive: bool = False, surface_on: bool = True, ras_object=None) -> int

Toggle RASMapper terrain-layer visibility in a project .rasmap.

Parameters:

Name Type Description Default
ras_project_path Optional[Union[str, Path]]

Project folder, .prj file, or .rasmap file. If omitted, the active RasPrj object is used.

None
terrain_name Optional[str]

Optional terrain layer display name. When omitted, all terrain layers are targeted.

None
checked bool

True to show matching terrain layers.

True
exclusive bool

If True, hide non-matching terrain layers first.

False
surface_on bool

Keep the terrain <Surface On="..."> state aligned with the checked state.

True
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
int

Number of XML attributes/elements modified.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def set_terrain_layer_visibility(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    terrain_name: Optional[str] = None,
    checked: bool = True,
    exclusive: bool = False,
    surface_on: bool = True,
    ras_object=None,
) -> int:
    """
    Toggle RASMapper terrain-layer visibility in a project ``.rasmap``.

    Args:
        ras_project_path: Project folder, ``.prj`` file, or ``.rasmap`` file.
            If omitted, the active ``RasPrj`` object is used.
        terrain_name: Optional terrain layer display name. When omitted, all
            terrain layers are targeted.
        checked: ``True`` to show matching terrain layers.
        exclusive: If ``True``, hide non-matching terrain layers first.
        surface_on: Keep the terrain ``<Surface On="...">`` state aligned
            with the checked state.
        ras_object (RasPrj, optional): Optional ``RasPrj`` object instance.

    Returns:
        int: Number of XML attributes/elements modified.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.set_terrain_layer_visibility(
        resolved_project_path,
        terrain_name=terrain_name,
        checked=checked,
        exclusive=exclusive,
        surface_on=surface_on,
    )

list_terrain_display_settings staticmethod

Python
list_terrain_display_settings(ras_project_path: Optional[Union[str, Path]] = None, *, terrain_name: Optional[str] = None, ras_object=None) -> pd.DataFrame

List terrain display settings persisted in a project .rasmap file.

The returned DataFrame includes hillshade, contour, and stitch-edge display controls for each Type="TerrainLayer" entry. These settings are read directly from RASMapper XML; no GUI automation is used.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_terrain_display_settings(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    terrain_name: Optional[str] = None,
    ras_object=None,
) -> pd.DataFrame:
    """
    List terrain display settings persisted in a project ``.rasmap`` file.

    The returned DataFrame includes hillshade, contour, and stitch-edge
    display controls for each ``Type="TerrainLayer"`` entry. These settings
    are read directly from RASMapper XML; no GUI automation is used.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.list_terrain_display_settings(
        resolved_project_path,
        terrain_name=terrain_name,
    )

get_terrain_display_settings staticmethod

Python
get_terrain_display_settings(ras_project_path: Optional[Union[str, Path]] = None, *, terrain_name: Optional[str] = None, ras_object=None) -> Dict[str, Any]

Read persisted terrain display settings for one terrain layer.

Provide terrain_name when the project has multiple terrain layers. The name match uses the RASMapper display name.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def get_terrain_display_settings(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    terrain_name: Optional[str] = None,
    ras_object=None,
) -> Dict[str, Any]:
    """
    Read persisted terrain display settings for one terrain layer.

    Provide ``terrain_name`` when the project has multiple terrain layers.
    The name match uses the RASMapper display name.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.get_terrain_display_settings(
        resolved_project_path,
        terrain_name=terrain_name,
    )

set_terrain_display_settings staticmethod

Python
set_terrain_display_settings(ras_project_path: Optional[Union[str, Path]] = None, *, terrain_name: Optional[str] = None, hillshade_enabled: Optional[bool] = None, hillshade_z_factor: Optional[float] = None, contour_enabled: Optional[bool] = None, contour_interval: Optional[float] = None, stitch_edges_enabled: Optional[bool] = None, stitch_tin_edges_enabled: Optional[bool] = None, level0_stitch_edges_enabled: Optional[bool] = None, level0_stitch_tin_edges_enabled: Optional[bool] = None, remove_stitch_rendering_enabled: Optional[bool] = None, ras_object=None) -> int

Write persisted terrain display settings in a project .rasmap file.

Parameters:

Name Type Description Default
ras_project_path Optional[Union[str, Path]]

Project folder, .prj file, or .rasmap file. If omitted, the active RasPrj object is used.

None
terrain_name Optional[str]

Optional terrain layer display name. When omitted, all terrain layers are targeted.

None
hillshade_enabled Optional[bool]

Toggle Symbology/HillShade display.

None
hillshade_z_factor Optional[float]

Set the hillshade Z factor where persisted.

None
contour_enabled Optional[bool]

Toggle Symbology/Contour display.

None
contour_interval Optional[float]

Set the contour interval where persisted.

None
stitch_edges_enabled Optional[bool]

Toggle Plot stitch TIN edges.

None
level0_stitch_edges_enabled Optional[bool]

Toggle Plot Level0 stitch TIN edges.

None
remove_stitch_rendering_enabled Optional[bool]

Toggle Remove Stitch Rendering.

None
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
int

Number of XML attributes/elements modified.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def set_terrain_display_settings(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    terrain_name: Optional[str] = None,
    hillshade_enabled: Optional[bool] = None,
    hillshade_z_factor: Optional[float] = None,
    contour_enabled: Optional[bool] = None,
    contour_interval: Optional[float] = None,
    stitch_edges_enabled: Optional[bool] = None,
    stitch_tin_edges_enabled: Optional[bool] = None,
    level0_stitch_edges_enabled: Optional[bool] = None,
    level0_stitch_tin_edges_enabled: Optional[bool] = None,
    remove_stitch_rendering_enabled: Optional[bool] = None,
    ras_object=None,
) -> int:
    """
    Write persisted terrain display settings in a project ``.rasmap`` file.

    Args:
        ras_project_path: Project folder, ``.prj`` file, or ``.rasmap`` file.
            If omitted, the active ``RasPrj`` object is used.
        terrain_name: Optional terrain layer display name. When omitted, all
            terrain layers are targeted.
        hillshade_enabled: Toggle ``Symbology/HillShade`` display.
        hillshade_z_factor: Set the hillshade Z factor where persisted.
        contour_enabled: Toggle ``Symbology/Contour`` display.
        contour_interval: Set the contour interval where persisted.
        stitch_edges_enabled: Toggle ``Plot stitch TIN edges``.
        level0_stitch_edges_enabled: Toggle ``Plot Level0 stitch TIN edges``.
        remove_stitch_rendering_enabled: Toggle ``Remove Stitch Rendering``.
        ras_object (RasPrj, optional): Optional ``RasPrj`` object instance.

    Returns:
        int: Number of XML attributes/elements modified.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.set_terrain_display_settings(
        resolved_project_path,
        terrain_name=terrain_name,
        hillshade_enabled=hillshade_enabled,
        hillshade_z_factor=hillshade_z_factor,
        contour_enabled=contour_enabled,
        contour_interval=contour_interval,
        stitch_edges_enabled=stitch_edges_enabled,
        stitch_tin_edges_enabled=stitch_tin_edges_enabled,
        level0_stitch_edges_enabled=level0_stitch_edges_enabled,
        level0_stitch_tin_edges_enabled=level0_stitch_tin_edges_enabled,
        remove_stitch_rendering_enabled=remove_stitch_rendering_enabled,
    )

set_update_legend_with_view staticmethod

Python
set_update_legend_with_view(ras_project_path: Optional[Union[str, Path]] = None, *, checked: bool = True, include_results: bool = True, include_terrain: bool = True, include_geometry: bool = False, include_map_layers: bool = False, ras_object=None) -> int

Set RASMapper Update Legend with View for raster surface fills.

RASMapper persists this checkbox as RegenerateForScreen on SurfaceFill XML elements. By default this targets result layers and terrain layers, which are the surfaces most commonly used in inspection screenshots.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def set_update_legend_with_view(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    checked: bool = True,
    include_results: bool = True,
    include_terrain: bool = True,
    include_geometry: bool = False,
    include_map_layers: bool = False,
    ras_object=None,
) -> int:
    """
    Set RASMapper ``Update Legend with View`` for raster surface fills.

    RASMapper persists this checkbox as ``RegenerateForScreen`` on
    ``SurfaceFill`` XML elements. By default this targets result layers and
    terrain layers, which are the surfaces most commonly used in inspection
    screenshots.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.set_update_legend_with_view(
        resolved_project_path,
        checked=checked,
        include_results=include_results,
        include_terrain=include_terrain,
        include_geometry=include_geometry,
        include_map_layers=include_map_layers,
    )

get_geometry_layer_bounds staticmethod

Python
get_geometry_layer_bounds(geometry_hdf_path: Union[str, Path], *, layer_type: Optional[Union[str, Sequence[str]]] = None) -> Dict[str, Any]

Read HDF-derived bounds for a compiled geometry or geometry element.

Parameters:

Name Type Description Default
geometry_hdf_path Union[str, Path]

Path to a compiled .g##.hdf file.

required
layer_type Optional[Union[str, Sequence[str]]]

Optional RASMapper child layer type. When omitted, bounds are computed from all recognized geometry coordinate datasets.

None

Returns:

Type Description
Dict[str, Any]

Bounds, source dataset paths, and point count.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def get_geometry_layer_bounds(
    geometry_hdf_path: Union[str, Path],
    *,
    layer_type: Optional[Union[str, Sequence[str]]] = None,
) -> Dict[str, Any]:
    """
    Read HDF-derived bounds for a compiled geometry or geometry element.

    Args:
        geometry_hdf_path: Path to a compiled ``.g##.hdf`` file.
        layer_type: Optional RASMapper child layer type. When omitted, bounds
            are computed from all recognized geometry coordinate datasets.

    Returns:
        Dict[str, Any]: Bounds, source dataset paths, and point count.
    """
    from . import _rasmap_control_helper as _rch

    return _rch.geometry_layer_bounds(
        geometry_hdf_path,
        layer_type=layer_type,
    )

get_geometry_feature_bounds staticmethod

Python
get_geometry_feature_bounds(geometry_hdf_path: Union[str, Path], *, layer_type: str, feature_id: Optional[str] = None, feature_name: Optional[str] = None, feature_index: Optional[int] = None) -> Dict[str, Any]

Read HDF-derived bounds for a selected geometry feature.

Select the feature with feature_id from list_geometry_features(), a display name, or a zero-based feature index.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def get_geometry_feature_bounds(
    geometry_hdf_path: Union[str, Path],
    *,
    layer_type: str,
    feature_id: Optional[str] = None,
    feature_name: Optional[str] = None,
    feature_index: Optional[int] = None,
) -> Dict[str, Any]:
    """
    Read HDF-derived bounds for a selected geometry feature.

    Select the feature with ``feature_id`` from ``list_geometry_features()``,
    a display name, or a zero-based feature index.
    """
    from . import _rasmap_control_helper as _rch

    return _rch.geometry_feature_bounds(
        geometry_hdf_path,
        layer_type=layer_type,
        feature_id=feature_id,
        feature_name=feature_name,
        feature_index=feature_index,
    )

zoom_to_geometry_layer staticmethod

Python
zoom_to_geometry_layer(ras_project_path: Optional[Union[str, Path]] = None, *, layer_id: Optional[str] = None, layer_type: Optional[Union[str, Sequence[str]]] = None, layer_name: Optional[str] = None, geometry_name: Optional[str] = None, geometry_number: Optional[str] = None, feature_id: Optional[str] = None, feature_name: Optional[str] = None, feature_index: Optional[int] = None, padding_fraction: Optional[float] = None, min_padding: float = 0.0, ras_object=None) -> Dict[str, Any]

Set CurrentView to the HDF-derived extent of a geometry element.

Select the target with a layer_id from list_geometry_layers() or with a combination of parent geometry and child layer filters. Pass a sequence to layer_type to zoom to the combined extent of multiple geometry elements. To center the viewport on one feature inside a layer, pass feature_id, feature_name, or feature_index; the layer stays visible, but the viewport is centered on that feature. When padding_fraction is omitted, layer views use 5% per-side padding and feature views use 25% per-side padding, which expands the feature extent by 50% overall for surrounding mesh context.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def zoom_to_geometry_layer(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    layer_id: Optional[str] = None,
    layer_type: Optional[Union[str, Sequence[str]]] = None,
    layer_name: Optional[str] = None,
    geometry_name: Optional[str] = None,
    geometry_number: Optional[str] = None,
    feature_id: Optional[str] = None,
    feature_name: Optional[str] = None,
    feature_index: Optional[int] = None,
    padding_fraction: Optional[float] = None,
    min_padding: float = 0.0,
    ras_object=None,
) -> Dict[str, Any]:
    """
    Set ``CurrentView`` to the HDF-derived extent of a geometry element.

    Select the target with a ``layer_id`` from ``list_geometry_layers()`` or
    with a combination of parent geometry and child layer filters. Pass a
    sequence to ``layer_type`` to zoom to the combined extent of multiple
    geometry elements. To center the viewport on one feature inside a layer,
    pass ``feature_id``, ``feature_name``, or ``feature_index``; the layer
    stays visible, but the viewport is centered on that feature. When
    ``padding_fraction`` is omitted, layer views use 5% per-side padding and
    feature views use 25% per-side padding, which expands the feature extent
    by 50% overall for surrounding mesh context.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.zoom_to_geometry_layer(
        resolved_project_path,
        layer_id=layer_id,
        layer_type=layer_type,
        layer_name=layer_name,
        geometry_name=geometry_name,
        geometry_number=geometry_number,
        feature_id=feature_id,
        feature_name=feature_name,
        feature_index=feature_index,
        padding_fraction=padding_fraction,
        min_padding=min_padding,
    )

open_rasmapper staticmethod

Python
open_rasmapper(ras_project_path: Optional[Union[str, Path]] = None, *, rasmapper_exe_path: Optional[Union[str, Path]] = None, ras_version: Optional[str] = None, wait: bool = False, ras_object=None) -> subprocess.Popen

Launch standalone RasMapper.exe directly against the project .rasmap.

This avoids HEC-RAS menu automation. It is intended for inspection and documentation workflows after the .rasmap view/layer state has been configured.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def open_rasmapper(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    rasmapper_exe_path: Optional[Union[str, Path]] = None,
    ras_version: Optional[str] = None,
    wait: bool = False,
    ras_object=None,
) -> subprocess.Popen:
    """
    Launch standalone ``RasMapper.exe`` directly against the project ``.rasmap``.

    This avoids HEC-RAS menu automation. It is intended for inspection and
    documentation workflows after the ``.rasmap`` view/layer state has been
    configured.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.open_rasmapper(
        resolved_project_path,
        rasmapper_exe_path=rasmapper_exe_path,
        ras_version=ras_version,
        ras_object=ras_object,
        wait=wait,
    )

capture_rasmapper_snapshot staticmethod

Python
capture_rasmapper_snapshot(*, pid: Optional[int] = None, output_path: Optional[Union[str, Path]] = None, delay_seconds: float = 1.0, timeout_seconds: float = 1800.0, poll_interval_seconds: float = 0.5) -> Optional[Path]

Capture a visible standalone RASMapper window to PNG.

Parameters:

Name Type Description Default
pid Optional[int]

Optional RASMapper process id returned by open_rasmapper().

None
output_path Optional[Union[str, Path]]

Optional PNG output path.

None
delay_seconds float

Initial delay before capture polling starts.

1.0
timeout_seconds float

Maximum time to wait for a visible RASMapper window. Defaults to 1800 seconds because large projects can take many minutes to open in RASMapper.

1800.0
poll_interval_seconds float

Window polling interval.

0.5

Returns:

Type Description
Optional[Path]

Screenshot path, or None if no window was found.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def capture_rasmapper_snapshot(
    *,
    pid: Optional[int] = None,
    output_path: Optional[Union[str, Path]] = None,
    delay_seconds: float = 1.0,
    timeout_seconds: float = 1800.0,
    poll_interval_seconds: float = 0.5,
) -> Optional[Path]:
    """
    Capture a visible standalone RASMapper window to PNG.

    Args:
        pid: Optional RASMapper process id returned by ``open_rasmapper()``.
        output_path: Optional PNG output path.
        delay_seconds: Initial delay before capture polling starts.
        timeout_seconds: Maximum time to wait for a visible RASMapper window.
            Defaults to 1800 seconds because large projects can take many
            minutes to open in RASMapper.
        poll_interval_seconds: Window polling interval.

    Returns:
        Optional[Path]: Screenshot path, or ``None`` if no window was found.
    """
    from . import _rasmap_control_helper as _rch

    return _rch.capture_rasmapper_snapshot(
        pid=pid,
        output_path=output_path,
        delay_seconds=delay_seconds,
        timeout_seconds=timeout_seconds,
        poll_interval_seconds=poll_interval_seconds,
    )

close_rasmapper staticmethod

Python
close_rasmapper(*, pid: Optional[int] = None) -> int

Close visible standalone RASMapper windows.

Parameters:

Name Type Description Default
pid Optional[int]

Optional process id to restrict which RASMapper window is closed.

None

Returns:

Type Description
int

Number of visible RASMapper windows sent a close message.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def close_rasmapper(*, pid: Optional[int] = None) -> int:
    """
    Close visible standalone RASMapper windows.

    Args:
        pid: Optional process id to restrict which RASMapper window is closed.

    Returns:
        int: Number of visible RASMapper windows sent a close message.
    """
    from . import _rasmap_control_helper as _rch

    return _rch.close_rasmapper(pid=pid)

screenshot_model staticmethod

Python
screenshot_model(ras_project_path: Union[str, Path], output_path: Optional[Union[str, Path]] = None, *, delay_seconds: float = 5.0, timeout_seconds: float = 1800.0, ras_version: Optional[str] = None, configure_layers: bool = True) -> Optional[Path]

One-call screenshot: backup rasmap, open RASMapper, capture, close, restore.

This is a convenience wrapper around open_rasmapper, capture_rasmapper_snapshot, and close_rasmapper for the common case of capturing a model's current RASMapper view.

Parameters:

Name Type Description Default
ras_project_path Union[str, Path]

Path to the .prj file (no init_ras_project needed).

required
output_path Optional[Union[str, Path]]

Where to save the PNG. Defaults to {project_folder}/{project_name}_screenshot.png.

None
delay_seconds float

Wait time for RASMapper to render before capture.

5.0
timeout_seconds float

Max time to wait for RASMapper window.

1800.0
ras_version Optional[str]

HEC-RAS version for finding RASMapper.exe.

None
configure_layers bool

If True (default), enable terrain and geometry layers in the .rasmap before opening RASMapper so the screenshot shows model content. The original .rasmap is restored afterward.

True

Returns:

Type Description
Optional[Path]

Path to the saved PNG, or None if capture failed.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def screenshot_model(
    ras_project_path: Union[str, Path],
    output_path: Optional[Union[str, Path]] = None,
    *,
    delay_seconds: float = 5.0,
    timeout_seconds: float = 1800.0,
    ras_version: Optional[str] = None,
    configure_layers: bool = True,
) -> Optional[Path]:
    """
    One-call screenshot: backup rasmap, open RASMapper, capture, close, restore.

    This is a convenience wrapper around ``open_rasmapper``,
    ``capture_rasmapper_snapshot``, and ``close_rasmapper`` for the
    common case of capturing a model's current RASMapper view.

    Args:
        ras_project_path: Path to the .prj file (no init_ras_project needed).
        output_path: Where to save the PNG. Defaults to
            ``{project_folder}/{project_name}_screenshot.png``.
        delay_seconds: Wait time for RASMapper to render before capture.
        timeout_seconds: Max time to wait for RASMapper window.
        ras_version: HEC-RAS version for finding RASMapper.exe.
        configure_layers: If True (default), enable terrain and geometry layers
            in the .rasmap before opening RASMapper so the screenshot shows
            model content. The original .rasmap is restored afterward.

    Returns:
        Path to the saved PNG, or None if capture failed.
    """
    import shutil
    from . import _rasmap_control_helper as _rch

    prj_path = Path(ras_project_path)
    project_folder = prj_path.parent
    project_name = prj_path.stem
    rasmap_path = expected_rasmap_path(project_folder, project_name)

    # Backup .rasmap
    rasmap_backup = None
    if rasmap_path.exists():
        rasmap_backup = rasmap_path.with_suffix(".rasmap.screenshot_bak")
        shutil.copy2(rasmap_path, rasmap_backup)

    # Enable terrain and geometry layers and zoom view to the model extent so
    # the screenshot is not blank.  Errors are suppressed — the original .rasmap
    # is restored in the finally block regardless.
    if configure_layers and rasmap_path.exists():
        try:
            _rch.set_terrain_layer_visibility(rasmap_path, checked=True)
        except Exception:
            pass
        try:
            _rch.set_geometry_layer_visibility(rasmap_path, checked=True)
        except Exception:
            pass
        try:
            _rch.zoom_to_geometry_layer(rasmap_path)
        except Exception:
            pass

    # Default output path
    if output_path is None:
        output_path = project_folder / f"{project_name}_screenshot.png"
    output_path = Path(output_path)

    screenshot_result = None
    try:
        proc = _rch.open_rasmapper(
            prj_path,
            ras_version=ras_version,
            wait=False,
        )
        pid = proc.pid if proc else None

        screenshot_result = _rch.capture_rasmapper_snapshot(
            pid=pid,
            output_path=output_path,
            delay_seconds=delay_seconds,
            timeout_seconds=timeout_seconds,
        )

        _rch.close_rasmapper(pid=pid)
    finally:
        # Restore .rasmap from backup
        if rasmap_backup and rasmap_backup.exists():
            shutil.copy2(rasmap_backup, rasmap_path)
            rasmap_backup.unlink()

    if screenshot_result and screenshot_result.exists():
        logger.info("Screenshot saved: %s", screenshot_result.name)
        logger.debug("Screenshot path: %s", screenshot_result)
    else:
        logger.warning("Screenshot capture returned no file")

    return screenshot_result
Python
screenshot_model_gallery(models: List[Tuple[Union[str, Path], str]], output_dir: Union[str, Path], *, delay_seconds: float = 5.0, timeout_seconds: float = 1800.0, ras_version: Optional[str] = None) -> List[Dict[str, Any]]

Capture screenshots of multiple models into a gallery directory.

Parameters:

Name Type Description Default
models List[Tuple[Union[str, Path], str]]

List of (project_path, label) tuples. Each project_path is a .prj file; label is used for the output filename.

required
output_dir Union[str, Path]

Directory for all screenshots.

required
delay_seconds float

Render wait per model.

5.0
timeout_seconds float

Max wait per model.

1800.0
ras_version Optional[str]

HEC-RAS version for finding RASMapper.exe.

None

Returns:

Type Description
List of dicts with keys

label, project_path, screenshot_path, success.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def screenshot_model_gallery(
    models: List[Tuple[Union[str, Path], str]],
    output_dir: Union[str, Path],
    *,
    delay_seconds: float = 5.0,
    timeout_seconds: float = 1800.0,
    ras_version: Optional[str] = None,
) -> List[Dict[str, Any]]:
    """
    Capture screenshots of multiple models into a gallery directory.

    Args:
        models: List of (project_path, label) tuples. Each project_path
            is a .prj file; label is used for the output filename.
        output_dir: Directory for all screenshots.
        delay_seconds: Render wait per model.
        timeout_seconds: Max wait per model.
        ras_version: HEC-RAS version for finding RASMapper.exe.

    Returns:
        List of dicts with keys: label, project_path, screenshot_path, success.
    """
    out = Path(output_dir)
    out.mkdir(parents=True, exist_ok=True)

    results = []
    for project_path, label in models:
        safe_label = "".join(c if c.isalnum() or c in "-_ " else "_" for c in label)
        png_path = out / f"{safe_label}.png"

        try:
            result_path = RasMap.screenshot_model(
                project_path,
                output_path=png_path,
                delay_seconds=delay_seconds,
                timeout_seconds=timeout_seconds,
                ras_version=ras_version,
            )
            results.append(
                {
                    "label": label,
                    "project_path": str(project_path),
                    "screenshot_path": str(result_path) if result_path else None,
                    "success": result_path is not None and result_path.exists(),
                }
            )
        except Exception as e:
            logger.error(f"Failed to screenshot '{label}': {e}")
            results.append(
                {
                    "label": label,
                    "project_path": str(project_path),
                    "screenshot_path": None,
                    "success": False,
                }
            )

    successful = sum(1 for r in results if r["success"])
    logger.info(
        "Screenshot gallery complete: %s/%s captured", successful, len(models)
    )
    logger.debug("Screenshot gallery output directory: %s", out)
    return results

create_spatial_review_package staticmethod

Python
create_spatial_review_package(ras_project_path: Optional[Union[str, Path]] = None, *, output_dir: Optional[Union[str, Path]] = None, geometry_number: Optional[str] = None, geometry_name: Optional[str] = None, layer_type: Optional[Union[str, Sequence[str]]] = None, layer_name: Optional[str] = None, feature_id: Optional[str] = None, feature_name: Optional[str] = None, feature_index: Optional[int] = None, terrain_name: Optional[str] = None, result_plan_name: Optional[Union[str, Sequence[str]]] = None, result_layer_name: Optional[Union[str, Sequence[str]]] = None, result_layer_type: Optional[Union[str, Sequence[str]]] = None, map_layer_name: Optional[Union[str, Sequence[str]]] = None, map_layer_type: Optional[Union[str, Sequence[str]]] = None, map_layer_category: Optional[Union[str, Sequence[str]]] = None, include_terrain: bool = True, include_results: bool = False, include_map_layers: bool = False, exclusive_geometry: bool = True, exclusive_terrain: bool = True, exclusive_results: bool = True, exclusive_map_layers: bool = True, update_legend_with_view: bool = True, zoom_to_layer: bool = True, padding_fraction: Optional[float] = None, min_padding: float = 0.0, capture_snapshot: bool = False, snapshot_filename: str = 'rasmapper_spatial_review.png', delay_seconds: float = 5.0, snapshot_timeout_seconds: float = 1800.0, snapshot_poll_interval_seconds: float = 0.5, close_after_capture: bool = True, viewport_width: Optional[int] = None, viewport_height: Optional[int] = None, dpi: Optional[int] = None, expanded_tree_paths: Optional[Sequence[str]] = None, ramp_id: Optional[str] = None, range_mode: Optional[str] = None, selected_layer: Optional[str] = None, result_profile: Optional[str] = None, render_mode: Optional[str] = None, basemap: Optional[str] = None, web_manifest_url: Optional[str] = None, rasmapper_exe_path: Optional[Union[str, Path]] = None, ras_version: Optional[str] = None, strict_preflight: bool = True, require_snapshot: bool = False, ras_object=None) -> Dict[str, Any]

Build a deterministic RASMapper spatial QA/QC evidence bundle.

The bundle records before/after .rasmap state, layer catalogs, preflight checks, view/zoom metadata, and a findings template. It is headless by default; pass capture_snapshot=True to launch standalone RASMapper and add a screenshot on a Windows review machine. The snapshot_timeout_seconds parameter defaults to 1800 seconds and can be shortened for smoke tests or lengthened for very large projects. Feature-focused views keep the full RASMapper layer visible and center on the selected HDF feature, with 50% overall viewport expansion by default for surrounding mesh and terrain context. Result and map layers are hidden by default unless included or selected, which keeps review figures deterministic.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def create_spatial_review_package(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    output_dir: Optional[Union[str, Path]] = None,
    geometry_number: Optional[str] = None,
    geometry_name: Optional[str] = None,
    layer_type: Optional[Union[str, Sequence[str]]] = None,
    layer_name: Optional[str] = None,
    feature_id: Optional[str] = None,
    feature_name: Optional[str] = None,
    feature_index: Optional[int] = None,
    terrain_name: Optional[str] = None,
    result_plan_name: Optional[Union[str, Sequence[str]]] = None,
    result_layer_name: Optional[Union[str, Sequence[str]]] = None,
    result_layer_type: Optional[Union[str, Sequence[str]]] = None,
    map_layer_name: Optional[Union[str, Sequence[str]]] = None,
    map_layer_type: Optional[Union[str, Sequence[str]]] = None,
    map_layer_category: Optional[Union[str, Sequence[str]]] = None,
    include_terrain: bool = True,
    include_results: bool = False,
    include_map_layers: bool = False,
    exclusive_geometry: bool = True,
    exclusive_terrain: bool = True,
    exclusive_results: bool = True,
    exclusive_map_layers: bool = True,
    update_legend_with_view: bool = True,
    zoom_to_layer: bool = True,
    padding_fraction: Optional[float] = None,
    min_padding: float = 0.0,
    capture_snapshot: bool = False,
    snapshot_filename: str = "rasmapper_spatial_review.png",
    delay_seconds: float = 5.0,
    snapshot_timeout_seconds: float = 1800.0,
    snapshot_poll_interval_seconds: float = 0.5,
    close_after_capture: bool = True,
    viewport_width: Optional[int] = None,
    viewport_height: Optional[int] = None,
    dpi: Optional[int] = None,
    expanded_tree_paths: Optional[Sequence[str]] = None,
    ramp_id: Optional[str] = None,
    range_mode: Optional[str] = None,
    selected_layer: Optional[str] = None,
    result_profile: Optional[str] = None,
    render_mode: Optional[str] = None,
    basemap: Optional[str] = None,
    web_manifest_url: Optional[str] = None,
    rasmapper_exe_path: Optional[Union[str, Path]] = None,
    ras_version: Optional[str] = None,
    strict_preflight: bool = True,
    require_snapshot: bool = False,
    ras_object=None,
) -> Dict[str, Any]:
    """
    Build a deterministic RASMapper spatial QA/QC evidence bundle.

    The bundle records before/after ``.rasmap`` state, layer catalogs,
    preflight checks, view/zoom metadata, and a findings template. It is
    headless by default; pass ``capture_snapshot=True`` to launch standalone
    RASMapper and add a screenshot on a Windows review machine. The
    ``snapshot_timeout_seconds`` parameter defaults to 1800 seconds and can
    be shortened for smoke tests or lengthened for very large projects.
    Feature-focused views keep the full RASMapper layer visible and center
    on the selected HDF feature, with 50% overall viewport expansion by
    default for surrounding mesh and terrain context. Result and map layers
    are hidden by default unless included or selected, which keeps review
    figures deterministic.
    """
    from . import _rasmap_control_helper as _rch

    resolved_project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object,
    )
    return _rch.create_spatial_review_package(
        resolved_project_path,
        output_dir=output_dir,
        geometry_number=geometry_number,
        geometry_name=geometry_name,
        layer_type=layer_type,
        layer_name=layer_name,
        feature_id=feature_id,
        feature_name=feature_name,
        feature_index=feature_index,
        terrain_name=terrain_name,
        result_plan_name=result_plan_name,
        result_layer_name=result_layer_name,
        result_layer_type=result_layer_type,
        map_layer_name=map_layer_name,
        map_layer_type=map_layer_type,
        map_layer_category=map_layer_category,
        include_terrain=include_terrain,
        include_results=include_results,
        include_map_layers=include_map_layers,
        exclusive_geometry=exclusive_geometry,
        exclusive_terrain=exclusive_terrain,
        exclusive_results=exclusive_results,
        exclusive_map_layers=exclusive_map_layers,
        update_legend_with_view=update_legend_with_view,
        zoom_to_layer=zoom_to_layer,
        padding_fraction=padding_fraction,
        min_padding=min_padding,
        capture_snapshot=capture_snapshot,
        snapshot_filename=snapshot_filename,
        delay_seconds=delay_seconds,
        snapshot_timeout_seconds=snapshot_timeout_seconds,
        snapshot_poll_interval_seconds=snapshot_poll_interval_seconds,
        close_after_capture=close_after_capture,
        viewport_width=viewport_width,
        viewport_height=viewport_height,
        dpi=dpi,
        expanded_tree_paths=expanded_tree_paths,
        ramp_id=ramp_id,
        range_mode=range_mode,
        selected_layer=selected_layer,
        result_profile=result_profile,
        render_mode=render_mode,
        basemap=basemap,
        web_manifest_url=web_manifest_url,
        rasmapper_exe_path=rasmapper_exe_path,
        ras_version=ras_version,
        strict_preflight=strict_preflight,
        require_snapshot=require_snapshot,
        ras_object=ras_object,
    )

set_water_surface_render_mode staticmethod

Python
set_water_surface_render_mode(mode: str = 'horizontal', reduce_shallow_to_horizontal: bool = True, use_depth_weighted_faces: bool = False, ras_object=None) -> bool

Set the water surface rendering mode in the RASMapper configuration file.

This modifies the .rasmap file to change how RASMapper renders water surfaces when generating raster outputs. The setting affects stored map exports and on-screen display.

Parameters:

Name Type Description Default
mode str

Rendering mode. Options: - "horizontal": Constant water surface elevation per mesh cell. Each cell displays a single, flat water surface. Faster rendering. - "sloping": Sloped water surface using 4-corner cell elevations. Basic interpolation within each cell. - "slopingPretty": Enhanced sloped mode using 8-point interpolation (4 corners + 4 face centers). Smoothest visualization. Supports optional reduce_shallow_to_horizontal and use_depth_weighted_faces flags.

'horizontal'
reduce_shallow_to_horizontal bool

When True, shallow cells fall back to horizontal rendering. Only applies to slopingPretty mode. Default: True.

True
use_depth_weighted_faces bool

When True, face contributions are weighted by depth. Only applies to slopingPretty mode. Default: False.

False
ras_object RasPrj

Optional RAS object instance.

None

Returns:

Type Description
bool

True if successful, False otherwise.

Raises:

Type Description
ValueError

If an invalid mode is specified.

FileNotFoundError

If the .rasmap file doesn't exist.

Examples:

Python Console Session
>>> from ras_commander import init_ras_project, RasMap
>>> init_ras_project(r"C:/Projects/MyModel", "7.0")
>>>
>>> # Set horizontal mode (flat WSE per cell)
>>> RasMap.set_water_surface_render_mode("horizontal")
>>>
>>> # Set basic sloping mode (4-corner interpolation)
>>> RasMap.set_water_surface_render_mode("sloping")
>>>
>>> # Set slopingPretty mode (8-point interpolation, smoothest)
>>> RasMap.set_water_surface_render_mode("slopingPretty")
>>>
>>> # slopingPretty with depth-weighted faces (HEC-RAS 6.31 style)
>>> RasMap.set_water_surface_render_mode(
...     "slopingPretty",
...     reduce_shallow_to_horizontal=True,
...     use_depth_weighted_faces=True
... )
Notes
  • Changes take effect the next time RASMapper generates raster outputs
  • "horizontal" mode uses constant WSE per cell
  • "sloping" mode uses 4-corner interpolation within each cell
  • "slopingPretty" mode uses 8-point interpolation for smoothest results
  • The original .rasmap file is modified in place (no backup created)
  • The legacy mode name "sloped" is accepted as an alias for "slopingPretty"
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def set_water_surface_render_mode(
    mode: str = "horizontal",
    reduce_shallow_to_horizontal: bool = True,
    use_depth_weighted_faces: bool = False,
    ras_object=None,
) -> bool:
    """
    Set the water surface rendering mode in the RASMapper configuration file.

    This modifies the .rasmap file to change how RASMapper renders water surfaces
    when generating raster outputs. The setting affects stored map exports and
    on-screen display.

    Args:
        mode (str): Rendering mode. Options:
            - "horizontal": Constant water surface elevation per mesh cell.
              Each cell displays a single, flat water surface. Faster rendering.
            - "sloping": Sloped water surface using 4-corner cell elevations.
              Basic interpolation within each cell.
            - "slopingPretty": Enhanced sloped mode using 8-point interpolation
              (4 corners + 4 face centers). Smoothest visualization.
              Supports optional reduce_shallow_to_horizontal and
              use_depth_weighted_faces flags.
        reduce_shallow_to_horizontal (bool): When True, shallow cells fall back
            to horizontal rendering. Only applies to slopingPretty mode.
            Default: True.
        use_depth_weighted_faces (bool): When True, face contributions are
            weighted by depth. Only applies to slopingPretty mode.
            Default: False.
        ras_object (RasPrj, optional): Optional RAS object instance.

    Returns:
        bool: True if successful, False otherwise.

    Raises:
        ValueError: If an invalid mode is specified.
        FileNotFoundError: If the .rasmap file doesn't exist.

    Examples:
        >>> from ras_commander import init_ras_project, RasMap
        >>> init_ras_project(r"C:/Projects/MyModel", "7.0")
        >>>
        >>> # Set horizontal mode (flat WSE per cell)
        >>> RasMap.set_water_surface_render_mode("horizontal")
        >>>
        >>> # Set basic sloping mode (4-corner interpolation)
        >>> RasMap.set_water_surface_render_mode("sloping")
        >>>
        >>> # Set slopingPretty mode (8-point interpolation, smoothest)
        >>> RasMap.set_water_surface_render_mode("slopingPretty")
        >>>
        >>> # slopingPretty with depth-weighted faces (HEC-RAS 6.31 style)
        >>> RasMap.set_water_surface_render_mode(
        ...     "slopingPretty",
        ...     reduce_shallow_to_horizontal=True,
        ...     use_depth_weighted_faces=True
        ... )

    Notes:
        - Changes take effect the next time RASMapper generates raster outputs
        - "horizontal" mode uses constant WSE per cell
        - "sloping" mode uses 4-corner interpolation within each cell
        - "slopingPretty" mode uses 8-point interpolation for smoothest results
        - The original .rasmap file is modified in place (no backup created)
        - The legacy mode name "sloped" is accepted as an alias for "slopingPretty"
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    # Validate and normalize mode
    mode_lower = mode.lower()
    # Accept legacy alias
    if mode_lower == "sloped":
        mode_lower = "slopingpretty"
    valid_modes = {"horizontal", "sloping", "slopingpretty"}
    if mode_lower not in valid_modes:
        raise ValueError(
            f"Invalid mode '{mode}'. Valid options: 'horizontal', 'sloping', 'slopingPretty'"
        )

    # Get rasmap path
    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    if not rasmap_path.exists():
        raise FileNotFoundError(f"RASMapper file not found: {rasmap_path}")

    try:
        # Parse the XML file
        tree = ET.parse(rasmap_path)
        root = tree.getroot()

        # Find or create RenderMode element
        render_mode_elem = root.find("RenderMode")
        if render_mode_elem is None:
            # Insert after Units element or at the end
            units_elem = root.find("Units")
            if units_elem is not None:
                idx = list(root).index(units_elem) + 1
                render_mode_elem = ET.Element("RenderMode")
                root.insert(idx, render_mode_elem)
            else:
                render_mode_elem = ET.SubElement(root, "RenderMode")

        # Find existing depth-weighted and reduce-shallow elements
        depth_weighted_elem = root.find("UseDepthWeightedFaces")
        reduce_shallow_elem = root.find("ReduceShallowToHorizontal")

        if mode_lower == "horizontal":
            render_mode_elem.text = "horizontal"

            # Remove sloped-specific elements if present
            if depth_weighted_elem is not None:
                root.remove(depth_weighted_elem)
            if reduce_shallow_elem is not None:
                root.remove(reduce_shallow_elem)

            logger.info("Set water surface render mode to 'horizontal'")

        elif mode_lower == "sloping":
            render_mode_elem.text = "sloping"

            # Remove slopingPretty-specific elements if present
            if depth_weighted_elem is not None:
                root.remove(depth_weighted_elem)
            if reduce_shallow_elem is not None:
                root.remove(reduce_shallow_elem)

            logger.info("Set water surface render mode to 'sloping'")

        elif mode_lower == "slopingpretty":
            render_mode_elem.text = "slopingPretty"

            # Add/update reduce-shallow element
            if reduce_shallow_to_horizontal:
                if reduce_shallow_elem is None:
                    idx = list(root).index(render_mode_elem) + 1
                    reduce_shallow_elem = ET.Element("ReduceShallowToHorizontal")
                    root.insert(idx, reduce_shallow_elem)
                reduce_shallow_elem.text = "true"
            else:
                if reduce_shallow_elem is not None:
                    root.remove(reduce_shallow_elem)

            # Add/update depth-weighted faces element
            if use_depth_weighted_faces:
                if depth_weighted_elem is None:
                    # Insert after RenderMode (or after ReduceShallowToHorizontal if present)
                    after_elem = (
                        reduce_shallow_elem
                        if reduce_shallow_elem is not None
                        else render_mode_elem
                    )
                    idx = list(root).index(after_elem) + 1
                    depth_weighted_elem = ET.Element("UseDepthWeightedFaces")
                    root.insert(idx, depth_weighted_elem)
                depth_weighted_elem.text = "true"
            else:
                if depth_weighted_elem is not None:
                    root.remove(depth_weighted_elem)

            logger.info(
                f"Set water surface render mode to 'slopingPretty' "
                f"(reduceShallow={reduce_shallow_to_horizontal}, "
                f"depthWeighted={use_depth_weighted_faces})"
            )

        # Write the modified XML back
        _write_ras_xml(tree, rasmap_path, encoding="utf-8", xml_declaration=True)
        logger.debug("Updated RASMapper configuration: %s", rasmap_path)

        return True

    except Exception as e:
        logger.error(f"Error setting water surface render mode: {e}")
        return False

get_water_surface_render_mode staticmethod

Python
get_water_surface_render_mode(ras_object=None) -> Optional[dict]

Get the current water surface rendering mode from the RASMapper configuration.

Parameters:

Name Type Description Default
ras_object RasPrj

Optional RAS object instance.

None

Returns:

Type Description
Optional[dict]

Rendering mode configuration with keys: - "mode": The rendering mode string — "horizontal", "sloping", or "slopingPretty" - "reduce_shallow_to_horizontal": bool, whether shallow cells fall back to horizontal (only for slopingPretty) - "use_depth_weighted_faces": bool, whether face contributions are depth-weighted (only for slopingPretty) Returns None if .rasmap file not found or mode not set.

Examples:

Python Console Session
>>> from ras_commander import init_ras_project, RasMap
>>> init_ras_project(r"C:/Projects/MyModel", "7.0")
>>> render_info = RasMap.get_water_surface_render_mode()
>>> print(f"Mode: {render_info['mode']}")
>>> # For slopingPretty, check flags:
>>> if render_info['mode'] == 'slopingPretty':
...     print(f"Depth weighted: {render_info['use_depth_weighted_faces']}")
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def get_water_surface_render_mode(ras_object=None) -> Optional[dict]:
    """
    Get the current water surface rendering mode from the RASMapper configuration.

    Args:
        ras_object (RasPrj, optional): Optional RAS object instance.

    Returns:
        Optional[dict]: Rendering mode configuration with keys:
            - "mode": The rendering mode string — "horizontal", "sloping",
              or "slopingPretty"
            - "reduce_shallow_to_horizontal": bool, whether shallow cells
              fall back to horizontal (only for slopingPretty)
            - "use_depth_weighted_faces": bool, whether face contributions
              are depth-weighted (only for slopingPretty)
            Returns None if .rasmap file not found or mode not set.

    Examples:
        >>> from ras_commander import init_ras_project, RasMap
        >>> init_ras_project(r"C:/Projects/MyModel", "7.0")
        >>> render_info = RasMap.get_water_surface_render_mode()
        >>> print(f"Mode: {render_info['mode']}")
        >>> # For slopingPretty, check flags:
        >>> if render_info['mode'] == 'slopingPretty':
        ...     print(f"Depth weighted: {render_info['use_depth_weighted_faces']}")
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    if not rasmap_path.exists():
        logger.warning(f"RASMapper file not found: {rasmap_path}")
        return None

    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()

        render_mode_elem = root.find("RenderMode")
        if render_mode_elem is None or render_mode_elem.text is None:
            return None

        mode_text = render_mode_elem.text.strip()

        # Read associated flags
        depth_weighted_elem = root.find("UseDepthWeightedFaces")
        reduce_shallow_elem = root.find("ReduceShallowToHorizontal")

        has_depth_weighted = (
            depth_weighted_elem is not None
            and depth_weighted_elem.text is not None
            and depth_weighted_elem.text.strip().lower() == "true"
        )
        has_reduce_shallow = (
            reduce_shallow_elem is not None
            and reduce_shallow_elem.text is not None
            and reduce_shallow_elem.text.strip().lower() == "true"
        )

        # Normalize mode text to canonical form
        mode_lower = mode_text.lower()
        if mode_lower == "horizontal":
            canonical_mode = "horizontal"
        elif mode_lower == "slopingpretty":
            canonical_mode = "slopingPretty"
        elif mode_lower == "sloping":
            # "sloping" with both flags is effectively slopingPretty (HEC-RAS 6.31 style)
            if has_depth_weighted and has_reduce_shallow:
                canonical_mode = "slopingPretty"
            else:
                canonical_mode = "sloping"
        else:
            logger.warning(f"Unknown render mode in rasmap: {mode_text}")
            canonical_mode = mode_text

        return {
            "mode": canonical_mode,
            "reduce_shallow_to_horizontal": has_reduce_shallow,
            "use_depth_weighted_faces": has_depth_weighted,
        }

    except Exception as e:
        logger.error(f"Error reading water surface render mode: {e}")
        return None

RASMapper layers and associations

Import RasMap from ras_commander and call its static methods. Project-path readers and initialized-project methods have different signatures: pass the project path or ras_object accepted by the selected method rather than assuming every method uses the global project.

Operation Input Return / persisted effect
parse_rasmap, layer-list methods .rasmap or project path, as documented below DataFrames or lists describing configured layers
add_terrain_layer Existing terrain HDF Registers terrain in .rasmap; does not create elevation data
add_landcover_layer, add_soils_layer, add_infiltration_layer Classification sources and project Created layer HDF path and registration
Classification polygon CRUD Layer HDF, feature selectors and polygon/class data GeoDataFrame; native polygon edits for authoring calls
Reference maps and basemaps Existing vector file or supported basemap name .rasmap registration, with method-specific path or Boolean return
Geometry association inspection/validation Compiled geometry HDF or project Association dictionaries or diagnostic DataFrames
associate_geometry_layers Compiled geometry and terrain/classification paths Updated geometry HDF path
recompute_property_tables Geometry and selected native version Updated HDF path after native property-table processing

Native classification creation and polygon authoring require the HEC-RAS runtime supported by that method; reading a layer inventory is a separate operation. Check source CRS, project units and extent explicitly; see the spatial extent contract.

Before computing property tables, inspect and validate the compiled-HDF associations. Afterwards inspect final cell properties, including Manning's n, using the HDF API. An XML registration alone is insufficient. RasProcess.validate_geometry_association_cli() on the geometry completion page is a mutating native reference validator, intended for disposable copies, not a read-only association check.

Examples with retained outputs: 233 — classification polygons and 931 — native terrain export.

Layer discovery and authoring

Class for parsing and accessing information from HEC-RAS mapper configuration files (.rasmap).

This class provides methods to extract paths to terrain, soil, land cover data, and various project settings from the .rasmap file associated with a HEC-RAS project. It also includes functionality to automate the post-processing of stored maps.

parse_rasmap staticmethod

Python
parse_rasmap(rasmap_path: Union[str, Path], ras_object=None) -> pd.DataFrame

Parse a .rasmap file and extract relevant information.

Parameters:

Name Type Description Default
rasmap_path Union[str, Path]

Path to the .rasmap file.

required
ras_object RasPrj

Optional RAS object instance. Retained for API compatibility; parsing does not require project state.

None

Returns:

Type Description
DataFrame

A single-row frame containing extracted information and explicit parse provenance.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def parse_rasmap(rasmap_path: Union[str, Path], ras_object=None) -> pd.DataFrame:
    """
    Parse a .rasmap file and extract relevant information.

    Args:
        rasmap_path (Union[str, Path]): Path to the .rasmap file.
        ras_object (RasPrj, optional): Optional RAS object instance. Retained for API
            compatibility; parsing does not require project state.

    Returns:
        pd.DataFrame: A single-row frame containing extracted information
            and explicit parse provenance.
    """
    rasmap_path = Path(rasmap_path)

    try:
        if not rasmap_path.exists():
            logger.error(f"RASMapper file not found: {rasmap_path}")
            return create_rasmap_dataframe(
                rasmap_path=rasmap_path,
                rasmap_status="absent",
            )

        try:
            root = ET.fromstring(rasmap_path.read_bytes())
        except ET.ParseError as e:
            logger.error(f"Error parsing XML in {rasmap_path}: {e}")
            return create_rasmap_dataframe(
                rasmap_path=rasmap_path,
                rasmap_status="failed",
                rasmap_error=f"ParseError: {e}",
            )

        root_name = root.tag.rsplit("}", 1)[-1]
        if root_name != "RASMapper":
            message = (
                "ValueError: Expected RASMapper root element, "
                f"found {root.tag!r}"
            )
            logger.error("Invalid RASMapper document %s: %s", rasmap_path, message)
            return create_rasmap_dataframe(
                rasmap_path=rasmap_path,
                rasmap_status="failed",
                rasmap_error=message,
            )

        from . import _land_classification_helper as _lch
        from . import _rasmap_layer_helper as _mlh

        map_layers = _mlh.top_level_map_layers(root)
        data = create_rasmap_dataframe(
            rasmap_path=rasmap_path,
            rasmap_status="parsed",
        ).to_dict(orient="list")
        field_errors: Dict[str, str] = {}

        def record_field_error(
            columns: Union[str, Sequence[str]],
            description: str,
            exc: Exception,
        ) -> None:
            affected_columns = [columns] if isinstance(columns, str) else columns
            message = f"{type(exc).__name__}: {exc}"
            for column in affected_columns:
                previous = field_errors.get(column)
                field_errors[column] = (
                    f"{previous}; {message}" if previous else message
                )
            logger.warning("Error extracting %s: %s", description, message)

        # Extract projection path
        try:
            projection_elem = root.find(".//RASProjectionFilename")
            if projection_elem is not None and "Filename" in projection_elem.attrib:
                projection_path = _lch.resolve_rasmap_relative_path(
                    rasmap_path.parent,
                    projection_elem.attrib["Filename"],
                )
                data["projection_path"][0] = (
                    str(projection_path) if projection_path is not None else None
                )
        except Exception as e:
            record_field_error("projection_path", "projection path", e)

        # Extract profile lines path
        try:
            profile_lines_elem = root.find(
                ".//Features/Layer[@Name='Profile Lines']"
            )
            if (
                profile_lines_elem is not None
                and "Filename" in profile_lines_elem.attrib
            ):
                profile_lines_path = _lch.resolve_rasmap_relative_path(
                    rasmap_path.parent,
                    profile_lines_elem.attrib["Filename"],
                )
                if profile_lines_path is not None:
                    data["profile_lines_path"][0].append(str(profile_lines_path))
        except Exception as e:
            record_field_error("profile_lines_path", "profile lines path", e)

        land_columns = (
            "soil_layer_path",
            "infiltration_hdf_path",
            "landcover_hdf_path",
        )
        try:
            land_records = []
            for layer in map_layers:
                if layer.attrib.get("Type") not in _mlh.LAND_CLASSIFICATION_LAYER_TYPES:
                    continue
                try:
                    if not layer.attrib.get("Filename", "").strip():
                        raise ValueError(
                            "Land-classification declaration is missing Filename"
                        )
                    land_records.append(
                        _lch.build_land_classification_record(
                            layer,
                            rasmap_path.parent,
                        )
                    )
                except Exception as e:
                    record_field_error(
                        land_columns,
                        "land-classification layer declaration",
                        e,
                    )

            if land_records:
                land_layers = pd.DataFrame(land_records)
                for kind, target_column in (
                    ("soils", "soil_layer_path"),
                    ("infiltration", "infiltration_hdf_path"),
                    ("landcover", "landcover_hdf_path"),
                ):
                    paths = [
                        str(path)
                        for path in land_layers.loc[
                            land_layers["classification_kind"] == kind,
                            "resolved_path",
                        ]
                        .dropna()
                        .tolist()
                    ]
                    data[target_column][0] = paths
        except Exception as e:
            record_field_error(
                land_columns,
                "land-classification layer paths",
                e,
            )

        # Extract terrain HDF paths
        try:
            terrain_layers = root.findall(".//Terrains/Layer")
            terrain_paths = []
            for layer in terrain_layers:
                try:
                    filename = layer.attrib.get("Filename", "")
                    if not filename.strip():
                        raise ValueError(
                            "Terrain layer declaration is missing Filename"
                        )
                    terrain_path = _lch.resolve_rasmap_relative_path(
                        rasmap_path.parent,
                        filename,
                    )
                    if terrain_path is not None:
                        terrain_paths.append(str(terrain_path))
                except Exception as e:
                    record_field_error(
                        "terrain_hdf_path",
                        "terrain layer declaration",
                        e,
                    )
            data["terrain_hdf_path"][0] = terrain_paths
        except Exception as e:
            record_field_error("terrain_hdf_path", "terrain HDF paths", e)

        try:
            reference_names = []
            reference_paths = []
            for layer in map_layers:
                if layer.attrib.get("Type") not in _mlh.REFERENCE_MAP_LAYER_TYPES:
                    continue
                reference_names.append(layer.attrib.get("Name", ""))
                filename = layer.attrib.get("Filename", "")
                if not filename.strip():
                    record_field_error(
                        "reference_map_layer_path",
                        "reference map layer declaration",
                        ValueError(
                            "Reference map layer declaration is missing Filename"
                        ),
                    )
                    continue
                try:
                    resolved_path = _lch.resolve_rasmap_relative_path(
                        rasmap_path.parent,
                        filename,
                    )
                    if resolved_path is not None:
                        reference_paths.append(str(resolved_path))
                except Exception as e:
                    record_field_error(
                        "reference_map_layer_path",
                        "reference map layer declaration",
                        e,
                    )
            data["reference_map_layer_names"][0] = reference_names
            data["reference_map_layer_path"][0] = reference_paths
        except Exception as e:
            record_field_error(
                ("reference_map_layer_names", "reference_map_layer_path"),
                "reference map layers",
                e,
            )

        try:
            basemap_names = []
            basemap_paths = []
            for layer in map_layers:
                if layer.attrib.get("Type") != _mlh.BASEMAP_LAYER_TYPE:
                    continue
                basemap_names.append(layer.attrib.get("Name", ""))
                filename = layer.attrib.get("Filename", "")
                if not filename.strip():
                    record_field_error(
                        "basemap_layer_path",
                        "basemap layer declaration",
                        ValueError("Basemap layer declaration is missing Filename"),
                    )
                    continue
                try:
                    resolved_path = _lch.resolve_rasmap_relative_path(
                        rasmap_path.parent,
                        filename,
                    )
                    if resolved_path is not None:
                        basemap_paths.append(str(resolved_path))
                except Exception as e:
                    record_field_error(
                        "basemap_layer_path",
                        "basemap layer declaration",
                        e,
                    )
            data["basemap_layer_names"][0] = basemap_names
            data["basemap_layer_path"][0] = basemap_paths
        except Exception as e:
            record_field_error(
                ("basemap_layer_names", "basemap_layer_path"),
                "basemap layers",
                e,
            )

        # Extract current settings
        current_settings = {}
        try:
            settings_elem = root.find(".//CurrentSettings")
            if settings_elem is not None:
                # Extract ProjectSettings
                project_settings_elem = settings_elem.find("ProjectSettings")
                if project_settings_elem is not None:
                    for child in project_settings_elem:
                        current_settings[child.tag] = child.text

                # Extract Folders
                folders_elem = settings_elem.find("Folders")
                if folders_elem is not None:
                    for child in folders_elem:
                        current_settings[child.tag] = child.text

            data["current_settings"][0] = current_settings
        except Exception as e:
            record_field_error("current_settings", "current settings", e)

        data["rasmap_field_errors"][0] = field_errors
        data["rasmap_status"][0] = (
            "parsed_with_errors" if field_errors else "parsed"
        )
        df = pd.DataFrame(data)
        logger.debug(
            "Parsed RASMapper file: %s (status=%s, terrains=%d, "
            "reference_layers=%d, basemaps=%d)",
            rasmap_path.name,
            data["rasmap_status"][0],
            len(data.get("terrain_hdf_path", [[]])[0] or []),
            len(data.get("reference_map_layer_names", [[]])[0] or []),
            len(data.get("basemap_layer_names", [[]])[0] or []),
        )
        return df

    except Exception as e:
        logger.error(
            f"Unexpected error processing RASMapper file {rasmap_path}: {e}"
        )
        return create_rasmap_dataframe(
            rasmap_path=rasmap_path,
            rasmap_status="failed",
            rasmap_error=f"{type(e).__name__}: {e}",
        )

list_land_classification_layers staticmethod

Python
list_land_classification_layers(ras_project_path: Union[str, Path], ras_object=None) -> pd.DataFrame

List semantic land-classification layers from a project .rasmap file.

Classifies each modern Type="LandCoverLayer" and legacy Type="LandCover" entry as landcover, soils, infiltration, or unknown using filename and selected parameter semantics rather than exact display names.

Parameters:

Name Type Description Default
ras_project_path Union[str, Path]

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

required
ras_object RasPrj

Optional RasPrj object. Present for API consistency.

None

Returns:

Type Description
DataFrame

DataFrame with one row per LandCoverLayer entry.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_land_classification_layers(
    ras_project_path: Union[str, Path],
    ras_object=None,
) -> pd.DataFrame:
    """
    List semantic land-classification layers from a project .rasmap file.

    Classifies each modern ``Type="LandCoverLayer"`` and legacy
    ``Type="LandCover"`` entry as ``landcover``, ``soils``,
    ``infiltration``, or ``unknown`` using filename and selected parameter
    semantics rather than exact display names.

    Args:
        ras_project_path: Project folder, .prj file, or .rasmap file.
        ras_object (RasPrj, optional): Optional RasPrj object. Present for API consistency.

    Returns:
        DataFrame with one row per LandCoverLayer entry.
    """
    ras_project_path = Path(ras_project_path)
    from . import _land_classification_helper as _lch

    project_paths = _lch.resolve_project_paths(ras_project_path)
    rasmap_path = project_paths.rasmap_path

    columns = [
        "name",
        "type",
        "checked",
        "filename",
        "resolved_path",
        "selected_parameter",
        "classification_kind",
        "classification_layer_count",
        "classification_layer_filenames",
        "classification_layer_paths",
    ]

    if not rasmap_path.exists():
        logger.warning(f"RASMapper file not found: {rasmap_path}")
        return pd.DataFrame(columns=columns)

    try:
        root = ET.parse(rasmap_path).getroot()
    except ET.ParseError as e:
        logger.error(f"Error parsing .rasmap XML: {e}")
        return pd.DataFrame(columns=columns)

    from . import _rasmap_layer_helper as _mlh

    records = []
    for layer in _mlh.top_level_map_layers(root):
        if layer.attrib.get("Type") not in _mlh.LAND_CLASSIFICATION_LAYER_TYPES:
            continue
        records.append(
            _lch.build_land_classification_record(
                layer,
                project_paths.project_folder,
            )
        )

    if not records:
        return pd.DataFrame(columns=columns)

    return pd.DataFrame(records, columns=columns)

list_terrain_layers staticmethod

Python
list_terrain_layers(ras_project_path: Union[str, Path], ras_object=None) -> pd.DataFrame

List terrain layers registered in a project .rasmap file.

Parameters:

Name Type Description Default
ras_project_path Union[str, Path]

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

required
ras_object RasPrj

Optional RasPrj object. Present for API consistency.

None

Returns:

Type Description
DataFrame

DataFrame with one row per Terrains/Layer entry.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_terrain_layers(
    ras_project_path: Union[str, Path],
    ras_object=None,
) -> pd.DataFrame:
    """
    List terrain layers registered in a project .rasmap file.

    Args:
        ras_project_path: Project folder, .prj file, or .rasmap file.
        ras_object (RasPrj, optional): Optional RasPrj object. Present for API consistency.

    Returns:
        DataFrame with one row per ``Terrains/Layer`` entry.
    """
    ras_project_path = Path(ras_project_path)
    from . import _land_classification_helper as _lch

    project_paths = _lch.resolve_project_paths(ras_project_path)
    rasmap_path = project_paths.rasmap_path
    columns = [
        "name",
        "filename",
        "resolved_path",
        "checked",
        "type",
        "resample_method",
        "surface_on",
    ]

    if not rasmap_path.exists():
        logger.warning(f"RASMapper file not found: {rasmap_path}")
        return pd.DataFrame(columns=columns)

    try:
        root = ET.parse(rasmap_path).getroot()
    except ET.ParseError as e:
        logger.error(f"Error parsing .rasmap XML: {e}")
        return pd.DataFrame(columns=columns)

    records = []
    for layer in root.findall(".//Terrains/Layer"):
        filename = layer.attrib.get("Filename")
        resolved_path = _lch.resolve_rasmap_relative_path(
            project_paths.project_folder,
            filename,
        )
        surface = layer.find("Surface")
        records.append(
            {
                "name": layer.attrib.get("Name", ""),
                "filename": filename,
                "resolved_path": (
                    str(resolved_path) if resolved_path is not None else None
                ),
                "checked": layer.attrib.get("Checked", "True").lower() == "true",
                "type": layer.attrib.get("Type", ""),
                "resample_method": layer.findtext("ResampleMethod"),
                "surface_on": (
                    surface.attrib.get("On", "False").lower() == "true"
                    if surface is not None
                    else None
                ),
            }
        )

    return pd.DataFrame(records, columns=columns)

list_landcover_layers staticmethod

Python
list_landcover_layers(ras_project_path: Union[str, Path], ras_object=None) -> pd.DataFrame

List land-cover layers registered in a project .rasmap file.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_landcover_layers(
    ras_project_path: Union[str, Path],
    ras_object=None,
) -> pd.DataFrame:
    """List land-cover layers registered in a project .rasmap file."""
    layers = RasMap.list_land_classification_layers(
        ras_project_path,
        ras_object=ras_object,
    )
    return layers.loc[layers["classification_kind"] == "landcover"].copy()

list_soils_layers staticmethod

Python
list_soils_layers(ras_project_path: Union[str, Path], ras_object=None) -> pd.DataFrame

List hydrologic soils layers registered in a project .rasmap file.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_soils_layers(
    ras_project_path: Union[str, Path],
    ras_object=None,
) -> pd.DataFrame:
    """List hydrologic soils layers registered in a project .rasmap file."""
    layers = RasMap.list_land_classification_layers(
        ras_project_path,
        ras_object=ras_object,
    )
    return layers.loc[layers["classification_kind"] == "soils"].copy()

list_infiltration_layers staticmethod

Python
list_infiltration_layers(ras_project_path: Union[str, Path], ras_object=None) -> pd.DataFrame

List infiltration layers registered in a project .rasmap file.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_infiltration_layers(
    ras_project_path: Union[str, Path],
    ras_object=None,
) -> pd.DataFrame:
    """List infiltration layers registered in a project .rasmap file."""
    layers = RasMap.list_land_classification_layers(
        ras_project_path,
        ras_object=ras_object,
    )
    return layers.loc[layers["classification_kind"] == "infiltration"].copy()

list_land_classification_polygons staticmethod

Python
list_land_classification_polygons(layer_hdf_path: Union[str, Path], ras_object=None) -> GeoDataFrame

List classification polygon overrides stored in a land-classification HDF.

Parameters:

Name Type Description Default
layer_hdf_path Union[str, Path]

Land-cover, soils, or infiltration sidecar HDF.

required
ras_object RasPrj

Optional RasPrj object. Present for API consistency.

None

Returns:

Type Description
GeoDataFrame

GeoDataFrame with polygon_index, class_name, and geometry.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_land_classification_polygons(
    layer_hdf_path: Union[str, Path],
    ras_object=None,
) -> "GeoDataFrame":
    """
    List classification polygon overrides stored in a land-classification HDF.

    Args:
        layer_hdf_path: Land-cover, soils, or infiltration sidecar HDF.
        ras_object (RasPrj, optional): Optional RasPrj object. Present for API consistency.

    Returns:
        GeoDataFrame with ``polygon_index``, ``class_name``, and geometry.
    """
    from . import _land_classification_helper as _lch

    return _lch.list_land_classification_polygons(layer_hdf_path)

add_land_classification_polygon staticmethod

Python
add_land_classification_polygon(layer_hdf_path: Union[str, Path], polygon: Any, class_name: str, class_id: Optional[int] = None, variable_values: Optional[Mapping[str, Any]] = None, backup: bool = True, hecras_version: Optional[str] = None, ras_object=None) -> GeoDataFrame

Add one land-cover classification polygon through native RasMapperLib.

The class must already exist in the native land-cover sidecar; this method does not create or remap raster classifications. HEC-RAS 6.x and 7.0.x LC Type=LandCover sidecars are supported. HEC-RAS 5.x callers should use the durable geometry Manning-region APIs instead. A GeoSeries/GeoDataFrame must declare the same CRS as the sidecar. Raw Shapely/GeoJSON coordinates are assumed to already use the sidecar CRS. One-member, hole-free MultiPolygon input is normalized. True multipart input and interior rings are rejected before mutation because HEC-RAS 6.0 through 7.0.1 classification resampling cannot honor them. The returned GeoDataFrame exposes classification_hdf_path, backup_path, recompute_required, and class_update in .attrs.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def add_land_classification_polygon(
    layer_hdf_path: Union[str, Path],
    polygon: Any,
    class_name: str,
    class_id: Optional[int] = None,
    variable_values: Optional[Mapping[str, Any]] = None,
    backup: bool = True,
    hecras_version: Optional[str] = None,
    ras_object=None,
) -> "GeoDataFrame":
    """Add one land-cover classification polygon through native RasMapperLib.

    The class must already exist in the native land-cover sidecar; this
    method does not create or remap raster classifications. HEC-RAS 6.x
    and 7.0.x ``LC Type=LandCover`` sidecars are supported. HEC-RAS 5.x
    callers should use the durable geometry Manning-region APIs instead.
    A GeoSeries/GeoDataFrame must declare the same CRS as the sidecar.
    Raw Shapely/GeoJSON coordinates are assumed to already use the sidecar
    CRS. One-member, hole-free ``MultiPolygon`` input is normalized. True
    multipart input and interior rings are rejected before mutation because
    HEC-RAS 6.0 through 7.0.1 classification resampling cannot honor them.
    The returned GeoDataFrame exposes ``classification_hdf_path``,
    ``backup_path``, ``recompute_required``, and ``class_update`` in
    ``.attrs``.
    """
    from . import _land_classification_polygon_native as _lcpn

    version = _resolve_native_hecras_version(hecras_version, ras_object)
    return _lcpn.add_land_classification_polygon(
        layer_hdf_path=layer_hdf_path,
        polygon=polygon,
        class_name=class_name,
        class_id=class_id,
        variable_values=variable_values,
        backup=backup,
        hecras_version=version,
    )

update_land_classification_polygon staticmethod

Python
update_land_classification_polygon(layer_hdf_path: Union[str, Path], polygon_index: int, polygon: Optional[Any] = None, class_name: Optional[str] = None, class_id: Optional[int] = None, variable_values: Optional[Mapping[str, Any]] = None, backup: bool = True, hecras_version: Optional[str] = None, ras_object=None) -> GeoDataFrame

Update one native 6.x/7.0.x land-cover polygon using an existing class.

Polygon and CRS validation follow :meth:add_land_classification_polygon. The returned GeoDataFrame exposes durable backup and recomputation metadata in .attrs.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def update_land_classification_polygon(
    layer_hdf_path: Union[str, Path],
    polygon_index: int,
    polygon: Optional[Any] = None,
    class_name: Optional[str] = None,
    class_id: Optional[int] = None,
    variable_values: Optional[Mapping[str, Any]] = None,
    backup: bool = True,
    hecras_version: Optional[str] = None,
    ras_object=None,
) -> "GeoDataFrame":
    """Update one native 6.x/7.0.x land-cover polygon using an existing class.

    Polygon and CRS validation follow
    :meth:`add_land_classification_polygon`. The returned GeoDataFrame
    exposes durable backup and recomputation metadata in ``.attrs``.
    """
    from . import _land_classification_polygon_native as _lcpn

    version = _resolve_native_hecras_version(hecras_version, ras_object)
    return _lcpn.update_land_classification_polygon(
        layer_hdf_path=layer_hdf_path,
        polygon_index=polygon_index,
        polygon=polygon,
        class_name=class_name,
        class_id=class_id,
        variable_values=variable_values,
        backup=backup,
        hecras_version=version,
    )

delete_land_classification_polygon staticmethod

Python
delete_land_classification_polygon(layer_hdf_path: Union[str, Path], polygon_index: Optional[int] = None, class_name: Optional[str] = None, remove_unused_class: bool = False, backup: bool = True, hecras_version: Optional[str] = None, ras_object=None) -> GeoDataFrame

Delete native 6.x/7.0.x land-cover classification polygons.

The returned GeoDataFrame exposes durable backup, recomputation, and removed-class metadata in .attrs. remove_unused_class=True fails closed because the public native API cannot safely remove a class; rebuild the sidecar classification table instead.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def delete_land_classification_polygon(
    layer_hdf_path: Union[str, Path],
    polygon_index: Optional[int] = None,
    class_name: Optional[str] = None,
    remove_unused_class: bool = False,
    backup: bool = True,
    hecras_version: Optional[str] = None,
    ras_object=None,
) -> "GeoDataFrame":
    """Delete native 6.x/7.0.x land-cover classification polygons.

    The returned GeoDataFrame exposes durable backup, recomputation, and
    removed-class metadata in ``.attrs``. ``remove_unused_class=True``
    fails closed because the public native API cannot safely remove a
    class; rebuild the sidecar classification table instead.
    """
    from . import _land_classification_polygon_native as _lcpn

    version = _resolve_native_hecras_version(hecras_version, ras_object)
    return _lcpn.delete_land_classification_polygon(
        layer_hdf_path=layer_hdf_path,
        polygon_index=polygon_index,
        class_name=class_name,
        remove_unused_class=remove_unused_class,
        backup=backup,
        hecras_version=version,
    )

add_landcover_layer staticmethod

Python
add_landcover_layer(ras_project_path: Union[str, Path], source_path: Union[str, Path], classification_table: Union[DataFrame, str, Path], cell_size: float, source_field: Optional[str] = None, output_hdf_path: Optional[Union[str, Path]] = None, restrict_to_extent: Optional[Any] = None, layer_name: str = 'LandCover', buffer_distance: float = 0.0, hecras_version: Optional[str] = None, ras_object=None) -> Path

Create and register a land-cover classification layer for a RAS project.

restrict_to_extent may be a valid Shapely Polygon, a MultiPolygon containing exactly one non-empty polygonal part, a one-effective-geometry GeoSeries/GeoDataFrame, a four-value bounds tuple/list, a bounds dict/object, or RasMapperLib.Extent. buffer_distance is applied before raster bounds are derived, in project CRS units, and defaults to 0.0. Callers are responsible for supplying geometry in the project CRS. Empty, invalid, non-polygon, and true multipart geometry inputs raise ValueError.

HEC-RAS authors the output TIFF and HDF through RasMapperLib. Version 5.x uses its byte-class legacy schema in a 32-bit helper process; versions 6.x and newer use LandCoverComputable followed by LandCoverLayer.Save() for native V2 normalization.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def add_landcover_layer(
    ras_project_path: Union[str, Path],
    source_path: Union[str, Path],
    classification_table: Union[pd.DataFrame, str, Path],
    cell_size: float,
    source_field: Optional[str] = None,
    output_hdf_path: Optional[Union[str, Path]] = None,
    restrict_to_extent: Optional[Any] = None,
    layer_name: str = "LandCover",
    buffer_distance: float = 0.0,
    hecras_version: Optional[str] = None,
    ras_object=None,
) -> Path:
    """
    Create and register a land-cover classification layer for a RAS project.

    ``restrict_to_extent`` may be a valid Shapely ``Polygon``, a
    ``MultiPolygon`` containing exactly one non-empty polygonal part, a
    one-effective-geometry GeoSeries/GeoDataFrame, a four-value bounds
    tuple/list, a bounds dict/object, or ``RasMapperLib.Extent``.
    ``buffer_distance`` is applied before raster bounds are derived, in
    project CRS units, and defaults to ``0.0``. Callers are responsible for
    supplying geometry in the project CRS. Empty, invalid, non-polygon, and
    true multipart geometry inputs raise ``ValueError``.

    HEC-RAS authors the output TIFF and HDF through RasMapperLib. Version
    5.x uses its byte-class legacy schema in a 32-bit helper process;
    versions 6.x and newer use ``LandCoverComputable`` followed by
    ``LandCoverLayer.Save()`` for native V2 normalization.
    """
    ras_project_path = Path(ras_project_path)
    source_path = Path(source_path)
    output_hdf_path = Path(output_hdf_path) if output_hdf_path is not None else None
    version = _resolve_native_hecras_version(hecras_version, ras_object)
    from . import _land_classification_helper as _lch

    return _lch.add_landcover_layer(
        ras_project_path=ras_project_path,
        source_path=source_path,
        classification_table=classification_table,
        cell_size=cell_size,
        source_field=source_field,
        output_hdf_path=output_hdf_path,
        restrict_to_extent=restrict_to_extent,
        layer_name=layer_name,
        buffer_distance=buffer_distance,
        hecras_version=version,
    )

add_soils_layer staticmethod

Python
add_soils_layer(ras_project_path: Union[str, Path], gssurgo_path: Union[str, Path], cell_size: float, output_hdf_path: Optional[Union[str, Path]] = None, restrict_to_extent: Optional[Any] = None, buffer_distance: float = 0.0, hecras_version: Optional[str] = None, ras_object=None) -> Path

Create and register a soils layer from direct GSSURGO input.

For restricted extents, read whole polygons intersecting the buffered, grid-aligned bounds. Rasterize in tiles of at most 10 million cells; all tiles share one mapping and feed one native soils-layer computation.

restrict_to_extent accepts the same polygon and legacy bounds inputs as :meth:add_landcover_layer. buffer_distance is applied in project CRS units before raster bounds are derived and defaults to 0.0. Multipart, empty, invalid, and non-polygon geometry inputs fail closed.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def add_soils_layer(
    ras_project_path: Union[str, Path],
    gssurgo_path: Union[str, Path],
    cell_size: float,
    output_hdf_path: Optional[Union[str, Path]] = None,
    restrict_to_extent: Optional[Any] = None,
    buffer_distance: float = 0.0,
    hecras_version: Optional[str] = None,
    ras_object=None,
) -> Path:
    """
    Create and register a soils layer from direct GSSURGO input.

    For restricted extents, read whole polygons intersecting the buffered,
    grid-aligned bounds. Rasterize in tiles of at most 10 million cells;
    all tiles share one mapping and feed one native soils-layer computation.

    ``restrict_to_extent`` accepts the same polygon and legacy bounds inputs
    as :meth:`add_landcover_layer`. ``buffer_distance`` is applied in project
    CRS units before raster bounds are derived and defaults to ``0.0``.
    Multipart, empty, invalid, and non-polygon geometry inputs fail closed.
    """
    ras_project_path = Path(ras_project_path)
    gssurgo_path = Path(gssurgo_path)
    output_hdf_path = Path(output_hdf_path) if output_hdf_path is not None else None
    version = _resolve_native_hecras_version(hecras_version, ras_object)
    from . import _land_classification_helper as _lch

    return _lch.add_soils_layer(
        ras_project_path=ras_project_path,
        gssurgo_path=gssurgo_path,
        cell_size=cell_size,
        output_hdf_path=output_hdf_path,
        restrict_to_extent=restrict_to_extent,
        buffer_distance=buffer_distance,
        hecras_version=version,
    )

add_infiltration_layer staticmethod

Python
add_infiltration_layer(ras_project_path: Union[str, Path], infiltration_method: str = 'scs_curve_number', landcover_hdf_path: Optional[Union[str, Path]] = None, soil_layer_path: Optional[Union[str, Path]] = None, output_hdf_path: Optional[Union[str, Path]] = None, scs_reset_time_hours: Optional[float] = None, hecras_version: Optional[str] = None, ras_object=None) -> Path

Create and register an infiltration classification layer.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def add_infiltration_layer(
    ras_project_path: Union[str, Path],
    infiltration_method: str = "scs_curve_number",
    landcover_hdf_path: Optional[Union[str, Path]] = None,
    soil_layer_path: Optional[Union[str, Path]] = None,
    output_hdf_path: Optional[Union[str, Path]] = None,
    scs_reset_time_hours: Optional[float] = None,
    hecras_version: Optional[str] = None,
    ras_object=None,
) -> Path:
    """
    Create and register an infiltration classification layer.
    """
    ras_project_path = Path(ras_project_path)
    landcover_hdf_path = (
        Path(landcover_hdf_path) if landcover_hdf_path is not None else None
    )
    soil_layer_path = Path(soil_layer_path) if soil_layer_path is not None else None
    output_hdf_path = Path(output_hdf_path) if output_hdf_path is not None else None
    version = _resolve_native_hecras_version(hecras_version, ras_object)
    from . import _land_classification_helper as _lch

    return _lch.add_infiltration_layer(
        ras_project_path=ras_project_path,
        infiltration_method=infiltration_method,
        landcover_hdf_path=landcover_hdf_path,
        soil_layer_path=soil_layer_path,
        output_hdf_path=output_hdf_path,
        scs_reset_time_hours=scs_reset_time_hours,
        hecras_version=version,
    )

get_rasmap_path staticmethod

Python
get_rasmap_path(ras_object=None) -> Optional[Path]

Get the path to the .rasmap file based on the current project.

Parameters:

Name Type Description Default
ras_object RasPrj

Optional RAS object instance.

None

Returns:

Type Description
Optional[Path]

Path to the .rasmap file if found, None otherwise.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def get_rasmap_path(ras_object=None) -> Optional[Path]:
    """
    Get the path to the .rasmap file based on the current project.

    Args:
        ras_object (RasPrj, optional): Optional RAS object instance.

    Returns:
        Optional[Path]: Path to the .rasmap file if found, None otherwise.
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    project_name = ras_obj.project_name
    project_folder = ras_obj.project_folder
    rasmap_path = expected_rasmap_path(project_folder, project_name)

    if not rasmap_path.exists():
        logger.warning(f"RASMapper file not found: {rasmap_path}")
        return None

    return rasmap_path

initialize_rasmap_df staticmethod

Python
initialize_rasmap_df(ras_object=None) -> pd.DataFrame

Initialize the rasmap_df as part of project initialization.

Parameters:

Name Type Description Default
ras_object RasPrj

Optional RAS object instance.

None

Returns:

Type Description
DataFrame

DataFrame containing information from the .rasmap file.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def initialize_rasmap_df(ras_object=None) -> pd.DataFrame:
    """
    Initialize the rasmap_df as part of project initialization.

    Args:
        ras_object (RasPrj, optional): Optional RAS object instance.

    Returns:
        pd.DataFrame: DataFrame containing information from the .rasmap file.
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    rasmap_path = RasMap.get_rasmap_path(ras_obj)
    if rasmap_path is None:
        logger.debug(
            "No .rasmap file found for this project. Creating empty rasmap_df."
        )
        return create_rasmap_dataframe(
            rasmap_path=expected_rasmap_path(
                ras_obj.project_folder,
                ras_obj.project_name,
            ),
            rasmap_status="absent",
        )

    return RasMap.parse_rasmap(rasmap_path, ras_obj)

get_terrain_names staticmethod

Python
get_terrain_names(rasmap_path: Union[str, Path]) -> List[str]

Extracts terrain layer names from a given .rasmap file.

Parameters:

Name Type Description Default
rasmap_path Union[str, Path]

Path to the .rasmap file.

required

Returns:

Type Description
List[str]

A list of terrain names.

Raises:

Type Description
FileNotFoundError

If the rasmap file does not exist.

ValueError

If the file is not a valid XML or lacks a 'Terrains' section.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def get_terrain_names(rasmap_path: Union[str, Path]) -> List[str]:
    """
    Extracts terrain layer names from a given .rasmap file.

    Args:
        rasmap_path (Union[str, Path]): Path to the .rasmap file.

    Returns:
        List[str]: A list of terrain names.

    Raises:
        FileNotFoundError: If the rasmap file does not exist.
        ValueError: If the file is not a valid XML or lacks a 'Terrains' section.
    """
    rasmap_path = Path(rasmap_path)
    if not rasmap_path.is_file():
        raise FileNotFoundError(f"The file '{rasmap_path}' does not exist.")

    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()
    except ET.ParseError as e:
        raise ValueError(
            f"Failed to parse the RASMAP file. Ensure it is a valid XML file. Error: {e}"
        )

    terrains_element = root.find("Terrains")
    if terrains_element is None:
        logger.debug("No Terrains section found in %s", rasmap_path.name)
        return []

    terrain_names = [
        layer.get("Name")
        for layer in terrains_element.findall("Layer")
        if layer.get("Name")
    ]
    logger.debug(
        "Found %d terrain layer(s) in %s: %s",
        len(terrain_names),
        rasmap_path.name,
        terrain_names,
    )
    return terrain_names

list_map_layers staticmethod

Python
list_map_layers(ras_project_path: Optional[Union[str, Path]] = None, *, as_dataframe: Optional[bool] = None, ras_object=None) -> Union[pd.DataFrame, List[Dict[str, Any]]]

List top-level MapLayers entries in the RASMapper configuration.

Parameters:

Name Type Description Default
ras_project_path Optional[Union[str, Path]]

Project folder, .prj file, or .rasmap file. If omitted, the active project is used.

None
as_dataframe Optional[bool]

Return a DataFrame when True. When omitted, explicit ras_project_path calls return a DataFrame and legacy active-project calls return the historical list-of-dicts shape.

None
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
Union[DataFrame, List[Dict[str, Any]]]

DataFrame with one row per top-level map layer, or legacy

Union[DataFrame, List[Dict[str, Any]]]

list[dict] when called in legacy mode.

Examples:

Python Console Session
>>> from ras_commander import RasMap
>>> layers = RasMap.list_map_layers("/path/to/project")
>>> layers[["name", "type", "category", "filename"]]
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_map_layers(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    as_dataframe: Optional[bool] = None,
    ras_object=None,
) -> Union[pd.DataFrame, List[Dict[str, Any]]]:
    """
    List top-level ``MapLayers`` entries in the RASMapper configuration.

    Args:
        ras_project_path: Project folder, .prj file, or .rasmap file. If omitted,
            the active project is used.
        as_dataframe: Return a DataFrame when True. When omitted, explicit
            ``ras_project_path`` calls return a DataFrame and legacy active-project
            calls return the historical list-of-dicts shape.
        ras_object (RasPrj, optional): Optional RasPrj object instance.

    Returns:
        DataFrame with one row per top-level map layer, or legacy
        ``list[dict]`` when called in legacy mode.

    Examples:
        >>> from ras_commander import RasMap
        >>> layers = RasMap.list_map_layers("/path/to/project")
        >>> layers[["name", "type", "category", "filename"]]
    """
    from . import _rasmap_layer_helper as _mlh

    legacy_active_call = ras_project_path is None or (
        ras_object is None
        and ras_project_path is not None
        and hasattr(ras_project_path, "check_initialized")
    )
    project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object=ras_object,
    )
    layers = _mlh.list_map_layers(project_path)

    legacy_mode = as_dataframe is False or (
        as_dataframe is None and legacy_active_call
    )
    if legacy_mode:
        warnings.warn(
            "RasMap.list_map_layers() without an explicit project path returns "
            "the legacy list[dict] shape. Pass as_dataframe=True or an explicit "
            "project path for the DataFrame map-layer catalog.",
            FutureWarning,
            stacklevel=2,
        )
        return layers[["name", "type", "filename", "checked"]].to_dict(
            orient="records",
        )

    logger.debug("Found %d map layer(s) in .rasmap", len(layers))
    return layers

list_reference_map_layers staticmethod

Python
list_reference_map_layers(ras_project_path: Optional[Union[str, Path]] = None, *, ras_object=None) -> pd.DataFrame

List shapefile and GeoJSON reference map layers in a project .rasmap.

Reference map layers are top-level MapLayers/Layer entries with Type set to PointFeatureLayer, PolylineFeatureLayer, or PolygonFeatureLayer.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_reference_map_layers(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    ras_object=None,
) -> pd.DataFrame:
    """
    List shapefile and GeoJSON reference map layers in a project ``.rasmap``.

    Reference map layers are top-level ``MapLayers/Layer`` entries with
    ``Type`` set to ``PointFeatureLayer``, ``PolylineFeatureLayer``, or
    ``PolygonFeatureLayer``.
    """
    from . import _rasmap_layer_helper as _mlh

    project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object=ras_object,
    )
    return _mlh.list_reference_map_layers(project_path)

list_basemap_layers staticmethod

Python
list_basemap_layers(ras_project_path: Optional[Union[str, Path]] = None, *, ras_object=None) -> pd.DataFrame

List WMS basemap layers registered in a project .rasmap.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_basemap_layers(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    ras_object=None,
) -> pd.DataFrame:
    """List WMS basemap layers registered in a project ``.rasmap``."""
    from . import _rasmap_layer_helper as _mlh

    project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object=ras_object,
    )
    return _mlh.list_basemap_layers(project_path)

set_map_layer_visibility staticmethod

Python
set_map_layer_visibility(ras_project_path: Optional[Union[str, Path]] = None, *, checked: bool = True, layer_name: Optional[Union[str, Sequence[str]]] = None, layer_type: Optional[Union[str, Sequence[str]]] = None, category: Optional[Union[str, Sequence[str]]] = None, exclusive: bool = False, ras_object=None) -> int

Toggle top-level RASMapper MapLayers entries.

Targets reference maps, basemaps, land-classification layers, or other map-layer entries by name, type, or category. When no selector is supplied, all map layers are targeted. Use exclusive=True with checked=True to hide every non-matching map layer and show only the layers needed for a figure.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def set_map_layer_visibility(
    ras_project_path: Optional[Union[str, Path]] = None,
    *,
    checked: bool = True,
    layer_name: Optional[Union[str, Sequence[str]]] = None,
    layer_type: Optional[Union[str, Sequence[str]]] = None,
    category: Optional[Union[str, Sequence[str]]] = None,
    exclusive: bool = False,
    ras_object=None,
) -> int:
    """
    Toggle top-level RASMapper ``MapLayers`` entries.

    Targets reference maps, basemaps, land-classification layers, or other
    map-layer entries by name, type, or category. When no selector is
    supplied, all map layers are targeted. Use ``exclusive=True`` with
    ``checked=True`` to hide every non-matching map layer and show only the
    layers needed for a figure.
    """
    from . import _rasmap_layer_helper as _mlh

    project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object=ras_object,
    )
    return _mlh.set_map_layer_visibility(
        project_path,
        checked=checked,
        layer_name=layer_name,
        layer_type=layer_type,
        category=category,
        exclusive=exclusive,
    )

list_standard_basemap_layers staticmethod

Python
list_standard_basemap_layers() -> pd.DataFrame

List standard HEC-RAS 6.x basemap layer names supported for insertion.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_standard_basemap_layers() -> pd.DataFrame:
    """List standard HEC-RAS 6.x basemap layer names supported for insertion."""
    from . import _rasmap_layer_helper as _mlh

    return _mlh.list_available_basemaps()

add_reference_map_layer staticmethod

Python
add_reference_map_layer(ras_project_path: Optional[Union[str, Path]] = None, source_path: Optional[Union[str, Path]] = None, *, layer_name: Optional[str] = None, layer_type: Optional[Union[str, Sequence[str]]] = None, checked: bool = True, label_field: Optional[str] = None, label_config: Optional[Dict[str, Any]] = None, symbology: Optional[Dict[str, Any]] = None, replace_existing: bool = True, validate_geojson_wgs84: bool = True, ras_object=None) -> Path

Add or replace a shapefile/GeoJSON reference map layer in .rasmap.

GeoJSON sources are validated for RASMapper compatibility before the XML is changed. They must either declare WGS84/EPSG:4326 or have coordinate bounds consistent with WGS84 longitude/latitude.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def add_reference_map_layer(
    ras_project_path: Optional[Union[str, Path]] = None,
    source_path: Optional[Union[str, Path]] = None,
    *,
    layer_name: Optional[str] = None,
    layer_type: Optional[Union[str, Sequence[str]]] = None,
    checked: bool = True,
    label_field: Optional[str] = None,
    label_config: Optional[Dict[str, Any]] = None,
    symbology: Optional[Dict[str, Any]] = None,
    replace_existing: bool = True,
    validate_geojson_wgs84: bool = True,
    ras_object=None,
) -> Path:
    """
    Add or replace a shapefile/GeoJSON reference map layer in ``.rasmap``.

    GeoJSON sources are validated for RASMapper compatibility before the XML
    is changed. They must either declare WGS84/EPSG:4326 or have coordinate
    bounds consistent with WGS84 longitude/latitude.
    """
    if source_path is None:
        if ras_project_path is None:
            raise TypeError("source_path is required")
        source_path = ras_project_path
        ras_project_path = None

    from . import _rasmap_layer_helper as _mlh

    project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object=ras_object,
    )
    return _mlh.add_reference_map_layer(
        project_path,
        source_path,
        layer_name=layer_name,
        layer_type=layer_type,
        checked=checked,
        label_field=label_field,
        label_config=label_config,
        symbology=symbology,
        replace_existing=replace_existing,
        validate_geojson_wgs84=validate_geojson_wgs84,
    )

add_basemap_layer staticmethod

Python
add_basemap_layer(ras_project_path: Optional[Union[str, Path]] = None, basemap_name: Optional[str] = None, *, checked: bool = True, replace_existing: bool = True, ras_object=None) -> Path

Add or replace a standard HEC-RAS basemap layer in .rasmap.

Use :meth:list_standard_basemap_layers to discover valid names.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def add_basemap_layer(
    ras_project_path: Optional[Union[str, Path]] = None,
    basemap_name: Optional[str] = None,
    *,
    checked: bool = True,
    replace_existing: bool = True,
    ras_object=None,
) -> Path:
    """
    Add or replace a standard HEC-RAS basemap layer in ``.rasmap``.

    Use :meth:`list_standard_basemap_layers` to discover valid names.
    """
    if basemap_name is None:
        if ras_project_path is None:
            raise TypeError("basemap_name is required")
        basemap_name = str(ras_project_path)
        ras_project_path = None

    from . import _rasmap_layer_helper as _mlh

    project_path = _resolve_optional_ras_project_path(
        ras_project_path,
        ras_object=ras_object,
    )
    return _mlh.add_basemap_layer(
        project_path,
        basemap_name,
        checked=checked,
        replace_existing=replace_existing,
    )

add_map_layer staticmethod

Python
add_map_layer(layer_name: str, layer_file: Union[str, Path], layer_type: str = 'PolylineFeatureLayer', checked: bool = True, label_field: Optional[str] = None, label_config: Optional[Dict[str, Any]] = None, symbology: Optional[Dict[str, Any]] = None, replace_existing: bool = False, validate_geojson_wgs84: bool = True, ras_object=None) -> bool

Add a reference map layer to the RASMapper configuration file.

This legacy active-project method is retained for compatibility. New code should use :meth:add_reference_map_layer, which returns the modified .rasmap path and accepts an explicit project path.

Parameters:

Name Type Description Default
layer_name str

Display name for the layer in RASMapper.

required
layer_file Union[str, Path]

Path to GeoJSON, shapefile, or other supported file.

required
layer_type str

RASMapper layer type: - "PolylineFeatureLayer" (default) - for lines (cross-sections) - "PolygonFeatureLayer" - for polygons - "PointFeatureLayer" - for points

'PolylineFeatureLayer'
checked bool

Whether layer is visible by default (True).

True
label_field Optional[str]

Field name to use for labels (e.g., "dss_path").

None
label_config Optional[Dict[str, Any]]

Optional label configuration dict with keys: - "font_size": float (default 8.25) - "color": int (default -16777216 = black) - "position": int (0=center, 1=above, etc.)

None
symbology Optional[Dict[str, Any]]

Optional symbology configuration dict with keys: - "line_color": tuple (R, G, B, A) - "line_width": int - "fill_color": tuple (R, G, B, A) for polygons

None
replace_existing bool

Replace an existing reference layer with the same name. Default False preserves the historical append behavior.

False
validate_geojson_wgs84 bool

Raise if a GeoJSON source is not WGS84-compatible.

True
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
bool

True if layer was successfully added.

Raises:

Type Description
FileNotFoundError

If .rasmap file doesn't exist.

ValueError

If layer_file doesn't exist.

Note

GeoJSON files MUST be in WGS84 (EPSG:4326) coordinate system for RASMapper to display them correctly. Always reproject your GeoDataFrame to WGS84 before saving:

gdf_wgs84 = gdf.to_crs("EPSG:4326") gdf_wgs84.to_file("output.geojson", driver="GeoJSON")

Examples:

Python Console Session
>>> from ras_commander import init_ras_project, RasMap
>>> init_ras_project("/path/to/project", "7.0")
>>>
>>> # Add boundary conditions GeoJSON
>>> RasMap.add_map_layer(
...     layer_name="Boundary Conditions",
...     layer_file="boundary_cross_sections.geojson",
...     label_field="dss_path"
... )
>>>
>>> # Add with custom symbology
>>> RasMap.add_map_layer(
...     layer_name="BC Locations",
...     layer_file="bc_points.shp",
...     layer_type="PointFeatureLayer",
...     symbology={"line_color": (255, 0, 0, 255), "line_width": 2}
... )
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def add_map_layer(
    layer_name: str,
    layer_file: Union[str, Path],
    layer_type: str = "PolylineFeatureLayer",
    checked: bool = True,
    label_field: Optional[str] = None,
    label_config: Optional[Dict[str, Any]] = None,
    symbology: Optional[Dict[str, Any]] = None,
    replace_existing: bool = False,
    validate_geojson_wgs84: bool = True,
    ras_object=None,
) -> bool:
    """
    Add a reference map layer to the RASMapper configuration file.

    This legacy active-project method is retained for compatibility. New code
    should use :meth:`add_reference_map_layer`, which returns the modified
    ``.rasmap`` path and accepts an explicit project path.

    Args:
        layer_name: Display name for the layer in RASMapper.
        layer_file: Path to GeoJSON, shapefile, or other supported file.
        layer_type: RASMapper layer type:
            - "PolylineFeatureLayer" (default) - for lines (cross-sections)
            - "PolygonFeatureLayer" - for polygons
            - "PointFeatureLayer" - for points
        checked: Whether layer is visible by default (True).
        label_field: Field name to use for labels (e.g., "dss_path").
        label_config: Optional label configuration dict with keys:
            - "font_size": float (default 8.25)
            - "color": int (default -16777216 = black)
            - "position": int (0=center, 1=above, etc.)
        symbology: Optional symbology configuration dict with keys:
            - "line_color": tuple (R, G, B, A)
            - "line_width": int
            - "fill_color": tuple (R, G, B, A) for polygons
        replace_existing: Replace an existing reference layer with the same name.
            Default False preserves the historical append behavior.
        validate_geojson_wgs84: Raise if a GeoJSON source is not WGS84-compatible.
        ras_object (RasPrj, optional): Optional RasPrj object instance.

    Returns:
        bool: True if layer was successfully added.

    Raises:
        FileNotFoundError: If .rasmap file doesn't exist.
        ValueError: If layer_file doesn't exist.

    Note:
        **GeoJSON files MUST be in WGS84 (EPSG:4326) coordinate system** for
        RASMapper to display them correctly. Always reproject your GeoDataFrame
        to WGS84 before saving:

        >>> gdf_wgs84 = gdf.to_crs("EPSG:4326")
        >>> gdf_wgs84.to_file("output.geojson", driver="GeoJSON")

    Examples:
        >>> from ras_commander import init_ras_project, RasMap
        >>> init_ras_project("/path/to/project", "7.0")
        >>>
        >>> # Add boundary conditions GeoJSON
        >>> RasMap.add_map_layer(
        ...     layer_name="Boundary Conditions",
        ...     layer_file="boundary_cross_sections.geojson",
        ...     label_field="dss_path"
        ... )
        >>>
        >>> # Add with custom symbology
        >>> RasMap.add_map_layer(
        ...     layer_name="BC Locations",
        ...     layer_file="bc_points.shp",
        ...     layer_type="PointFeatureLayer",
        ...     symbology={"line_color": (255, 0, 0, 255), "line_width": 2}
        ... )
    """
    warnings.warn(
        "RasMap.add_map_layer() is a legacy alias for reference layers. "
        "Use RasMap.add_reference_map_layer() for new workflows.",
        FutureWarning,
        stacklevel=2,
    )
    RasMap.add_reference_map_layer(
        None,
        layer_file,
        layer_name=layer_name,
        layer_type=layer_type,
        checked=checked,
        label_field=label_field,
        label_config=label_config,
        symbology=symbology,
        replace_existing=replace_existing,
        validate_geojson_wgs84=validate_geojson_wgs84,
        ras_object=ras_object,
    )
    return True

remove_map_layer staticmethod

Python
remove_map_layer(layer_name: str, ras_object=None) -> bool

Remove a map layer from the RASMapper configuration file (.rasmap).

Parameters:

Name Type Description Default
layer_name str

Name of the layer to remove.

required
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
bool

True if layer was found and removed, False if not found.

Examples:

Python Console Session
>>> from ras_commander import init_ras_project, RasMap
>>> init_ras_project("/path/to/project", "7.0")
>>> RasMap.remove_map_layer("Boundary Conditions")
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def remove_map_layer(layer_name: str, ras_object=None) -> bool:
    """
    Remove a map layer from the RASMapper configuration file (.rasmap).

    Args:
        layer_name: Name of the layer to remove.
        ras_object (RasPrj, optional): Optional RasPrj object instance.

    Returns:
        bool: True if layer was found and removed, False if not found.

    Examples:
        >>> from ras_commander import init_ras_project, RasMap
        >>> init_ras_project("/path/to/project", "7.0")
        >>> RasMap.remove_map_layer("Boundary Conditions")
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    if not rasmap_path.exists():
        logger.warning(f"RASMapper file not found: {rasmap_path}")
        return False

    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()
    except ET.ParseError as e:
        logger.error(f"Error parsing .rasmap XML: {e}")
        return False

    from . import _rasmap_layer_helper as _mlh

    map_layers = _mlh.map_layers_element(root)
    if map_layers is None:
        logger.warning("No MapLayers section found in .rasmap")
        return False

    # Find and remove layer by name
    for layer in _mlh.top_level_map_layers(root):
        if layer.get("Name") == layer_name:
            map_layers.remove(layer)
            _write_ras_xml(
                tree, rasmap_path, encoding="utf-8", xml_declaration=True
            )
            logger.info("Removed map layer '%s'", layer_name)
            logger.debug("Updated RASMapper file: %s", rasmap_path)
            return True

    logger.warning(f"Layer '{layer_name}' not found in .rasmap")
    return False

ensure_rasmap_compatible staticmethod

Python
ensure_rasmap_compatible(ras_object=None, auto_upgrade=True) -> Dict[str, Any]

Ensure .rasmap file is compatible with current HEC-RAS version.

For HEC-RAS 5.0.7 projects opened in HEC-RAS 6.x, the .rasmap file needs to be upgraded to the 6.x format (adds section). This function detects version incompatibility and attempts automatic upgrade via GUI automation.

Parameters:

Name Type Description Default
ras_object RasPrj

Optional RasPrj object instance (default: global ras).

None
auto_upgrade bool

If True, attempt automatic upgrade via GUI automation. If False, only detect version and return status without upgrading.

True

Returns:

Type Description
Dict[str, Any]

Status dictionary with keys: - 'status' (str): One of: - 'ready': .rasmap is already compatible - 'upgraded': Successfully upgraded .rasmap file - 'manual_needed': Upgrade required but auto-upgrade failed - 'message' (str): Human-readable status message - 'version' (str): Detected .rasmap version (e.g., "5.0.7", "7.0")

Examples:

Python Console Session
>>> from ras_commander import init_ras_project, RasMap
>>> init_ras_project("/path/to/project", "7.0")
>>>
>>> # Check compatibility (auto-upgrade if needed)
>>> result = RasMap.ensure_rasmap_compatible(auto_upgrade=True)
>>> print(result['status'])  # 'ready', 'upgraded', or 'manual_needed'
>>>
>>> # Check only (no auto-upgrade)
>>> result = RasMap.ensure_rasmap_compatible(auto_upgrade=False)
Notes
  • Detection Logic:

    • Parses .rasmap XML for element
    • Checks for section (present in 6.x, missing in 5.0.7)
    • Upgrade needed if version starts with "5." AND no section
  • Auto-upgrade Process (if auto_upgrade=True):

    • Opens HEC-RAS with the project
    • Uses GUI automation to click "GIS Tools" > "RAS Mapper"
    • Waits for RASMapper to open (triggers .rasmap upgrade dialog)
    • Closes RASMapper and HEC-RAS
    • Verifies upgrade by re-parsing .rasmap
  • Integration:

    • Called automatically by postprocess_stored_maps()
    • Should be called before RasProcess.store_maps() workflows
    • Always needed before RasProcess.store_maps()
Source code in ras_commander/RasMap.py
Python
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
@staticmethod
@log_call
def ensure_rasmap_compatible(ras_object=None, auto_upgrade=True) -> Dict[str, Any]:
    """
    Ensure .rasmap file is compatible with current HEC-RAS version.

    For HEC-RAS 5.0.7 projects opened in HEC-RAS 6.x, the .rasmap file needs to be
    upgraded to the 6.x format (adds <Results> section). This function detects
    version incompatibility and attempts automatic upgrade via GUI automation.

    Args:
        ras_object (RasPrj, optional): Optional RasPrj object instance (default: global ras).
        auto_upgrade (bool): If True, attempt automatic upgrade via GUI automation.
            If False, only detect version and return status without upgrading.

    Returns:
        Dict[str, Any]: Status dictionary with keys:
            - 'status' (str): One of:
                - 'ready': .rasmap is already compatible
                - 'upgraded': Successfully upgraded .rasmap file
                - 'manual_needed': Upgrade required but auto-upgrade failed
            - 'message' (str): Human-readable status message
            - 'version' (str): Detected .rasmap version (e.g., "5.0.7", "7.0")

    Examples:
        >>> from ras_commander import init_ras_project, RasMap
        >>> init_ras_project("/path/to/project", "7.0")
        >>>
        >>> # Check compatibility (auto-upgrade if needed)
        >>> result = RasMap.ensure_rasmap_compatible(auto_upgrade=True)
        >>> print(result['status'])  # 'ready', 'upgraded', or 'manual_needed'
        >>>
        >>> # Check only (no auto-upgrade)
        >>> result = RasMap.ensure_rasmap_compatible(auto_upgrade=False)

    Notes:
        - Detection Logic:
            * Parses .rasmap XML for <Version> element
            * Checks for <Results> section (present in 6.x, missing in 5.0.7)
            * Upgrade needed if version starts with "5." AND no <Results> section

        - Auto-upgrade Process (if auto_upgrade=True):
            * Opens HEC-RAS with the project
            * Uses GUI automation to click "GIS Tools" > "RAS Mapper"
            * Waits for RASMapper to open (triggers .rasmap upgrade dialog)
            * Closes RASMapper and HEC-RAS
            * Verifies upgrade by re-parsing .rasmap

        - Integration:
            * Called automatically by postprocess_stored_maps()
            * Should be called before RasProcess.store_maps() workflows
            * Always needed before RasProcess.store_maps()
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    # Get .rasmap path
    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)

    if not rasmap_path.exists():
        logger.warning(f"No .rasmap file found: {rasmap_path}")
        return {
            "status": "manual_needed",
            "message": f"No .rasmap file found at {rasmap_path}",
            "version": None,
        }

    # Parse .rasmap XML to detect version
    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()

        # Extract version
        version_elem = root.find("Version")
        version = version_elem.text if version_elem is not None else "unknown"

        # Check for Results section (present in 6.x, missing in 5.0.7)
        results_elem = root.find("Results")

        # Determine if upgrade needed
        needs_upgrade = (
            version.startswith("5.")  # Old version number
            and results_elem is None  # Missing modern Results section
        )

        if not needs_upgrade:
            logger.debug(".rasmap file is already compatible (version %s)", version)
            return {
                "status": "ready",
                "message": f"Already compatible (version {version})",
                "version": version,
            }

        logger.info(f".rasmap file needs upgrade from version {version}")

    except ET.ParseError as e:
        logger.error(f"Error parsing .rasmap XML: {e}")
        return {
            "status": "manual_needed",
            "message": f"XML parse error: {e}",
            "version": None,
        }

    # If upgrade not needed or auto_upgrade disabled, return status
    if not auto_upgrade:
        return {
            "status": "manual_needed",
            "message": f"Upgrade needed from version {version} (auto_upgrade=False)",
            "version": version,
        }

    # Attempt GUI automation to upgrade .rasmap
    logger.info("Attempting automatic .rasmap upgrade via GUI automation...")

    try:
        # Import GUI automation (lazy import to avoid dependencies if not needed)
        try:
            import win32gui
            import win32con
            import time
            import subprocess
            import sys
        except ImportError as e:
            logger.error(f"GUI automation requires win32gui: {e}")
            return {
                "status": "manual_needed",
                "message": f"GUI automation requires pywin32 package: {e}",
                "version": version,
            }

        # Open HEC-RAS with project
        ras_exe = ras_obj.ras_exe_path
        prj_path = str(ras_obj.prj_file)

        logger.debug("Opening HEC-RAS for .rasmap upgrade")
        logger.debug("HEC-RAS upgrade command: %s %s", ras_exe, prj_path)

        if sys.platform == "win32":
            process = subprocess.Popen(f'"{ras_exe}" "{prj_path}"')
        else:
            raise RuntimeError("GUI automation only supported on Windows")

        # Wait for HEC-RAS main window to appear
        time.sleep(5)  # Initial wait

        # Find HEC-RAS main window
        hecras_hwnd = None
        for _ in range(30):  # Try for up to 30 seconds
            hecras_hwnd = win32gui.FindWindow(
                None, f"HEC-RAS {ras_obj.ras_version}"
            )
            if hecras_hwnd:
                break
            time.sleep(1)

        if not hecras_hwnd:
            logger.error("Could not find HEC-RAS window")
            process.terminate()
            return {
                "status": "manual_needed",
                "message": "HEC-RAS window not found (GUI automation failed)",
                "version": version,
            }

        logger.debug("Found HEC-RAS window handle: %s", hecras_hwnd)

        # Helper function to find RASMapper window
        def find_rasmapper_window():
            """Find any RAS Mapper window"""

            def callback(hwnd, windows):
                if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(
                    hwnd
                ):
                    try:
                        window_title = win32gui.GetWindowText(hwnd)
                        if "RAS Mapper" in window_title:
                            windows.append((hwnd, window_title))
                    except Exception:
                        pass
                return True

            windows = []
            win32gui.EnumWindows(callback, windows)
            return windows

        # Helper function to wait for window to appear
        def wait_for_window(find_window_func, timeout=90, check_interval=2):
            """Wait for a window to appear"""
            start_time = time.time()
            while time.time() - start_time < timeout:
                windows = find_window_func()
                if windows:
                    return windows
                time.sleep(check_interval)
            return None

        # Helper function to close RASMapper
        def close_rasmapper():
            """Close RASMapper window"""
            windows = find_rasmapper_window()
            for hwnd, title in windows:
                try:
                    win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
                    logger.debug(f"Sent WM_CLOSE to RASMapper window: {title}")
                    return True
                except Exception:
                    pass
            return False

        # Step 1: Open RASMapper via menu
        logger.debug("Opening RASMapper via menu")
        win32gui.SetForegroundWindow(hecras_hwnd)
        time.sleep(0.5)

        # Enumerate menus to find "GIS Tools" > "RAS Mapper"
        menu_bar = win32gui.GetMenu(hecras_hwnd)
        if menu_bar:
            menu_count = win32gui.GetMenuItemCount(menu_bar)
            rasmapper_found = False

            for i in range(menu_count):
                submenu = win32gui.GetSubMenu(menu_bar, i)
                if submenu:
                    submenu_count = win32gui.GetMenuItemCount(submenu)
                    for j in range(submenu_count):
                        try:
                            # Get menu item info
                            menu_id = win32gui.GetMenuItemID(submenu, j)
                            # Try to get menu string (may not work for all items)

                            # For RASMapper, we'll try a different approach
                            # Send the menu command for typical RASMapper menu ID
                            # This varies by version, so we'll try clicking and checking
                            if menu_id > 0:
                                # Try sending this menu command
                                win32gui.PostMessage(
                                    hecras_hwnd, win32con.WM_COMMAND, menu_id, 0
                                )
                                time.sleep(1)

                                # Check if RASMapper opened
                                if find_rasmapper_window():
                                    logger.debug(
                                        "RASMapper opened successfully via menu"
                                    )
                                    rasmapper_found = True
                                    break
                        except Exception:
                            continue
                    if rasmapper_found:
                        break

            # Fallback: Try keyboard shortcut
            if not rasmapper_found:
                logger.debug("Menu enumeration failed, trying keyboard shortcut")
                import win32api

                win32api.keybd_event(0x12, 0, 0, 0)  # Alt down
                time.sleep(0.1)
                win32api.keybd_event(ord("G"), 0, 0, 0)  # G
                time.sleep(0.1)
                win32api.keybd_event(0x12, 0, 0x0002, 0)  # Alt up
                time.sleep(0.5)
                win32api.keybd_event(ord("M"), 0, 0, 0)  # M for Mapper
                time.sleep(0.1)

        # Step 2: Wait for RASMapper window to appear (60-90 second timeout)
        logger.debug("Waiting for RASMapper to open (up to 90 seconds)")
        rasmapper_windows = wait_for_window(
            find_rasmapper_window, timeout=90, check_interval=2
        )

        if not rasmapper_windows:
            logger.error("RASMapper window did not appear within timeout")
            return {
                "status": "manual_needed",
                "message": "RASMapper window did not open automatically. Please open RASMapper manually.",
                "version": version,
            }

        logger.debug("RASMapper opened")
        logger.debug("RASMapper window title: %s", rasmapper_windows[0][1])

        # Step 3: Wait 2 additional seconds for .rasmap file write
        logger.debug("Allowing time for .rasmap update")
        time.sleep(2)

        # Step 4: Close RASMapper cleanly (with retry)
        logger.debug("Attempting to close RASMapper")
        close_attempts = 0
        max_attempts = 10

        while close_attempts < max_attempts:
            if close_rasmapper():
                logger.debug("Sent close message to RASMapper")
                break
            logger.debug(
                f"Retry {close_attempts + 1}/{max_attempts} to close RASMapper..."
            )
            time.sleep(2)
            close_attempts += 1

        if close_attempts >= max_attempts:
            logger.warning("Could not send close message to RASMapper")

        # Step 5: Wait until RASMapper is fully closed
        logger.debug("Waiting for RASMapper to fully close")
        close_wait_start = time.time()
        close_timeout = 30

        while time.time() - close_wait_start < close_timeout:
            if not find_rasmapper_window():
                logger.debug("RASMapper closed successfully")
                break
            logger.debug("Waiting for RASMapper to fully close...")
            time.sleep(2)

        # Step 6: Close HEC-RAS
        logger.debug("Closing HEC-RAS")
        win32gui.PostMessage(hecras_hwnd, win32con.WM_CLOSE, 0, 0)
        time.sleep(1)

        # Wait for HEC-RAS to close
        try:
            process.wait(timeout=10)
            logger.debug("HEC-RAS closed")
        except Exception:
            logger.warning("HEC-RAS did not close cleanly, may still be running")

        # Re-parse .rasmap to verify upgrade
        time.sleep(1)
        tree = ET.parse(rasmap_path)
        root = tree.getroot()
        results_elem = root.find("Results")

        if results_elem is not None:
            logger.info(".rasmap file successfully upgraded")
            return {
                "status": "upgraded",
                "message": f"Successfully upgraded from version {version}",
                "version": version,
            }
        else:
            logger.warning(".rasmap file was not upgraded")
            return {
                "status": "manual_needed",
                "message": "Upgrade verification failed - please open RASMapper manually",
                "version": version,
            }

    except Exception as e:
        logger.error(f"GUI automation failed: {e}")
        return {
            "status": "manual_needed",
            "message": f"Auto-upgrade failed: {e}. Please open RASMapper manually.",
            "version": version,
        }

add_terrain_layer staticmethod

Python
add_terrain_layer(terrain_hdf: Union[str, Path], rasmap_path: Union[str, Path], layer_name: str = 'Terrain', projection_prj: Optional[Union[str, Path]] = None, ras_object=None, relative_paths: bool = False) -> None

Add terrain layer to RASMapper configuration.

After creating terrain with RasTerrain.create_terrain_hdf(), register it in project's .rasmap file. This method creates the required XML structure in the Terrains section.

Parameters:

Name Type Description Default
terrain_hdf Union[str, Path]

Path to terrain HDF file (e.g., "./Terrain/MyTerrain.hdf")

required
rasmap_path Union[str, Path]

Path to .rasmap file to modify

required
layer_name str

Display name for terrain layer (default: "Terrain")

'Terrain'
projection_prj Optional[Union[str, Path]]

Path to ESRI PRJ file. If provided, updates RASProjectionFilename element. Default: None (keeps existing).

None
ras_object RasPrj

Optional RasPrj object instance (default: global ras).

None
relative_paths bool

Include sibling and parent folders in relative terrain and projection references on the same drive. Default False keeps the existing descendant-only behavior. Different drives retain absolute references. Use True for relocatable cloned bundles.

False

Returns:

Type Description
None

None

Raises:

Type Description
FileNotFoundError

If rasmap_path or terrain_hdf does not exist.

ValueError

If rasmap file is not valid XML.

Example

from ras_commander import RasMap

After creating terrain HDF

RasMap.add_terrain_layer( ... terrain_hdf="./Terrain/Terrain50.hdf", ... rasmap_path="./Project.rasmap", ... layer_name="Terrain50" ... )

With projection file

RasMap.add_terrain_layer( ... terrain_hdf="./Terrain/NewTerrain.hdf", ... rasmap_path="./Project.rasmap", ... layer_name="NewTerrain", ... projection_prj="./Terrain/Projection.prj" ... )

Notes
  • Creates Terrains section if it doesn't exist
  • Generates XML structure compatible with HEC-RAS 6.x: near
  • Calculates relative path from .rasmap to terrain HDF
  • If layer with same name exists, it will be replaced
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def add_terrain_layer(
    terrain_hdf: Union[str, Path],
    rasmap_path: Union[str, Path],
    layer_name: str = "Terrain",
    projection_prj: Optional[Union[str, Path]] = None,
    ras_object=None,
    relative_paths: bool = False,
) -> None:
    """
    Add terrain layer to RASMapper configuration.

    After creating terrain with RasTerrain.create_terrain_hdf(),
    register it in project's .rasmap file. This method creates the
    required XML structure in the Terrains section.

    Args:
        terrain_hdf: Path to terrain HDF file (e.g., "./Terrain/MyTerrain.hdf")
        rasmap_path: Path to .rasmap file to modify
        layer_name: Display name for terrain layer (default: "Terrain")
        projection_prj: Path to ESRI PRJ file. If provided, updates
            RASProjectionFilename element. Default: None (keeps existing).
        ras_object (RasPrj, optional): Optional RasPrj object instance (default: global ras).
        relative_paths: Include sibling and parent folders in relative terrain
            and projection references on the same drive. Default False keeps
            the existing descendant-only behavior. Different drives retain
            absolute references. Use True for relocatable cloned bundles.

    Returns:
        None

    Raises:
        FileNotFoundError: If rasmap_path or terrain_hdf does not exist.
        ValueError: If rasmap file is not valid XML.

    Example:
        >>> from ras_commander import RasMap
        >>>
        >>> # After creating terrain HDF
        >>> RasMap.add_terrain_layer(
        ...     terrain_hdf="./Terrain/Terrain50.hdf",
        ...     rasmap_path="./Project.rasmap",
        ...     layer_name="Terrain50"
        ... )
        >>>
        >>> # With projection file
        >>> RasMap.add_terrain_layer(
        ...     terrain_hdf="./Terrain/NewTerrain.hdf",
        ...     rasmap_path="./Project.rasmap",
        ...     layer_name="NewTerrain",
        ...     projection_prj="./Terrain/Projection.prj"
        ... )

    Notes:
        - Creates Terrains section if it doesn't exist
        - Generates XML structure compatible with HEC-RAS 6.x:
          <Terrains Checked="True" Expanded="True">
            <Layer Name="{layer_name}" Type="TerrainLayer" Checked="True"
                   Filename=".\\Terrain\\{name}.hdf">
              <ResampleMethod>near</ResampleMethod>
              <Surface On="True" />
            </Layer>
          </Terrains>
        - Calculates relative path from .rasmap to terrain HDF
        - If layer with same name exists, it will be replaced
    """
    rasmap_path = Path(rasmap_path)
    terrain_hdf = Path(terrain_hdf)

    # Validate files exist
    if not rasmap_path.exists():
        raise FileNotFoundError(f"RASMapper file not found: {rasmap_path}")

    if not terrain_hdf.exists():
        raise FileNotFoundError(f"Terrain HDF file not found: {terrain_hdf}")

    if projection_prj is not None:
        projection_prj = Path(projection_prj)
        if not projection_prj.exists():
            raise FileNotFoundError(
                f"Projection PRJ file not found: {projection_prj}"
            )

    # Parse existing rasmap
    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()
    except ET.ParseError as e:
        raise ValueError(f"Error parsing .rasmap XML: {e}")

    # Import safe_resolve to preserve Windows drive letters on mapped network drives
    from .RasUtils import RasUtils

    # Calculate relative path from rasmap to terrain HDF
    rasmap_dir = RasUtils.safe_resolve(rasmap_path.parent)
    terrain_hdf_resolved = RasUtils.safe_resolve(terrain_hdf)

    try:
        # Calculate relative path
        rel_path = (
            Path(os.path.relpath(terrain_hdf_resolved, rasmap_dir))
            if relative_paths
            else terrain_hdf_resolved.relative_to(rasmap_dir)
        )
        # Format as Windows-style relative path with .\ prefix
        rel_path_str = ".\\" + str(rel_path).replace("/", "\\")
    except ValueError:
        # If terrain is not relative to rasmap dir, use absolute path
        logger.warning(
            "Terrain HDF is not under rasmap directory. Using absolute path."
        )
        rel_path_str = str(terrain_hdf_resolved).replace("/", "\\")

    # Find or create Terrains section
    terrains = root.find("Terrains")
    if terrains is None:
        # Create Terrains section - insert after common elements
        terrains = ET.Element("Terrains")
        terrains.set("Checked", "True")
        terrains.set("Expanded", "True")

        # Find appropriate insertion point (after Results if exists, else after Geometries)
        insert_index = 0
        for i, child in enumerate(root):
            if child.tag in ["Results", "Geometries", "EventConditions"]:
                insert_index = i + 1
        root.insert(insert_index, terrains)
        logger.debug("Created new Terrains section in .rasmap file")

    # Check for existing layer with same name and remove it
    existing_layer = None
    for layer in terrains.findall("Layer"):
        if layer.get("Name") == layer_name:
            existing_layer = layer
            break

    if existing_layer is not None:
        terrains.remove(existing_layer)
        logger.debug("Replaced existing terrain layer: %s", layer_name)

    # Create terrain layer element
    layer = ET.SubElement(terrains, "Layer")
    layer.set("Name", layer_name)
    layer.set("Type", "TerrainLayer")
    layer.set("Checked", "True")
    layer.set("Filename", rel_path_str)

    # Add default settings (matching HEC-RAS 6.x format)
    resample = ET.SubElement(layer, "ResampleMethod")
    resample.text = "near"

    surface = ET.SubElement(layer, "Surface")
    surface.set("On", "True")

    # Update projection reference if provided
    if projection_prj is not None:
        try:
            projection_resolved = RasUtils.safe_resolve(projection_prj)
            prj_rel_path = (
                Path(os.path.relpath(projection_resolved, rasmap_dir))
                if relative_paths
                else projection_resolved.relative_to(rasmap_dir)
            )
            prj_rel_path_str = ".\\" + str(prj_rel_path).replace("/", "\\")
        except ValueError:
            prj_rel_path_str = str(RasUtils.safe_resolve(projection_prj)).replace(
                "/", "\\"
            )

        # Find or create RASProjectionFilename element
        proj_elem = root.find("RASProjectionFilename")
        if proj_elem is None:
            # Insert after Version element
            proj_elem = ET.Element("RASProjectionFilename")
            version_elem = root.find("Version")
            if version_elem is not None:
                insert_idx = list(root).index(version_elem) + 1
            else:
                insert_idx = 0
            root.insert(insert_idx, proj_elem)

        proj_elem.set("Filename", prj_rel_path_str)
        logger.debug("Updated RASMapper projection reference")
        logger.debug("RASMapper projection reference: %s", prj_rel_path_str)

    # Write updated rasmap file
    # Use a custom write to preserve XML formatting
    _write_ras_xml(tree, rasmap_path, encoding="utf-8", xml_declaration=False)

    action = "Replaced" if existing_layer is not None else "Added"
    logger.info("%s terrain layer '%s' in .rasmap", action, layer_name)
    logger.debug("Terrain layer '%s' filename: %s", layer_name, rel_path_str)

prune_event_condition_layers staticmethod

Python
prune_event_condition_layers(keep_filenames: Sequence[Union[str, Path]], rasmap_path: Optional[Union[str, Path]] = None, ras_object=None, backup: bool = True) -> Dict[str, Any]

Remove stale event-condition layers from a cloned project.

HEC-RAS evaluates RASEventConditions layers during unsteady preprocessing, including unchecked layers inherited from other plans or source-project folders. A cloned breakout project can therefore fail with Error processing event conditions even when its current plan and unsteady-flow file are valid.

This method retains only exact filename matches, removes unmatched event-condition layers anywhere in the .rasmap tree, writes atomically, and validates exact readback. It never edits the referenced HDF files. Pass an empty sequence to remove every event-condition layer.

Parameters:

Name Type Description Default
keep_filenames Sequence[Union[str, Path]]

Exact layer Filename values to retain. Paths inside the project folder may be supplied as absolute paths; they are normalized to .\ relative Windows form.

required
rasmap_path Optional[Union[str, Path]]

Explicit .rasmap path. When omitted, resolve it from ras_object.

None
ras_object RasPrj

Optional initialized project object.

None
backup bool

Create a durable sibling backup before mutation.

True

Returns:

Type Description
Dict[str, Any]

JSON-safe mutation evidence including removed/retained layers,

Dict[str, Any]

backup path, and exact readback counts.

Raises:

Type Description
FileNotFoundError

If the .rasmap does not exist.

FileExistsError

If the backup or atomic staging path exists.

ValueError

If XML is invalid or a requested retained filename is absent before mutation.

RuntimeError

If exact readback validation fails.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def prune_event_condition_layers(
    keep_filenames: Sequence[Union[str, Path]],
    rasmap_path: Optional[Union[str, Path]] = None,
    ras_object=None,
    backup: bool = True,
) -> Dict[str, Any]:
    """Remove stale event-condition layers from a cloned project.

    HEC-RAS evaluates ``RASEventConditions`` layers during unsteady
    preprocessing, including unchecked layers inherited from other plans
    or source-project folders.  A cloned breakout project can therefore
    fail with ``Error processing event conditions`` even when its current
    plan and unsteady-flow file are valid.

    This method retains only exact filename matches, removes unmatched
    event-condition layers anywhere in the ``.rasmap`` tree, writes
    atomically, and validates exact readback.  It never edits the referenced
    HDF files.  Pass an empty sequence to remove every event-condition
    layer.

    Args:
        keep_filenames: Exact layer ``Filename`` values to retain. Paths
            inside the project folder may be supplied as absolute paths;
            they are normalized to ``.\\`` relative Windows form.
        rasmap_path: Explicit ``.rasmap`` path. When omitted, resolve it
            from ``ras_object``.
        ras_object (RasPrj, optional): Optional initialized project object.
        backup: Create a durable sibling backup before mutation.

    Returns:
        JSON-safe mutation evidence including removed/retained layers,
        backup path, and exact readback counts.

    Raises:
        FileNotFoundError: If the ``.rasmap`` does not exist.
        FileExistsError: If the backup or atomic staging path exists.
        ValueError: If XML is invalid or a requested retained filename is
            absent before mutation.
        RuntimeError: If exact readback validation fails.
    """
    ras_obj = ras_object or ras
    if rasmap_path is None:
        resolved = RasMap.get_rasmap_path(ras_obj)
        if resolved is None:
            raise FileNotFoundError("Project .rasmap file was not found")
        target = Path(resolved)
    else:
        target = Path(rasmap_path)
    if not target.is_file():
        raise FileNotFoundError(f"RASMapper file not found: {target}")

    def normalize_filename(value: Union[str, Path]) -> str:
        raw = str(value).strip()
        candidate = Path(raw)
        if candidate.is_absolute():
            try:
                raw = ".\\" + str(
                    RasUtils.safe_resolve(candidate).relative_to(
                        RasUtils.safe_resolve(target.parent)
                    )
                )
            except ValueError:
                raw = str(candidate)
        return raw.replace("/", "\\").casefold()

    requested = {normalize_filename(value) for value in keep_filenames}
    try:
        tree = ET.parse(target)
    except ET.ParseError as exc:
        raise ValueError(f"Error parsing .rasmap XML: {exc}") from exc
    root = tree.getroot()

    layers = []
    for parent in root.iter():
        for layer in list(parent):
            if (
                layer.tag == "Layer"
                and layer.get("Type") == "RASEventConditions"
            ):
                layers.append((parent, layer))
    available = {
        normalize_filename(layer.get("Filename") or "")
        for _parent, layer in layers
    }
    missing = sorted(requested - available)
    if missing:
        raise ValueError(
            "Requested event-condition layer filename(s) are absent: "
            + ", ".join(missing)
        )

    removed = []
    retained = []
    for parent, layer in layers:
        record = {
            "name": layer.get("Name") or "",
            "filename": layer.get("Filename") or "",
            "checked": layer.get("Checked"),
        }
        if normalize_filename(record["filename"]) in requested:
            retained.append(record)
        else:
            parent.remove(layer)
            removed.append(record)

    backup_path = None
    staging = target.with_name(f".{target.name}.event-conditions.tmp")
    if removed:
        if staging.exists():
            raise FileExistsError(
                f"Atomic .rasmap staging path already exists: {staging}"
            )
        if backup:
            backup_path = target.with_name(
                f"{target.stem}.event-conditions.bak{target.suffix}"
            )
            if backup_path.exists():
                raise FileExistsError(
                    f"Event-condition backup already exists: {backup_path}"
                )
            shutil.copy2(target, backup_path)
        try:
            _write_ras_xml(tree, staging, encoding="utf-8", xml_declaration=False)
            ET.parse(staging)
            os.replace(staging, target)
        finally:
            if staging.exists():
                staging.unlink()

    readback_root = ET.parse(target).getroot()
    readback = []
    for layer in readback_root.iter("Layer"):
        if layer.get("Type") == "RASEventConditions":
            readback.append(
                {
                    "name": layer.get("Name") or "",
                    "filename": layer.get("Filename") or "",
                    "checked": layer.get("Checked"),
                }
            )
    readback_filenames = {
        normalize_filename(layer["filename"]) for layer in readback
    }
    if readback_filenames != requested:
        raise RuntimeError(
            "Event-condition readback mismatch: expected "
            f"{sorted(requested)}, observed {sorted(readback_filenames)}"
        )

    evidence = {
        "rasmap_path": str(target),
        "backup_path": str(backup_path) if backup_path is not None else None,
        "requested_filenames": sorted(requested),
        "before_count": len(layers),
        "removed_count": len(removed),
        "retained_count": len(retained),
        "readback_count": len(readback),
        "removed": removed,
        "retained": retained,
        "readback": readback,
        "changed": bool(removed),
    }
    logger.info(
        "Pruned %d stale event-condition layer(s); retained %d",
        len(removed),
        len(retained),
    )
    return evidence

ensure_2d_encroachment_plan_layers staticmethod

Python
ensure_2d_encroachment_plan_layers(plan_number_or_path: Union[str, int, float, Path], *, geom_hdf_path: Optional[Union[str, Path]] = None, checked: bool = True, ras_object=None) -> Path

Register editable 2D encroachment plan layers in the RASMapper Plans tree.

Adds or updates the plan-level RASEncroachments parent plus the RASEncroachmentZones and RASEncroachmentPolygons child layers used by RASMapper for 2D floodway authoring.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def ensure_2d_encroachment_plan_layers(
    plan_number_or_path: Union[str, int, float, Path],
    *,
    geom_hdf_path: Optional[Union[str, Path]] = None,
    checked: bool = True,
    ras_object=None,
) -> Path:
    """
    Register editable 2D encroachment plan layers in the RASMapper ``Plans`` tree.

    Adds or updates the plan-level ``RASEncroachments`` parent plus the
    ``RASEncroachmentZones`` and ``RASEncroachmentPolygons`` child layers
    used by RASMapper for 2D floodway authoring.
    """
    plan_path = _resolve_plan_file_for_rasmap(
        plan_number_or_path,
        ras_object=ras_object,
    )
    project_folder = plan_path.parent
    project_name = _project_name_from_plan_path(plan_path)
    rasmap_path = expected_rasmap_path(project_folder, project_name)

    if rasmap_path.exists():
        try:
            tree = ET.parse(rasmap_path)
            root = tree.getroot()
        except ET.ParseError as e:
            raise ValueError(f"Error parsing .rasmap XML: {e}") from e
    else:
        root = ET.Element("RASMapper")
        tree = ET.ElementTree(root)

    plans = root.find("Plans")
    if plans is None:
        plans = ET.Element("Plans", {"Checked": "True", "Expanded": "True"})
        results = root.find("Results")
        if results is not None:
            root.insert(list(root).index(results), plans)
        else:
            root.append(plans)

    rel_plan = _rasmap_relative_path(project_folder, plan_path)
    geom_hdf = (
        Path(geom_hdf_path)
        if geom_hdf_path is not None
        else _infer_plan_geometry_hdf(plan_path)
    )
    rel_geom = (
        _rasmap_relative_path(project_folder, geom_hdf)
        if geom_hdf is not None
        else ""
    )

    plan_layer = None
    rel_plan_norm = _normalize_rasmap_filename(rel_plan)
    for layer in plans.findall("Layer"):
        if layer.get("Type") != "RASPlan":
            continue
        if _normalize_rasmap_filename(layer.get("Filename")) == rel_plan_norm:
            plan_layer = layer
            break

    if plan_layer is None:
        plan_layer = ET.SubElement(plans, "Layer")

    plan_layer.set("Name", _plan_display_name_for_rasmap(plan_path))
    plan_layer.set("Type", "RASPlan")
    plan_layer.set("Filename", rel_plan)
    plan_layer.set("Checked", "True" if checked else "False")
    if rel_geom:
        plan_layer.set("GeometryHDF", rel_geom)

    child_specs = [
        ("Encroachments", "RASEncroachments"),
        ("Zones", "RASEncroachmentZones"),
        ("Regions", "RASEncroachmentPolygons"),
    ]
    for name, layer_type in child_specs:
        child = None
        for existing in plan_layer.findall("Layer"):
            if existing.get("Type") == layer_type:
                child = existing
                break
        if child is None:
            child = ET.SubElement(plan_layer, "Layer")
        child.set("Name", name)
        child.set("Type", layer_type)
        child.set("Filename", rel_plan)

    _write_ras_xml(tree, rasmap_path, encoding="utf-8", xml_declaration=False)
    logger.info("Ensured 2D encroachment plan layers")
    logger.debug("Updated RASMapper file: %s", rasmap_path)
    return rasmap_path

Compiled geometry associations

Class for parsing and accessing information from HEC-RAS mapper configuration files (.rasmap).

This class provides methods to extract paths to terrain, soil, land cover data, and various project settings from the .rasmap file associated with a HEC-RAS project. It also includes functionality to automate the post-processing of stored maps.

associate_geometry_layers staticmethod

Python
associate_geometry_layers(ras_project_path: Union[str, Path], geom_file: Union[str, Path], landcover_hdf_path: Optional[Union[str, Path]] = None, soil_layer_path: Optional[Union[str, Path]] = None, infiltration_hdf_path: Optional[Union[str, Path]] = None, terrain_hdf_path: Optional[Union[str, Path]] = None, sediment_soils_hdf_path: Optional[Union[str, Path]] = None, hecras_version: Optional[str] = None, ras_object=None) -> Path

Associate terrain / classification layers to a compiled geometry HDF.

This workflow delegates association writes to the selected HEC-RAS RasMapperLib generation. It does not hand-write /Geometry attributes.

soil_layer_path is a deprecated compatibility parameter through v1.1.x. Hydrologic soils are not a geometry association: pass them to :meth:add_infiltration_layer, then associate its infiltration_hdf_path. Use sediment_soils_hdf_path only for the distinct HEC-RAS SedimentSoilsFilename bed-material association.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def associate_geometry_layers(
    ras_project_path: Union[str, Path],
    geom_file: Union[str, Path],
    landcover_hdf_path: Optional[Union[str, Path]] = None,
    soil_layer_path: Optional[Union[str, Path]] = None,
    infiltration_hdf_path: Optional[Union[str, Path]] = None,
    terrain_hdf_path: Optional[Union[str, Path]] = None,
    sediment_soils_hdf_path: Optional[Union[str, Path]] = None,
    hecras_version: Optional[str] = None,
    ras_object=None,
) -> Path:
    """
    Associate terrain / classification layers to a compiled geometry HDF.

    This workflow delegates association writes to the selected HEC-RAS
    RasMapperLib generation. It does not hand-write ``/Geometry``
    attributes.

    ``soil_layer_path`` is a deprecated compatibility parameter through
    v1.1.x. Hydrologic soils are not a geometry association: pass them to
    :meth:`add_infiltration_layer`, then associate its
    ``infiltration_hdf_path``. Use ``sediment_soils_hdf_path`` only for the
    distinct HEC-RAS ``SedimentSoilsFilename`` bed-material association.
    """
    ras_project_path = Path(ras_project_path)
    geom_file = Path(geom_file)
    landcover_hdf_path = (
        Path(landcover_hdf_path) if landcover_hdf_path is not None else None
    )
    soil_layer_path = Path(soil_layer_path) if soil_layer_path is not None else None
    infiltration_hdf_path = (
        Path(infiltration_hdf_path) if infiltration_hdf_path is not None else None
    )
    terrain_hdf_path = (
        Path(terrain_hdf_path) if terrain_hdf_path is not None else None
    )
    sediment_soils_hdf_path = (
        Path(sediment_soils_hdf_path)
        if sediment_soils_hdf_path is not None
        else None
    )
    version = _resolve_native_hecras_version(hecras_version, ras_object)
    from . import _land_classification_helper as _lch

    return _lch.associate_geometry_layers(
        ras_project_path=ras_project_path,
        geom_file=geom_file,
        landcover_hdf_path=landcover_hdf_path,
        soil_layer_path=soil_layer_path,
        infiltration_hdf_path=infiltration_hdf_path,
        terrain_hdf_path=terrain_hdf_path,
        sediment_soils_hdf_path=sediment_soils_hdf_path,
        hecras_version=version,
        ras_object=ras_object,
    )

set_geometry_association staticmethod

Python
set_geometry_association(geom_number: Union[str, Number, Path], terrain_hdf_path: Optional[Union[str, Path]] = None, landcover_hdf_path: Optional[Union[str, Path]] = None, infiltration_hdf_path: Optional[Union[str, Path]] = None, sediment_soils_hdf_path: Optional[Union[str, Path]] = None, hecras_dir: Optional[Union[str, Path]] = None, ras_object=None, validate: bool = True) -> Path

Associate terrain / classification layers directly on a geometry HDF.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def set_geometry_association(
    geom_number: Union[str, Number, Path],
    terrain_hdf_path: Optional[Union[str, Path]] = None,
    landcover_hdf_path: Optional[Union[str, Path]] = None,
    infiltration_hdf_path: Optional[Union[str, Path]] = None,
    sediment_soils_hdf_path: Optional[Union[str, Path]] = None,
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
    validate: bool = True,
) -> Path:
    """
    Associate terrain / classification layers directly on a geometry HDF.
    """
    from .geom.GeomMesh import GeomMesh

    return GeomMesh.set_geometry_association(
        geom_number,
        terrain_hdf_path=terrain_hdf_path,
        landcover_hdf_path=landcover_hdf_path,
        infiltration_hdf_path=infiltration_hdf_path,
        sediment_soils_hdf_path=sediment_soils_hdf_path,
        hecras_dir=hecras_dir,
        ras_object=ras_object,
        validate=validate,
    )

get_geometry_association staticmethod

Python
get_geometry_association(geom_number: Union[str, Number, Path], hecras_dir: Optional[Union[str, Path]] = None, ras_object=None, resolve_paths: bool = True) -> dict

Read terrain / classification associations from a geometry HDF.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def get_geometry_association(
    geom_number: Union[str, Number, Path],
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
    resolve_paths: bool = True,
) -> dict:
    """
    Read terrain / classification associations from a geometry HDF.
    """
    from .geom.GeomMesh import GeomMesh

    return GeomMesh.get_geometry_association(
        geom_number,
        hecras_dir=hecras_dir,
        ras_object=ras_object,
        resolve_paths=resolve_paths,
    )

list_geometry_associations staticmethod

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

Inventory live compiled-HDF associations for project geometries.

A layer registered in .rasmap is not necessarily associated with a compiled geometry. This method reads each .g##.hdf directly and returns one row per geometry, with every referencing plan collected in plan_numbers. It does not cache association state on geom_df or plan_df.

Parameters:

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

Optional geometry number to select. When omitted, all project geometries are inspected.

None
ras_object RasPrj

Optional initialized :class:RasPrj instance.

None

Returns:

Type Description
DataFrame

DataFrame described by the geometry_associations schema.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_geometry_associations(
    geom_number: Optional[Union[str, Number]] = None,
    ras_object=None,
) -> pd.DataFrame:
    """Inventory live compiled-HDF associations for project geometries.

    A layer registered in ``.rasmap`` is not necessarily associated with a
    compiled geometry. This method reads each ``.g##.hdf`` directly and
    returns one row per geometry, with every referencing plan collected in
    ``plan_numbers``. It does not cache association state on ``geom_df`` or
    ``plan_df``.

    Args:
        geom_number: Optional geometry number to select. When omitted, all
            project geometries are inspected.
        ras_object (RasPrj, optional): Optional initialized :class:`RasPrj` instance.

    Returns:
        DataFrame described by the ``geometry_associations`` schema.
    """
    from ._geometry_association import read_geometry_association

    ras_obj = ras_object or ras
    ras_obj.check_initialized()
    geom_df = getattr(ras_obj, "geom_df", None)
    if geom_df is None:
        geom_df = ras_obj.get_geom_entries()
    selected = geom_df.copy()

    if geom_number is not None:
        normalized = RasUtils.normalize_ras_number(geom_number)
        selected = selected.loc[
            selected["geom_number"].astype(str).str.zfill(2).eq(normalized)
        ]
        if selected.empty:
            available = sorted(
                geom_df["geom_number"].astype(str).str.zfill(2).tolist()
            )
            raise ValueError(
                f"Geometry {normalized!r} was not found. Available: {available}"
            )

    plans_by_geometry: dict[str, list[str]] = {}
    plan_df = getattr(ras_obj, "plan_df", None)
    if plan_df is not None:
        for _, plan_row in plan_df.iterrows():
            raw_geometry = plan_row.get("geometry_number")
            if pd.isna(raw_geometry) or str(raw_geometry).strip() == "":
                raw_geometry = plan_row.get("Geom File")
            if pd.isna(raw_geometry) or str(raw_geometry).strip() == "":
                continue
            try:
                geometry_key = RasUtils.normalize_ras_number(raw_geometry)
                plan_key = RasUtils.normalize_ras_number(
                    plan_row.get("plan_number")
                )
            except (TypeError, ValueError):
                continue
            plans_by_geometry.setdefault(geometry_key, []).append(plan_key)

    records = []
    for _, geom_row in selected.iterrows():
        geometry_key = RasUtils.normalize_ras_number(
            geom_row.get("geom_number")
        )
        geom_path = Path(str(geom_row.get("full_path")))
        raw_hdf_path = geom_row.get("hdf_path")
        geom_hdf_path = (
            Path(str(raw_hdf_path))
            if raw_hdf_path is not None and not pd.isna(raw_hdf_path)
            else Path(str(geom_path) + ".hdf")
        )
        raw_has_2d = geom_row.get("has_2d_mesh")
        has_2d_mesh = (
            None if pd.isna(raw_has_2d) else bool(raw_has_2d)
        )
        record = {
            "geom_number": geometry_key,
            "geom_path": str(geom_path),
            "geom_hdf_path": str(geom_hdf_path),
            "geom_hdf_exists": geom_hdf_path.exists(),
            "plan_numbers": tuple(
                sorted(set(plans_by_geometry.get(geometry_key, [])))
            ),
            "has_2d_mesh": has_2d_mesh,
            "has_spatial_mannings": _geometry_has_spatial_mannings_authoring(
                geom_path
            ),
            "inspection_status": "missing_hdf",
            "inspection_error": (
                None
                if geom_hdf_path.exists()
                else f"Geometry HDF not found: {geom_hdf_path}"
            ),
        }
        for layer in _GEOMETRY_ASSOCIATION_LAYER_KEYS:
            record.update(
                {
                    f"{layer}_associated": False,
                    f"{layer}_raw_filename": None,
                    f"{layer}_layer_name": None,
                    f"{layer}_hdf_path": None,
                    f"{layer}_path_exists": False,
                }
            )

        if geom_hdf_path.exists():
            try:
                association = read_geometry_association(
                    geom_hdf_path,
                    resolve_paths=True,
                )
                for layer, path_key in _GEOMETRY_ASSOCIATION_LAYER_KEYS.items():
                    raw_key = path_key.replace(
                        "_hdf_path",
                        "_raw_filename",
                    )
                    layer_key = path_key.replace(
                        "_hdf_path",
                        "_layer_name",
                    )
                    associated_path = association.get(path_key)
                    raw_filename = association.get(raw_key)
                    record.update(
                        {
                            f"{layer}_associated": bool(
                                raw_filename or associated_path
                            ),
                            f"{layer}_raw_filename": raw_filename,
                            f"{layer}_layer_name": association.get(layer_key),
                            f"{layer}_hdf_path": associated_path,
                            f"{layer}_path_exists": bool(
                                associated_path
                                and Path(associated_path).exists()
                            ),
                        }
                    )
                record["inspection_status"] = "available"
                record["inspection_error"] = None
            except Exception as exc:
                from .fast_hdf import reraise_required

                reraise_required(exc)
                record["inspection_status"] = "failed"
                record["inspection_error"] = str(exc)
        records.append(record)

    return pd.DataFrame.from_records(
        records,
        columns=_GEOMETRY_ASSOCIATION_COLUMNS,
    )

validate_geometry_associations staticmethod

Python
validate_geometry_associations(geom_number: Optional[Union[str, Number]] = None, required_layers: Sequence[str] = ('terrain', 'landcover'), require_existing_paths: bool = True, raise_on_failure: bool = True, ras_object=None) -> pd.DataFrame

Validate required compiled-geometry layer associations.

.rasmap registration is deliberately not accepted as proof of an association. Use this before property-table generation, then inspect a temporary plan HDF before compute and the final plan HDF afterward.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def validate_geometry_associations(
    geom_number: Optional[Union[str, Number]] = None,
    required_layers: Sequence[str] = ("terrain", "landcover"),
    require_existing_paths: bool = True,
    raise_on_failure: bool = True,
    ras_object=None,
) -> pd.DataFrame:
    """Validate required compiled-geometry layer associations.

    ``.rasmap`` registration is deliberately not accepted as proof of an
    association. Use this before property-table generation, then inspect a
    temporary plan HDF before compute and the final plan HDF afterward.
    """
    aliases = {
        "land_cover": "landcover",
        "mannings": "landcover",
        "mannings_n": "landcover",
        "sediment": "sediment_soils",
    }
    if isinstance(required_layers, str):
        required_layers = (required_layers,)
    normalized_layers = tuple(
        aliases.get(str(layer).strip().lower(), str(layer).strip().lower())
        for layer in required_layers
    )
    unknown = sorted(
        set(normalized_layers) - set(_GEOMETRY_ASSOCIATION_LAYER_KEYS)
    )
    if unknown:
        raise ValueError(
            "Unsupported required_layers: "
            + ", ".join(unknown)
            + ". Expected terrain, landcover, infiltration, or "
            "sediment_soils."
        )

    report = RasMap.list_geometry_associations(
        geom_number=geom_number,
        ras_object=ras_object,
    ).copy()
    missing_values = []
    broken_values = []
    passed_values = []
    reason_values = []
    for row in report.itertuples(index=False):
        missing = tuple(
            layer
            for layer in normalized_layers
            if not bool(getattr(row, f"{layer}_associated"))
        )
        broken = tuple(
            layer
            for layer in normalized_layers
            if bool(getattr(row, f"{layer}_associated"))
            and not bool(getattr(row, f"{layer}_path_exists"))
        ) if require_existing_paths else ()
        reasons = []
        if row.inspection_status != "available":
            reasons.append(row.inspection_error or row.inspection_status)
        if missing:
            reasons.append("missing required layers: " + ", ".join(missing))
        if broken:
            reasons.append("broken association paths: " + ", ".join(broken))
        missing_values.append(missing)
        broken_values.append(broken)
        passed_values.append(not reasons)
        reason_values.append("; ".join(reasons))

    report["missing_required_layers"] = missing_values
    report["broken_association_layers"] = broken_values
    report["passed"] = passed_values
    report["failure_reason"] = reason_values

    if raise_on_failure and (
        report.empty or not bool(report["passed"].all())
    ):
        details = (
            "; ".join(
                f"g{row.geom_number}: {row.failure_reason}"
                for row in report.itertuples(index=False)
                if not row.passed
            )
            if not report.empty
            else "no project geometries were found"
        )
        raise RuntimeError(f"Geometry association validation failed: {details}")
    return report

get_hdf_geometry_association staticmethod

Python
get_hdf_geometry_association(hdf_path: Union[str, Path], resolve_paths: bool = True, include_2d_area_attrs: bool = True, ras_object=None) -> dict

Read /Geometry association attrs from a geometry, plan, or result HDF.

This is read-only and intended for QA/QC workflows that need to audit terrain, land-cover, infiltration, or sediment bed-material links already stored in HEC-RAS HDF artifacts. When include_2d_area_attrs=True, the two_d_area_terrain_associations list contains one record per named 2D flow-area group. Optional terrain fields are None when HEC-RAS has not populated an area-level association.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def get_hdf_geometry_association(
    hdf_path: Union[str, Path],
    resolve_paths: bool = True,
    include_2d_area_attrs: bool = True,
    ras_object=None,
) -> dict:
    """
    Read ``/Geometry`` association attrs from a geometry, plan, or result HDF.

    This is read-only and intended for QA/QC workflows that need to audit
    terrain, land-cover, infiltration, or sediment bed-material links
    already stored in HEC-RAS HDF artifacts. When
    ``include_2d_area_attrs=True``, the
    ``two_d_area_terrain_associations`` list contains one record per named
    2D flow-area group. Optional terrain fields are ``None`` when HEC-RAS
    has not populated an area-level association.
    """
    from ._geometry_association import read_geometry_association

    return read_geometry_association(
        hdf_path,
        resolve_paths=resolve_paths,
        include_2d_area_attrs=include_2d_area_attrs,
    )

recompute_property_tables staticmethod

Python
recompute_property_tables(ras_project_path: Union[str, Path], geom_file: Union[str, Path], hecras_version: Optional[str] = None, audit_mannings: bool = False, ras_object=None) -> Path

Recompute property tables with the selected native RASMapper version.

Completion is required for every geometry. When 2D flow areas are present, the native cell-volume and face-area table pairs must also be nonempty before this method returns. A complete 1D-only geometry has no 2D-array postcondition.

Set audit_mannings=True to require materially diverse, associated final Manning values after the native command.

Modern native computation runs in an isolated process using the selected HEC-RAS installation's bundled HDF5 DLLs, with a 1,800-second timeout. That process runs RasMapperLib with the .NET Framework 4.7.2 target semantics of HEC-RAS's own hosts, so sorting ties in face profiles resolve as in HEC-RAS plan compute. Mutates the supplied geometry HDF in its existing CRS/units; use a disposable model copy. Process success does not replace the complete-geometry/table-pair checks or hydraulic QA.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def recompute_property_tables(
    ras_project_path: Union[str, Path],
    geom_file: Union[str, Path],
    hecras_version: Optional[str] = None,
    audit_mannings: bool = False,
    ras_object=None,
) -> Path:
    """
    Recompute property tables with the selected native RASMapper version.

    Completion is required for every geometry. When 2D flow areas are
    present, the native cell-volume and face-area table pairs must also be
    nonempty before this method returns. A complete 1D-only geometry has
    no 2D-array postcondition.

    Set ``audit_mannings=True`` to require materially diverse, associated
    final Manning values after the native command.

    Modern native computation runs in an isolated process using the
    selected HEC-RAS installation's bundled HDF5 DLLs, with a 1,800-second
    timeout. That process runs RasMapperLib with the .NET Framework 4.7.2
    target semantics of HEC-RAS's own hosts, so sorting ties in face
    profiles resolve as in HEC-RAS plan compute.
    Mutates the supplied geometry HDF in its existing CRS/units;
    use a disposable model copy. Process success does not replace the
    complete-geometry/table-pair checks or hydraulic QA.
    """
    ras_project_path = Path(ras_project_path)
    geom_file = Path(geom_file)
    version = _resolve_native_hecras_version(hecras_version, ras_object)
    from . import _land_classification_helper as _lch

    return _lch.recompute_property_tables(
        ras_project_path,
        geom_file,
        ras_object=ras_object,
        hecras_version=version,
        audit_mannings=audit_mannings,
    )

Layer validation

RasMapValidation performs format, CRS, raster and spatial checks and returns validation results (or the Boolean convenience result from is_valid_layer). These checks do not run the hydraulic solver.

Validation methods for HEC-RAS map layers.

Validates layer formats (GeoJSON, Shapefile, GeoTIFF, HDF), CRS/projections, raster metadata, spatial extents, and terrain/land cover layer configurations.

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

check_layer_format staticmethod

Python
check_layer_format(layer_file: Union[str, Path]) -> ValidationResult

Check layer file format validity.

Validates: - File exists - Format is supported (GeoJSON, Shapefile, GeoTIFF, HDF) - File can be opened and read

Parameters:

Name Type Description Default
layer_file Union[str, Path]

Path to layer file

required

Returns:

Type Description
ValidationResult

ValidationResult with format validation

Example

from ras_commander import RasMapValidation result = RasMapValidation.check_layer_format("terrain.tif") if result.is_valid: ... print(f"Format valid: {result.context.get('format')}")

Source code in ras_commander/RasMapValidation.py
Python
@staticmethod
@log_call
def check_layer_format(layer_file: Union[str, Path]) -> 'ValidationResult':
    """
    Check layer file format validity.

    Validates:
    - File exists
    - Format is supported (GeoJSON, Shapefile, GeoTIFF, HDF)
    - File can be opened and read

    Args:
        layer_file: Path to layer file

    Returns:
        ValidationResult with format validation

    Example:
        >>> from ras_commander import RasMapValidation
        >>> result = RasMapValidation.check_layer_format("terrain.tif")
        >>> if result.is_valid:
        ...     print(f"Format valid: {result.context.get('format')}")
    """
    from ras_commander.RasValidation import ValidationResult, ValidationSeverity

    layer_file = Path(layer_file)

    if not layer_file.exists():
        return ValidationResult(
            check_name="file_existence",
            severity=ValidationSeverity.ERROR,
            passed=False,
            message=f"File not found: {layer_file}"
        )

    try:
        with open(layer_file, 'rb') as f:
            _ = f.read(1)
    except PermissionError:
        return ValidationResult(
            check_name="file_accessibility",
            severity=ValidationSeverity.ERROR,
            passed=False,
            message=f"Permission denied reading file: {layer_file}"
        )
    except Exception as e:
        return ValidationResult(
            check_name="file_accessibility",
            severity=ValidationSeverity.ERROR,
            passed=False,
            message=f"Cannot read file: {e}"
        )

    suffix = layer_file.suffix.lower()
    format_map = {
        '.geojson': 'geojson', '.json': 'geojson',
        '.shp': 'shapefile',
        '.tif': 'geotiff', '.tiff': 'geotiff',
        '.hdf': 'hdf', '.h5': 'hdf'
    }

    detected_format = format_map.get(suffix)

    if detected_format is None:
        return ValidationResult(
            check_name="format_detection",
            severity=ValidationSeverity.WARNING,
            passed=True,
            message=f"Unrecognized file extension: {suffix}",
            details={"extension": suffix}
        )

    try:
        if detected_format == 'geojson':
            return RasMapValidation._validate_geojson_format(layer_file)
        elif detected_format == 'shapefile':
            return RasMapValidation._validate_shapefile_format(layer_file)
        elif detected_format == 'geotiff':
            return RasMapValidation._validate_geotiff_format(layer_file)
        elif detected_format == 'hdf':
            return RasMapValidation._validate_hdf_format(layer_file)
    except ImportError:
        return ValidationResult(
            check_name="format_validation",
            severity=ValidationSeverity.WARNING,
            passed=True,
            message=f"File format appears valid ({detected_format}), but validation library not available",
            details={"format": detected_format}
        )

    return ValidationResult(
        check_name="format_validation",
        severity=ValidationSeverity.INFO,
        passed=True,
        message=f"File format appears valid: {detected_format}",
        details={"format": detected_format}
    )

check_layer_crs staticmethod

Python
check_layer_crs(layer_file: Union[str, Path], expected_epsg: Optional[int] = None) -> ValidationResult

Check layer CRS/projection validity.

For GeoJSON files, enforces WGS84 (EPSG:4326) requirement. For other formats, checks against expected CRS if provided.

Parameters:

Name Type Description Default
layer_file Union[str, Path]

Path to layer file

required
expected_epsg Optional[int]

Optional expected EPSG code (e.g., 4326 for WGS84)

None

Returns:

Type Description
ValidationResult

ValidationResult with CRS validation

Source code in ras_commander/RasMapValidation.py
Python
@staticmethod
@log_call
def check_layer_crs(
    layer_file: Union[str, Path],
    expected_epsg: Optional[int] = None
) -> 'ValidationResult':
    """
    Check layer CRS/projection validity.

    For GeoJSON files, enforces WGS84 (EPSG:4326) requirement.
    For other formats, checks against expected CRS if provided.

    Args:
        layer_file: Path to layer file
        expected_epsg: Optional expected EPSG code (e.g., 4326 for WGS84)

    Returns:
        ValidationResult with CRS validation
    """
    from ras_commander.RasValidation import ValidationResult, ValidationSeverity

    layer_file = Path(layer_file)
    suffix = layer_file.suffix.lower()
    expected_crs = f"EPSG:{expected_epsg}" if expected_epsg else None

    try:
        if suffix in ['.geojson', '.json', '.shp']:
            import geopandas as gpd
            gdf = gpd.read_file(layer_file)

            if gdf.crs is None:
                return ValidationResult(check_name="crs_validation", severity=ValidationSeverity.WARNING,
                                        passed=True, message="Layer has no CRS defined (assuming WGS84)",
                                        details={"crs": None})

            crs_string = gdf.crs.to_string()

            if suffix in ['.geojson', '.json'] and crs_string != "EPSG:4326":
                return ValidationResult(check_name="crs_validation", severity=ValidationSeverity.ERROR,
                                        passed=False,
                                        message=f"GeoJSON must be in WGS84 (EPSG:4326), got {crs_string}",
                                        details={"actual_crs": crs_string, "required_crs": "EPSG:4326"})

            if expected_crs and crs_string != expected_crs:
                return ValidationResult(check_name="crs_validation", severity=ValidationSeverity.WARNING,
                                        passed=True,
                                        message=f"CRS mismatch: expected {expected_crs}, got {crs_string}",
                                        details={"expected_crs": expected_crs, "actual_crs": crs_string})

            return ValidationResult(check_name="crs_validation", severity=ValidationSeverity.INFO,
                                    passed=True, message=f"CRS valid: {crs_string}",
                                    details={"crs": crs_string})

        elif suffix in ['.tif', '.tiff']:
            import rasterio
            with rasterio.open(layer_file) as src:
                if src.crs is None:
                    return ValidationResult(check_name="crs_validation", severity=ValidationSeverity.WARNING,
                                            passed=True, message="Raster has no CRS defined",
                                            details={"crs": None})

                crs_string = src.crs.to_string()
                if expected_crs and crs_string != expected_crs:
                    return ValidationResult(check_name="crs_validation", severity=ValidationSeverity.WARNING,
                                            passed=True,
                                            message=f"CRS mismatch: expected {expected_crs}, got {crs_string}",
                                            details={"expected_crs": expected_crs, "actual_crs": crs_string})

                return ValidationResult(check_name="crs_validation", severity=ValidationSeverity.INFO,
                                        passed=True, message=f"CRS valid: {crs_string}",
                                        details={"crs": crs_string})

    except ImportError as e:
        return ValidationResult(check_name="crs_validation", severity=ValidationSeverity.WARNING,
                                passed=True, message=f"Required library not available: {e}")
    except Exception as e:
        return ValidationResult(check_name="crs_validation", severity=ValidationSeverity.WARNING,
                                passed=True, message=f"Could not check CRS: {e}")

    return ValidationResult(check_name="crs_validation", severity=ValidationSeverity.INFO,
                            passed=True, message="CRS check not applicable for this file type")

check_raster_metadata staticmethod

Python
check_raster_metadata(layer_file: Union[str, Path], max_resolution: Optional[float] = 100.0, check_nodata: bool = True) -> List[ValidationResult]

Check raster metadata (resolution, extent, nodata).

Parameters:

Name Type Description Default
layer_file Union[str, Path]

Path to raster file

required
max_resolution Optional[float]

Maximum acceptable resolution in meters (warn if coarser)

100.0
check_nodata bool

If True, check nodata percentage

True

Returns:

Type Description
List[ValidationResult]

Raster metadata validation results

Source code in ras_commander/RasMapValidation.py
Python
@staticmethod
@log_call
def check_raster_metadata(
    layer_file: Union[str, Path],
    max_resolution: Optional[float] = 100.0,
    check_nodata: bool = True
) -> List['ValidationResult']:
    """
    Check raster metadata (resolution, extent, nodata).

    Args:
        layer_file: Path to raster file
        max_resolution: Maximum acceptable resolution in meters (warn if coarser)
        check_nodata: If True, check nodata percentage

    Returns:
        List[ValidationResult]: Raster metadata validation results
    """
    from ras_commander.RasValidation import ValidationResult, ValidationSeverity

    layer_file = Path(layer_file)
    results = []

    try:
        import rasterio
        import numpy as np

        with rasterio.open(layer_file) as src:
            resolution = max(abs(src.res[0]), abs(src.res[1]))

            if max_resolution and resolution > max_resolution:
                results.append(ValidationResult(
                    check_name="resolution_check", severity=ValidationSeverity.WARNING, passed=True,
                    message=f"Raster resolution is coarse: {resolution:.2f} meters (limit: {max_resolution} m)",
                    details={"resolution": resolution, "max_resolution": max_resolution}))
            else:
                results.append(ValidationResult(
                    check_name="resolution_check", severity=ValidationSeverity.INFO, passed=True,
                    message=f"Raster resolution acceptable: {resolution:.2f} meters",
                    details={"resolution": resolution}))

            if check_nodata:
                try:
                    data = src.read(1, masked=True)
                    if hasattr(data, 'mask'):
                        nodata_pct = (data.mask.sum() / data.size) * 100
                        severity = ValidationSeverity.WARNING if nodata_pct > 50 else ValidationSeverity.INFO
                        results.append(ValidationResult(
                            check_name="nodata_check", severity=severity, passed=True,
                            message=f"Raster nodata: {nodata_pct:.1f}%",
                            details={"nodata_percent": nodata_pct}))
                    else:
                        results.append(ValidationResult(
                            check_name="nodata_check", severity=ValidationSeverity.INFO, passed=True,
                            message="Raster has no masked/nodata values"))
                except Exception as e:
                    results.append(ValidationResult(
                        check_name="nodata_check", severity=ValidationSeverity.WARNING, passed=True,
                        message=f"Could not check nodata: {e}"))

            bounds = src.bounds
            results.append(ValidationResult(
                check_name="extent_info", severity=ValidationSeverity.INFO, passed=True,
                message=f"Raster extent: ({bounds.left:.2f}, {bounds.bottom:.2f}, {bounds.right:.2f}, {bounds.top:.2f})",
                details={"bounds": (bounds.left, bounds.bottom, bounds.right, bounds.top)}))

    except ImportError:
        results.append(ValidationResult(check_name="raster_metadata", severity=ValidationSeverity.WARNING,
                                        passed=True, message="rasterio not available, cannot validate raster metadata"))
    except Exception as e:
        results.append(ValidationResult(check_name="raster_metadata", severity=ValidationSeverity.ERROR,
                                        passed=False, message=f"Failed to read raster metadata: {e}"))
    return results

check_spatial_extent staticmethod

Python
check_spatial_extent(layer_file: Union[str, Path], model_extent: tuple, min_coverage_pct: float = 50.0) -> ValidationResult

Check layer spatial extent vs model domain.

Parameters:

Name Type Description Default
layer_file Union[str, Path]

Path to layer file

required
model_extent tuple

Model bounding box (minx, miny, maxx, maxy)

required
min_coverage_pct float

Minimum coverage percentage (warn if below)

50.0

Returns:

Type Description
ValidationResult

Spatial extent validation result

Source code in ras_commander/RasMapValidation.py
Python
@staticmethod
@log_call
def check_spatial_extent(
    layer_file: Union[str, Path],
    model_extent: tuple,
    min_coverage_pct: float = 50.0
) -> 'ValidationResult':
    """
    Check layer spatial extent vs model domain.

    Args:
        layer_file: Path to layer file
        model_extent: Model bounding box (minx, miny, maxx, maxy)
        min_coverage_pct: Minimum coverage percentage (warn if below)

    Returns:
        ValidationResult: Spatial extent validation result
    """
    from ras_commander.RasValidation import ValidationResult, ValidationSeverity

    layer_file = Path(layer_file)
    suffix = layer_file.suffix.lower()

    try:
        from shapely.geometry import box
        model_box = box(*model_extent)

        if suffix in ['.tif', '.tiff']:
            import rasterio
            with rasterio.open(layer_file) as src:
                layer_box = box(*src.bounds)
        elif suffix in ['.geojson', '.json', '.shp']:
            import geopandas as gpd
            gdf = gpd.read_file(layer_file)
            layer_box = box(*gdf.total_bounds)
        else:
            return ValidationResult(check_name="spatial_coverage", severity=ValidationSeverity.INFO,
                                    passed=True, message="Spatial coverage check not applicable for this file type")

        if not model_box.intersects(layer_box):
            return ValidationResult(
                check_name="spatial_coverage", severity=ValidationSeverity.ERROR, passed=False,
                message="Layer does not overlap with model domain",
                details={"model_extent": model_extent, "layer_extent": layer_box.bounds})

        intersection = model_box.intersection(layer_box)
        coverage_pct = (intersection.area / model_box.area) * 100

        if coverage_pct < min_coverage_pct:
            return ValidationResult(
                check_name="spatial_coverage", severity=ValidationSeverity.WARNING, passed=True,
                message=f"Layer only covers {coverage_pct:.1f}% of model domain (minimum: {min_coverage_pct:.1f}%)",
                details={"coverage_percent": coverage_pct, "min_coverage_pct": min_coverage_pct})

        return ValidationResult(
            check_name="spatial_coverage", severity=ValidationSeverity.INFO, passed=True,
            message=f"Layer covers {coverage_pct:.1f}% of model domain",
            details={"coverage_percent": coverage_pct})

    except ImportError as e:
        return ValidationResult(check_name="spatial_coverage", severity=ValidationSeverity.WARNING,
                                passed=True, message=f"Required library not available: {e}")
    except Exception as e:
        return ValidationResult(check_name="spatial_coverage", severity=ValidationSeverity.WARNING,
                                passed=True, message=f"Could not check spatial coverage: {e}")

check_terrain_layer staticmethod

Python
check_terrain_layer(rasmap_path: Union[str, Path], layer_name: str) -> ValidationResult

Check terrain layer configuration in rasmap file.

Parameters:

Name Type Description Default
rasmap_path Union[str, Path]

Path to .rasmap file

required
layer_name str

Name of terrain layer

required

Returns:

Type Description
ValidationResult

Terrain validation result

Source code in ras_commander/RasMapValidation.py
Python
@staticmethod
@log_call
def check_terrain_layer(
    rasmap_path: Union[str, Path],
    layer_name: str
) -> 'ValidationResult':
    """
    Check terrain layer configuration in rasmap file.

    Args:
        rasmap_path: Path to .rasmap file
        layer_name: Name of terrain layer

    Returns:
        ValidationResult: Terrain validation result
    """
    from ras_commander.RasValidation import ValidationResult, ValidationSeverity
    from .RasMap import RasMap

    rasmap_path = Path(rasmap_path)
    try:
        terrain_names = RasMap.get_terrain_names(rasmap_path)
        if layer_name not in terrain_names:
            return ValidationResult(
                check_name="terrain_layer_exists", severity=ValidationSeverity.ERROR, passed=False,
                message=f"Terrain layer '{layer_name}' not found in rasmap",
                details={"layer_name": layer_name, "available": terrain_names})
    except Exception as e:
        return ValidationResult(
            check_name="terrain_layer_exists", severity=ValidationSeverity.ERROR, passed=False,
            message=f"Failed to read rasmap file: {e}")

    return ValidationResult(
        check_name="terrain_layer_validation", severity=ValidationSeverity.INFO, passed=True,
        message=f"Terrain layer '{layer_name}' found in rasmap",
        details={"layer_name": layer_name})

check_land_cover_layer staticmethod

Python
check_land_cover_layer(rasmap_path: Union[str, Path], layer_name: str) -> ValidationResult

Check land cover layer configuration in rasmap file.

Parameters:

Name Type Description Default
rasmap_path Union[str, Path]

Path to .rasmap file

required
layer_name str

Name of land cover layer

required

Returns:

Type Description
ValidationResult

Land cover validation result

Source code in ras_commander/RasMapValidation.py
Python
@staticmethod
@log_call
def check_land_cover_layer(
    rasmap_path: Union[str, Path],
    layer_name: str
) -> 'ValidationResult':
    """
    Check land cover layer configuration in rasmap file.

    Args:
        rasmap_path: Path to .rasmap file
        layer_name: Name of land cover layer

    Returns:
        ValidationResult: Land cover validation result
    """
    from ras_commander.RasValidation import ValidationResult, ValidationSeverity

    return ValidationResult(
        check_name="land_cover_validation", severity=ValidationSeverity.INFO, passed=True,
        message=f"Land cover validation for '{layer_name}' not yet implemented",
        details={"layer_name": layer_name})

check_layer staticmethod

Python
check_layer(rasmap_path: Union[str, Path], layer_name: str, layer_type: Optional[str] = None) -> ValidationReport

Comprehensive layer validation.

Parameters:

Name Type Description Default
rasmap_path Union[str, Path]

Path to .rasmap file

required
layer_name str

Name of layer to validate

required
layer_type Optional[str]

Optional layer type ('Terrain', 'Land Cover', etc.)

None

Returns:

Type Description
ValidationReport

ValidationReport with all validation results

Source code in ras_commander/RasMapValidation.py
Python
@staticmethod
@log_call
def check_layer(
    rasmap_path: Union[str, Path],
    layer_name: str,
    layer_type: Optional[str] = None
) -> 'ValidationReport':
    """
    Comprehensive layer validation.

    Args:
        rasmap_path: Path to .rasmap file
        layer_name: Name of layer to validate
        layer_type: Optional layer type ('Terrain', 'Land Cover', etc.)

    Returns:
        ValidationReport with all validation results
    """
    from ras_commander.RasValidation import ValidationReport
    from datetime import datetime

    rasmap_path = Path(rasmap_path)
    results = []

    if layer_type == "Terrain":
        results.append(RasMapValidation.check_terrain_layer(rasmap_path, layer_name))
    elif layer_type == "Land Cover":
        results.append(RasMapValidation.check_land_cover_layer(rasmap_path, layer_name))
    else:
        from ras_commander.RasValidation import ValidationResult, ValidationSeverity
        results.append(ValidationResult(
            check_name="layer_type", severity=ValidationSeverity.INFO, passed=True,
            message=f"Layer type '{layer_type}' validation not specialized",
            details={"layer_name": layer_name, "layer_type": layer_type}))

    return ValidationReport(target=f"{rasmap_path} - {layer_name}",
                            timestamp=datetime.now(), results=results)

is_valid_layer staticmethod

Python
is_valid_layer(rasmap_path: Union[str, Path], layer_name: str, layer_type: Optional[str] = None) -> bool

Quick boolean check for layer validity.

Parameters:

Name Type Description Default
rasmap_path Union[str, Path]

Path to .rasmap file

required
layer_name str

Name of layer to validate

required
layer_type Optional[str]

Optional layer type

None

Returns:

Type Description
bool

True if layer is valid

Source code in ras_commander/RasMapValidation.py
Python
@staticmethod
def is_valid_layer(
    rasmap_path: Union[str, Path],
    layer_name: str,
    layer_type: Optional[str] = None
) -> bool:
    """
    Quick boolean check for layer validity.

    Args:
        rasmap_path: Path to .rasmap file
        layer_name: Name of layer to validate
        layer_type: Optional layer type

    Returns:
        True if layer is valid
    """
    report = RasMapValidation.check_layer(rasmap_path, layer_name, layer_type)
    return all(result.passed for result in report.results)

RASMapper geometry completion

Geometry completion creates native geometry-derived layers in an existing compiled geometry HDF. It is distinct from compiling geometry text, generating 2D computation points, and executing a hydraulic plan.

API Runtime Inputs and outputs
RasGeometryCompute.compute_geometry Windows, pythonnet, HEC-RAS 6.6+ Geometry HDF and optional .rasmap; mutates HDF and returns GeometryCompleteResult
Individual generate_* methods Same in-process native bridge Selected edge lines, interpolation surface or flow paths; GeometryLayerResult
validate_geometry, is_valid_geometry Native geometry validation Diagnostics or Boolean convenience result
Reach-length and flow-path audits See method-specific requirements below Audit tables or FlowPathPolicyResult
RasProcess.compute_geometry Windows or supported Linux/Wine subprocess path Full native completion; dictionary with semantic validation and process evidence

The full completion pipeline includes edge lines, the cross-section interpolation surface and other geometry/property-table work. Flow paths are separate: use generate_flow_paths() when needed. Completion may rebuild 2D property tables and mutate more than one layer. Work on a project copy and review diagnostics and resulting geometry before accepting it.

With the default overwrite=False, RasGeometryCompute.compute_geometry() skips the pipeline if both edge lines and the interpolation surface already exist. That path returns success=True without a separate skipped flag; success alone does not prove the current call recomputed property tables.

Use RasGeometryCompute for the Windows in-process path; use the documented RasProcess path for Linux/Wine completion. Do not infer that every in-process method has a Wine equivalent. RasProcess.complete_geometry() is a deprecated alias for compute_geometry().

On Windows with HEC-RAS 7.0.2, use RasProcess.compute_geometry() when the in-process bridge fails with missing H5E_LOGFAIL_g. This was reproduced when h5py loaded HDF5 2.0 before the vendor bridge. The subprocess isolates the vendor DLLs; pass ras_version= with the exact executable path or installation directory. This route completed the public BaldEagle geometry and matched the 7.0.1 control's three meshes dataset for dataset. It mutates geometry in place, so use a project copy.

Ras.exe preprocessing requires a registered installation: an isolated 7.0.2 administrative image failed with an unregistered per-release RAS Mapper COM class. After official installation and API TCU acceptance, Windows preprocessing and unsteady plan computation passed with the single-plan launch workaround. The genuine 7.0.2 temporary HDF also passed guarded schema/write-readback checks; Linux solve after mutation remains unqualified. Precipitation forcing, corner preparation, and Linux/Wine execution were not qualified on 7.0.2 by these checks.

Read native output layers through HdfXsec.get_river_edge_lines(), get_xs_interpolation_surface() and get_river_flow_paths() in the HDF API. 234 — geometry completion contains retained execution outputs.

In-process completion and diagnostics

Headless RASMapper geometry completion via pythonnet (Windows only).

generate_edge_lines staticmethod

Python
generate_edge_lines(geom_hdf_path: Union[str, Path], rasmap_path: Optional[Union[str, Path]] = None, overwrite: bool = False, backup: bool = True, ras_object=None, hecras_version: Optional[str] = None) -> GeometryLayerResult

Generate HEC-RAS river edge lines into Geometry/River Edge Lines.

RASMapper's Create Edge Lines at XS Limits, run in-process. Unlike HdfXsec.generate_river_edge_lines() (a pure-Python XS-endpoint approximation used by get_1d_footprint()), this produces HEC-RAS's own bank-line-anchored offset-curve edge lines and writes the group-level Source Data Hash so HEC-RAS treats them as authoritative. Read the result with HdfXsec.get_river_edge_lines().

Parameters

geom_hdf_path : str or Path Geometry HDF (.g##.hdf), mutated in place. rasmap_path : str or Path, optional .rasmap for spatial reference; auto-resolved from ras_object when omitted. Not required (geometry operations are coordinate-space). overwrite : bool, default False When False and the layer already exists, skip without recomputing. backup : bool, default True When overwriting an existing layer, first export it to a dated .geojson.bak sidecar. ras_object : RasPrj, optional Used only to auto-resolve the .rasmap. hecras_version : str, optional Specific HEC-RAS version to bind the CLR to (e.g. "6.6").

Returns

GeometryLayerResult

Source code in ras_commander/RasGeometryCompute.py
Python
@staticmethod
@log_call
def generate_edge_lines(
    geom_hdf_path: Union[str, Path],
    rasmap_path: Optional[Union[str, Path]] = None,
    overwrite: bool = False,
    backup: bool = True,
    ras_object=None,
    hecras_version: Optional[str] = None,
) -> GeometryLayerResult:
    """
    Generate HEC-RAS river edge lines into ``Geometry/River Edge Lines``.

    RASMapper's *Create Edge Lines at XS Limits*, run in-process. Unlike
    ``HdfXsec.generate_river_edge_lines()`` (a pure-Python XS-endpoint
    approximation used by ``get_1d_footprint()``), this produces HEC-RAS's
    own bank-line-anchored offset-curve edge lines and writes the group-level
    ``Source Data Hash`` so HEC-RAS treats them as authoritative. Read the
    result with ``HdfXsec.get_river_edge_lines()``.

    Parameters
    ----------
    geom_hdf_path : str or Path
        Geometry HDF (``.g##.hdf``), mutated in place.
    rasmap_path : str or Path, optional
        ``.rasmap`` for spatial reference; auto-resolved from ``ras_object``
        when omitted. Not required (geometry operations are coordinate-space).
    overwrite : bool, default False
        When False and the layer already exists, skip without recomputing.
    backup : bool, default True
        When overwriting an existing layer, first export it to a dated
        ``.geojson.bak`` sidecar.
    ras_object : RasPrj, optional
        Used only to auto-resolve the ``.rasmap``.
    hecras_version : str, optional
        Specific HEC-RAS version to bind the CLR to (e.g. ``"6.6"``).

    Returns
    -------
    GeometryLayerResult
    """
    return RasGeometryCompute._generate_layer(
        geom_hdf_path, rasmap_path, overwrite, backup, ras_object, hecras_version,
        group=_GROUP_EDGE_LINES, layer_name="River Edge Lines", tag="edge_lines",
        reader=RasGeometryCompute._read_edge_lines,
        compute=lambda geom: geom.EdgeLines.ComputeEdgeLines(True),
    )

generate_interpolation_surface staticmethod

Python
generate_interpolation_surface(geom_hdf_path: Union[str, Path], rasmap_path: Optional[Union[str, Path]] = None, overwrite: bool = False, backup: bool = True, ras_object=None, hecras_version: Optional[str] = None) -> GeometryLayerResult

Generate the XS interpolation surface into Geometry/Cross Section Interpolation Surfaces.

RASMapper's Compute XS Interpolation Surface, run in-process. HEC-RAS self-ensures bank lines and edge lines first, so those layers are also (re)generated as a side effect when out of date. Read the result with HdfXsec.get_xs_interpolation_surface().

Parameters and returns mirror generate_edge_lines().

Source code in ras_commander/RasGeometryCompute.py
Python
@staticmethod
@log_call
def generate_interpolation_surface(
    geom_hdf_path: Union[str, Path],
    rasmap_path: Optional[Union[str, Path]] = None,
    overwrite: bool = False,
    backup: bool = True,
    ras_object=None,
    hecras_version: Optional[str] = None,
) -> GeometryLayerResult:
    """
    Generate the XS interpolation surface into
    ``Geometry/Cross Section Interpolation Surfaces``.

    RASMapper's *Compute XS Interpolation Surface*, run in-process. HEC-RAS
    self-ensures bank lines and edge lines first, so those layers are also
    (re)generated as a side effect when out of date. Read the result with
    ``HdfXsec.get_xs_interpolation_surface()``.

    Parameters and returns mirror ``generate_edge_lines()``.
    """
    return RasGeometryCompute._generate_layer(
        geom_hdf_path, rasmap_path, overwrite, backup, ras_object, hecras_version,
        group=_GROUP_INTERP_SURFACE, layer_name="Cross Section Interpolation Surfaces",
        tag="interpolation_surface",
        reader=RasGeometryCompute._read_interp_surface,
        compute=lambda geom: geom.XSInterpolationSurface.ComputeInterpolationSurface(True),
    )

generate_flow_paths staticmethod

Python
generate_flow_paths(geom_hdf_path: Union[str, Path], rasmap_path: Optional[Union[str, Path]] = None, overwrite: bool = False, backup: bool = True, ras_object=None, hecras_version: Optional[str] = None) -> GeometryLayerResult

Generate river flow paths into Geometry/River Flow Paths.

RASMapper's Create Flow Paths from XS Layout, run in-process. Read the result with HdfXsec.get_river_flow_paths().

Manually defined or corrected flow paths must not be overwritten. HEC-RAS keeps no cache hash for flow paths, so any regeneration unconditionally replaces them. This method therefore defaults to overwrite=False (skip when flow paths already exist). Set overwrite=True to regenerate; with backup=True (default) the existing flow paths are first exported to a dated .geojson.bak sidecar. Use HdfXsec.get_river_flow_paths() to check for existing flow paths before deciding.

Parameters and returns mirror generate_edge_lines().

Source code in ras_commander/RasGeometryCompute.py
Python
@staticmethod
@log_call
def generate_flow_paths(
    geom_hdf_path: Union[str, Path],
    rasmap_path: Optional[Union[str, Path]] = None,
    overwrite: bool = False,
    backup: bool = True,
    ras_object=None,
    hecras_version: Optional[str] = None,
) -> GeometryLayerResult:
    """
    Generate river flow paths into ``Geometry/River Flow Paths``.

    RASMapper's *Create Flow Paths from XS Layout*, run in-process. Read the
    result with ``HdfXsec.get_river_flow_paths()``.

    **Manually defined or corrected flow paths must not be overwritten.**
    HEC-RAS keeps no cache hash for flow paths, so any regeneration
    unconditionally replaces them. This method therefore defaults to
    ``overwrite=False`` (skip when flow paths already exist). Set
    ``overwrite=True`` to regenerate; with ``backup=True`` (default) the
    existing flow paths are first exported to a dated ``.geojson.bak``
    sidecar. Use ``HdfXsec.get_river_flow_paths()`` to check for existing
    flow paths before deciding.

    Parameters and returns mirror ``generate_edge_lines()``.
    """
    return RasGeometryCompute._generate_layer(
        geom_hdf_path, rasmap_path, overwrite, backup, ras_object, hecras_version,
        group=_GROUP_FLOW_PATHS, layer_name="River Flow Paths", tag="flow_paths",
        reader=RasGeometryCompute._read_flow_paths,
        compute=lambda geom: geom.FlowPathLines.ComputeFlowPathLines(),
    )

compute_geometry staticmethod

Python
compute_geometry(geom_hdf_path: Union[str, Path], rasmap_path: Optional[Union[str, Path]] = None, overwrite: bool = False, backup: bool = True, ras_object=None, hecras_version: Optional[str] = None) -> GeometryCompleteResult

Run the full RASMapper geometry-completion pipeline, in-process.

In-process equivalent of RasProcess.compute_geometry() and RASMapper's "Compute Geometry" action (RasMapperLib RASGeometry.CompleteForComputations). Generates bank lines, ineffective areas, blocked obstructions, edge lines, the XS interpolation surface, storage-area / structure connectivity, and 2D property tables. Flow paths are not part of this pipeline (HEC-RAS does not compute them during geometry completion); use generate_flow_paths() for those.

Mutates the geometry HDF in place. No subprocess; Windows only (on Linux, use RasProcess.compute_geometry()).

If h5py has loaded HDF5 2.0 into this process, vendor HDF.PInvoke can fail with a missing H5E_LOGFAIL_g export (observed on HEC-RAS 7.0.2). Use RasProcess.compute_geometry() on a separate project copy to isolate the vendor DLLs from Python's native dependencies.

Parameters

geom_hdf_path, rasmap_path, ras_object, hecras_version As in generate_edge_lines(). overwrite : bool, default False When False and edge lines already exist, skip the whole pipeline. backup : bool, default True Back up existing edge lines to a dated .geojson.bak before an overwrite.

Returns

GeometryCompleteResult

Source code in ras_commander/RasGeometryCompute.py
Python
@staticmethod
@log_call
def compute_geometry(
    geom_hdf_path: Union[str, Path],
    rasmap_path: Optional[Union[str, Path]] = None,
    overwrite: bool = False,
    backup: bool = True,
    ras_object=None,
    hecras_version: Optional[str] = None,
) -> GeometryCompleteResult:
    """
    Run the full RASMapper geometry-completion pipeline, in-process.

    In-process equivalent of ``RasProcess.compute_geometry()`` and RASMapper's
    "Compute Geometry" action (RasMapperLib ``RASGeometry.CompleteForComputations``).
    Generates bank lines, ineffective areas, blocked obstructions, edge lines,
    the XS interpolation surface, storage-area / structure connectivity, and
    2D property tables. **Flow paths are not part of this pipeline** (HEC-RAS
    does not compute them during geometry completion); use
    ``generate_flow_paths()`` for those.

    Mutates the geometry HDF in place. No subprocess; Windows only (on Linux,
    use ``RasProcess.compute_geometry()``).

    If h5py has loaded HDF5 2.0 into this process, vendor HDF.PInvoke can
    fail with a missing ``H5E_LOGFAIL_g`` export (observed on HEC-RAS 7.0.2).
    Use ``RasProcess.compute_geometry()`` on a separate project copy to
    isolate the vendor DLLs from Python's native dependencies.

    Parameters
    ----------
    geom_hdf_path, rasmap_path, ras_object, hecras_version
        As in ``generate_edge_lines()``.
    overwrite : bool, default False
        When False and edge lines already exist, skip the whole pipeline.
    backup : bool, default True
        Back up existing edge lines to a dated ``.geojson.bak`` before an
        overwrite.

    Returns
    -------
    GeometryCompleteResult
    """
    geom_hdf_path = Path(geom_hdf_path)
    if not geom_hdf_path.exists():
        raise FileNotFoundError(f"Geometry HDF not found: {geom_hdf_path}")
    RasGeometryCompute._require_windows()

    start = time.perf_counter()
    backup_path = None
    geom = None

    def _fail(msg):
        return GeometryCompleteResult(
            success=False, geom_hdf_path=geom_hdf_path, backup_path=backup_path,
            elapsed_seconds=time.perf_counter() - start, error=msg,
        )

    with _LOCK:
        try:
            edge_exists = RasGeometryCompute._layer_exists(geom_hdf_path, _GROUP_EDGE_LINES)
            interp_exists = RasGeometryCompute._layer_exists(geom_hdf_path, _GROUP_INTERP_SURFACE)
        except Exception as exc:
            logger.error(f"Could not inspect {geom_hdf_path.name}: {exc}")
            return _fail(f"Could not inspect geometry HDF: {exc}")

        # Skip only when the completion artifacts are BOTH present (edge lines
        # alone do not prove the pipeline ran to completion).
        if edge_exists and interp_exists and not overwrite:
            logger.info("Geometry already completed (edge lines + interpolation "
                        "surface present); skipping")
            return GeometryCompleteResult(
                success=True, geom_hdf_path=geom_hdf_path,
                edge_lines_written=True, interpolation_surface_written=True,
                flow_paths_written=RasGeometryCompute._layer_exists(
                    geom_hdf_path, _GROUP_FLOW_PATHS),
                elapsed_seconds=time.perf_counter() - start,
            )

        if edge_exists and overwrite and backup:
            try:
                backup_path = RasGeometryCompute._backup_layer(
                    geom_hdf_path, "edge_lines", RasGeometryCompute._read_edge_lines)
            except Exception as exc:
                return _fail(f"Refusing to overwrite: edge-line backup failed: {exc}")
            if backup_path is None:
                return _fail(
                    "Refusing to overwrite: existing edge lines produced no backup "
                    "(possible read anomaly). Pass backup=False to override."
                )

        try:
            RasGeometryCompute._ensure_clr(hecras_version)
            rasmap = RasGeometryCompute._resolve_rasmap(rasmap_path, geom_hdf_path, ras_object)
            geom = RasGeometryCompute._load_geometry(geom_hdf_path, rasmap)
            ok = bool(geom.CompleteForComputations(False, None))
            edge_written = RasGeometryCompute._layer_exists(geom_hdf_path, _GROUP_EDGE_LINES)
            interp_written = RasGeometryCompute._layer_exists(geom_hdf_path, _GROUP_INTERP_SURFACE)
            flow_written = RasGeometryCompute._layer_exists(geom_hdf_path, _GROUP_FLOW_PATHS)
        except Exception as exc:
            logger.error(f"compute_geometry failed: {exc}")
            return _fail(str(exc))
        finally:
            RasGeometryCompute._release_geometry(geom)

    success = ok and edge_written and interp_written
    if not success:
        logger.warning("compute_geometry did not produce all required artifacts "
                       f"(ok={ok}, edge={edge_written}, interp={interp_written})")
    return GeometryCompleteResult(
        success=success,
        geom_hdf_path=geom_hdf_path,
        edge_lines_written=edge_written,
        interpolation_surface_written=interp_written,
        flow_paths_written=flow_written,
        backup_path=backup_path,
        elapsed_seconds=time.perf_counter() - start,
    )

validate_geometry staticmethod

Python
validate_geometry(geom_hdf_path: Union[str, Path], rasmap_path: Optional[Union[str, Path]] = None, ras_object=None, hecras_version: Optional[str] = None) -> 'object'

Run HEC-RAS geometry validation and return the diagnostics.

RASMapper's Validate Geometry (RasMapperLib RASGeometry.ValidateGeometry + RASGeometry.Errors), run in-process. Surfaces per-feature construction problems such as self-intersecting edge lines, overlapping cross-section cut lines, XS profile/polyline length mismatches, and bankline/flow-path intersections — the issues that block edge-line and interpolation-surface generation. One row per individual error.

Not to be confused with RasProcess.validate_geometry_association_cli(), which validates terrain/land-cover association attributes, not per-feature geometry construction.

Returns

GeoDataFrame Columns: severity (INFO/WARNING/ERROR), level (raw RASMapper level), layer, River, Reach, RS (parsed from the feature name when it matches River, Reach (RS); else None), feature (raw feature name), process, message, geometry (currently None; reserved for the offending feature geometry). Empty GeoDataFrame when no problems are found.

Source code in ras_commander/RasGeometryCompute.py
Python
@staticmethod
@log_call
def validate_geometry(
    geom_hdf_path: Union[str, Path],
    rasmap_path: Optional[Union[str, Path]] = None,
    ras_object=None,
    hecras_version: Optional[str] = None,
) -> "object":
    """
    Run HEC-RAS geometry validation and return the diagnostics.

    RASMapper's *Validate Geometry* (RasMapperLib
    ``RASGeometry.ValidateGeometry`` + ``RASGeometry.Errors``), run
    in-process. Surfaces per-feature construction problems such as
    self-intersecting edge lines, overlapping cross-section cut lines,
    XS profile/polyline length mismatches, and bankline/flow-path
    intersections — the issues that block edge-line and interpolation-surface
    generation. One row per individual error.

    Not to be confused with ``RasProcess.validate_geometry_association_cli()``,
    which validates terrain/land-cover association attributes, not per-feature
    geometry construction.

    Returns
    -------
    GeoDataFrame
        Columns: ``severity`` (INFO/WARNING/ERROR), ``level`` (raw RASMapper
        level), ``layer``, ``River``, ``Reach``, ``RS`` (parsed from the
        feature name when it matches ``River, Reach (RS)``; else None),
        ``feature`` (raw feature name), ``process``, ``message``, ``geometry``
        (currently None; reserved for the offending feature geometry). Empty
        GeoDataFrame when no problems are found.
    """
    import geopandas as gpd

    geom_hdf_path = Path(geom_hdf_path)
    if not geom_hdf_path.exists():
        raise FileNotFoundError(f"Geometry HDF not found: {geom_hdf_path}")
    RasGeometryCompute._require_windows()

    geom = None
    with _LOCK:
        try:
            RasGeometryCompute._ensure_clr(hecras_version)
            rasmap = RasGeometryCompute._resolve_rasmap(rasmap_path, geom_hdf_path, ras_object)
            geom = RasGeometryCompute._load_geometry(geom_hdf_path, rasmap)
            rows = RasGeometryCompute._harvest_errors(geom)
        finally:
            RasGeometryCompute._release_geometry(geom)

    if not rows:
        return gpd.GeoDataFrame(
            columns=["severity", "level", "layer", "River", "Reach", "RS",
                     "feature", "process", "message", "geometry"],
            geometry="geometry",
        )
    return gpd.GeoDataFrame(rows, geometry="geometry")

is_valid_geometry staticmethod

Python
is_valid_geometry(geom_hdf_path: Union[str, Path], rasmap_path: Optional[Union[str, Path]] = None, ras_object=None, hecras_version: Optional[str] = None) -> bool

Return True when validate_geometry() reports no ERROR-level problems.

Convenience wrapper matching the is_valid_* validation-framework naming. WARNING/INFO diagnostics do not fail the check.

Source code in ras_commander/RasGeometryCompute.py
Python
@staticmethod
@log_call
def is_valid_geometry(
    geom_hdf_path: Union[str, Path],
    rasmap_path: Optional[Union[str, Path]] = None,
    ras_object=None,
    hecras_version: Optional[str] = None,
) -> bool:
    """
    Return True when ``validate_geometry()`` reports no ERROR-level problems.

    Convenience wrapper matching the ``is_valid_*`` validation-framework
    naming. WARNING/INFO diagnostics do not fail the check.
    """
    report = RasGeometryCompute.validate_geometry(
        geom_hdf_path, rasmap_path=rasmap_path, ras_object=ras_object,
        hecras_version=hecras_version,
    )
    if report is None or report.empty:
        return True
    return not (report["severity"] == "ERROR").any()

audit_reach_lengths staticmethod

Python
audit_reach_lengths(geom_hdf_path: Union[str, Path], flow_paths: str = 'existing_or_generate', tolerance: float = 0.5, keep_working_copy: bool = False, rasmap_path: Optional[Union[str, Path]] = None, ras_object=None, hecras_version: Optional[str] = None) -> 'object'

Audit XS reach (flow) lengths against the current cut lines and flow paths.

A 1D unsteady model requires LOB / channel / ROB reach lengths on every cross section; HEC-RAS measures those along the flow paths, so they go stale when cut lines move. This copies the whole project to a temporary location (the original is never modified), recomputes the reach lengths from the flow paths on the copy (RASMapper's "Update Reach Lengths on XSs"), and returns a per-XS before/after comparison so you can see which lengths have drifted.

The project (not just the geometry HDF) is copied because RASGeometry needs the full project context to build the XS / river / flow-path intersections that reach-length measurement depends on. For large projects this copies the project directory; pass keep_working_copy=True to keep the recomputed copy for inspection instead of deleting it.

Parameters

geom_hdf_path : str or Path Geometry HDF to audit (must sit in its HEC-RAS project folder). Not modified. flow_paths : {'existing_or_generate', 'regenerate', 'existing'} How to obtain flow paths on the copy before measuring lengths. 'existing_or_generate' (default) leaves existing flow paths untouched (protecting manual edits) and generates them only when absent; 'regenerate' always regenerates them on the copy; 'existing' requires them and raises if absent. tolerance : float, default 0.5 Absolute length change (project units) above which a length is flagged as changed. keep_working_copy : bool, default False Keep the temporary project copy (with recomputed lengths) instead of deleting it. The copied geometry HDF path is returned in report.attrs['working_copy']. rasmap_path, ras_object, hecras_version As in the generators.

Returns

GeoDataFrame One row per cross section: River, Reach, RS, len_{left,channel,right}_stored / _recomputed, delta_{left,channel,right}, reach_end (bool; the downstream-most XS of a reach whose recomputed lengths are undefined), changed (bool), and geometry (the XS cut line). .attrs carries a summary (changed_count, used_existing_flow_paths, working_copy).

Raises

ValueError If flow_paths is unrecognized, flow_paths='existing' but the geometry has none, or the geometry has no cross sections.

Source code in ras_commander/RasGeometryCompute.py
Python
@staticmethod
@log_call
def audit_reach_lengths(
    geom_hdf_path: Union[str, Path],
    flow_paths: str = "existing_or_generate",
    tolerance: float = 0.5,
    keep_working_copy: bool = False,
    rasmap_path: Optional[Union[str, Path]] = None,
    ras_object=None,
    hecras_version: Optional[str] = None,
) -> "object":
    """
    Audit XS reach (flow) lengths against the current cut lines and flow paths.

    A 1D unsteady model requires LOB / channel / ROB reach lengths on every
    cross section; HEC-RAS measures those along the flow paths, so they go
    stale when cut lines move. This copies the **whole project** to a
    temporary location (the original is never modified), recomputes the reach
    lengths from the flow paths on the copy (RASMapper's "Update Reach Lengths
    on XSs"), and returns a per-XS before/after comparison so you can see which
    lengths have drifted.

    The project (not just the geometry HDF) is copied because RASGeometry
    needs the full project context to build the XS / river / flow-path
    intersections that reach-length measurement depends on. For large projects
    this copies the project directory; pass ``keep_working_copy=True`` to keep
    the recomputed copy for inspection instead of deleting it.

    Parameters
    ----------
    geom_hdf_path : str or Path
        Geometry HDF to audit (must sit in its HEC-RAS project folder).
        **Not** modified.
    flow_paths : {'existing_or_generate', 'regenerate', 'existing'}
        How to obtain flow paths on the copy before measuring lengths.
        'existing_or_generate' (default) leaves existing flow paths untouched
        (protecting manual edits) and generates them only when absent;
        'regenerate' always regenerates them on the copy; 'existing' requires
        them and raises if absent.
    tolerance : float, default 0.5
        Absolute length change (project units) above which a length is flagged
        as ``changed``.
    keep_working_copy : bool, default False
        Keep the temporary project copy (with recomputed lengths) instead of
        deleting it. The copied geometry HDF path is returned in
        ``report.attrs['working_copy']``.
    rasmap_path, ras_object, hecras_version
        As in the generators.

    Returns
    -------
    GeoDataFrame
        One row per cross section: ``River``, ``Reach``, ``RS``,
        ``len_{left,channel,right}_stored`` / ``_recomputed``,
        ``delta_{left,channel,right}``, ``reach_end`` (bool; the
        downstream-most XS of a reach whose recomputed lengths are undefined),
        ``changed`` (bool), and ``geometry`` (the XS cut line). ``.attrs``
        carries a summary (``changed_count``, ``used_existing_flow_paths``,
        ``working_copy``).

    Raises
    ------
    ValueError
        If ``flow_paths`` is unrecognized, ``flow_paths='existing'`` but the
        geometry has none, or the geometry has no cross sections.
    """
    if flow_paths not in ("existing_or_generate", "regenerate", "existing"):
        raise ValueError(
            "flow_paths must be 'existing_or_generate', 'regenerate', or "
            f"'existing', got {flow_paths!r}"
        )
    import numpy as np
    if not isinstance(tolerance, (int, float)) or np.isnan(tolerance) or tolerance < 0:
        raise ValueError(f"tolerance must be a non-negative number, got {tolerance!r}")

    geom_hdf_path = Path(geom_hdf_path)
    if not geom_hdf_path.exists():
        raise FileNotFoundError(f"Geometry HDF not found: {geom_hdf_path}")
    RasGeometryCompute._require_windows()

    from .hdf.HdfXsec import HdfXsec
    from .RasUtils import RasUtils

    # The geometry HDF must live in its HEC-RAS project folder (RASGeometry
    # needs the full project context, resolved relative to the .prj).
    project_folder = geom_hdf_path.parent
    if not any(project_folder.glob("*.prj")):
        raise ValueError(
            f"{geom_hdf_path.name} is not in a HEC-RAS project folder (no .prj "
            f"found in {project_folder}); audit_reach_lengths needs the project "
            f"context to compute reach lengths.")

    tmp_root = Path(tempfile.mkdtemp(prefix="reach_audit_"))
    work_project = tmp_root / project_folder.name
    used_existing_flow_paths = False
    audit_completed = False
    try:
        geom = None
        # Serialize the whole snapshot+compute so the copy is consistent with
        # (and not racing) any concurrent in-process geometry writer.
        with _LOCK:
            try:
                shutil.copytree(project_folder, work_project,
                                ignore=RasUtils.ignore_windows_reserved)
                work = work_project / geom_hdf_path.name

                stored = HdfXsec.get_cross_sections(work, ras_object=ras_object)
                if stored is None or stored.empty:
                    raise ValueError("No cross sections found; cannot audit reach lengths")

                RasGeometryCompute._ensure_clr(hecras_version)
                rasmap = RasGeometryCompute._resolve_rasmap(rasmap_path, work, ras_object)
                geom = RasGeometryCompute._load_geometry(work, rasmap)

                from .dotnet.geometry_save import suppress_feature_table_reloads

                # Without reload suppression the flow-path write, or Save()
                # itself, can reload the XS table from disk and discard the
                # recomputed lengths before they are written (#361).
                with suppress_feature_table_reloads(geom):
                    fp_exists = RasGeometryCompute._layer_exists(work, _GROUP_FLOW_PATHS)
                    if flow_paths == "existing":
                        if not fp_exists:
                            raise ValueError(
                                "flow_paths='existing' but the geometry has no flow paths")
                        used_existing_flow_paths = True
                    elif flow_paths == "regenerate" or not fp_exists:
                        geom.FlowPathLines.ComputeFlowPathLines()
                    else:  # existing_or_generate and flow paths already present
                        used_existing_flow_paths = True

                    from System.Collections.Generic import List  # type: ignore
                    from System import Int32  # type: ignore
                    xsids = List[Int32]()
                    for i in range(int(geom.XS.FeatureCount())):
                        xsids.Add(i)
                    # ref RiverMap defaults to null -> HEC-RAS builds it internally.
                    geom.ComputeReachLengthsForXSs(xsids, None)
                    geom.Save()
            finally:
                RasGeometryCompute._release_geometry(geom)

        recomputed = HdfXsec.get_cross_sections(work, ras_object=ras_object)

        # No-op guard: a real recompute writes NaN to the downstream-most XS of
        # every reach (no downstream XS). Zero NaNs means the recompute silently
        # did nothing (e.g. missing project context or flow paths).
        len_cols = ["Len Left", "Len Channel", "Len Right"]
        if not recomputed[len_cols].isna().to_numpy().any():
            raise RuntimeError(
                "Reach-length recompute produced no reach-end NaN values; it "
                "likely no-op'd (missing project context or flow paths). No "
                "reliable audit could be produced.")

        report = RasGeometryCompute._reach_length_diff(stored, recomputed, tolerance)
        report.attrs["changed_count"] = int(report["changed"].sum())
        report.attrs["invalid_recompute_count"] = int(report["invalid_recompute"].sum())
        report.attrs["used_existing_flow_paths"] = used_existing_flow_paths
        report.attrs["working_copy"] = str(work) if keep_working_copy else None
        audit_completed = True
        return report
    finally:
        if not keep_working_copy or not audit_completed:
            release_native_sessions(tmp_root)
            shutil.rmtree(tmp_root, ignore_errors=True)

assess_flow_path_policy staticmethod

Python
assess_flow_path_policy(geom_hdf_path: Union[str, Path], tolerance_fraction: float = 0.01, *, join_upstream_xs: Optional[tuple[str, str, Union[str, float, int]]] = None, join_downstream_xs: Optional[tuple[str, str, Union[str, float, int]]] = None, review_segments_path: Optional[Union[str, Path]] = None, keep_working_copy: bool = False, rasmap_path: Optional[Union[str, Path]] = None, ras_object=None, hecras_version: Optional[str] = None) -> FlowPathPolicyResult

Recommend how a 1D join should handle overbank flow paths.

The original project is never modified. This method copies the whole project, regenerates RAS Mapper flow paths on the copy, recomputes every XS LOB/channel/ROB reach length, and compares the regenerated values to the stored source values.

regenerate_and_recompute is recommended only when every usable LOB and ROB interval agrees with its stored value within tolerance_fraction. Otherwise the conservative recommendation is preserve_and_recompute_only_at_join_boundary. The conservative policy is also selected when the source has no flow-path layer but stored LOB or ROB lengths differ from the stored channel length.

Pass both join_upstream_xs and join_downstream_xs as (river, reach, river_station) tuples after a provisional joined geometry exists. The regenerated left/right flow paths are then clipped between those adjacent cross sections and returned in join_segments_gdf. The segments are review evidence for updating only the new join interval; they do not modify the source or destination.

review_segments_path optionally writes those two segments as GeoParquet. Existing files are never overwritten.

Source code in ras_commander/RasGeometryCompute.py
Python
@staticmethod
@log_call
def assess_flow_path_policy(
    geom_hdf_path: Union[str, Path],
    tolerance_fraction: float = 0.01,
    *,
    join_upstream_xs: Optional[tuple[str, str, Union[str, float, int]]] = None,
    join_downstream_xs: Optional[tuple[str, str, Union[str, float, int]]] = None,
    review_segments_path: Optional[Union[str, Path]] = None,
    keep_working_copy: bool = False,
    rasmap_path: Optional[Union[str, Path]] = None,
    ras_object=None,
    hecras_version: Optional[str] = None,
) -> FlowPathPolicyResult:
    """Recommend how a 1D join should handle overbank flow paths.

    The original project is never modified.  This method copies the whole
    project, regenerates RAS Mapper flow paths on the copy, recomputes every
    XS LOB/channel/ROB reach length, and compares the regenerated values to
    the stored source values.

    ``regenerate_and_recompute`` is recommended only when every usable LOB
    and ROB interval agrees with its stored value within
    ``tolerance_fraction``.  Otherwise the conservative recommendation is
    ``preserve_and_recompute_only_at_join_boundary``. The conservative policy is
    also selected when the source has no flow-path layer but stored LOB or
    ROB lengths differ from the stored channel length.

    Pass both ``join_upstream_xs`` and ``join_downstream_xs`` as
    ``(river, reach, river_station)`` tuples after a provisional joined
    geometry exists.  The regenerated left/right flow paths are then clipped
    between those adjacent cross sections and returned in
    ``join_segments_gdf``.  The segments are review evidence for updating
    only the new join interval; they do not modify the source or destination.

    ``review_segments_path`` optionally writes those two segments as
    GeoParquet.  Existing files are never overwritten.
    """
    tolerance_fraction = RasGeometryCompute._validate_tolerance_fraction(
        tolerance_fraction
    )
    if (join_upstream_xs is None) != (join_downstream_xs is None):
        raise ValueError(
            "join_upstream_xs and join_downstream_xs must be supplied together"
        )
    if review_segments_path is not None and join_upstream_xs is None:
        raise ValueError(
            "review_segments_path requires join_upstream_xs and "
            "join_downstream_xs"
        )

    geom_hdf_path = Path(geom_hdf_path)
    if not geom_hdf_path.exists():
        raise FileNotFoundError(f"Geometry HDF not found: {geom_hdf_path}")

    from .hdf.HdfXsec import HdfXsec

    source_flow_paths = HdfXsec.get_river_flow_paths(geom_hdf_path)
    audit = RasGeometryCompute.audit_reach_lengths(
        geom_hdf_path,
        flow_paths="regenerate",
        tolerance=0.0,
        keep_working_copy=True,
        rasmap_path=rasmap_path,
        ras_object=ras_object,
        hecras_version=hecras_version,
    )
    working_value = audit.attrs.get("working_copy")
    if not working_value:
        raise RuntimeError("Reach-length audit did not retain its working copy")
    working_copy = Path(str(working_value))
    cleanup_root = working_copy.parent.parent

    try:
        regenerated_flow_paths = HdfXsec.get_river_flow_paths(working_copy)
        if regenerated_flow_paths.empty:
            raise RuntimeError(
                "RAS Mapper regenerated no flow paths on the working copy"
            )

        xs_metrics = RasGeometryCompute._augment_reach_length_metrics(
            audit, tolerance_fraction
        )
        source_flow_path_counts = (
            RasGeometryCompute._count_flow_paths_by_reach(
                source_flow_paths, xs_metrics
            )
        )
        reach_metrics = RasGeometryCompute._summarize_flow_path_policy(
            xs_metrics,
            tolerance_fraction=tolerance_fraction,
            source_flow_path_counts=source_flow_path_counts,
        )
        if reach_metrics.empty:
            raise RuntimeError("No usable river/reach policy evidence was produced")
        preserve_policy = "preserve_and_recompute_only_at_join_boundary"
        recommended_policy = (
            preserve_policy
            if (reach_metrics["recommended_policy"] == preserve_policy).any()
            else "regenerate_and_recompute"
        )

        join_segments = RasGeometryCompute._empty_join_segments(
            getattr(regenerated_flow_paths, "crs", None)
        )
        if join_upstream_xs is not None and join_downstream_xs is not None:
            joined_xs = HdfXsec.get_cross_sections(working_copy)
            centerlines = HdfXsec.get_river_centerlines(working_copy)
            join_segments = RasGeometryCompute._clip_join_flow_path_segments(
                regenerated_flow_paths,
                joined_xs,
                centerlines,
                join_upstream_xs,
                join_downstream_xs,
            )

        saved_review_path = None
        if review_segments_path is not None:
            review_path = Path(review_segments_path)
            if review_path.suffix.lower() not in {".parquet", ".geoparquet"}:
                raise ValueError(
                    "review_segments_path must use .parquet or .geoparquet"
                )
            if review_path.exists():
                raise FileExistsError(review_path)
            review_path.parent.mkdir(parents=True, exist_ok=True)
            join_segments.to_parquet(review_path, index=False)
            saved_review_path = review_path

        retained_copy = working_copy if keep_working_copy else None
        return FlowPathPolicyResult(
            geom_hdf_path=geom_hdf_path,
            recommended_policy=recommended_policy,
            tolerance_fraction=tolerance_fraction,
            xs_metrics_df=xs_metrics,
            reach_metrics_df=reach_metrics,
            source_flow_paths_gdf=source_flow_paths,
            regenerated_flow_paths_gdf=regenerated_flow_paths,
            join_segments_gdf=join_segments,
            review_segments_path=saved_review_path,
            working_copy=retained_copy,
        )
    finally:
        if not keep_working_copy:
            RasGeometryCompute._remove_reach_audit_copy(cleanup_root)

audit_main_channel_lengths staticmethod

Python
audit_main_channel_lengths(geom_path: Union[str, Path], tolerance_fraction: float = 0.01, *, ras_object=None) -> 'gpd.GeoDataFrame'

Compare stored channel lengths to distances along the river line.

Accepts a plain-text .g## geometry or compiled .g##.hdf and does not modify or clone it. This is an informative, cross-platform QA check. main_channel_flagged is true for a non-terminal XS whose stored and centerline-measured channel lengths differ by more than the relative tolerance, or whose river-line intersection is invalid.

Source code in ras_commander/RasGeometryCompute.py
Python
@staticmethod
@log_call
def audit_main_channel_lengths(
    geom_path: Union[str, Path],
    tolerance_fraction: float = 0.01,
    *,
    ras_object=None,
) -> "gpd.GeoDataFrame":
    """Compare stored channel lengths to distances along the river line.

    Accepts a plain-text ``.g##`` geometry or compiled ``.g##.hdf`` and does
    not modify or clone it.  This is an informative, cross-platform QA
    check. ``main_channel_flagged`` is true for a non-terminal XS whose
    stored and centerline-measured channel lengths differ by more than the
    relative tolerance, or whose river-line intersection is invalid.
    """
    tolerance_fraction = RasGeometryCompute._validate_tolerance_fraction(
        tolerance_fraction
    )
    geom_path = Path(geom_path)
    if not geom_path.is_file():
        raise FileNotFoundError(geom_path)

    if geom_path.name.lower().endswith(".hdf"):
        from .hdf.HdfXsec import HdfXsec

        xs = HdfXsec.get_cross_sections(geom_path, ras_object=ras_object)
        centerlines = HdfXsec.get_river_centerlines(geom_path)
        xs = xs.rename(columns={"Len Channel": "Length_Channel"})
        centerlines = centerlines.rename(
            columns={"River Name": "River", "Reach Name": "Reach"}
        )
    else:
        from .geom.GeomCrossSection import GeomCrossSection
        from .geom.GeomParser import GeomParser

        xs = GeomCrossSection.get_cross_sections(geom_path)
        cut_lines = GeomParser.get_xs_cut_lines(geom_path).rename(
            columns={"river": "River", "reach": "Reach", "station": "RS"}
        )
        xs = xs.loc[xs["Type"] == 1].merge(
            cut_lines[["River", "Reach", "RS", "geometry"]],
            on=["River", "Reach", "RS"],
            how="left",
            validate="one_to_one",
        )
        centerlines = GeomParser.get_river_centerlines(geom_path).rename(
            columns={"river": "River", "reach": "Reach"}
        )

    result = RasGeometryCompute._measure_main_channel_lengths(
        xs, centerlines, tolerance_fraction
    )
    result.attrs["tolerance_fraction"] = tolerance_fraction
    result.attrs["flagged_count"] = int(result["main_channel_flagged"].sum())
    result.attrs["source_geometry"] = str(geom_path)
    return result

Subprocess completion and native association validation

validate_geometry_association_cli() mutates its target HDF; use an intentional validation copy. It is not a read-only check.

Static class for automating HEC-RAS operations via RasProcess.exe CLI.

This class provides methods to: - Find RasProcess.exe in standard HEC-RAS installation paths - Generate stored maps using StoreAllMaps command - Configure stored maps in .rasmap files - Fix georeferencing issues in generated TIFs - Run on Linux via Wine (auto-detected, no code changes needed)

All methods are static and follow the ras-commander pattern of accepting an optional ras_object parameter for multi-project support.

Example (Windows - unchanged): >>> from ras_commander import init_ras_project, RasProcess >>> init_ras_project("path/to/project", "7.0") >>> results = RasProcess.store_maps( ... plan_number="01", ... output_folder="Maps", ... wse=True, ... depth=True, ... velocity=True ... )

Example (Linux with Wine): >>> from ras_commander import init_ras_project, RasProcess >>> # Auto-detects Linux and uses default Wine prefix >>> init_ras_project("/path/to/project", "7.0") >>> results = RasProcess.store_maps(plan_number="01") >>> >>> # Or configure Wine explicitly: >>> RasProcess.configure_wine( ... wine_prefix="/opt/hecras-wine", ... ras_install_dir="/opt/hecras-wine/drive_c/HEC-RAS/6.6" ... )

compute_geometry staticmethod

Python
compute_geometry(geom_hdf_path: Union[str, Path], rasmap_path: Optional[Union[str, Path]] = None, ras_object=None, ras_version: str = None, timeout: int = 1800, semantic_stable_seconds: float = 10.0) -> Dict[str, Any]

Run HEC-RAS's headless geometry completion (RasProcess.exe CompleteGeometry).

This is the GUI-free equivalent of RASMapper's Compute Geometry action. It wraps RASGeometry.CompleteForComputations(), the same pipeline the RASMapper GUI runs, so it authors HEC-RAS's own River Edge Lines ("Create Edge Lines at XS Limits") and XS Interpolation Surface, plus bank lines, ineffective areas, blocked obstructions, storage-area and structure connectivity, and 2D property tables. The edge lines it produces use HEC-RAS's bank-line-anchored offset-curve algorithm and carry the group-level Source Data Hash, so HEC-RAS treats them as authoritative and will not silently recompute them. (Flow paths are not part of this pipeline.)

Platform guidance

This runs RasProcess.exe as a subprocess and works on both Windows (native) and Linux (via Wine, auto-detected). On Windows, prefer RasGeometryCompute.compute_geometry() — it runs the same pipeline in-process via pythonnet (no subprocess), exposes each layer separately (edge lines / interpolation surface / flow paths), and returns structured ValidateGeometry diagnostics. This subprocess method remains the only supported geometry-completion path for Linux/Wine execution.

Warning

This runs the entire geometry-completion pipeline (there is no narrower "just edge lines" RasProcess subcommand) and mutates the geometry HDF in place. Point it at a disposable copy unless you intend to complete the original geometry. On models with large 2D flow areas the pipeline also (re)builds 2D property tables and can take minutes.

Notes

HEC-RAS 7.0 exposes a ComputePropertyTables command, but its ExecuteWith implementation raises NotImplementedException. CompleteGeometry is the working command. Its CLI key is GeomFilename (not the .NET property name GeometryFilename). RasProcess.exe can report a native failure on either output stream while returning exit code zero.

Parameters

geom_hdf_path : str or Path Geometry HDF (.g##.hdf) to complete, mutated in place. rasmap_path : str or Path, optional .rasmap used to resolve the spatial reference. When None and a ras_object is available, it is discovered via RasMap.get_rasmap_path. ras_object : RasPrj, optional RAS project object used to locate the .rasmap and version-matched RasProcess.exe when not supplied. ras_version : str, optional HEC-RAS release, executable path, or installation directory for the RasProcess.exe lookup. An explicit path keeps completion on that runtime. timeout : int, optional Command timeout in seconds (default 1800). semantic_stable_seconds : float, optional Under Wine, terminate only the owned RasProcess.exe tree after this invocation reports Completed Writing Geometry, changes the geometry file, and leaves valid HDF semantics and size/mtime stable for this many seconds (default 10). Preexisting tables cannot trigger this fallback. Native Windows waits for normal process exit.

Returns

dict rasprocess_path, command_args, return_code, stdout, stderr, edge_lines_written, interpolation_surface_written, completion_mode, semantic_validation, owned_process_cleanup, success, error (None on success), and warnings. Success requires a completed command, no native failure diagnostics, and valid geometry completion artifacts in an updated HDF. warnings lists each record HEC-RAS labels WARNING:, with its detail lines joined by |; warnings do not fail the call.

Raises

FileNotFoundError If the geometry HDF or RasProcess.exe cannot be found.

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def compute_geometry(
    geom_hdf_path: Union[str, Path],
    rasmap_path: Optional[Union[str, Path]] = None,
    ras_object=None,
    ras_version: str = None,
    timeout: int = 1800,
    semantic_stable_seconds: float = 10.0,
) -> Dict[str, Any]:
    """
    Run HEC-RAS's headless geometry completion (RasProcess.exe CompleteGeometry).

    This is the GUI-free equivalent of RASMapper's *Compute Geometry* action.
    It wraps ``RASGeometry.CompleteForComputations()``, the same pipeline the
    RASMapper GUI runs, so it authors HEC-RAS's own **River Edge Lines**
    ("Create Edge Lines at XS Limits") and **XS Interpolation Surface**, plus
    bank lines, ineffective areas, blocked obstructions, storage-area and
    structure connectivity, and 2D property tables. The edge lines it produces
    use HEC-RAS's bank-line-anchored offset-curve algorithm and carry the
    group-level ``Source Data Hash``, so HEC-RAS treats them as authoritative
    and will not silently recompute them. (Flow paths are not part of this
    pipeline.)

    Platform guidance
    -----------------
    This runs ``RasProcess.exe`` as a subprocess and works on both Windows
    (native) and Linux (via Wine, auto-detected). **On Windows, prefer
    ``RasGeometryCompute.compute_geometry()``** — it runs the same pipeline
    in-process via pythonnet (no subprocess), exposes each layer separately
    (edge lines / interpolation surface / flow paths), and returns structured
    ``ValidateGeometry`` diagnostics. This subprocess method remains the only
    supported geometry-completion path for **Linux/Wine** execution.

    Warning
    -------
    This runs the **entire** geometry-completion pipeline (there is no
    narrower "just edge lines" RasProcess subcommand) and **mutates the
    geometry HDF in place**. Point it at a disposable copy unless you intend
    to complete the original geometry. On models with large 2D flow areas the
    pipeline also (re)builds 2D property tables and can take minutes.

    Notes
    -----
    HEC-RAS 7.0 exposes a ``ComputePropertyTables`` command, but its
    ``ExecuteWith`` implementation raises ``NotImplementedException``.
    ``CompleteGeometry`` is the working command. Its CLI key is
    ``GeomFilename`` (not the .NET property name ``GeometryFilename``).
    RasProcess.exe can report a native failure on either output stream
    while returning exit code zero.

    Parameters
    ----------
    geom_hdf_path : str or Path
        Geometry HDF (``.g##.hdf``) to complete, mutated in place.
    rasmap_path : str or Path, optional
        ``.rasmap`` used to resolve the spatial reference. When None and a
        ``ras_object`` is available, it is discovered via
        ``RasMap.get_rasmap_path``.
    ras_object : RasPrj, optional
        RAS project object used to locate the ``.rasmap`` and version-matched
        RasProcess.exe when not supplied.
    ras_version : str, optional
        HEC-RAS release, executable path, or installation directory for the
        RasProcess.exe lookup. An explicit path keeps completion on that runtime.
    timeout : int, optional
        Command timeout in seconds (default 1800).
    semantic_stable_seconds : float, optional
        Under Wine, terminate only the owned ``RasProcess.exe`` tree after
        this invocation reports ``Completed Writing Geometry``, changes the
        geometry file, and leaves valid HDF semantics and size/mtime stable
        for this many seconds (default 10). Preexisting tables cannot trigger
        this fallback. Native Windows waits for normal process exit.

    Returns
    -------
    dict
        ``rasprocess_path``, ``command_args``, ``return_code``, ``stdout``,
        ``stderr``, ``edge_lines_written``, ``interpolation_surface_written``,
        ``completion_mode``, ``semantic_validation``, ``owned_process_cleanup``,
        ``success``, ``error`` (``None`` on success), and ``warnings``.
        Success requires a completed command, no native failure diagnostics,
        and valid geometry completion artifacts in an updated HDF.
        ``warnings`` lists each record HEC-RAS labels ``WARNING:``, with its
        detail lines joined by `` | ``; warnings do not fail the call.

    Raises
    ------
    FileNotFoundError
        If the geometry HDF or RasProcess.exe cannot be found.
    """
    geom_hdf_path = Path(geom_hdf_path)
    if not geom_hdf_path.exists():
        raise FileNotFoundError(f"Geometry HDF not found: {geom_hdf_path}")

    # Resolve the .rasmap for the spatial reference when not supplied.
    if rasmap_path is None:
        ras_obj = ras_object or ras
        try:
            if getattr(ras_obj, "initialized", False) or getattr(
                ras_obj, "project_folder", None
            ):
                rasmap_path = RasMap.get_rasmap_path(ras_obj)
        except Exception as e:
            logger.debug(f"Could not auto-resolve .rasmap: {e}")
    rasmap_path = Path(rasmap_path) if rasmap_path else None

    # Prefer the RasProcess.exe shipped beside the project's own Ras.exe.
    # This keeps preprocessing aligned with the HEC-RAS version that will
    # compute the plan; fall back to normal version discovery otherwise.
    ras_obj = ras_object or ras
    rasprocess = None
    if ras_version is None:
        ras_exe_path = getattr(ras_obj, "ras_exe_path", None)
        if ras_exe_path:
            candidate = Path(ras_exe_path).parent / "RasProcess.exe"
            if candidate.exists():
                rasprocess = candidate

    if rasprocess is None:
        rasprocess = RasProcess.find_rasprocess(ras_version)
    if rasprocess is None:
        raise FileNotFoundError("RasProcess.exe not found")

    args = [
        "CompleteGeometry",
        f"GeomFilename={RasProcess._resolve_path_for_rasprocess(geom_hdf_path)}",
    ]
    if rasmap_path is not None and rasmap_path.exists():
        args.append(
            f"RasMapFilename={RasProcess._resolve_path_for_rasprocess(rasmap_path)}"
        )

    logger.info(f"Running RasProcess.exe CompleteGeometry on {geom_hdf_path.name}")
    initial_hdf_state = RasProcess._geometry_hdf_state(geom_hdf_path)
    completion_mode = "process_exit"
    owned_process_cleanup = None
    if _is_wine_helper_runtime():
        result, completion_mode, owned_process_cleanup = (
            RasProcess._run_complete_geometry_supervised(
                rasprocess,
                args,
                geom_hdf_path,
                timeout=timeout,
                working_dir=geom_hdf_path.parent,
                semantic_stable_seconds=semantic_stable_seconds,
            )
        )
    else:
        result = RasProcess._run_rasprocess(
            rasprocess,
            args,
            timeout=timeout,
            working_dir=geom_hdf_path.parent,
        )
    stdout = result.stdout or ""
    stderr = result.stderr or ""

    semantic_validation = RasProcess._geometry_completion_semantics(
        geom_hdf_path
    )
    edge_lines_written = semantic_validation["edge_lines_written"]
    interp_surface_written = semantic_validation[
        "interpolation_surface_written"
    ]

    error = native_failure_message(stdout, stderr)
    if error is None:
        final_hdf_state = RasProcess._geometry_hdf_state(geom_hdf_path)
        if result.returncode != 0 and completion_mode != "semantic_hdf_stable":
            detail = (stderr.strip() or stdout.strip()).splitlines()
            error = f"RasProcess exited with code {result.returncode}"
            if detail:
                error += f". {detail[-1]}"
        elif not semantic_validation["success"]:
            error = (
                semantic_validation["error"]
                or "Geometry HDF lacks required completion artifacts"
            )
        elif completion_mode != "semantic_hdf_stable" and (
            initial_hdf_state is None
            or final_hdf_state is None
            or final_hdf_state == initial_hdf_state
        ):
            error = "Geometry HDF was not updated"
    if error is not None:
        logger.warning("CompleteGeometry failed. %s", error)
    native_warnings = native_warning_messages(stderr, stdout)
    if native_warnings:
        logger.warning(
            "CompleteGeometry reported %d HEC-RAS warning(s): %s",
            len(native_warnings),
            "; ".join(native_warnings),
        )

    return {
        "rasprocess_path": str(rasprocess),
        "command_args": args,
        "return_code": result.returncode,
        "stdout": stdout,
        "stderr": stderr,
        "edge_lines_written": edge_lines_written,
        "interpolation_surface_written": interp_surface_written,
        "completion_mode": completion_mode,
        "semantic_validation": semantic_validation,
        "owned_process_cleanup": owned_process_cleanup,
        "success": error is None,
        "error": error,
        "warnings": native_warnings,
    }

complete_geometry staticmethod

Python
complete_geometry(geom_hdf_path: Union[str, Path], rasmap_path: Optional[Union[str, Path]] = None, ras_object=None, ras_version: str = None, timeout: int = 1800, semantic_stable_seconds: float = 10.0) -> Dict[str, Any]

Deprecated alias for :meth:compute_geometry. Use compute_geometry.

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def complete_geometry(
    geom_hdf_path: Union[str, Path],
    rasmap_path: Optional[Union[str, Path]] = None,
    ras_object=None,
    ras_version: str = None,
    timeout: int = 1800,
    semantic_stable_seconds: float = 10.0,
) -> Dict[str, Any]:
    """Deprecated alias for :meth:`compute_geometry`. Use ``compute_geometry``."""
    warnings.warn(
        "RasProcess.complete_geometry() is renamed to compute_geometry(); "
        "the old name will be removed in a future release.",
        DeprecationWarning,
        stacklevel=2,
    )
    return RasProcess.compute_geometry(
        geom_hdf_path,
        rasmap_path=rasmap_path,
        ras_object=ras_object,
        ras_version=ras_version,
        timeout=timeout,
        semantic_stable_seconds=semantic_stable_seconds,
    )

validate_geometry_association_cli staticmethod

Python
validate_geometry_association_cli(hdf_path: Union[str, Path], terrain_hdf_path: Optional[Union[str, Path]] = None, landcover_hdf_path: Optional[Union[str, Path]] = None, infiltration_hdf_path: Optional[Union[str, Path]] = None, sediment_soils_hdf_path: Optional[Union[str, Path]] = None, ras_version: str = None, timeout: int = 600, ras_object=None) -> Dict[str, Any]

Validate geometry association behavior against RasProcess.exe.

Warning

This method runs RasProcess.exe SetGeometryAssociation in-place and mutates the supplied geometry HDF. It is a reference/validation path only. Normal workflows should call RasMap.associate_geometry_layers(...), which delegates to the selected HEC-RAS generation's native geometry-association API and validates its readback.

Parameters:

Name Type Description Default
hdf_path Union[str, Path]

Existing geometry HDF to mutate and validate.

required
terrain_hdf_path Optional[Union[str, Path]]

Optional terrain HDF to associate.

None
landcover_hdf_path Optional[Union[str, Path]]

Optional land-cover/Manning's n HDF.

None
infiltration_hdf_path Optional[Union[str, Path]]

Optional infiltration HDF.

None
sediment_soils_hdf_path Optional[Union[str, Path]]

Optional sediment bed-material soils HDF.

None
ras_version str

Optional HEC-RAS version for RasProcess.exe lookup.

None
timeout int

Command timeout in seconds.

600
ras_object RasPrj

Optional RasPrj object. Present for API consistency.

None

Returns:

Type Description
Dict[str, Any]

Dict containing command args, return code, stdout/stderr,

Dict[str, Any]

before/after association attrs, expected attrs, mismatches, and

Dict[str, Any]

passed.

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def validate_geometry_association_cli(
    hdf_path: Union[str, Path],
    terrain_hdf_path: Optional[Union[str, Path]] = None,
    landcover_hdf_path: Optional[Union[str, Path]] = None,
    infiltration_hdf_path: Optional[Union[str, Path]] = None,
    sediment_soils_hdf_path: Optional[Union[str, Path]] = None,
    ras_version: str = None,
    timeout: int = 600,
    ras_object=None,
) -> Dict[str, Any]:
    """
    Validate geometry association behavior against RasProcess.exe.

    Warning:
        This method runs RasProcess.exe ``SetGeometryAssociation`` in-place
        and mutates the supplied geometry HDF. It is a reference/validation
        path only. Normal workflows should call
        ``RasMap.associate_geometry_layers(...)``, which delegates to the
        selected HEC-RAS generation's native geometry-association API and
        validates its readback.

    Args:
        hdf_path: Existing geometry HDF to mutate and validate.
        terrain_hdf_path: Optional terrain HDF to associate.
        landcover_hdf_path: Optional land-cover/Manning's n HDF.
        infiltration_hdf_path: Optional infiltration HDF.
        sediment_soils_hdf_path: Optional sediment bed-material soils HDF.
        ras_version: Optional HEC-RAS version for RasProcess.exe lookup.
        timeout: Command timeout in seconds.
        ras_object (RasPrj, optional): Optional RasPrj object. Present for API consistency.

    Returns:
        Dict containing command args, return code, stdout/stderr,
        before/after association attrs, expected attrs, mismatches, and
        ``passed``.
    """
    from ._geometry_association import (
        build_expected_geometry_association_attrs,
        build_set_geometry_association_args,
        compare_expected_geometry_association_attrs,
        read_geometry_association,
        safe_resolve_path,
    )

    hdf_path = safe_resolve_path(hdf_path)
    if not hdf_path.exists():
        raise FileNotFoundError(f"Geometry HDF not found: {hdf_path}")

    supplied = {
        "terrain_hdf_path": terrain_hdf_path,
        "landcover_hdf_path": landcover_hdf_path,
        "infiltration_hdf_path": infiltration_hdf_path,
        "sediment_soils_hdf_path": sediment_soils_hdf_path,
    }
    if all(path is None for path in supplied.values()):
        raise ValueError("Provide at least one geometry association path.")

    resolved_paths: Dict[str, Path] = {}
    for key, path_value in supplied.items():
        if path_value is None:
            continue
        resolved_path = safe_resolve_path(path_value)
        if not resolved_path.exists():
            raise FileNotFoundError(
                f"Association artifact not found for {key}: {resolved_path}"
            )
        resolved_paths[key] = resolved_path

    before = read_geometry_association(hdf_path, resolve_paths=True)
    expected_attrs = build_expected_geometry_association_attrs(
        hdf_path,
        resolved_paths,
        project_folder=hdf_path.parent,
    )

    rasprocess = RasProcess.find_rasprocess(ras_version)
    if rasprocess is None:
        raise FileNotFoundError("RasProcess.exe not found")

    command_args = build_set_geometry_association_args(
        hdf_path,
        resolved_paths,
        path_formatter=RasProcess._resolve_path_for_rasprocess,
    )
    result = RasProcess._run_rasprocess(
        rasprocess,
        command_args,
        timeout=timeout,
        working_dir=hdf_path.parent,
    )

    after = read_geometry_association(hdf_path, resolve_paths=True)
    mismatches = compare_expected_geometry_association_attrs(
        hdf_path,
        after,
        expected_attrs,
    )
    passed = (
        result.returncode == 0
        and native_failure_message(result.stdout or "", result.stderr or "") is None
        and not mismatches
    )

    return {
        "rasprocess_path": str(rasprocess),
        "command_args": command_args,
        "return_code": result.returncode,
        "stdout": result.stdout or "",
        "stderr": result.stderr or "",
        "before": before,
        "after": after,
        "expected_attrs": expected_attrs,
        "mismatches": mismatches,
        "passed": passed,
    }

Completion result records

GeometryLayerResult dataclass

Result of a single RasGeometryCompute layer-generation call.

Returned by RasGeometryCompute.generate_edge_lines() / generate_interpolation_surface() / generate_flow_paths(). Backward compatible with bool via bool.

Attributes:

Name Type Description
success bool

Whether the layer was generated (or already present when skipped).

layer str

Native HDF group written, e.g. "River Edge Lines".

geom_hdf_path Path

Geometry HDF that was operated on.

skipped bool

True when the layer already existed and overwrite=False.

backup_path Optional[Path]

Path to the dated GeoJSON backup of pre-existing features, when one was written before overwriting.

elapsed_seconds float

Wall-clock time for the generation call.

error Optional[str]

Error message on failure, else None.

Source code in ras_commander/ComputeResults.py
Python
@dataclass
class GeometryLayerResult:
    """
    Result of a single RasGeometryCompute layer-generation call.

    Returned by RasGeometryCompute.generate_edge_lines() /
    generate_interpolation_surface() / generate_flow_paths(). Backward compatible
    with bool via __bool__.

    Attributes:
        success: Whether the layer was generated (or already present when skipped).
        layer: Native HDF group written, e.g. "River Edge Lines".
        geom_hdf_path: Geometry HDF that was operated on.
        skipped: True when the layer already existed and overwrite=False.
        backup_path: Path to the dated GeoJSON backup of pre-existing features,
            when one was written before overwriting.
        elapsed_seconds: Wall-clock time for the generation call.
        error: Error message on failure, else None.
    """
    success: bool
    layer: str
    geom_hdf_path: Path
    skipped: bool = False
    backup_path: Optional[Path] = None
    elapsed_seconds: float = 0.0
    error: Optional[str] = None

    def __bool__(self) -> bool:
        return self.success

    def __repr__(self) -> str:
        if self.skipped:
            status = 'SKIPPED'
        elif self.success:
            status = 'SUCCESS'
        else:
            status = 'FAILED'
        time_str = f"{self.elapsed_seconds:.1f}s" if self.elapsed_seconds > 0 else "N/A"
        return f"GeometryLayerResult({status}, layer={self.layer!r}, time={time_str})"

GeometryCompleteResult dataclass

Result of RasGeometryCompute.compute_geometry() (RASGeometry.CompleteForComputations).

Backward compatible with bool via bool. Distinct from GeometryPreprocessResult, which wraps HEC-RAS's numerical geometry preprocessor (a different pipeline).

Attributes:

Name Type Description
success bool

Whether the geometry-completion pipeline succeeded.

geom_hdf_path Path

Geometry HDF that was completed.

edge_lines_written bool

River Edge Lines present after the run.

interpolation_surface_written bool

XS Interpolation Surfaces present after the run.

flow_paths_written bool

River Flow Paths present after the run.

backup_path Optional[Path]

Path to a dated GeoJSON backup written before overwriting, if any.

elapsed_seconds float

Wall-clock time for the call.

error Optional[str]

Error message on failure, else None.

Source code in ras_commander/ComputeResults.py
Python
@dataclass
class GeometryCompleteResult:
    """
    Result of RasGeometryCompute.compute_geometry() (RASGeometry.CompleteForComputations).

    Backward compatible with bool via __bool__. Distinct from
    GeometryPreprocessResult, which wraps HEC-RAS's numerical geometry
    preprocessor (a different pipeline).

    Attributes:
        success: Whether the geometry-completion pipeline succeeded.
        geom_hdf_path: Geometry HDF that was completed.
        edge_lines_written: River Edge Lines present after the run.
        interpolation_surface_written: XS Interpolation Surfaces present after the run.
        flow_paths_written: River Flow Paths present after the run.
        backup_path: Path to a dated GeoJSON backup written before overwriting, if any.
        elapsed_seconds: Wall-clock time for the call.
        error: Error message on failure, else None.
    """
    success: bool
    geom_hdf_path: Path
    edge_lines_written: bool = False
    interpolation_surface_written: bool = False
    flow_paths_written: bool = False
    backup_path: Optional[Path] = None
    elapsed_seconds: float = 0.0
    error: Optional[str] = None

    def __bool__(self) -> bool:
        return self.success

    def __repr__(self) -> str:
        status = 'SUCCESS' if self.success else 'FAILED'
        time_str = f"{self.elapsed_seconds:.1f}s" if self.elapsed_seconds > 0 else "N/A"
        return (
            f"GeometryCompleteResult({status}, "
            f"edge_lines={self.edge_lines_written}, "
            f"interp_surface={self.interpolation_surface_written}, "
            f"flow_paths={self.flow_paths_written}, time={time_str})"
        )

FlowPathPolicyResult dataclass

Evidence used to select a safe 1D overbank flow-path policy.

RasGeometryCompute.assess_flow_path_policy() creates the evidence on an isolated project copy. The two supported recommendations are "regenerate_and_recompute" and "preserve_and_recompute_only_at_join_boundary".

Attributes

geom_hdf_path Original geometry HDF. It is never modified by the assessment. recommended_policy Conservative model-level recommendation. A preserve recommendation on any reach controls the model-level value. tolerance_fraction Relative tolerance used to compare stored and regenerated lengths. xs_metrics_df Per-cross-section stored/regenerated length evidence. reach_metrics_df Per-river/reach policy and main-channel QA summary. source_flow_paths_gdf Flow paths present in the original geometry, if any. regenerated_flow_paths_gdf RAS Mapper flow paths generated on the isolated copy. join_segments_gdf Optional regenerated left/right flow-path segments clipped between the two cross sections adjacent to a proposed join. review_segments_path GeoParquet path written for join_segments_gdf, when requested. working_copy Retained copied geometry HDF when keep_working_copy=True.

Source code in ras_commander/ComputeResults.py
Python
@dataclass
class FlowPathPolicyResult:
    """Evidence used to select a safe 1D overbank flow-path policy.

    ``RasGeometryCompute.assess_flow_path_policy()`` creates the evidence on an
    isolated project copy.  The two supported recommendations are
    ``"regenerate_and_recompute"`` and
    ``"preserve_and_recompute_only_at_join_boundary"``.

    Attributes
    ----------
    geom_hdf_path
        Original geometry HDF.  It is never modified by the assessment.
    recommended_policy
        Conservative model-level recommendation.  A preserve recommendation
        on any reach controls the model-level value.
    tolerance_fraction
        Relative tolerance used to compare stored and regenerated lengths.
    xs_metrics_df
        Per-cross-section stored/regenerated length evidence.
    reach_metrics_df
        Per-river/reach policy and main-channel QA summary.
    source_flow_paths_gdf
        Flow paths present in the original geometry, if any.
    regenerated_flow_paths_gdf
        RAS Mapper flow paths generated on the isolated copy.
    join_segments_gdf
        Optional regenerated left/right flow-path segments clipped between the
        two cross sections adjacent to a proposed join.
    review_segments_path
        GeoParquet path written for ``join_segments_gdf``, when requested.
    working_copy
        Retained copied geometry HDF when ``keep_working_copy=True``.
    """

    geom_hdf_path: Path
    recommended_policy: str
    tolerance_fraction: float
    xs_metrics_df: "gpd.GeoDataFrame"
    reach_metrics_df: pd.DataFrame
    source_flow_paths_gdf: "gpd.GeoDataFrame"
    regenerated_flow_paths_gdf: "gpd.GeoDataFrame"
    join_segments_gdf: "gpd.GeoDataFrame"
    review_segments_path: Optional[Path] = None
    working_copy: Optional[Path] = None

    def __repr__(self) -> str:
        return (
            "FlowPathPolicyResult("
            f"policy={self.recommended_policy!r}, "
            f"tolerance={self.tolerance_fraction:.4g})"
        )

Lower-level screenshot utilities

RasMap is the project-aware entry point above. For an already identified window or dialog, RasScreenshot exposes capture and evidence-folder utilities. These GUI calls require the documented Windows dependencies and desktop; listing saved screenshots does not establish that a fresh capture succeeded.

Static class for capturing HEC-RAS window screenshots.

Uses Win32 Device Context (DC) and BitBlt to capture window pixels directly. Screenshots capture only the target window frame, not extra desktop pixels around it.

All methods are static and use the @log_call decorator.

capture_all_ras_windows staticmethod

Python
capture_all_ras_windows(pid: int, output_folder: Optional[Path] = None) -> List[Path]

Capture screenshots of ALL windows for a HEC-RAS process.

capture_dialog staticmethod

Python
capture_dialog(title_pattern: str, output_path: Optional[Path] = None, exact_match: bool = False) -> Optional[Path]

Capture screenshot of a dialog window by title pattern.

capture_foreground staticmethod

Python
capture_foreground(output_path: Optional[Path] = None) -> Optional[Path]

Capture screenshot of the current foreground window.

capture_hecras_main staticmethod

Python
capture_hecras_main(pid: int, output_path: Optional[Path] = None) -> Optional[Path]

Capture screenshot of main HEC-RAS window by process ID.

capture_menu_exploration staticmethod

Python
capture_menu_exploration(hwnd: int, menu_id: int, delay_after_click: float = 1.5) -> Tuple[bool, Optional[Path], Optional[Path]]

Click a menu item and capture both before and after screenshots.

capture_window staticmethod

Python
capture_window(hwnd: int, output_path: Optional[Path] = None, include_timestamp: bool = True, restore_if_minimized: bool = True, crop_to_visible_frame: bool = True) -> Optional[Path]

Capture a screenshot of a specific window by handle.

capture_with_delay staticmethod

Python
capture_with_delay(hwnd: int, delay_seconds: float = 1.0, output_path: Optional[Path] = None) -> Optional[Path]

Capture window screenshot after a delay.

document_dialog staticmethod

Python
document_dialog(hwnd: int, capture_screenshot: bool = True) -> Dict[str, Any]

Document a dialog window's controls and optionally capture screenshot.

get_screenshot_folder staticmethod

Python
get_screenshot_folder() -> Path

Get or create the screenshot output folder.

list_screenshots staticmethod

Python
list_screenshots(folder: Optional[Path] = None, pattern: str = '*.png') -> List[Path]

List all screenshots in the output folder.